{"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": "\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": "#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": "/* ---------------------------------------------------------------------\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": "// 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": "#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": "#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 <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élie 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 * 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": "// 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": "/* -*- 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// 内参\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n// 基线\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": "#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": "/*-------------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 * 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 * 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": "#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": "// 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": "//=======================================================================\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// 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": "// $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": "#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": " // 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 <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": "/* \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": "﻿#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 <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": "#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": "//    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 (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": "#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–1077. \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": "\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 <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": "#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; // 集団に属さない受験者の部分はスキップ\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の反応パタンのところは計算ループから外れる。\r\n          a = t0(j,0);\r\n          if(a == 0) continue;\r\n          b = t0(j,1);\r\n          c = t0(j,2);\r\n          u = xall(i,j);\r\n          if(u == 1){ // 正答した場合の尤度\r\n            tt = c+(1.0-c)/(1.0+exp(-D*a*(x-b)));\r\n          } else if (u == 0) { // 誤答した場合の尤度\r\n            tt = 1.0-(c+(1.0-c)/(1.0+exp(-D*a*(x-b))));\r\n          } else { // 欠測値の場合は尤度を計算しないので，1\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  // 各受検者のthetaごとに事後分布の重みを計算する。\r\n  double uu;\r\n  double f = 0; // 周辺対数尤度代入用\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; // 集団に属さない受験者の部分はスキップ\r\n      u = 0;\r\n      for(int m=0; m<N; m++){ // 総和を1にするための分母の計算 // sum\r\n        l = Lim[g][i][m];\r\n        w = 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    // 対数尤度の計算に失敗したら，計算を中止する。\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++){ // 各分点の期待度数\r\n      if(ind(g,j) == 0) continue;\r\n      for(int m=0; m<N; m++){\r\n        k = 0;\r\n        for(int i=0; i<ni; i++){ // 欠測値がある場合，項目ごとに受検者数が異なる。\r\n          if(resp(i,j)==0) continue;\r\n          //double d = resp(i,j);\r\n          kk = Gim[g][i][m];\r\n          k += 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++){ // 各分点の正答受検者の期待度数\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); // そもそもその項目に回答していない場合は，度数に数え上げない\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": "// 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 Çetin Kaya Koç\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 Çetin Kaya Koç\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öller\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âmara, Conrado P. L. Gouvêa, Julio López, 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 Çetin Kaya Koç\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 <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 \"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": "/*************************************************************************\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” 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": "// 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/√L) X U D^{-½}\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^{-½} U^t (1/L) X^t X U D^{-½} = 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√L) X X^t X U D^{-½}\n\t\t//           = (1/√L) X U D U^t U D^{-½}\n\t\t//           = (1/√L) X U D^½\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": "#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 \"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": "#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": "//  (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": "//\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": "#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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_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": "// 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": "// 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 <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": "/**\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": "//==============================================================================\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": "#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": "#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": "//============================================================================\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": "/*\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": "/*\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// 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 * 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// β-detected nuclear magnetic resonance (β-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": "#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": "// #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": "// 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": "#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": "// 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": "/*\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": "#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": "\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": "#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": "<<<<<<< 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": "// 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 * \\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 Δt\n//          // at a time.\n//          // So compute the transition matrix for a single step.\n//          // Computing the matrix exponential for a Δt time step.\n//          // By default we are using Δt = 1\n//          // A = e^{Ac * Δt)\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 Δt\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+Δt} = e^{Ac * Δt } * 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 * Δt } * 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 Δt.\n          //                  The actual line of code represents,\n          //                        s_t = e^{Ac * Δt } * 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 = ∅\n              //\n              //    one_off_constraints.at(ts) = ∅ => Unconstrained ∀ ts\n              //\n              //    one_off_constraints.at(ts) ‡ ∅\n              //        => ∃ 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 ‡ ∅\n              //                => The if condition is true ∀ subsequent time steps\n              //                   after ts (the first time step s.t.\n              //                   one_off_constraints.at(ts) ‡ ∅\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 *                                 ┍━━━━━━━━━━━━━━━━━━━━━━━━┑\n *                                 │           How          ┃\n *                                 ┝━━━━━━━━━━┳━━━━━━━━━━━━━┫\n *                                 │ One-off  ┃  Perpetual  ┃\n * ━━━━━━┳━━━━━━━━━━━━┯━━━━━━━━━━━━┿━━━━━━━━━━┻━━━━━━━━━━━━━┫\n *       ┃            │ Clamp at   │           v - x_{ts-1} ┃\n *       ┃            │ (by ppls@) │   ts-1 to ──────────── ┃\n *       ┃            │            │               Δt       ┃\n *       ┃ Derivative ├┈┈┈┈┈┈┈┈┈┈┈┈┼┈┈┈┈┈┈┈┈┈┈┰┈┈┈┈┈┈┈┈┈┈┈┈┈┨\n * Where ┃            │ Reset at   │ ts to ẋ₀ ┃ ts to 0     ┃\n *       ┃            │ (by glss)  │ from S₀  ┃             ┃\n *       ┣━━━━━━━━━━━━┿━━━━━━━━━━━━┿━━━━━━━━━━╋━━━━━━━━━━━━━┫\n *       ┃ Value      │ Clamp at   │ ts to v  ┃ ∀ t≥ts to v ┃\n *       ┃            │ (by ppls@) │          ┃             ┃\n * ━━━━━━┻━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━┻━━━━━━━━━━━━━┛\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 ∂v/∂t\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₆ = x_c. So we have to set the\n            //      derivative at t=6-1=5, ẋ₅, as follows:\n            //                  x_c - x₅\n            //             ẋ₅ = --------- ........... (1)\n            //                     Δt\n            //             x₆ = x₅ + (ẋ₅ × Δt)\n            //                = x_c\n            //      Thus clamping ẋ₅ (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    //      μ = 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": "/*\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": "/*\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örwald\n *  All 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": "// 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/******************************************************************************\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 \"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; /**< 杨氏模量 */\r\nfloat Poisson_r = 0.3f; /**< 泊松比 [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; /**< 微元体积 */\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()); /**< 形变率 */\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()); /**< 形变率 */\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        // 迭代多轮, 防止穿透\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": "#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,// 注册点类型宏\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 \"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": "/**\n * Copyright (c) 2018, University Osnabrück\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the University Osnabrück nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL University Osnabrück BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * EigenSVDPointAlign.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": "\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": "/* 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": "/**  \\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": "// 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": "///////////////////////////////////////////////////////////////////////////////\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); //基于区间树查找相交box\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); //基于区间树查找相交box\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": "#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": "// 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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <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": "#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 \"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": "// Copyright © 2016-2019 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#include <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": "// 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": "/**\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": "//=======================================================================\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": "/*    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": "//\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": "/*\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": "/*\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(\"オプション\");\n  options.add_options()\n    (\"help,h\",    \"ヘルプを表示\")\n    (\"input,i\", boost::program_options::value<std::string>(),  \"入力ファイル\")\n    (\"note,n\", boost::program_options::value<int>()->default_value(60),  \"音階\")\n    (\"harmonic,H\", boost::program_options::value<int>()->default_value(0),  \"倍音のみ\")\n    (\"match,m\", boost::program_options::value<bool>()->default_value(false),  \"減衰曲線をマッチさせる\")\n    (\"resolution,r\", boost::program_options::value<int>()->default_value(13),  \"分解能\");\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": "///////////////////////////////////////////////////////////////////////////////\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": "\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// 首先是通常的头文件列表，这些文件已经在以前的示例程序中使用过了。\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// 这里是头文件中仅有的三个新东西：一个包含文件，其中实现了等级为2和4的对称张量，正如介绍中所介绍的那样。\n\n#include <deal.II/base/symmetric_tensor.h> \n\n// 最后是一个包含一些函数的头文件，这些函数将帮助我们计算域中特定点的局部坐标系的旋转矩阵。\n\n#include <deal.II/physics/transformations.h> \n\n// 然后，这又是简单的C++。\n\n#include <fstream> \n#include <iostream> \n#include <iomanip> \n\n// 最后一步和以前所有的程序一样。\n\nnamespace Step18 \n{ \n  using namespace dealii; \n// @sect3{The <code>PointHistory</code> class}  \n\n// 正如介绍中提到的，我们必须在正交点存储旧的应力，这样我们就可以在下一个时间步骤中计算这一点的残余力。仅仅这一点还不能保证只有一个成员的结构，但在更复杂的应用中，我们还必须在正交点上存储更多的信息，比如塑性的历史变量等。从本质上讲，我们必须在这里存储所有影响材料当前状态的信息，在塑性中，这些信息是由变形历史变量决定的。\n\n// 除了能够存储数据之外，我们不会给这个类任何有意义的功能，也就是说，没有构造函数、析构函数或其他成员函数。在这种 \"哑巴 \"类的情况下，我们通常选择将其声明为  <code>struct</code> rather than <code>class</code>  ，以表明它们更接近于C语言风格的结构而不是C++风格的类。\n\n  template <int dim> \n  struct PointHistory \n  { \n    SymmetricTensor<2, dim> old_stress; \n  }; \n// @sect3{The stress-strain tensor}  \n\n// 接下来，我们定义弹性中的应力和应变的线性关系。它由一个等级为4的张量给出，通常被写成  $C_{ijkl} = \\mu (\\delta_{ik} \\delta_{jl} + \\delta_{il} \\delta_{jk}) + \\lambda \\delta_{ij} \\delta_{kl}$  的形式。这个张量将等级2的对称张量映射到等级2的对称张量。对于Lam&eacute;常数 $\\lambda$ 和 $\\mu$ 的给定值，一个实现其创建的函数是直接的。\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// 通过这个函数，我们将在下面的主类中定义一个静态成员变量，在整个程序中作为应力-应变张量使用。请注意，在更复杂的程序中，这可能是某个类的成员变量，或者是一个根据其他输入返回应力-应变关系的函数。例如，在损伤理论模型中，Lam&eacute;常数被认为是一个点的先前应力/应变历史的函数。相反，在塑性中，如果材料在某一点达到了屈服应力，那么应力-应变张量的形式就会被修改，而且可能还取决于其先前的历史。\n\n// 然而，在本程序中，我们假设材料是完全弹性和线性的，恒定的应力-应变张量对我们目前的目的来说是足够的。\n\n//  @sect3{Auxiliary functions}  \n\n// 在程序的其他部分之前，这里有几个我们需要的函数作为工具。这些是在内循环中调用的小函数，所以我们把它们标记为  <code>inline</code>  。\n\n// 第一个是通过形成这个形状函数的对称梯度来计算形状函数 <code>shape_func</code> at quadrature point <code>q_point</code> 的对称应变张量。当我们想形成矩阵时，我们需要这样做，比如说。\n\n// 我们应该注意到，在以前处理矢量值问题的例子中，我们总是问有限元对象在哪个矢量分量中的形状函数实际上是不为零的，从而避免计算任何我们反正可以证明为零的项。为此，我们使用了 <code>fe.system_to_component_index</code> 函数来返回形状函数在哪个分量中为零，同时 <code>fe_values.shape_value</code> 和 <code>fe_values.shape_grad</code> 函数只返回形状函数的单个非零分量的值和梯度，如果这是一个矢量值元素。\n\n// 这是一个优化，如果不是非常关键的时间，我们可以用一个更简单的技术来解决：只需向 <code>fe_values</code> 询问一个给定形状函数的给定分量在给定正交点的值或梯度。这就是  <code>fe_values.shape_grad_component(shape_func,q_point,i)</code>  调用的作用：返回形状函数  <code>shape_func</code>  的第  <code>q_point</code>  个分量在正交点的全部梯度。如果某个形状函数的某个分量总是为零，那么这将简单地总是返回零。\n\n// 如前所述，使用 <code>fe_values.shape_grad_component</code> 而不是 <code>fe.system_to_component_index</code> 和 <code>fe_values.shape_grad</code> 的组合可能效率较低，但其实现已针对这种情况进行了优化，应该不会有很大的减慢。我们在这里演示这个技术，因为它是如此的简单和直接。\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// 声明一个将保存返回值的暂存器。\n\n    SymmetricTensor<2, dim> tmp; \n\n// 首先，填充对角线项，这只是矢量值形状函数的方向 <code>i</code> of the <code>i</code> 分量的导数。\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// 然后填充应变张量的其余部分。注意，由于张量是对称的，我们只需要计算一半（这里：右上角）的非对角线元素， <code>SymmetricTensor</code> 类的实现确保至少到外面的对称条目也被填充（实际上，这个类当然只存储一份）。在这里，我们选择了张量的右上半部分，但是左下半部分也一样好。\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// 第二个函数做了非常类似的事情（因此被赋予相同的名字）：从一个矢量值场的梯度计算对称应变张量。如果你已经有了一个解场， <code>fe_values.get_function_gradients</code> 函数允许你在一个正交点上提取解场的每个分量的梯度。它返回的是一个秩-1张量的矢量：解的每个矢量分量有一个秩-1张量（梯度）。由此，我们必须通过转换数据存储格式和对称化来重建（对称的）应变张量。我们用和上面一样的方法来做，也就是说，我们通过首先填充对角线，然后只填充对称张量的一半来避免一些计算（ <code>SymmetricTensor</code> 类确保只写两个对称分量中的一个就足够了）。\n\n// 不过在我们这样做之前，我们要确保输入有我们期望的那种结构：即有 <code>dim</code> 个矢量分量，即每个坐标方向有一个位移分量。我们用 <code>Assert</code> 宏来测试这一点，如果不符合条件，我们的程序就会被终止。\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// 最后，下面我们将需要一个函数来计算某一点的位移所引起的旋转矩阵。当然，事实上，单点的位移只有一个方向和一个幅度，诱发旋转的是方向和幅度的变化。实际上，旋转矩阵可以通过位移的梯度来计算，或者更具体地说，通过卷曲来计算。\n\n// 确定旋转矩阵的公式有点笨拙，特别是在三维中。对于2D来说，有一个更简单的方法，所以我们把这个函数实现了两次，一次用于2D，一次用于3D，这样我们就可以在两个空间维度上编译和使用这个程序，如果需要的话--毕竟，deal.II是关于独立维度编程和重复使用算法的，在2D的廉价计算中经过测试，在3D的更昂贵的计算中使用。下面是一种情况，我们必须为2D和3D实现不同的算法，但可以用独立于空间维度的方式来编写程序的其余部分。\n\n// 所以，不用再多说了，来看看2D的实现。\n\n  Tensor<2, 2> get_rotation_matrix(const std::vector<Tensor<1, 2>> &grad_u) \n  { \n\n// 首先，根据梯度计算出速度场的卷曲。注意，我们是在2d中，所以旋转是一个标量。\n\n    const double curl = (grad_u[1][0] - grad_u[0][1]); \n\n// 由此计算出旋转的角度。\n\n    const double angle = std::atan(curl); \n\n// 由此，建立反对称的旋转矩阵。我们希望这个旋转矩阵能够代表本地坐标系相对于全局直角坐标系的旋转，所以我们用一个负的角度来构建它。因此，这个旋转矩阵代表了从本地坐标系移动到全局坐标系所需的旋转。\n\n    return Physics::Transformations::Rotations::rotation_matrix_2d(-angle); \n  } \n\n// 三维的情况就比较复杂了。\n\n  Tensor<2, 3> get_rotation_matrix(const std::vector<Tensor<1, 3>> &grad_u) \n  { \n\n// 同样首先计算速度场的卷曲。这一次，它是一个实数向量。\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// 从这个矢量中，利用它的大小，计算出旋转角度的正切值，并由此计算出相对于直角坐标系的实际旋转角度。\n\n    const double tan_angle = std::sqrt(curl * curl); \n    const double angle     = std::atan(tan_angle); \n\n// 现在，这里有一个问题：如果旋转角度太小，那就意味着没有旋转发生（例如平移运动）。在这种情况下，旋转矩阵就是身份矩阵。\n\n// 我们强调这一点的原因是，在这种情况下，我们有  <code>tan_angle==0</code>  。再往下看，我们在计算旋转轴的时候需要除以这个数字，这样做除法的时候会遇到麻烦。因此，让我们走捷径，如果旋转角度真的很小，就简单地返回同一矩阵。\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// 否则计算真实的旋转矩阵。为此，我们再次依靠一个预定义的函数来计算本地坐标系的旋转矩阵。\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// 这就是程序的主类。由于命名空间已经表明了我们要解决的问题，让我们用它的作用来称呼它：它引导着程序的流程，也就是说，它是顶层驱动。\n\n// 这个类的成员变量基本上和以前一样，即它必须有一个三角形，一个DoF处理程序和相关的对象，如约束条件，描述线性系统的变量等。现在还有很多成员函数，我们将在下面解释。\n\n// 然而，该类的外部接口是不变的：它有一个公共的构造函数和析构函数，并且它有一个 <code>run</code> 函数来启动所有的工作。\n\n  template <int dim> \n  class TopLevel \n  { \n  public: \n    TopLevel(); \n    ~TopLevel(); \n    void run(); \n\n  private: \n\n// 私有接口比  step-17  中的更加广泛。首先，我们显然需要创建初始网格的函数，设置描述当前网格上的线性系统的变量（即矩阵和向量），然后是实际组装系统的函数，指导每个时间步长中必须解决的问题，一个解决每个时间步长中出现的线性系统的函数（并返回它的迭代次数），最后在正确的网格上输出解向量。\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// 除了前两个，所有这些函数都在每个时间步中被调用。由于第一个时间步骤有点特殊，我们有单独的函数来描述一个时间步骤中必须发生的事情：一个用于第一个时间步骤，一个用于所有后续时间步骤。\n\n    void do_initial_timestep(); \n\n    void do_timestep(); \n\n// 然后我们需要一大堆函数来做各种事情。第一个是细化初始网格：我们从原始状态的粗网格开始，解决这个问题，然后看一下，并相应地细化网格，然后重新开始同样的过程，再次以原始状态。因此，细化初始网格比在两个连续的时间步骤之间细化网格要简单一些，因为它不涉及将数据从旧的三角测量转移到新的三角测量，特别是存储在每个正交点的历史数据。\n\n    void refine_initial_grid(); \n\n// 在每个时间步骤结束时，我们要根据这个时间步骤计算的增量位移来移动网格顶点。这就是完成这个任务的函数。\n\n    void move_mesh(); \n\n// 接下来是两个处理存储在每个正交点的历史变量的函数。第一个函数在第一个时间步长之前被调用，为历史变量设置一个原始状态。它只对属于当前处理器的单元上的正交点起作用。\n\n    void setup_quadrature_point_history(); \n\n// 第二项是在每个时间段结束时更新历史变量。\n\n    void update_quadrature_point_history(); \n\n// 这是新的共享三角法。\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// 这个程序的一个不同之处在于，我们在类声明中声明了正交公式。原因是在所有其他程序中，如果我们在计算矩阵和右手边时使用不同的正交公式，并没有什么坏处，比如说。然而，在目前的情况下，它确实如此：我们在正交点中存储了信息，所以我们必须确保程序的所有部分都同意它们的位置以及每个单元格上有多少个。因此，让我们首先声明将在整个程序中使用的正交公式...。\n\n    const QGauss<dim> quadrature_formula; \n\n// ......然后也有一个历史对象的向量，在我们负责的那些单元格上的每个正交点都有一个（也就是说，我们不为其他处理器拥有的单元格上的正交点存储历史数据）。请注意，我们可以像在  step-44  中那样使用 CellDataStorage 类来代替我们自己存储和管理这些数据。然而，为了演示的目的，在这种情况下，我们手动管理存储。\n\n    std::vector<PointHistory<dim>> quadrature_point_history; \n\n// 这个对象的访问方式是通过每个单元格、面或边持有的 <code>user pointer</code> ：它是一个 <code>void*</code> 指针，可以被应用程序用来将任意的数据与单元格、面或边联系起来。程序对这些数据的实际操作属于自己的职责范围，库只是为这些指针分配了一些空间，而应用程序可以设置和读取这些对象中的每个指针。\n\n// 进一步说：我们需要待解的线性系统的对象，即矩阵、右手边的向量和解向量。由于我们预计要解决大问题，我们使用了与 step-17 中相同的类型，即建立在PETSc库之上的分布式%并行矩阵和向量。方便的是，它们也可以在只在一台机器上运行时使用，在这种情况下，这台机器正好是我们的%并行宇宙中唯一的机器。\n\n// 然而，与 step-17 不同的是，我们不以分布式方式存储解向量--这里是在每个时间步骤中计算的增量位移。也就是说，在计算时它当然必须是一个分布式矢量，但紧接着我们确保每个处理器都有一个完整的副本。原因是我们已经在 step-17 中看到，许多函数需要一个完整的副本。虽然得到它并不难，但这需要在网络上进行通信，因此很慢。此外，这些都是重复的相同操作，这当然是不可取的，除非不必总是存储整个向量的收益超过了它。在编写这个程序时，事实证明，我们在很多地方都需要一份完整的解决方案，以至于只在必要时才获得它似乎不值得。相反，我们选择一劳永逸地获得完整的副本，而立即摆脱分散的副本。因此，请注意， <code>incremental_displacement</code> 的声明并没有像中间命名空间 <code>MPI</code> 所表示的那样，表示一个分布式向量。\n\n    PETScWrappers::MPI::SparseMatrix system_matrix; \n\n    PETScWrappers::MPI::Vector system_rhs; \n\n    Vector<double> incremental_displacement; \n\n// 接下来的变量块与问题的时间依赖性有关：它们表示我们要模拟的时间间隔的长度，现在的时间和时间步数，以及现在时间步数的长度。\n\n    double       present_time; \n    double       present_timestep; \n    double       end_time; \n    unsigned int timestep_no; \n\n// 然后是几个与%并行处理有关的变量：首先，一个变量表示我们使用的MPI通信器，然后是两个数字，告诉我们有多少个参与的处理器，以及我们在这个世界上的位置。最后，一个流对象，确保只有一个处理器实际产生输出到控制台。这与  step-17  中的所有内容相同。\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// 我们正在存储本地拥有的和本地相关的索引。\n\n    IndexSet locally_owned_dofs; \n    IndexSet locally_relevant_dofs; \n\n// 最后，我们有一个静态变量，表示应力和应变之间的线性关系。由于它是一个不依赖任何输入的常量对象（至少在这个程序中不依赖），我们把它作为一个静态变量，并将在我们定义这个类的构造函数的同一个地方初始化它。\n\n    static const SymmetricTensor<4, dim> stress_strain_tensor; \n  }; \n// @sect3{The <code>BodyForce</code> class}  \n\n// 在我们进入这个程序的主要功能之前，我们必须定义哪些力将作用在我们想要研究的变形的体上。这些力可以是体力，也可以是边界力。体力通常是由四种基本的物理力类型之一所介导的：重力、强弱相互作用和电磁力。除非人们想考虑亚原子物体（对于这些物体，无论如何准静态变形是不相关的，也是不合适的描述），否则只需要考虑引力和电磁力。为了简单起见，让我们假设我们的身体有一定的质量密度，但要么是非磁性的，不导电的，要么周围没有明显的电磁场。在这种情况下，身体的力只是 <code>rho g</code>, where <code>rho</code> 是材料密度， <code>g</code> 是一个负Z方向的矢量，大小为9.81米/秒^2。 密度和 <code>g</code> 都是在函数中定义的，我们把7700 kg/m^3作为密度，这是对钢材通常假定的值。\n\n// 为了更普遍一点，也为了能够在2d中进行计算，我们意识到体力总是一个返回 <code>dim</code> 维矢量的函数。我们假设重力沿着最后一个，即 <code>dim-1</code> 个坐标的负方向作用。考虑到以前的例子程序中的类似定义，这个函数的其余实现应该大部分是不言自明的。请注意，身体的力量与位置无关；为了避免编译器对未使用的函数参数发出警告，我们因此注释了 <code>vector_value</code> 函数的第一个参数的名称。\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// 除了身体的力之外，运动还可以由边界力和强制边界位移引起。后一种情况相当于以这样的方式选择力，使其诱发某种位移。\n\n// 对于准静态位移，典型的边界力是对一个体的压力，或者对另一个体的切向摩擦。我们在这里选择了一种更简单的情况：我们规定了边界（部分）的某种运动，或者至少是位移矢量的某些分量。我们用另一个矢量值函数来描述，对于边界上的某一点，返回规定的位移。\n\n// 由于我们有一个随时间变化的问题，边界的位移增量等于在时间段内累积的位移。因此，该类必须同时知道当前时间和当前时间步长，然后可以将位移增量近似为当前速度乘以当前时间步长。\n\n// 在本程序中，我们选择了一种简单的边界位移形式：我们以恒定的速度向下位移顶部的边界。边界的其余部分要么是固定的（然后用一个 <code>Functions::ZeroFunction</code> 类型的对象来描述），要么是自由的（Neumann类型，在这种情况下不需要做任何特殊的事情）。 利用我们在前面所有的例子程序中获得的知识，描述持续向下运动的类的实现应该是很明显的。\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// 现在是主类的实现。首先，我们初始化应力应变张量，我们将其声明为一个静态常量变量。我们选择了适合于钢铁的Lam&eacute;常数。\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// 下一步是构造函数和析构函数的定义。这里没有什么惊喜：我们为解的每个 <code>dim</code> 矢量分量选择线性和连续的有限元，以及每个坐标方向上有2个点的高斯正交公式。解构器应该是显而易见的。\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// 最后一个公共函数是指导所有工作的函数，  <code>run()</code>  。它初始化了描述我们目前所处时间位置的变量，然后运行第一个时间步骤，再循环所有其他时间步骤。请注意，为了简单起见，我们使用一个固定的时间步长，而一个更复杂的程序当然要以某种更合理的方式自适应地选择它。\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// 按照上面声明的顺序，下一个函数是创建粗略网格的函数，我们从这里开始。在这个示例程序中，我们想计算一个圆柱体在轴向压缩下的变形。因此第一步是生成一个长度为3，内外半径分别为0.8和1的圆柱体的网格。幸运的是，有一个库函数可以生成这样的网格。\n\n// 在第二步中，我们必须在圆柱体的上表面和下表面关联边界条件。我们为边界面选择一个边界指示器0，这些边界面的中点的Z坐标为0（底面），Z=3的指示器为1（顶面）；最后，我们对圆柱体外壳内部的所有面使用边界指示器2，外部使用3。\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// 一旦完成了这些，我们就可以对网格进行一次全面的细化。\n\n    triangulation.refine_global(1); \n\n// 作为最后一步，我们需要设置一个干净的数据状态，我们将这些数据存储在目前处理器上处理的所有单元的正交点中。\n\n    setup_quadrature_point_history(); \n  } \n\n//  @sect4{TopLevel::setup_system}  \n\n// 下一个函数是为一个给定的网格设置数据结构。这与 step-17 中的方法基本相同：分配自由度，然后对这些自由度进行排序，使每个处理器得到一个连续的块。请注意，每个处理器的细分块是在创建或完善网格的函数中处理的，与之前的例子程序不同（发生这种情况的时间点主要是口味问题；在这里，我们选择在创建网格时进行，因为在 <code>do_initial_timestep</code> 和 <code>do_timestep</code> 函数中，我们想在还没有调用当前函数的时候输出每个处理器上的单元数量）。\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// 下一步是设置由于悬挂节点而产生的约束。这在以前已经处理过很多次了。\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// 然后我们要设置矩阵。这里我们偏离了  step-17  ，在那里我们简单地使用了PETSc的能力，即只知道矩阵的大小，随后分配那些被写入的非零元素。虽然从正确性的角度来看，这样做很好，但是效率却不高：如果我们不给PETSc提供关于哪些元素被写入的线索，那么当我们第一次设置矩阵中的元素时（即在第一个时间步中），它的速度会慢得令人难以忍受。后来，当元素被分配后，一切都快多了。在我们所做的实验中，如果我们指示PETSc哪些元素将被使用，哪些不被使用，那么第一个时间步骤可以加快近两个数量级。\n\n// 要做到这一点，我们首先要生成我们要处理的矩阵的稀疏模式，并确保浓缩的悬挂节点约束在稀疏模式中增加必要的额外条目。\n\n    DynamicSparsityPattern sparsity_pattern(locally_relevant_dofs); \n    DoFTools::make_sparsity_pattern(dof_handler, \n                                    sparsity_pattern, \n                                    hanging_node_constraints, \n                                    /*保持约束性dofs  */ false)\n\n    SparsityTools::distribute_sparsity_pattern(sparsity_pattern, \n                                               locally_owned_dofs, \n                                               mpi_communicator, \n                                               locally_relevant_dofs); \n\n// 注意，我们在这里使用了已经在 step-11 中介绍过的 <code>DynamicSparsityPattern</code> 类，而不是我们在所有其他情况下使用的 <code>SparsityPattern</code> 类。其原因是，为了使后一个类发挥作用，我们必须给每一行的条目数提供一个初始的上限，这项任务传统上是由 <code>DoFHandler::max_couplings_between_dofs()</code> 完成。然而，这个函数有一个严重的问题：它必须计算每一行中非零项的数量的上限，而这是一个相当复杂的任务，特别是在3D中。实际上，虽然它在2D中相当准确，但在3D中经常得出太大的数字，在这种情况下， <code>SparsityPattern</code> 一开始就分配了太多的内存，经常是几百MB。后来当 <code>DoFTools::make_sparsity_pattern</code> 被调用时，我们意识到我们不需要那么多的内存，但这时已经太晚了：对于大问题，临时分配太多的内存会导致内存不足的情况。\n\n// 为了避免这种情况，我们采用了 <code>DynamicSparsityPattern</code> 类，该类速度较慢，但不需要预先估计每行非零条目的数量。因此，它在任何时候都只分配它所需要的内存，而且我们甚至可以为大型的三维问题建立它。\n\n// 值得注意的是，由于 parallel::shared::Triangulation, 的特殊性，我们构建的稀疏模式是全局的，即包括所有的自由度，无论它们是属于我们所在的处理器还是另一个处理器（如果这个程序是通过MPI并行运行的）。这当然不是最好的--它限制了我们可以解决的问题的规模，因为在每个处理器上存储整个稀疏模式（即使只是短时间）的规模并不大。然而，在程序中还有几个地方我们是这样做的，例如，我们总是把全局三角测量和DoF处理对象保留在周围，即使我们只对它们的一部分进行工作。目前，deal.II没有必要的设施来完全分配这些对象（事实上，这项任务在自适应网格中很难实现，因为随着网格的自适应细化，领域的均衡分区往往会变得不均衡）。\n\n// 有了这个数据结构，我们就可以进入PETSc稀疏矩阵，告诉它预先分配所有我们以后要写入的条目。\n\n    system_matrix.reinit(locally_owned_dofs, \n                         locally_owned_dofs, \n                         sparsity_pattern, \n                         mpi_communicator); \n\n// 在这一点上，不再需要对稀疏模式有任何明确的了解，我们可以让 <code>sparsity_pattern</code> 这个变量离开范围，不会有任何问题。\n\n// 这个函数的最后一个任务是将右侧向量和求解向量重置为正确的大小；记住，求解向量是一个本地向量，不像右侧向量是一个分布式的%并行向量，因此需要知道MPI通信器，它应该通过这个通信器来传输消息。\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// 同样，组装系统矩阵和右手边的结构与之前许多例子程序中的结构相同。特别是，它主要等同于 step-17 ，除了不同的右手边，现在只需要考虑到内部应力。此外，通过使用 <code>SymmetricTensor</code> 类，组装矩阵明显变得更加透明：请注意形成2级和4级对称张量的标量积的优雅性。这个实现也更加通用，因为它与我们可能使用或不使用各向同性的弹性张量这一事实无关。\n\n// 汇编程序的第一部分和以往一样。\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// 如同在  step-17  中一样，我们只需要在属于当前处理器的所有单元中进行循环。\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// 然后在所有指数i,j和正交点上循环，并从这个单元中组合出系统矩阵的贡献。 注意我们如何从 <code>FEValues</code> 对象中提取给定正交点的形状函数的对称梯度（应变），以及我们如何优雅地形成三重收缩 <code>eps_phi_i : C : eps_phi_j</code> ；后者需要与 step-17 中需要的笨拙计算进行比较，无论是在介绍中还是在程序的相应位置。\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// 然后也要组装本地的右手边贡献。为此，我们需要访问这个正交点的先验应力值。为了得到它，我们使用该单元的用户指针，该指针指向全局数组中与当前单元的第一个正交点相对应的正交点数据，然后添加一个与我们现在考虑的正交点的索引相对应的偏移量。\n\n          const PointHistory<dim> *local_quadrature_points_data = \n            reinterpret_cast<PointHistory<dim> *>(cell->user_pointer()); \n\n// 此外，我们还需要这个单元上的正交点的外体力值。\n\n          body_force.vector_value_list(fe_values.get_quadrature_points(), \n                                       body_force_values); \n\n// 然后，我们可以循环计算这个单元上的所有自由度，并计算出对右侧的局部贡献。\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// 现在我们有了对线性系统的局部贡献，我们需要将其转移到全局对象中。这与  step-17  中的做法完全相同。\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// 现在压缩矢量和系统矩阵。\n\n    system_matrix.compress(VectorOperation::add); \n    system_rhs.compress(VectorOperation::add); \n\n// 最后一步是再次修复边界值，就像我们在以前的程序中已经做的那样。一个稍微复杂的问题是， <code>apply_boundary_values</code> 函数希望有一个与矩阵和右手边兼容的解向量（即这里是一个分布式的%并行向量，而不是我们在这个程序中使用的顺序向量），以便用正确的边界值预设解向量的条目。我们以临时向量的形式提供这样一个兼容向量，然后将其复制到顺序向量中。\n\n// 我们通过展示边界值的灵活使用来弥补这种复杂性：按照我们创建三角形的方式，有三个不同的边界指标用来描述领域，分别对应于底面和顶面，以及内/外表面。我们希望施加以下类型的边界条件。内外圆柱体表面没有外力，这一事实对应于自然（诺伊曼型）边界条件，我们不需要做任何事情。在底部，我们希望完全没有运动，对应于圆柱体在边界的这一部分被夹住或粘住。然而，在顶部，我们希望有一个规定的垂直向下的运动来压缩圆柱体；此外，我们只希望限制垂直运动，而不是水平运动--可以把这种情况看作是一块油性良好的板坐在圆柱体的顶部将其向下推：圆柱体的原子被迫向下移动，但它们可以自由地沿着板水平滑动。\n\n//描述这种情况的方法如下：对于边界指标为零（底面）的边界，我们使用一个二维的零函数，代表在任何坐标方向都没有运动。对于指标1（顶面）的边界，我们使用 <code>IncrementalBoundaryValues</code> 类，但我们为 <code>VectorTools::interpolate_boundary_values</code> 函数指定一个额外的参数，表示它应该适用于哪些矢量分量；这是一个针对每个矢量分量的bools矢量，由于我们只想限制垂直运动，它只有最后一个分量的设置。\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// 下一个函数是控制一个时间段内必须发生的所有事情的函数。从函数名称上看，事情的顺序应该是相对不言自明的。\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// 再次求解线性系统的工作原理与之前基本相同。唯一不同的是，我们只想保留一份完整的本地解向量，而不是从PETSc的求解程序中得到的分布式向量。为此，我们为分布式向量声明一个本地临时变量，并用本地变量的内容对其进行初始化（记得 <code>apply_boundary_values</code> 中调用的 <code>assemble_system</code> 函数预设了该向量中边界节点的值），用它进行求解，并在函数结束时将其再次复制到我们声明为成员变量的完整本地向量中。然后，挂起的节点约束只分布在本地拷贝上，也就是说，在每个处理器上都是独立的。\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// 这个函数生成.vtu格式的图形输出，正如介绍中所解释的。每个进程将只对其拥有的单元格进行工作，然后将结果写入自己的文件中。此外，处理器0将写下引用所有.vtu文件的记录文件。\n\n// 这个函数的关键部分是给 <code>DataOut</code> 类提供一种方法，使其只对当前进程拥有的单元格进行工作。\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//然后，\n//就像在 step-17 中一样，定义求解变量的名称（这里是位移增量）并排队输出求解向量。请注意在下面的开关中，我们如何确保如果空间维度应该不被处理，我们抛出一个异常，说我们还没有实现这种情况（另一个防御性编程的案例）。\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// 接下来的事情是，我们想输出类似于我们在每个单元中存储的应力的平均规范。这看起来很复杂，因为在目前的处理器上，我们只在那些实际属于目前进程的单元格上存储正交点的应力。换句话说，我们似乎无法计算出所有单元的平均应力。然而，请记住，我们源自 <code>DataOut</code> 的类只迭代那些实际属于当前处理器的单元，也就是说，我们不必为所有其他单元计算任何东西，因为这些信息不会被触及。下面的小循环就是这样做的。我们将整个区块包围在一对大括号中，以确保迭代器变量不会在它们被使用的区块结束后仍然意外地可见。\n\n    Vector<double> norm_of_stress(triangulation.n_active_cells()); \n    { \n\n// 在所有的单元格上循环...\n\n      for (auto &cell : triangulation.active_cell_iterators()) \n        if (cell->is_locally_owned()) \n          { \n\n// 在这些单元上，将所有正交点的应力相加...\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// ...然后把平均值的常数写到它们的目的地。\n\n            norm_of_stress(cell->active_cell_index()) = \n              (accumulated_stress / quadrature_formula.size()).norm(); \n          } \n\n// 在我们不感兴趣的单元格上，将向量中各自的值设置为一个假值（规范必须是正值，大的负值应该能吸引你的眼球），以确保如果我们的假设有误，即这些元素不会出现在输出文件中，我们会通过观察图形输出发现。\n\n        else \n          norm_of_stress(cell->active_cell_index()) = -1e+20; \n    } \n\n// 最后把这个向量也附在上面，以便进行输出处理。\n\n    data_out.add_data_vector(norm_of_stress, \"norm_of_stress\"); \n\n// 作为最后一个数据，如果这是一个并行作业，让我们也把域划分为与处理器相关的子域。这与 step-17 程序中的工作方式完全相同。\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// 最后，有了这些数据，我们可以指示deal.II对信息进行整合，并产生一些中间数据结构，其中包含所有这些解决方案和其他数据向量。\n\n    data_out.build_patches(); \n\n// 让我们调用一个函数，打开必要的输出文件，将我们生成的数据写入其中。该函数根据给定的目录名（第一个参数）和文件名基数（第二个参数）自动构建文件名。它通过由时间步数和 \"片数 \"产生的片断来增加所产生的字符串，\"片数 \"对应于整个域的一部分，可以由一个或多个子域组成。\n\n// 该函数还为Paraview写了一个记录文件（后缀为`.pvd`），描述了所有这些输出文件如何组合成这个单一时间步骤的数据。\n\n    const std::string pvtu_filename = data_out.write_vtu_with_pvtu_record( \n      \"./\", \"solution\", timestep_no, mpi_communicator, 4); \n\n// 记录文件必须只写一次，而不是由每个处理器来写，所以我们在0号处理器上做这个。\n\n    if (this_mpi_process == 0) \n      { \n\n// 最后，我们写入paraview记录，它引用了所有.pvtu文件和它们各自的时间。注意，变量times_and_names被声明为静态的，所以它将保留前几个时间段的条目。\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// 这个函数和下一个函数分别处理第一个和下一个时间步骤的整体结构。第一个时间步骤的工作量稍大，因为我们要在连续细化的网格上多次计算，每次都从一个干净的状态开始。在这些计算的最后，我们每次都计算增量位移，我们使用最后得到的增量位移的结果来计算产生的应力更新并相应地移动网格。在这个新的网格上，我们再输出解决方案和任何我们认为重要的附加数据。\n\n// 所有这些都会穿插着产生输出到控制台，以更新屏幕上的人正在发生的事情。如同在 step-17 中一样，使用 <code>pcout</code> instead of <code>std::cout</code> 可以确保只有一个并行进程实际在向控制台写数据，而不需要在每个产生输出的地方明确地编码一个if语句。\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// 后续的时间步骤比较简单，鉴于上面对前一个函数的解释，可能不需要更多的文件。\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// 当在连续细化的网格上求解第一个时间步骤时，调用以下函数。每次迭代后，它都会计算一个细化准则，细化网格，并将每个正交点的历史变量再次设置为干净状态。\n\n  template <int dim> \n  void TopLevel<dim>::refine_initial_grid() \n  { \n\n// 首先，让每个进程计算其拥有的单元格的误差指标。\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// 然后建立一个全局向量，我们将来自每个%并行进程的局部指标合并到其中。\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// 一旦我们有了这个，就把它复制回所有处理器上的本地副本，并相应地完善网格。\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// 最后，在新的网格上再次设置正交点数据，并且只在那些我们已经确定是我们的单元上设置。\n\n    setup_quadrature_point_history(); \n  } \n\n//  @sect4{TopLevel::move_mesh}  \n\n// 在每个时间步骤结束时，我们根据这个时间步骤计算的增量位移来移动网格的节点。为了做到这一点，我们保留一个标志的向量，为每个顶点指示我们是否已经移动过它，然后在所有单元中循环，移动那些尚未移动的单元顶点。值得注意的是，我们从某个顶点相邻的单元中移动这个顶点并不重要：因为我们使用连续有限元计算位移，位移场也是连续的，我们可以从每个相邻的单元中计算某个顶点的位移。我们只需要确保每个节点都精确地移动一次，这就是为什么我们要保留标志的矢量。\n\n// 在这个函数中，有两个值得注意的地方。首先，我们如何使用 <code>cell-@>vertex_dof_index(v,d)</code> 函数获得给定顶点的位移场，该函数返回给定单元的 <code>d</code>th degree of freedom at vertex <code>v</code> 的索引。在本例中，k-th坐标方向的位移对应于有限元的k-th分量。使用这样的函数有一定的风险，因为它使用了我们在 <code>FESystem</code> 元素中为这个程序共同采取的元素顺序的知识。如果我们决定增加一个额外的变量，例如用于稳定的压力变量，并碰巧将其作为元素的第一个变量插入，那么下面的计算将开始产生无意义的结果。此外，这种计算还依赖于其他假设：首先，我们使用的元素确实有与顶点相关的自由度。对于目前的Q1元素来说确实如此，对于所有多项式阶的Qp元素来说也是如此  <code>p</code>  。然而，这对不连续的元素或混合公式的元素来说是不成立的。其次，它还建立在这样的假设上：一个顶点的位移只由与这个顶点相关的自由度的值决定；换句话说，所有对应于其他自由度的形状函数在这个特定的顶点是零。同样，对于目前的元素来说是这样的，但对于目前在deal.II中的所有元素来说并非如此。尽管有风险，我们还是选择使用这种方式，以便提出一种查询与顶点相关的单个自由度的方法。\n\n// 在这种情况下，指出一种更普遍的方法是很有意义的。对于一般的有限元来说，应该采用正交公式，将正交点放在单元的顶点上。梯形规则的 <code>QTrapezoid</code> 公式正是这样做的。有了这个正交公式，我们就可以在每个单元格中初始化一个 <code>FEValues</code> 对象，并使用 <code>FEValues::get_function_values</code> 函数来获得正交点，即单元格顶点的解函数值。这些是我们真正需要的唯一数值，也就是说，我们对与这个特定正交公式相关的权重（或 <code>JxW</code> 值）完全不感兴趣，这可以作为 <code>FEValues</code> 构造器的最后一个参数来指定。这个方案中唯一的一点小麻烦是，我们必须弄清楚哪个正交点对应于我们目前考虑的顶点，因为它们可能是以相同的顺序排列，也可能不是。\n\n// 如果有限元在顶点上有支持点（这里的支持点是有的；关于支持点的概念，见 @ref GlossSupport \"支持点\"），这种不便就可以避免了。对于这种情况，我们可以使用 FiniteElement::get_unit_support_points(). 构建一个自定义的正交规则，然后第一个 <code>cell-&gt;n_vertices()*fe.dofs_per_vertex</code> 正交点将对应于单元格的顶点，其顺序与 <code>cell-@>vertex(i)</code> 一致，同时考虑到矢量元素的支持点将被重复 <code>fe.dofs_per_vertex</code> 次。\n\n// 关于这个短函数值得解释的另一点是三角形类输出其顶点信息的方式：通过 <code>Triangulation::n_vertices</code> 函数，它公布了三角形中有多少个顶点。并非所有的顶点都是一直在使用的--有些是之前被粗化的单元的遗留物，自从deal.II以来一直存在，一旦一个顶点出现，即使数量较少的顶点消失了，也不会改变它的编号。其次， <code>cell-@>vertex(v)</code> 返回的位置不仅是一个类型为 <code>Point@<dim@></code> 的只读对象，而且事实上是一个可以写入的引用。这允许相对容易地移动网格的节点，但值得指出的是，使用该功能的应用程序有责任确保所得到的单元仍然有用，即没有扭曲到单元退化的程度（例如，用负的雅各布系数表示）。请注意，我们在这个函数中没有任何规定来实际保证这一点，我们只是有信心。\n\n// 在这个冗长的介绍之后，下面是全部20行左右的代码。\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// 在计算的开始，我们需要设置历史变量的初始值，例如材料中的现有应力，我们将其存储在每个正交点中。如上所述，我们使用每个单元中都有的 <code>user_pointer</code> 来做这个。\n\n// 为了从更大的角度看这个问题，我们注意到，如果我们的模型中有先前可用的应力（为了这个程序的目的，我们假定这些应力不存在），那么我们就需要将先前存在的应力场插值到正交点上。同样，如果我们要模拟具有硬化/软化的弹塑性材料，那么我们就必须在每个正交点存储额外的历史变量，如累积塑性应变的当前屈服应力。预先存在的硬化或弱化也将通过在当前函数中插值这些变量来实现。\n\n  template <int dim> \n  void TopLevel<dim>::setup_quadrature_point_history() \n  { \n\n// 为了慎重起见，我们把所有单元格的用户指针，不管是不是我们的，都设置为空指针。这样，如果我们访问了不应该访问的单元格的用户指针，一个分段故障将让我们知道这不应该发生。\n\n    triangulation.clear_user_data(); \n\n// 接下来，分配属于这个处理器职责范围内的正交对象。当然，这等于属于这个处理器的单元格的数量乘以我们的正交公式在每个单元格上的正交点的数量。由于`resize()`函数在要求的新大小小于旧大小的情况下，实际上并没有缩小分配的内存量，所以我们采用了一个技巧，首先释放所有的内存，然后再重新分配：我们声明一个空向量作为临时变量，然后交换旧向量和这个临时变量的内容。这就确保了`正交点历史'现在确实是空的，我们可以让现在保存着以前的向量内容的临时变量超出范围并被销毁。在下一步中，我们可以根据需要重新分配尽可能多的元素，矢量默认初始化`PointHistory`对象，这包括将压力变量设置为零。\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// 最后再次循环所有单元，并将属于本处理器的单元的用户指针设置为指向此类对象的向量中与本单元对应的第一个正交点对象。\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// 最后，为了慎重起见，确保我们对元素的计数是正确的，而且我们已经用完了之前分配的所有对象，并且没有指向任何超出向量末端的对象。这样的防御性编程策略总是很好的检查，以避免意外的错误，并防止将来对这个函数的修改忘记同时更新一个变量的所有用途。回顾一下，使用 <code>Assert</code> 宏的构造在优化模式下被优化掉了，所以不影响优化运行的运行时间。\n\n    Assert(history_index == quadrature_point_history.size(), \n           ExcInternalError()); \n  } \n\n//  @sect4{TopLevel::update_quadrature_point_history}  \n\n// 在每个时间步骤结束时，我们应该计算出一个增量的位移更新，使材料在其新的配置中能够容纳这个时间步骤中施加的外部体和边界力减去通过预先存在的内部应力施加的力之间的差异。为了在下一个时间步骤中获得预先存在的应力，我们必须用本时间步骤中计算的增量位移引起的应力来更新预先存在的应力。理想情况下，所产生的内应力之和将完全抵消所有的外力。事实上，一个简单的实验可以确保这一点：如果我们选择边界条件和体力与时间无关，那么强迫项（外力和内应力之和）应该正好是零。如果你做了这个实验，你会从每个时间步长的右手边的规范输出中意识到这几乎是事实：它并不完全是零，因为在第一个时间步长中，增量位移和应力的更新是相对于未变形的网格计算的，然后再进行变形。在第二个时间步骤中，我们再次计算位移和应力的更新，但这次是在变形的网格中 -- 在那里，结果的更新非常小但不完全是零。这可以迭代，在每一次迭代中，残差，即右手边向量的法线，都会减少；如果做这个小实验，就会发现这个残差的法线会随着迭代次数的增加而呈指数下降，在最初的快速下降之后，每次迭代大约会减少3.5倍（对于我看的一个测试案例，其他测试案例和其他未知数都会改变这个系数，但不会改变指数下降的情况）。\n\n// 在某种意义上，这可以被认为是一个准时序方案，以解决在一个以拉格朗日方式移动的网格上解决大变形弹性的非线性问题。\n\n// 另一个复杂的问题是，现有的（旧的）应力是在旧的网格上定义的，我们将在更新应力后移动这个网格。如果这个网格的更新涉及到单元的旋转，那么我们也需要对更新的应力进行旋转，因为它是相对于旧单元的坐标系计算的。\n\n// 因此，我们需要的是：在当前处理器拥有的每个单元上，我们需要从每个正交点存储的数据中提取旧的应力，计算应力更新，将两者相加，然后将结果与从当前正交点的增量位移计算出来的增量旋转一起旋转。下面我们将详细介绍这些步骤。\n\n  template <int dim> \n  void TopLevel<dim>::update_quadrature_point_history() \n  { \n\n// 首先，建立一个 <code>FEValues</code> 对象，我们将通过它来评估正交点的增量位移及其梯度，还有一个保存这些信息的向量。\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// 然后在所有单元格上循环，在属于我们子域的单元格中进行工作。\n\n    for (auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        { \n\n// 接下来，获得一个指向当前单元本地正交点历史数据的指针，作为防御措施，确保这个指针在全局数组的范围内。\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// 然后在本单元上初始化 <code>FEValues</code> 对象，并提取正交点上的位移梯度，以便以后计算应变。\n\n          fe_values.reinit(cell); \n          fe_values.get_function_gradients(incremental_displacement, \n                                           displacement_increment_grads); \n\n// 然后在这个单元的正交点上循环。\n\n          for (unsigned int q = 0; q < quadrature_formula.size(); ++q) \n            { \n\n// 在每个正交点上，从梯度中计算出应变增量，并将其乘以应力-应变张量，得到应力更新。然后将此更新添加到该点已有的应变中。\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// 最后，我们要对结果进行旋转。为此，我们首先要从增量位移中计算出目前正交点的旋转矩阵。事实上，它可以从梯度中计算出来，而且我们已经有一个函数用于这个目的。\n\n              const Tensor<2, dim> rotation = \n                get_rotation_matrix(displacement_increment_grads[q]); \n\n// 注意这个结果，即旋转矩阵，一般来说是一个等级为2的反对称张量，所以我们必须把它作为一个完整的张量来存储。\n\n// 有了这个旋转矩阵，在我们将对称张量 <code>new_stress</code> 扩展为全张量之后，我们可以通过从左和右的收缩来计算旋转的张量。\n\n              const SymmetricTensor<2, dim> rotated_new_stress = \n                symmetrize(transpose(rotation) * \n                           static_cast<Tensor<2, dim>>(new_stress) * rotation); \n\n// 注意，虽然这三个矩阵的乘法结果应该是对称的，但由于浮点舍入的原因，它并不是对称的：我们得到的结果的非对角线元素有1e-16的不对称性。当把结果赋给一个 <code>SymmetricTensor</code> 时，该类的构造函数会检查对称性并意识到它不是完全对称的；然后它会引发一个异常。为了避免这种情况，我们明确地对结果进行对称，使其完全对称。\n\n// 所有这些操作的结果会被写回到原来的地方。\n\n              local_quadrature_points_history[q].old_stress = \n                rotated_new_stress; \n            } \n        } \n  } \n\n// 这就结束了项目特定的命名空间  <code>Step18</code>  。其余的和往常一样，并且在  step-17  中已经显示：一个  <code>main()</code>  函数初始化和终止 PETSc，调用做实际工作的类，并确保我们捕捉所有传播到这一点的异常。\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": "//==================================================================================================\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": "/* -*- 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–Sutherland 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": "\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// 同样，前几个include文件已经知道了，所以我们不会对它们进行评论。\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// 现在，这些是多级方法所需的包括。第一个声明了如何处理多网格方法每个层次上的Dirichlet边界条件。对于自由度的实际描述，我们不需要任何新的包含文件，因为DoFHandler已经实现了所有必要的方法。我们只需要将自由度分配给更多的层次。\n\n// 其余的包含文件涉及到作为线性算子（求解器或预处理器）的多重网格的力学问题。\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// 我们将使用 MeshWorker::mesh_loop 来对单元格进行循环，所以在这里包括它。\n\n#include <deal.II/meshworker/mesh_loop.h> \n\n// 这就是C++。\n\n#include <iostream> \n#include <fstream> \n\nusing namespace dealii; \n\nnamespace Step16 \n{ \n// @sect3{The Scratch and Copy objects}  \n\n// 我们使用 MeshWorker::mesh_loop() 来组装我们的矩阵。为此，我们需要一个ScratchData对象来存储每个单元的临时数据（这只是FEValues对象）和一个CopyData对象，它将包含每个单元装配的输出。关于scratch和copy对象的用法的更多细节，请参见WorkStream命名空间。\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// 这个主类与  step-6  中的同一类相似。就成员函数而言，唯一增加的是。\n\n// --  <code>assemble_multigrid</code> 的函数，该函数组装了对应于中间层离散运算符的矩阵。\n\n// -  <code>cell_worker</code> 函数，它将我们的PDE集合在一个单元上。\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// 以下成员是多网格方法的基本数据结构。前四个表示稀疏模式和多级层次结构中各个层次的矩阵，非常类似于上面的全局网格的对象。\n\n// 然后，我们有两个新的矩阵，只需要在自适应网格上进行局部平滑的多网格方法。它们在细化区域的内部和细化边缘之间传递数据，在 @ref mg_paper \"多网格论文 \"中详细介绍过。\n\n// 最后一个对象存储了每个层次上的边界指数信息和位于两个不同细化层次之间的细化边缘上的指数信息。因此，它的作用与AffineConstraints相似，但在每个层次上。\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// 关于三角形的构造函数只有一个简短的评论：按照惯例，deal.II中所有自适应精化的三角形在单元格之间的面的变化不会超过一个级别。然而，对于我们的多网格算法，我们需要一个更严格的保证，即网格在连接两个单元的顶点上的变化也不超过细化级别。换句话说，我们必须防止出现以下情况。\n\n//  @image html limit_level_difference_at_vertices.png \"\"  \n\n// 这可以通过向三角化类的构造函数传递 Triangulation::limit_level_difference_at_vertices 标志来实现。\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// 除了只是在DoFHandler中分配自由度之外，我们在每一层都做同样的事情。然后，我们按照之前的程序，在叶子网格上设置系统。\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// 多网格约束必须被初始化。他们需要知道在哪里规定了Dirichlet边界条件。\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// 现在是关于多网格数据结构的事情。首先，我们调整多级对象的大小，以容纳每一级的矩阵和稀疏模式。粗略的级别是零（现在是强制性的，但在未来的修订中可能会改变）。注意，这些函数在这里采取的是一个完整的、包容的范围（而不是一个起始索引和大小），所以最细的级别是 <code>n_levels-1</code>  。我们首先要调整容纳SparseMatrix类的容器的大小，因为它们必须在调整大小时释放它们的SparsityPattern才能被销毁。\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// 现在，我们必须在每个级别上提供一个矩阵。为此，我们首先使用 MGTools::make_sparsity_pattern 函数在每个层次上生成一个初步的压缩稀疏模式（关于这个主题的更多信息，请参见 @ref Sparsity 模块），然后将其复制到我们真正想要的那一个。下一步是用拟合的稀疏度模式初始化接口矩阵。\n\n// 值得指出的是，界面矩阵只包含位于较粗和较细的网格之间的自由度的条目。因此，它们甚至比我们的多网格层次结构中的各个层次的矩阵还要稀疏。因此，我们使用一个专门为此目的而建立的函数来生成它。\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函数用于在给定的单元上组装矩阵和右手边。这个函数用于活动单元生成system_matrix，并在每个层次上建立层次矩阵。\n\n// 注意，当从assemble_multigrid()调用时，我们也会组装一个右手边，尽管它没有被使用。\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// 下面的函数将线性系统集合在网格的活动单元上。为此，我们向Mesh_loop()函数传递两个lambda函数。cell_worker函数重定向到同名的类成员函数，而copyer是这个函数特有的，它使用约束条件将本地矩阵和向量复制到相应的全局矩阵。\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// 下一个函数是建立矩阵，定义每一层网格上的多网格方法。集成的核心与上面的相同，但是下面的循环将遍历所有已存在的单元，而不仅仅是活动的单元，并且必须将结果输入正确的层矩阵。幸运的是，MeshWorker对我们隐藏了大部分的内容，因此这个函数和之前的函数的区别只在于汇编器的设置和循环中的不同迭代器。\n\n// 我们为每个层次生成一个AffineConstraints对象，其中包含边界和界面道夫作为约束条目。然后，相应的对象被用来生成层次矩阵。\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// 接口条目在填充mg_matrices[cd.level]时被上面的boundary_constraints对象所忽略。相反，我们手动将这些条目复制到当前级别的界面矩阵中。\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// 这是另外一个在支持多栅求解器（或者说，事实上，我们使用多栅方法的前提条件）方面有明显不同的函数。\n\n// 让我们从建立多层次方法的两个组成部分开始：层次间的转移运算器和最粗层次上的求解器。在有限元方法中，转移算子来自所涉及的有限元函数空间，通常可以用独立于所考虑问题的通用方式计算。在这种情况下，我们可以使用MGTransferPrebuilt类，给定最终线性系统的约束和MGConstrainedDoFs对象，该对象知道每个层次的边界条件和不同细化层次之间接口的自由度，可以从具有层次自由度的DoFHandler对象中建立这些转移操作的矩阵。\n\n// 下面几行的第二部分是关于粗略网格求解器的。由于我们的粗网格确实非常粗，我们决定采用直接求解器（最粗层次矩阵的Householder分解），即使其实现不是特别复杂。如果我们的粗网格比这里的5个单元多得多，那么这里显然需要更合适的东西。\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// 多级求解器或预处理器的下一个组成部分是，我们需要在每一级上设置平滑器。这方面常见的选择是使用松弛方法的应用（如SOR、Jacobi或Richardson方法）或求解器方法的少量迭代（如CG或GMRES）。 mg::SmootherRelaxation 和MGSmootherPrecondition类为这两种平滑器提供支持。这里，我们选择应用单一的SOR迭代。为此，我们定义一个适当的别名，然后设置一个平滑器对象。\n\n// 最后一步是用我们的水平矩阵初始化平滑器对象，并设置一些平滑参数。 <code>initialize()</code> 函数可以有选择地接受额外的参数，这些参数将被传递给每一级的平滑器对象。在目前SOR平滑器的情况下，这可能包括一个松弛参数。然而，我们在这里将这些参数保留为默认值。对 <code>set_steps()</code> 的调用表明我们将在每个级别上使用两个前平滑步骤和两个后平滑步骤；为了在不同级别上使用可变数量的平滑器步骤，可以在对 <code>mg_smoother</code> 对象的构造函数调用中设置更多选项。\n\n// 最后一步的结果是我们使用SOR方法作为平滑器的事实\n\n// --这不是对称的\n\n// 但我们在下面使用共轭梯度迭代（需要对称的预处理），我们需要让多级预处理确保我们得到一个对称的算子，即使是非对称的平滑器。\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// 下一个准备步骤是，我们必须将我们的水平和接口矩阵包裹在一个具有所需乘法函数的对象中。我们将为从粗到细的接口对象创建两个对象，反之亦然；多网格算法将在后面的操作中使用转置运算器，允许我们用已经建立的矩阵初始化该运算器的上下版本。\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// 现在，我们准备设置V型循环算子和多级预处理程序。\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// 有了这一切，我们终于可以用通常的方法来解决这个线性系统了。\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// 以下两个函数在计算出解决方案后对其进行后处理。特别是，第一个函数在每个周期开始时细化网格，第二个函数在每个周期结束时输出结果。这些函数与  step-6  中的函数几乎没有变化。\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// 和上面的几个函数一样，这几乎是对  step-6  中相应函数的复制。唯一的区别是对 <code>assemble_multigrid</code> 的调用，它负责形成我们在多网格方法中需要的每一层的矩阵。\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// 这又是与 step-6 中相同的函数。\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": "#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": "//\n//  ComputeHausdorffDistance.cpp\n//  Elasticity\n//\n//  Created by Wim van Rees on 12/28/16.\n//  Copyright © 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": "/*\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": "// 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": "#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": "#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": "/**\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": "// 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": "#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 <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// 曲线模型的顶点，模板参数：优化变量维度和数据类型\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    // 存盘和读盘：留空\n    virtual bool read( istream& in ) { return false; }\n    virtual bool write( ostream& out ) const { return false; }\n};\n\n// 误差模型 模板参数：观测值维度，类型，连接顶点类型\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    // 计算曲线模型误差\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 值， 9.8^2 值为 _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'))  //讀檔讀到跳行字元\n\t{\n\t\tvector<double> row_data;\n\t\tstringstream templine(line); // string 轉換成 stream\n\t\tstring data;\n\t\t while (getline( templine, data,',')) //讀檔讀到逗號\n\t\t {\n\t\t\t row_data.push_back(stof(data));  //string 轉換成數字\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    // 构建图优化，先设定g2o\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,1> > Block;  // 每个误差项优化变量维度为6，误差值维度为1\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); // 线性方程求解器\n    Block* solver_ptr = new Block( linearSolver );      // 矩阵块求解器\n    // 梯度下降方法，从GN, LM, DogLeg 中选\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;     // 图模型\n    optimizer.setAlgorithm( solver );   // 设置求解器\n    optimizer.setVerbose( true );       // 打开调试输出\n    \n    // 往图中增加顶点\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    // 往图中增加边\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 );                // 设置连接的顶点\n        edge->setMeasurement( 9.8*9.8 );      // 观测数值\n        edge->setInformation( Eigen::Matrix<double,1,1>::Identity() ); // 信息矩阵：协方差矩阵之逆\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    // 执行优化\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    // 输出优化值\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": "#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": "#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": "/* 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\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// 如果你读过 step-4 和 step-7 ，你会认识到我们已经在那里使用了以下所有的包含文件。因此，我们不会在这里再次解释它们的含义。\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//这个类几乎与 step-4 中的 <code>LaplaceProblem</code> 类完全相似。\n\n//本质上的区别是这样的。\n\n\n\n// - 模板参数现在表示嵌入空间的维度，它不再与域和我们计算的三角形的维度相同。我们通过调用参数 @p spacedim, 并引入一个等于域的维度的常数 @p dim 来表明这一点--这里等于 <code>spacedim-1</code>  。\n\n// - 所有具有几何特征的成员变量现在都需要知道它们自己的维度以及嵌入空间的维度。因此，我们需要指定它们的模板参数，一个是网格的维度 @p dim, ，另一个是嵌入空间的维度， @p spacedim.  这正是我们在 step-34 中所做的，请看那里有更深的解释。\n\n// - 我们需要一个对象来描述从参考单元到三角形组成的单元所使用的哪种映射。从Mapping基类派生出来的类正是这样做的。在deal.II的大部分时间里，如果你不做任何事情，图书馆会假定你想要一个使用（双，三）线性映射的MappingQ1对象。在许多情况下，这就足够了，这就是为什么这些对象的使用大多是可选的：例如，如果你有一个二维空间中的多边形二维域，参考单元到三角形单元的双线性映射会产生该域的精确表示。如果你有一个弯曲的域，你可能想对那些位于域的边界的单元使用一个高阶映射--例如，这就是我们在 step-11 中所做的。然而，在这里我们有一个弯曲的域，而不仅仅是一个弯曲的边界，虽然我们可以用双线性映射的单元来近似它，但对所有单元使用高阶映射才是真正谨慎的。因此，这个类有一个MappingQ类型的成员变量；我们将选择映射的多项式程度等于计算中使用的有限元的多项式程度，以确保最佳近似，尽管这种等参数性不是必须的。\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// 接下来，让我们定义描述问题的精确解和右手边的类。这与 step-4 和 step-7 相类似，在那里我们也定义了此类对象。鉴于介绍中的讨论，实际的公式应该是不言自明的。值得关注的一点是，我们是如何使用一般模板的明确特化，分别定义2D和3D情况下的值和梯度函数的。另一种方法是定义通用模板，并为空间维度的每个可能的值设置一个 <code>switch</code> 语句（或一串 <code>if</code> s）。\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// 如果你知道  step-4  ，程序的其余部分实际上是很不引人注目的。我们的第一步是定义构造函数，设置有限元和映射的多项式程度，并将DoF处理程序与三角形关联。\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// 下一步是创建网格，分配自由度，并设置描述线性系统的各种变量。所有这些步骤都是标准的，只有如何创建一个描述曲面的网格除外。我们可以为我们感兴趣的领域生成一个网格，用一个网格生成器生成一个三角形，然后用GridIn类将其读入。或者，就像我们在这里做的那样，我们使用GridGenerator命名空间的设施来生成网格。\n\n// 具体来说，我们要做的是这样的（在下面的大括号中）：我们使用 <code>spacedim</code> 函数为半圆盘（2D）或半球（3D）生成一个 GridGenerator::half_hyper_ball 维度的网格。这个函数将位于圆盘/球周边的所有面的边界指标设置为零，而在将整个圆盘/球分成两半的直线部分设置为零。下一步是主要的一点。 GridGenerator::extract_boundary_mesh 函数创建的网格是由那些作为前一个网格的面的单元组成的，也就是说，它描述了原始（体积）网格的<i>surface</i>单元。然而，我们不需要所有的面：只需要那些在圆盘或球的周边，边界指示器为零的面；我们可以使用一组边界指示器来选择这些单元，并传递给 GridGenerator::extract_boundary_mesh. 。\n\n// 有一点需要提及。为了在流形是弯曲的情况下适当地细化表面网格（类似于细化与弯曲边界相邻的单元面），三角形必须要有一个对象附加在上面，描述新顶点应该位于何处。如果你不附加这样的边界对象，它们将位于现有顶点之间的中间位置；如果你有一个具有直线边界的域（例如多边形），这是很合适的，但如果像这里一样，流形具有曲率，则不合适。因此，为了让事情正常进行，我们需要将流形对象附加到我们的（表面）三角形上，其方式与我们在1d中为边界所做的大致相同。我们创建这样一个对象，并将其附加到三角剖面上。\n\n// 创建网格的最后一步是对其进行多次细化。该函数的其余部分与之前的教程程序中相同。\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// 下面是这个程序的中心函数，即组装与表面拉普拉斯（Laplace-Beltrami算子）相对应的矩阵。也许令人惊讶的是，它实际上与例如在  step-4  中讨论的普通拉普拉斯算子看起来完全一样。关键是 FEValues::shape_grad() 函数发挥了魔力：它返回 $i$ 第1个形状函数在 $q$ 第1个正交点的表面梯度 $\\nabla_K \\phi_i(x_q)$ 。其余的也不需要任何改变。\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// 下一个函数是解决线性系统的函数。在这里，也不需要做任何改变。\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// 这是一个从解决方案中生成图形输出的函数。它的大部分都是模板代码，但有两点值得指出。\n\n\n\n// -  DataOut::add_data_vector() 函数可以接受两种向量。  一种是之前通过 DataOut::attach_dof_handler(); 连接的DoFHandler对象定义的每个自由度有一个值的向量，另一种是三角测量的每个单元有一个值的向量，例如，输出每个单元的估计误差。通常，DataOut类知道如何区分这两种向量：自由度几乎总是比单元格多，所以我们可以通过两种向量的长度来区分。我们在这里也可以这样做，但只是因为我们很幸运：我们使用了一个半球体。如果我们用整个球体作为域和 $Q_1$ 元素，我们将有相同数量的单元格作为顶点，因此这两种向量将有相同数量的元素。为了避免由此产生的混乱，我们必须告诉 DataOut::add_data_vector() 函数我们有哪种矢量。DoF数据。这就是该函数的第三个参数的作用。\n\n// -  DataOut::build_patches() 函数可以生成细分每个单元的输出，这样可视化程序可以更好地解决弯曲流形或更高的多项式程度的形状函数。在这里，我们在每个坐标方向上对每个元素进行细分，细分的次数与使用的有限元的多项式程度相同。\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// 这是最后一块功能：我们要计算数值解的误差。它是之前在  step-7  中展示和讨论的代码的逐字复制。正如介绍中提到的， <code>Solution</code> 类提供了解决方案的（切向）梯度。为了避免只评估超收敛点的误差，我们选择一个足够高阶的正交规则。\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// 最后一个函数提供了顶层的逻辑。它的内容是不言自明的。\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// 该程序的其余部分由 <code>main()</code> 函数占据。它完全遵循首次在 step-6 中介绍的一般布局，并在随后的所有教程程序中使用。\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": "#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": "// Copyright (c) 2007–2018 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® (SwRI®)\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above copyright\n//       notice, this list of conditions and the following disclaimer in the\n//       documentation and/or other materials provided with the distribution.\n//     * Neither the name of Southwest Research Institute® (SwRI®) nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// *****************************************************************************\n\n#include <swri_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": "/**\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": "#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": "#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 <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": "/*\r\nThis sample illustrates how to use the Fréchet 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": "// 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 ṕarrallel 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 ín 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": "/*    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 <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": "#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 ĈU_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ŭ (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) {}//-«\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; }  //»-\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; }; //-«\n    template<class K> Vektor2D<K> al() const { eligu Vektor2D<K>(ŝanĝu_al<K>(x), ŝanĝu_al<K>(y)); } //»-\n    ℚ normon() const { eligu sqrt((ℚ) (x * x + y * y)); }\n    Vektor2D<T> dikunNormo(T celnormo) const;\n\n#ifdef ĈU_UZAS_QT\n    UZU_SE_(T, ĉu_estas_ℤ<P1>)\n    Vektor2D(const QPoint& p) : x(p.x()), y(p.y()) {};\n    UZU_SE_(T, ĉu_estas_ℚ_krom_ℤ<P1>)\n    Vektor2D(const QPointF& p) : x(p.x()), y(p.y()) {};\n    UZU_SE_(T, ĉu_estas_ℤ<P1>)\n    operator QPoint() { eligu QPoint(x, y); }\n    UZU_SE_(T, ĉu_estas_ℚ_krom_ℤ<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ŭ (a.x == b.x kaj (a.y < b.y aŭ (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) {} //-«\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; } //»-\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; }; // -«\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>(ŝanĝu_al<K>(x), ŝanĝu_al<K>(y), ŝanĝu_al<K>(z)); }\n    Vektor2D<T> xy() const { eligu Vektor2D<T>(x, y); }\n    ℚ normon() const { eligu sqrt((ℚ)(x * x + y * y + z * z)); }\n    Vektor<T> dikunNormo(T celnormo) const { premisu (normon() != 0); eligu (*this * celnormo) / normon(); } //»-\n    \n    T x, y, z;\n    TORENTU { torento & x & y & z; }\n};\n\n//-«\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; }//»-\n\ntypedef Vektor<ℕ2> BazaKoordinato;\ntypedef Vektor2D<ℕ2> BazaKoordinato2D;\n//typedef Vektor<FiksitaKomo<ℕ4, pow(2, bitojDen<ℕ4> - bitojDen<ℕ2>)>> 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 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": "/*\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": "#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": "/* -*- 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|  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": "\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 ◆開発環境\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のx値が互い違いになっている場合の為の処理。\n            // p0[0]==3, p1[0]==1の様にp0がp1より先のx地点にある場合。\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        // 計算\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のポイント４点を用いて４点間のcubicBezierの離散化したカーブ(point群)を生成する。\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 * \\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 \"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": "#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 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": "/* -*- 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 Ślusarski\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": "// 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": "#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": "// 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änkt), 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": "#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 ≤ j ≤ 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−1, . . . , 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": "// 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": "#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": "#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": "/*\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": "#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": "//==================================================================================================\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": "// 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 © 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": "// ----------------------------------------------------------------------------\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": "#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": "//\n// Created by Сергей Кривонос 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// 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": "/*\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 \"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": "// 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": "\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": "/** @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": "/*\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é, 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": "// 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": "#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    //配置求解器并求解，输出结果\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 <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": "#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": "#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–Ford 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–Ford algorithm: an edge from u to v, having length\n  // w(u,v), is given the new length w(u,v) + h(u) − 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": "// 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": "// 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": "#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 – 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": "#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 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": "#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": "// 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ández\n * @author Paul Mathieu\n * @author Gérald 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": "#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": "#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": "#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": "#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": "/* 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–Boltzmann 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": "/*\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": "<%\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": "#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": "/**\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": "#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": "/*--\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": "/* -*- 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": "/* 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": "#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// 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": "#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étrique)\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éfinie\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 \"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 * 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 <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": "/*\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": "//  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": "// 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/图片/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": "#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 *             π   [         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": "// 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/*!\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// 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": "////////////////////////////////////////////////////////////////////////////////\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 (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 © 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": "#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": "#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": "\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": "/*\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": "//\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 <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": "#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": "// 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": "// 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// 这个程序的包含文件与之前许多其他程序的包含文件是一样的。唯一的新文件是在介绍中讨论的声明FE_Nothing的文件。hp目录下的文件已经在  step-27  中讨论过了。\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/utilities.h> \n\n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/lac/sparse_direct.h> \n#include <deal.II/lac/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// 这是主类。如果你想的话，它是 step-8 和 step-22 的组合，因为它的成员变量要么针对全局问题（Triangulation和DoFHandler对象，以及 hp::FECollection 和各种线性代数对象），要么与弹性或斯托克斯子问题有关。然而，该类的一般结构与其他大多数实现静止问题的程序一样。\n\n// 有几个不言自明的辅助函数（<code>cell_is_in_fluid_domain, cell_is_in_solid_domain</code>）（对两个子域的符号名称进行操作，这些名称将被用作属于子域的单元的 material_ids。正如介绍中所解释的那样）和几个函数（<code>make_grid, set_active_fe_indices, assemble_interface_terms</code>），这些函数已经从其他的函数中分离出来，可以在其他的教程程序中找到，我们将在实现它们的时候讨论。\n\n// 最后一组变量 (  <code>viscosity, lambda, eta</code>  ) 描述了用于两个物理模型的材料属性。\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// 下面这个类如其名。速度的边界值分别为2d的 \n//  $\\mathbf u=(0, \\sin(\\pi x))^T$ 和3d的 $\\mathbf u=(0,\n//  0, \\sin(\\pi x)\\sin(\\pi y))^T$ 。\n//  这个问题的其余边界条件都是同质的，在介绍中已经讨论过。右边的强迫项对于流体和固体都是零，所以我们不需要为它设置额外的类。\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// 现在我们来谈谈这个程序的主类的实现。最初的几个函数是构造函数和辅助函数，可以用来确定一个单元格在域的哪个部分。鉴于介绍中对这些主题的讨论，它们的实现是相当明显的。在构造函数中，注意我们必须从斯托克斯和弹性的基本元素中构造 hp::FECollection 对象；使用 hp::FECollection::push_back 函数在这个集合中为它们分配了0和1的位置，我们必须记住这个顺序，并在程序的其余部分一致使用。\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// 接下来的一对函数是处理生成网格，并确保所有表示子域的标志都是正确的。  <code>make_grid</code>  ，正如在介绍中所讨论的，生成一个 $8\\times 8$ 的网格（或者一个 $8\\times 8\\times 8$ 的三维网格）以确保每个粗略的网格单元完全在一个子域内。生成这个网格后，我们在其边界上循环，并在顶部边界设置边界指标为1，这是我们设置非零迪里希特边界条件的唯一地方。在这之后，我们再次在所有单元上循环，设置材料指标&mdash;用来表示我们处于域的哪一部分，是流体指标还是固体指标。\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// 这对函数的第二部分决定在每个单元上使用哪个有限元。上面我们设置了每个粗略网格单元的材料指标，正如在介绍中提到的，这个信息在网格细化时将从母单元继承到子单元。\n\n// 换句话说，只要我们细化（或创建）了网格，我们就可以依靠材料指示器来正确描述一个单元所处的域的哪一部分。然后我们利用这一点将单元的活动FE索引设置为该类的 hp::FECollection 成员变量中的相应元素：流体单元为0，固体单元为1。\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// 下一步是为线性系统设置数据结构。为此，我们首先要用上面的函数设置活动FE指数，然后分配自由度，再确定线性系统的约束。后者包括像往常一样的悬挂节点约束，但也包括顶部流体边界的不均匀边界值，以及沿固体子域周边的零边界值。\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// 不过，我们还需要处理更多的约束条件：我们必须确保在流体和固体的界面上速度为零。下面这段代码已经在介绍中介绍过了。\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// 在这一切结束后，我们可以向约束对象声明，我们现在已经准备好了所有的约束，并且该对象可以重建其内部数据结构以提高效率。\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// 在这个函数的其余部分，我们创建了一个在介绍中广泛讨论的稀疏模式，并使用它来初始化矩阵；然后还将向量设置为正确的大小。\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// 下面是这个程序的中心函数：组装线性系统的函数。它在开始时有一长段设置辅助函数的内容：从创建正交公式到设置FEValues、FEFaceValues和FESubfaceValues对象，这些都是整合单元项以及界面项所必需的，以应对界面上的单元以相同大小或不同细化程度聚集在一起的情况...\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// ...描述局部对全局线性系统贡献所需的对象...\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// ...到变量，允许我们提取形状函数的某些成分并缓存它们的值，而不是在每个正交点重新计算它们。\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// 然后是所有单元格的主循环，和 step-27 一样，初始化当前单元格的 hp::FEValues 对象，提取适合当前单元格的FEValues对象。\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// 做完这些后，我们继续为属于斯托克斯和弹性区域的单元组装单元项。虽然我们原则上可以在一个公式中完成，实际上就是实现了介绍中所说的双线性形式，但我们意识到，我们的有限元空间的选择方式是，在每个单元上，有一组变量（速度和压力，或者位移）总是为零，因此，计算局部积分的更有效的方法是，根据测试我们处于域的哪一部分的 <code>if</code> 条款，只做必要的事情。\n\n// 局部矩阵的实际计算与 step-22 以及 @ref vector_valued 文件模块中给出的弹性方程的计算相同。\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// 一旦我们得到了单元积分的贡献，我们就把它们复制到全局矩阵中（通过 AffineConstraints::distribute_local_to_global 函数，立即处理约束）。请注意，我们没有向 <code>local_rhs</code> 变量中写入任何东西，尽管我们仍然需要传递它，因为消除非零边界值需要修改局部，因此也需要修改全局的右手值。\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// 这个函数更有趣的部分是我们看到关于两个子域之间的界面上的脸部条款。为此，我们首先要确保我们只组装一次，即使在所有单元的所有面的循环中会遇到界面的每一部分两次。我们武断地决定，只有当当前单元是固体子域的一部分，并且因此一个面不在边界上，并且它后面的潜在邻居是流体域的一部分时，我们才会评估界面条款。让我们从这些条件开始。\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// 在这一点上，我们知道当前的单元格是一个候选的整合对象，并且面 <code>f</code> 后面存在一个邻居。现在有三种可能性。           \n\n// - 邻居处于同一细化水平，并且没有孩子。     \n\n// - 邻居有子女。     \n\n// - 邻居比较粗糙。            在所有这三种情况下，我们只对它感兴趣，如果它是流体子域的一部分。因此，让我们从第一种最简单的情况开始：如果邻居处于同一层次，没有子女，并且是一个流体单元，那么这两个单元共享一个边界，这个边界是界面的一部分，我们想沿着这个边界整合界面项。我们所要做的就是用当前面和邻接单元的面初始化两个FEFaceValues对象（注意我们是如何找出邻接单元的哪个面与当前单元接壤的），然后把东西传给评估界面项的函数（这个函数的第三个到第五个参数为它提供了抓取数组）。然后，结果再次被复制到全局矩阵中，使用一个知道本地矩阵的行和列的DoF指数来自不同单元的函数。\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// 第二种情况是，如果邻居还有更多的孩子。在这种情况下，我们必须在邻居的所有子女中进行循环，看他们是否属于流体子域的一部分。如果它们是，那么我们就在共同界面上进行整合，这个界面是邻居的一个面和当前单元的一个子面，要求我们对邻居使用FEFaceValues，对当前单元使用FESubfaceValues。\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// 最后一个选项是，邻居比较粗大。在这种情况下，我们必须为邻居使用一个FESubfaceValues对象，为当前单元使用一个FEFaceValues；其余部分与之前相同。\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// 在组装全局系统的函数中，我们将计算接口条款传递给我们在此讨论的一个单独的函数。关键是，尽管我们无法预测FEFaceValues和FESubfaceValues对象的组合，但它们都是从FEFaceValuesBase类派生出来的，因此我们不必在意：该函数被简单地调用，有两个这样的对象表示面的两边的正交点上的形状函数值。然后我们做我们一直在做的事情：我们用形状函数的值和它们的导数来填充从头数组，然后循环计算矩阵的所有条目来计算局部积分。我们在这里评估的双线性形式的细节在介绍中给出。\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// 正如介绍中所讨论的，我们在这里使用了一个相当琐碎的求解器：我们只是将线性系统传递给SparseDirectUMFPACK直接求解器（例如，见 step-29  ）。在求解之后，我们唯一要做的是确保悬挂的节点和边界值约束是正确的。\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// 生成图形输出在这里相当简单：我们所要做的就是确定解向量的哪些成分属于标量和/或向量（例如，见 step-22 之前的例子），然后把它全部传递给DataOut类。\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// 下一步是细化网格。正如在介绍中所讨论的，这有点棘手，主要是因为流体和固体子域使用的变量具有不同的物理尺寸，因此，误差估计的绝对大小不能直接比较。因此，我们将不得不对它们进行缩放。因此，在函数的顶部，我们首先分别计算不同变量的误差估计值（在流体域中使用速度而不是压力，在固体域中使用位移）。\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// 然后，我们通过除以误差估计值的法线对其进行归一化处理，并按照介绍中所讨论的那样，将流体误差指标按4的系数进行缩放。然后将这些结果加在一起，形成一个包含所有单元的误差指标的向量。\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// 在实际细化网格之前，函数的倒数第二部分涉及到我们在介绍中已经提到的启发式方法：由于解是不连续的，KellyErrorEstimator类对位于子域之间边界的单元感到困惑：它认为那里的误差很大，因为梯度的跳跃很大，尽管这完全是预期的，事实上在精确解中也存在这一特征，因此不表明任何数值错误。\n\n// 因此，我们将界面上的所有单元的误差指标设置为零；决定影响哪些单元的条件略显尴尬，因为我们必须考虑到自适应细化网格的可能性，这意味着邻近的单元可能比当前的单元更粗，或者事实上可能被细化一些。这些嵌套条件的结构与我们在 <code>assemble_system</code> 中组装接口条款时遇到的情况基本相同。\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// 像往常一样，这是控制整个操作流程的函数。如果你读过教程程序  step-1  到  step-6  ，例如，那么你已经对以下结构相当熟悉。\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// 这个，最后的，函数所包含的内容几乎与其他大多数教程程序的内容完全一样。\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": "#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": "﻿/*! \\file solveeom.cpp\n    \\brief 単振り子に対して運動方程式を解くクラスの実装\n\n    Copyright ©  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 コンストラクタ\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 コンストラクタ\n\n    // #region publicメンバ関数\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メンバ関数\n\n    // #region privateメンバ関数\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 θ2 - θ1\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 ω1\n            auto den = M * l_ - m_ * l_ * std::cos(delta) * std::cos(delta);\n\n            // dθ/dt = ω, by definition\n            dxdt[Num_eqns::THETA_1] = x[Num_eqns::OMEGA_1];\n\n            // Compute ω1\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θ/dt = ω for θ2 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 ω2\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メンバ関数\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": "﻿/*! \\file foelement.cpp\n    \\brief Bogoliubov-de Gennes方程式を解くクラスの実装\n    Copyright ©  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 コンストラクタ\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 コンストラクタ\n\n    // #region publicメンバ関数\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メンバ関数\n\n    // #region privateメンバ関数\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メンバ関数\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": "// 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 <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": "#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": "/// 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 <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": "#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": "#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": "//==================================================================================================\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": "#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": "#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": "// 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": "//==================================================================================================\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        // 数据格式：图像文件名 tx, ty, tz, qx, qy, qz, qw ，注意是 TWC 而非 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": "#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 *  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": "/*\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": "///////////////////////////////////////////////////////////////////////////////\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": "#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": "// 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": "#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": "#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": "#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 <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": "///////////////////////////////////////////////////////////////////////////////\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/** 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": "\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": "// 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": "#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": "//==============================================================================\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": "#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": "//==================================================================================================\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": "#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 <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": "#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 \"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": "\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// 标准deal.II需要的典型文件。\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// 包括所有相关的多层次文件。\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// 我们将使用 MeshWorker::mesh_loop 功能来组装矩阵。\n\n#include <deal.II/meshworker/mesh_loop.h> \n// @sect3{MeshWorker data}  \n\n// 像往常一样，我们将把所有与这个程序有关的东西放到一个自己的命名空间中。\n\n// 由于我们将使用MeshWorker框架，第一步是定义以下由 MeshWorker::mesh_loop(): 使用的assemble_cell()函数所需要的结构 `ScratchData`包含一个FEValues对象，这是组装一个单元的局部贡献所需要的，而`CopyData`包含一个单元的局部贡献的输出和复制到全局系统的必要信息。它们的目的在WorkStream类的文档中也有解释）。\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// 第二步是定义处理要从输入文件中读取的运行时参数的类。\n\n// 我们将使用ParameterHandler在运行时传入参数。结构`Settings`解析并存储整个程序要查询的参数。\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/* 首先声明参数...   */ \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    /* ...然后尝试从输入文件中读取它们的值。  */ \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// 遍历单元和自由度的顺序将对乘法的收敛速度起作用。在这里，我们定义了一些函数，这些函数返回单元格的特定顺序，供块平滑器使用。\n\n// 对于每种类型的单元格排序，我们定义了一个用于活动网格的函数和一个用于水平网格的函数（即用于多网格层次结构中的某一层的单元格）。虽然求解系统所需的唯一重新排序是在水平网格上进行的，但为了可视化的目的，我们在output_results()中包含了主动网格的重新排序。\n\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                                  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// 产生随机排序的函数在精神上是相似的，它们首先将所有单元的信息放入一个数组。但是，它们不是对它们进行排序，而是利用C++提供的生成随机数的设施对元素进行随机洗牌。这样做的方式是在数组的所有元素上进行迭代，为之前的另一个元素抽取一个随机数，然后交换这些元素。其结果是对数组中的元素进行随机洗牌。\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// 本教程中所解决的问题是对<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>第118页上的例3.1.3的修改。主要的区别是我们在域的中心增加了一个洞，其边界条件为零的Dirichlet。\n\n// 为了获得完整的描述，我们需要首先实现零右手边的类（当然，我们可以直接使用 Functions::ZeroFunction):  。\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// 我们也有迪里希特的边界条件。在外部正方形边界的连接部分，我们将数值设置为1，其他地方（包括内部圆形边界）的数值设置为0。\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// 如果  $x=1$  ，或如果  $x>0.5$  和  $y=-1$  ，则将边界设为 1。\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// 流水线扩散方法有一个稳定常数，我们需要能够计算出来。这个参数的计算方式的选择取自于<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>。\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// 这是程序的主类，看起来应该与  step-16  非常相似。主要的区别是，由于我们是在运行时定义我们的多网格平滑器，我们选择定义一个函数`create_smoother()`和一个类对象`mg_smoother`，这是一个  `std::unique_ptr`  派生于MGSmoother的平滑器。请注意，对于从RelaxationBlock派生的平滑器，我们必须为每个级别包括一个`smoother_data`对象。这将包含关于单元格排序和单元格矩阵倒置方法的信息。\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// 在这里，我们首先为活动和多网格级别的网格设置DoFHandler、AffineConstraints和SparsityPattern对象。\n\n// 我们可以用DoFRenumbering类对活动DoF进行重新编号，但是平滑器只作用于多网格层，因此，这对计算并不重要。相反，我们将对每个多网格层的DoFs进行重新编号。\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// 在列举了全局自由度以及（上面最后一行）水平自由度之后，让我们对水平自由度进行重新编号，以获得一个更好的平滑器，正如介绍中所解释的。 如果需要的话，下面的第一个区块会对下游或上游方向的每个层次的自由度进行重新编号。这只对点平滑器（SOR和Jacobi）有必要，因为块平滑器是在单元上操作的（见`create_smoother()`）。然后，下面的块也实现了随机编号。\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// 该函数的其余部分只是设置了数据结构。下面代码的最后几行与其他GMG教程不同，因为它同时设置了接口输入和输出矩阵。我们需要这样做，因为我们的问题是非对称性的。\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// 这里我们定义了每个单元上的线性系统的装配，以便被下面的Mesh_loop()函数使用。这个函数为活动单元或水平单元（不管它的第一个参数是什么）装配单元矩阵，并且只有在调用活动单元时才装配右手边。\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// 如果我们使用流线扩散，我们必须把它的贡献加到单元格矩阵和单元格的右手边。如果我们不使用流线扩散，设置 $\\delta=0$ 就可以否定这个贡献，我们就可以使用标准的Galerkin有限元组合。\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// 本地矩阵的组装有两个部分。首先是Galerkin贡献。\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//然后是流线扩散贡献。\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// 同样的情况也适用于右手边。首先是Galerkin贡献。\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// 然后是流线扩散贡献。\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// 这里我们采用 MeshWorker::mesh_loop() 来翻阅单元格，为我们组装system_matrix、system_rhs和所有mg_matrices。\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// 与活动层的约束不同，我们选择在这个函数的本地为每个多网格层创建约束对象，因为它们在程序的其他地方从来不需要。\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// 如果 $(i,j)$ 是一个`interface_out` dof对，那么 $(j,i)$ 就是一个`interface_in` dof对。注意：对于 \"interface_in\"，我们加载接口条目的转置，即，dof对 $(j,i)$ 的条目被存储在 \"interface_in(i,j)\"。这是对对称情况的优化，允许在solve()中设置边缘矩阵时只使用一个矩阵。然而，在这里，由于我们的问题是非对称的，我们必须同时存储`interface_in`和`interface_out`矩阵。\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// 接下来，我们根据`.prm`文件中的设置来设置平滑器。两个重要的选项是多网格v周期每一级的平滑前和平滑后步骤的数量以及松弛参数。\n\n// 由于乘法往往比加法更强大，所以需要较少的平滑步骤来实现收敛，与网格大小无关。块平滑器比点平滑器也是如此。这反映在下面对每种平滑器的平滑步数的选择上。\n\n// 点平滑器的松弛参数是在试验和错误的基础上选择的，它反映了在我们细化网格时保持GMRES求解的迭代次数不变（或尽可能接近）的必要值。在`.prm`文件中给 \"Jacobi \"和 \"SOR \"的两个值是针对1度和3度有限元的。如果用户想改成其他度数，他们可能需要调整这些数字。对于块平滑器，这个参数有一个更直接的解释，即对于二维的加法，一个DoF可以有多达4个单元的重复贡献，因此我们必须将这些方法放松0.25来补偿。对于乘法来说，这不是一个问题，因为每个单元的逆向应用都会给其所有的DoF带来新的信息。\n\n// 最后，如上所述，点平滑器只对DoF进行操作，而块平滑器对单元进行操作，因此只有块平滑器需要被赋予有关单元排序的信息。点平滑器的DoF排序已经在`setup_system()`中得到了处理。\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// 在解决这个系统之前，我们必须首先设置多网格预处理程序。这需要设置各级之间的转换、粗略矩阵求解器和平滑器。这个设置几乎与 Step-16 相同，主要区别在于上面定义的各种平滑器，以及由于我们的问题是非对称的，我们需要不同的界面边缘矩阵。实际上，在本教程中，这些接口矩阵是空的，因为我们只使用全局细化，因此没有细化边。然而，我们在这里仍然包括了这两个矩阵，因为如果我们简单地切换到自适应细化方法，程序仍然可以正常运行）。)\n\n// 最后要注意的是，由于我们的问题是非对称的，我们必须使用适当的Krylov子空间方法。我们在这里选择使用GMRES，因为它能保证在每次迭代中减少残差。GMRES的主要缺点是，每次迭代，存储的临时向量的数量都会增加一个，而且还需要计算与之前存储的所有向量的标量积。这是很昂贵的。通过使用重启的GMRES方法可以放松这一要求，该方法对我们在任何时候需要存储的向量数量设置了上限（这里我们在50个临时向量后重启，即48次迭代）。这样做的缺点是我们失去了在整个迭代过程中收集的信息，因此我们可以看到收敛速度较慢。因此，在哪里重启是一个平衡内存消耗、CPU工作量和收敛速度的问题。然而，本教程的目标是通过使用强大的GMG预处理程序来实现非常低的迭代次数，所以我们选择了重启长度，使下面显示的所有结果在重启发生之前就能收敛，因此我们有一个标准的GMRES方法。如果用户有兴趣，deal.II中提供的另一种合适的方法是BiCGStab。\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// 最后一个感兴趣的函数会生成图形输出。这里我们以.vtu格式输出解决方案和单元格排序。\n\n// 在函数的顶部，我们为每个单元生成一个索引，以显示平滑器所使用的排序。请注意，我们只对活动单元而不是平滑器实际使用的层级做这个处理。对于点平滑器，我们对DoFs而不是单元进行重新编号，所以这只是对现实中发生的情况的一种近似。最后，这个随机排序不是我们实际使用的随机排序（见`create_smoother()`）。\n\n// 然后，单元格的（整数）排序被复制到一个（浮点）矢量中，用于图形输出。\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// 考虑到以前的教程程序，该函数的其余部分就很简单了。\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// 和大多数教程一样，这个函数创建/细化网格并调用上面定义的各种函数来设置、装配、求解和输出结果。\n\n// 在第0个循环中，我们在正方形 <code>[-1,1]^dim</code> 上生成网格，半径为3/10个单位的孔以原点为中心。对于`manifold_id`等于1的对象（即与洞相邻的面），我们指定了一个球形流形。\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// 最后，主函数和大多数教程一样。唯一有趣的一点是，我们要求用户传递一个`.prm`文件作为唯一的命令行参数。如果没有给出参数文件，程序将在屏幕上输出一个带有所有默认值的样本参数文件的内容，然后用户可以复制并粘贴到自己的`.prm`文件中。\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 * 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": "// 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 <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": "/* -*- 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 <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// 我们在这个程序中需要的大部分包含文件已经在以前的程序中讨论过了，特别是在  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// 下面的标头提供了我们用来表示材料属性的张量类。\n\n#include <deal.II/base/tensor.h> \n\n// 下面的标头对于deal.II的HDF5接口是必要的。\n\n#include <deal.II/base/hdf5.h> \n\n// 这个头是我们用来评估模拟结果的函数 VectorTools::point_value 所需要的。\n\n#include <deal.II/numerics/vector_tools.h> \n\n// 我们在函数 GridTools::find_active_cell_around_point 中使用的函数 `ElasticWave::store_frequency_step_data()` 需要这些头文件。\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}  下列类用于存储模拟的参数。\n\n//  @sect4{The `RightHandSide` class}  该类用于定义结构左侧的力脉冲。\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// 变量`data`是 HDF5::Group ，所有的模拟结果都将被储存在其中。请注意， `RightHandSide::data`, 变量 \n// `PML::data`,  \n// `Rho::data` 和 `Parameters::data` 指向HDF5文件的同一个组。当 HDF5::Group 被复制时，它将指向HDF5文件的同一组。\n\n    HDF5::Group data; \n\n// 仿真参数作为HDF5属性存储在`data`中。以下属性在jupyter笔记本中定义，作为HDF5属性存储在`data`中，然后由构造函数读取。\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// 在这个特定的模拟中，力只有一个 $x$ 分量， $F_y=0$  。\n\n    const unsigned int force_component = 0; \n  }; \n// @sect4{The `PML` class}  这个类是用来定义完美匹配层（PML）的形状，以吸收向边界传播的波。\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 ，所有的模拟结果将被存储在其中。\n\n    HDF5::Group data; \n\n// 和以前一样，以下属性在jupyter笔记本中定义，作为HDF5属性存储在`data`中，然后由构造函数读取。\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}  这个类是用来定义质量密度的。\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 ，所有的模拟结果将被存储在其中。\n\n    HDF5::Group data; \n\n// 和以前一样，以下属性在jupyter笔记本中定义，作为HDF5属性存储在`data`中，然后由构造函数读取。\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}  该类包含所有将在模拟中使用的参数。\n\n  template <int dim> \n  class Parameters \n  { \n  public: \n    Parameters(HDF5::Group &data); \n// HDF5::Group ，所有的模拟结果将被存储在其中。\n\n    HDF5::Group data; \n\n// 和以前一样，以下属性在jupyter笔记本中定义，作为HDF5属性存储在`data`中，然后由构造函数读取。\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}  质量和刚度矩阵的计算是非常昂贵的。这些矩阵对所有的频率步骤都是一样的。右手边的向量对所有的频率步长也是一样的。我们用这个类来存储这些对象，并在每个频率步骤中重新使用它们。请注意，这里我们不存储集合的质量和刚度矩阵以及右手边，而是存储单个单元的数据。QuadratureCache \"类与在  step-18  中使用过的 \"PointHistory \"类非常相似。\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// 我们在变量mass_coefficient和stiffness_coefficient中存储质量和刚度矩阵。我们还存储了右手边和JxW值，这些值对所有的频率步骤都是一样的。\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// 该函数返回材料的刚度张量。为了简单起见，我们认为刚度是各向同性和同质的；只有密度  $\\rho$  取决于位置。正如我们之前在  step-8  中所表明的，如果刚度是各向同性和均质的，那么刚度系数  $c_{ijkl}$  可以表示为两个系数  $\\lambda$  和  $\\mu$  的函数。系数张量简化为 \n// @f[\n//    c_{ijkl}\n//    =\n//    \\lambda \\delta_{ij} \\delta_{kl} +\n//    \\mu (\\delta_{ik} \\delta_{jl} + \\delta_{il} \\delta_{jk}).\n//  @f] 。\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// 接下来让我们声明这个程序的主类。它的结构与 step-40 的教程程序非常相似。主要的区别是。\n\n// - 扫过的频率值。\n\n// - 我们将刚度和质量矩阵保存在`quadrature_cache`中，并在每个频率步骤中使用它们。\n\n// - 我们在HDF5文件中存储每个频率步骤的探头测量的能量。\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// 在每个频率步骤之前都会调用这个，以便为缓存变量设置一个原始状态。\n\n    void setup_quadrature_cache(); \n\n// 这个函数在频率向量上循环，并在每个频率步骤上运行模拟。\n\n    void frequency_sweep(); \n\n// 参数存储在这个变量中。\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// 我们将每个单元的质量和刚度矩阵存储在这个向量中。\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// 这个向量包含我们要模拟的频率范围。\n\n    std::vector<double> frequency; \n\n// 这个向量包含了测量探头各点的坐标 $(x,y)$ 。\n\n    FullMatrix<double> probe_positions; \n\n// HDF5数据集来存储频率和`探头位置`向量。\n\n    HDF5::DataSet frequency_dataset; \n    HDF5::DataSet probe_positions_dataset; \n\n// HDF5数据集，存储探头测量的能量值。\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// 构造函数使用 HDF5::Group  `data`函数从 HDF5::Group::get_attribute()  读取所有参数。\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//这个函数定义了力矢量脉冲的空间形状，它采取高斯函数\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//  的形式，其中 $a$ 是取力的最大振幅， $\\sigma_x$ 和 $\\sigma_y$ 是 $x$ 和 $y$ 分量的标准偏差。请注意，脉冲已被裁剪为 $x_\\textrm{min}<x<x_\\textrm{max}$ 和 $y_\\textrm{min} <y<y_\\textrm{max}$  。\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// 和以前一样，构造函数使用 HDF5::Group 函数从 HDF5::Group::get_attribute() `data`中读取所有参数。正如我们所讨论的，在jupyter笔记本中已经定义了PML的二次开机。通过改变参数`pml_coeff_degree`，可以使用线性、立方或其他幂度。参数`pml_x`和`pml_y`可以用来开启和关闭`x`和`y`PML。\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`部分的PML系数的形式为  $s'_x = a_x x^{\\textrm{degree}}$  。\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// 这个类是用来定义质量密度的。正如我们之前所解释的，一个声学超晶格空腔是由两个[分布式反射器](https:en.wikipedia.org/wiki/Band_gap)、镜子和一个 $\\lambda/2$ 空腔组成的，其中 $\\lambda$ 是声波长。声学DBRs是一种周期性结构，其中一组具有对比性物理特性（声速指数）的双层堆栈被重复 $N$ 次。波速的变化是由具有不同密度的层交替产生的。\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// 为了提高精度，我们使用[subpixel smoothing]（https:meep.readthedocs.io/en/latest/Subpixel_Smoothing/）。\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// 声速由\n// @f[\n//   c = \\frac{K_e}{\\rho}\n//  @f]\n//  定义，其中 $K_e$ 是有效弹性常数， $\\rho$ 是密度。这里我们考虑的是波导宽度远小于波长的情况。在这种情况下，可以证明对于二维的情况\n//  @f[\n//   K_e = 4\\mu\\frac{\\lambda +\\mu}{\\lambda+2\\mu}\n//  @f]\n//  和三维的情况 $K_e$ 等于杨氏模量。\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//密度 $\\rho$ 采取以下形式 <img alt=\"声学超晶格空腔\" src=\"https:www.dealii.org/images/steps/developer/  step-62  .04.svg\" height=\"200\" //其中棕色代表材料_a，绿色代表材料_b。\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// 这里我们定义了[subpixel smoothing](https:meep.readthedocs.io/en/latest/Subpixel_Smoothing/)，它可以提高模拟的精度。\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// 然后是腔体\n\n    if (std::abs(p[0]) <= material_a_wavelength / 2) \n      { \n        return material_a_rho; \n      } \n\n// 材料层_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层\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// 最后，默认的是 material_a。\n\n    return material_a_rho; \n  } \n\n//  @sect4{The `Parameters` class implementation}  \n\n// 构造函数使用 HDF5::Group 函数从 HDF5::Group::get_attribute() `data`中读取所有参数。\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// 我们需要为质量和刚度矩阵以及右手边的矢量保留足够的空间。\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// 这与  step-40  的构造函数非常相似。此外，我们还创建了HDF5数据集`frequency_dataset`，`position_dataset`和`displacement`。注意在创建HDF5数据集时使用了 \"模板 \"关键字。这是C++的要求，使用`template`关键字是为了将`create_dataset`作为一个依赖的模板名称。\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// 这个函数没有什么新内容，与 step-40 的唯一区别是，我们不需要应用边界条件，因为我们使用PML来截断域。\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// 这个函数也与 step-40 非常相似，尽管有明显的区别。我们为每个频率/欧米茄步骤组装系统。在第一步中，我们设置`calculate_quadrature_data = True`，然后我们计算质量和刚度矩阵以及右手边的矢量。在随后的步骤中，我们将使用这些数据来加速计算。\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// 这里我们存储右手边的值，rho和PML的值。\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// 我们计算已经在jupyter笔记本中定义的 $\\lambda$ 和 $\\mu$ 的刚度张量。请注意，与 $\\rho$ 相反，刚度在整个领域中是恒定的。\n\n    const SymmetricTensor<4, dim> stiffness_tensor = \n      get_stiffness_tensor<dim>(parameters.lambda, parameters.mu); \n\n// 我们使用与 step-20 相同的方法处理矢量值问题。\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// 只有当我们要计算质量和刚度矩阵时，我们才必须计算右手边的rho和PML的值。否则我们可以跳过这个计算，这样可以大大减少总的计算时间。\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// 我们已经在  step-18  中做了这个工作。获得一个指向当前单元本地正交缓存数据的指针，作为防御措施，确保这个指针在全局数组的范围内。\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变量用于存储质量和刚度矩阵、右手边向量和`JxW`的值。\n\n              QuadratureCache<dim> &quadrature_data = \n                local_quadrature_points_data[q]; \n\n// 下面我们声明力向量和PML的参数  $s$  和  $\\xi$  。\n\n              Tensor<1, dim>                       force; \n              Tensor<1, dim, std::complex<double>> s; \n              std::complex<double>                 xi(1, 0); \n\n// 下面的块只在第一个频率步骤中计算。\n\n              if (calculate_quadrature_data) \n                { \n\n// 存储`JxW`的值。\n\n                  quadrature_data.JxW = fe_values.JxW(q); \n\n                  for (unsigned int component = 0; component < dim; ++component) \n                    { \n\n// 将向量转换为张量，并计算出xi\n\n                      force[component] = rhs_values[q][component]; \n                      s[component]     = pml_values[q][component]; \n                      xi *= s[component]; \n                    } \n\n// 这里我们计算 $\\alpha_{mnkl}$ 和 $\\beta_{mnkl}$ 张量。\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// 计算质量矩阵的值。\n\n                          quadrature_data.mass_coefficient[i][j] = \n                            rho_values[q] * xi * phi_i * phi_j; \n\n//在刚度张量的 $mnkl$ 指数上循环。\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// 这里我们计算刚度矩阵。                          \n//注意，由于PML的存在，刚度矩阵不是对称的。我们使用梯度函数（见[文档](https:www.dealii.org/current/doxygen/deal.II/group__vector__valued.html)），它是一个  <code>Tensor@<2,dim@></code>  。                          \n// 矩阵 $G_{ij}$ 由条目\n                          // @f[\n                          //  G_{ij}=\n                          //  \\frac{\\partial\\phi_i}{\\partial x_j}\n                          //  =\\partial_j \\phi_i\n                          // @f]\n                          // 组成 注意指数 $i$ 和 $j$ 的位置以及我们在本教程中使用的符号。  $\\partial_j\\phi_i$  . 由于刚度张量不是对称的，所以很容易出错。\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// 我们将刚度矩阵的值保存在quadrature_data中。\n\n                          quadrature_data.stiffness_coefficient[i][j] = \n                            stiffness_coefficient; \n                        } \n\n// 和正交数据中的右手边的值。\n\n \n                        phi_i * force * fe_values.JxW(q); \n                    } \n                } \n\n// 我们再次循环单元的自由度来计算系统矩阵。这些循环非常快，因为我们已经计算了刚度和质量矩阵，只有 $\\omega$ 的值发生了变化。\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// 这比  step-40  更加简单。我们使用并行的直接求解器MUMPS，它比迭代求解器需要更少的选项。缺点是它不能很好地扩展。用迭代求解器来解决Helmholtz方程并不简单。移位拉普拉斯多网格法是一种众所周知的预处理该系统的方法，但这超出了本教程的范围。\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// 我们用这个函数来计算位置向量的值。\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// 由于运算符+和\n\n// -被重载来减去两个点，所以必须做如下操作。`Point_b<dim> + (-Point_a<dim>)`。\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// 该函数在HDF5文件中存储探头测量的能量。\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// 我们存储 $x$ 方向的位移； $y$ 方向的位移可以忽略不计。\n\n    const unsigned int probe_displacement_component = 0; \n\n// 向量坐标包含HDF5文件中位于本地所有单元中的探测点的坐标。向量displacement_data包含这些点的位移值。\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// 然后，我们可以在`displacement_data`中存储探头各点的位移值。\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// 我们在HDF5文件中写入位移数据。调用 HDF5::DataSet::write_selection() 是MPI集体的，这意味着所有进程都要参与。\n\n    if (coordinates.size() > 0) \n      { \n        displacement.write_selection(displacement_data, coordinates); \n      } \n\n// 因此，即使进程没有数据可写，它也必须参与集体调用。为此我们可以使用  HDF5::DataSet::write_none().  注意，我们必须指定数据类型，在这种情况下  `std::complex<double>`.  。\n    else \n      { \n        displacement.write_none<std::complex<double>>(); \n      } \n\n// 如果输入文件中的变量`save_vtu_files`等于`True`，那么所有数据将被保存为vtu。写入`vtu'文件的过程已经在  step-40  中描述。\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// 在我们不感兴趣的单元格上，将各自的值设置为一个假值，以确保如果我们的假设有什么错误，我们会通过查看图形输出发现。\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// 该函数写入尚未写入的数据集。\n\n  template <int dim> \n  void ElasticWave<dim>::output_results() \n  { \n\n// 向量`频率`和`位置`对所有进程都是一样的。因此任何一个进程都可以写入相应的`数据集'。因为调用 HDF5::DataSet::write 是MPI集体的，其余进程将不得不调用 HDF5::DataSet::write_none.  。\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// 我们在计算开始时使用这个函数来设置缓存变量的初始值。这个函数在  step-18  中已经描述过。与  step-18  的函数没有区别。\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// 为了清楚起见，我们将 step-40 的函数`run`分为函数`run`和`frequency_sweep`。在函数`frequency_sweep`中，我们把迭代放在频率向量上。\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// 只写一次模拟参数\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// 我们计算出这个特定步骤的频率和欧米茄值。\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// 在第一个频率步骤中，我们计算出质量和刚度矩阵以及右手边的数据。在随后的频率步骤中，我们将使用这些值。这大大改善了计算时间。\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// 这个函数与  step-40  中的函数非常相似。\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// 主函数与  step-40  中的函数非常相似。\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// 每个模拟（位移和校准）都存储在一个单独的HDF5组中。\n\n      const std::vector<std::string> group_names = {\"displacement\", \n                                                    \"calibration\"}; \n      for (auto group_name : group_names) \n        { \n\n// 对于这两个组名中的每一个，我们现在创建组并将属性放入这些组。具体来说，这些是。\n\n// - 波导的尺寸（在 $x$ 和 $y$ 方向）。\n\n// - 探头的位置（在 $x$ 和 $y$ 方向）。\n\n// - 探针中的点的数量\n\n// - 全局细化水平\n\n// - 腔体谐振频率\n\n// - 镜像对的数量 \n\n// - 镜子的数量 \n\n// - 材料特性\n\n// - 力的参数\n\n// - PML参数\n\n// - 频率参数\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// 位移模拟。参数从位移HDF5组中读取，结果保存在同一HDF5组中。\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// 校准模拟。参数从校准HDF5组中读取，结果保存在同一HDF5组中。\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": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n/* 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 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// β-detected nuclear magnetic resonance (β-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": "#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": "#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": "#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 \"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": "#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": "// 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": "// 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": "// 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": "/*\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//  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 <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": "/* +------------------------------------------------------------------------+\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": "/*\n * Copyright (c) 2015 Claus Christmann <hcc |ä| 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 << \"° => \"<< 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// 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": "/*\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": "// 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 − p) × r / (r × 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ían que contener los índices a usar, no replicar los datos.\n        // 2: Las particiones tendrían 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ón de núeros 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ón 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ás informativos habría que proporcionar tambíen lo siguiente:\n        // (para cada partición)\n        // - Epocas que demoró en converger\n        // - Error\n        // Esto sirve para detectar (por ejemplo):\n        // - Si siempre está terminando el entrenamiento por límite de épocas\n        // - Si los errores están 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ón 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ón cruzada clásica\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 época\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": "/*\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 (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 <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": "#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": "/* 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": "/**********************************************************************\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": "//  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) 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": "/**\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// 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": "// 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": "/*\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": "#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": "#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": "//==================================================================================================\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": "#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": "#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": "// 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": "#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": "/*\nCopyright 2013 Henrik Mühe 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 <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": "//---------------------------------------------------------------------------//\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": "/**\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 <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\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": "#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 * @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": "/** @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": "// 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": "#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 <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²}\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": "#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": "//==============================================================================\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": "\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": "///////////////////////////////////////////////////////////////////////////////\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": "// 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": "/* 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": "// 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": "#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": "/*\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/*!\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": "#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": "#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": "#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\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 * \\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": "/* 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 * 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": "/*\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 <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": "\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": "#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 << \"°)\" << std::endl;\n    std::cout << \"car heading: \" << carPosition.h << \"(\" << rad2degree * carPosition.h << \"°)\" << std::endl;\n    std::cout << \"diff heading: \" << diff_heading_abs << \"(\" << rad2degree * diff_heading_abs << \"°)\" << std::endl;\n    std::cout << \"e: \" << e << std::endl;\n    std::cout << \"Theta_C: \" << theta_c << \"(\" << rad2degree * theta_c << \"°)\" << 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": "/**\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": "//\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": "//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": "/***************************************************************************\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": "#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": "#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": "//  (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": "//=======================================================================\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": "#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 \"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": "#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": "#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": "// 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": "#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": "#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 \"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": "//   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 * 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": "#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 ⊕ xe, u = ul ⊕ 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 <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": "/*!\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": "//  (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": "// 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": "#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": "#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": "/*\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": "#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": "// 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": "/*\n * PoseOptimizationGeometric.cpp\n *\n *  Created on: Aug 30, 2017\n *      Author: Péter 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// 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": "#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": "// 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": "// 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": "/**\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   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": "////////////////////////////////////////////////////////////////////////////////\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": "// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @file           coordinate.cpp\n*   @brief          飞行器用到的各种坐标系变换。\n*   @details        现有：地球坐标系，导航坐标系，机体坐标系。\n                    地球坐标系采用WGS-84坐标系各项参数。\n\t\t\t\t\t地球空间直角坐标系原点为参考椭球的中心，X轴和Y轴位于赤道平面，X轴通过零子午线，Z轴与椭球极轴一致。\n\t\t\t\t\t导航坐标系原点位于参考点，X轴指向北边，Y轴指向东边，Z轴指向地下。\n\t\t\t\t\t机体坐标系原点位于质心点，X轴指向机头前方，Y轴指向右侧，Z轴指向下方。\n\t\t\t\t\t所有坐标系均为右手系。\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, 首次创建\n*\n\n*/\n\n// --------------------------------------------------------------------------------------------------------------------------------\n/**\n*   @name           头文件。\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          计算重力加速度。\n*   @details        计算重力加速度。\n*   @param[out]     gravity         精确重力\n*   @param[in]      latitude        纬度(角度)\n*   @retval         0               正常\n*   @retval         1               错误\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          计算地球主曲率半径。\n*   @details        参考椭球子午圈上各点曲率半径RM和卯酉圈（它所在的平面与子午面垂直）上各点的曲率半径RN称为主曲率半径。\n*   @param[out]     RM              子午圈曲率半径\n*   @param[out]     RN              卯酉圈曲率半径\n*   @param[in]      latitude        纬度(角度)\n*   @retval         0               正常\n*   @retval         1               错误\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          地球空间直角坐标系转换到经纬度高度坐标系。\n*   @details        地球空间直角坐标系原点为参考椭球的中心，X轴和Y轴位于赤道平面，X轴通过零子午线，Z轴与椭球极轴一致。\n*   @param[out]     longitude       经度（角度）\n*   @param[out]     latitude        纬度（角度）\n*   @param[out]     height          高度\n*   @param[in]      x               地球空间直角坐标系X坐标\n*   @param[in]      y               地球空间直角坐标系Y坐标\n*   @param[in]      z               地球空间直角坐标系Z坐标\n*   @retval         0               正常\n*   @retval         1               错误\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//迭代法求纬度和高度\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          经纬度高度坐标系转换到地球空间直角坐标系。\n*   @details        地球空间直角坐标系原点为参考椭球的中心，X轴和Y轴位于赤道平面，X轴通过零子午线，Z轴与椭球极轴一致。\n*   @param[out]      x               地球空间直角坐标系X坐标\n*   @param[out]      y               地球空间直角坐标系Y坐标\n*   @param[out]      z               地球空间直角坐标系Z坐标\n*   @param[in]       longitude       经度（角度）\n*   @param[in]       latitude        纬度（角度）\n*   @param[in]       height          高度\n*   @retval          0               正常\n*   @retval          1               错误\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          地球经纬度坐标系转换到导航坐标系的旋转矩阵。\n*   @details        导航坐标系原点位于参考点，X轴指向北边，Y轴指向东边，Z轴指向地下。\n*   @param[out]     R_en            旋转矩阵:3x3,正交\n*   @param[in]      longitude0      导航坐标系参考点经度(角度)\n*   @param[in]      latitude0       导航坐标系参考点纬度(角度)\n*   @retval         0               正常\n*   @retval         1               错误\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//先转到天东北系\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//再从天东北转到北东地\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          导航坐标系转换到地球经纬度坐标系的旋转矩阵。\n*   @details        导航坐标系原点位于参考点，X轴指向北边，Y轴指向东边，Z轴指向地下。\n*   @param[out]     R_ne            旋转矩阵:3x3,正交\n*   @param[in]      longitude0      导航坐标系参考点经度(角度)\n*   @param[in]      latitude0       导航坐标系参考点纬度(角度)\n*   @retval         0               正常\n*   @retval         1               错误\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          地球经纬度坐标系转换到导航坐标系。\n*   @details        导航坐标系原点位于参考点，X轴指向北边，Y轴指向东边，Z轴指向地面。\n*   @param[out]     north            导航坐标系内东向坐标\n*   @param[out]     east           导航坐标系内北向坐标\n*   @param[out]     downward          导航坐标系内天向坐标\n*   @param[in]      longitude       机体经度（角度）\n*   @param[in]      latitude        机体纬度（角度）\n*   @param[in]      height          机体高度\n*   @param[in]      longitude0      导航坐标系参考点经度（角度）\n*   @param[in]      latitude0       导航坐标系参考点纬度（角度）\n*   @param[in]      height0         导航坐标系参考点高度\n*   @retval         0               正常\n*   @retval         1               错误\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          导航坐标系转换到地球经纬度坐标系。\n*   @details        导航坐标系原点位于参考点，X轴指向北边，Y轴指向东边，Z轴指向地面。\n*   @param[out]     longitude       机体经度（角度）\n*   @param[out]     latitude        机体纬度（角度）\n*   @param[out]     height          机体高度\n*   @param[in]      north            机体导航坐标系内东向坐标\n*   @param[in]      east           机体导航坐标系内北向坐标\n*   @param[in]      downward          机体导航坐标系内天向坐标\n*   @param[in]      longitude0      导航坐标系参考点经度（角度）\n*   @param[in]      latitude0       导航坐标系参考点纬度（角度）\n*   @param[in]      height0         导航坐标系参考点高度\n*   @retval         0               正常\n*   @retval         1               错误\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;//在导航系内的坐标\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          由欧拉角得到导航坐标系转换到机体坐标系的旋转矩阵。\n*   @details        导航坐标系原点位于参考点，X轴指向北边，Y轴指向东边，Z轴指向地下。\n                    机体坐标系原点位于质心点，X轴指向机头，Y轴指向右侧，Z轴指向下方。\n*   @param[out]     R_nb            旋转矩阵:3x3,正交\n*   @param[in]      roll            机体导航坐标系内横滚角（角度）\n*   @param[in]      pitch           机体导航坐标系内俯仰角（角度）\n*   @param[in]      yaw             机体导航坐标系内航向角（角度）\n*   @retval         0               正常\n*   @retval         1               错误\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////////先将东-北-天的导航坐标系转到北-东-地的方向\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//从北-东-地的导航坐标系以Z（航向）-Y（俯仰）-X（滚转）的顺序旋转到载体系的旋转矩阵：\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//可查Z1Y2X3顺规旋转矩阵如下：\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          机体坐标系转换到导航坐标系的旋转矩阵。\n*   @details        导航坐标系原点位于参考点，X轴指向北边，Y轴指向东边，Z轴指向地下。\n\t\t\t\t\t机体坐标系原点位于质心点，X轴指向机头，Y轴指向右侧，Z轴指向下方。\n*   @param[out]     R_bn            旋转矩阵:3x3,正交\n*   @param[in]      roll            机体导航坐标系内横滚角（角度）\n*   @param[in]      pitch           机体导航坐标系内俯仰角（角度）\n*   @param[in]      yaw             机体导航坐标系内航向角（角度）\n*   @retval         0               正常\n*   @retval         1               错误\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          由Rnb旋转矩阵得到欧拉角。\n*   @details        Rnb是导航坐标系转换到机体坐标系\n                    导航坐标系原点位于参考点，X轴指向北边，Y轴指向东边，Z轴指向地下。\n\t\t\t\t\t机体坐标系原点位于质心点，X轴指向机头，Y轴指向右侧，Z轴指向下方。\n*   @param[out]     roll            机体导航坐标系内横滚角（角度）\n*   @param[out]     pitch           机体导航坐标系内俯仰角（角度）\n*   @param[out]     yaw             机体导航坐标系内航向角（角度）\n*   @param[in]      R_nb            旋转矩阵:3x3,正交\n*   @retval         0               正常\n*   @retval         1               错误\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          由方向余弦旋转矩阵求四元数\n*   @details        由方向余弦旋转矩阵求四元数\n*   @param[out]     q               四元数:4维向量\n*   @param[in]      R               方向余弦旋转矩阵:3x3\n*   @retval         0               正常\n*   @retval         1               错误\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          由四元数求方向余弦旋转矩阵\n*   @details        由四元数求方向余弦旋转矩阵\n*   @param[out]     R               方向余弦旋转矩阵:3x3\n*   @param[in]      q               四元数:4维向量\n*   @retval         0               正常\n*   @retval         1               错误\n*/\nint quaternion_to_rotation(\n\tMatrix3d* R,\n\tconst Vector4d & q)//不加'&'会报错：具有 __declspec(align('16')) 的形参将不被对齐\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          由欧拉角求从载体系到导航系的转动四元数\n*   @details        由欧拉角求从载体系到导航系的转动四元数\n*   @param[out]     q               从载体系到导航系的转动四元数:4维向量\n*   @param[in]      roll            机体导航坐标系内横滚角（角度）\n*   @param[in]      pitch           机体导航坐标系内俯仰角（角度）\n*   @param[in]      yaw             机体导航坐标系内航向角（角度）\n*   @retval         0               正常\n*   @retval         1               错误\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          由从载体系到导航系的转动四元数求欧拉角\n*   @details        由从载体系到导航系的转动四元数求欧拉角\n*   @param[out]     roll            机体导航坐标系内横滚角（角度）\n*   @param[out]     pitch           机体导航坐标系内俯仰角（角度）\n*   @param[out]     yaw             机体导航坐标系内航向角（角度）\n*   @param[in]      q               四元数:4维向量\n*   @retval         0               正常\n*   @retval         1               错误\n*/\nint quaternion_bn_to_euler(\n\tdouble* roll,\n\tdouble* pitch,\n\tdouble* yaw,\n\tconst Vector4d& q)//不加'&'会报错：具有 __declspec(align('16')) 的形参将不被对齐\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          四元数归一化\n*   @details        四元数归一化\n*   @param[out]     qout            归一化后的四元数\n*   @param[in]      qin             四元数:4维向量\n*   @retval         0               正常\n*   @retval         1               错误\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": "/*\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": "#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// 平面\r\nenum Plane\r\n{\r\n\tXOY,\r\n\tXOZ,\r\n\tYOZ\r\n};\r\n\r\n\r\n// 空间直方图计算\r\n// 法向量的视点坐标\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// 重点：重载“<”，作为map的键\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// 读取文件点云数据\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// 获取要统计的平面的点云\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数据加载失败！\" << 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// 统计各个单位点云数目,\r\nmap<Point2D, int> countPointCloud(vector<Point2D> pointCloudDatas, vector<float> boudaryData, int segNum) {\r\n\t// 区间数10*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// 判断属于哪个区间，并统计该区间点云的个数\r\n\tfor (Point2D & pointCloudData : pointCloudDatas) {\r\n\t\tPoint2D tempData;\r\n\r\n\t\t// 值减去最小值再除以区间间隔值，判断属于哪个区间 \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// 计算相似度\r\nfloat cacular2Similarity(map<Point2D,int> data1, map<Point2D,int> data2, int segNum) {\r\n\t// 存储100个单元的点云数\r\n\tvector<int> unitPointNum1(segNum * segNum, 0);\r\n\tvector<int> unitPointNum2(segNum * segNum, 0);\r\n\t// 临时存储当前遍历的位置\r\n\tPoint2D curLoc;\r\n\tint k = 0;\r\n\r\n\t// 提取出100个单元中每个单元的点云数\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//二维平面栅格化后，相似度比较\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网格点云数目统计信息\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// 计算相似度\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 << \"========================相似度信息=========================\" << 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// 获取三维点云的数据，遍历点云获得边界X、Y、Z的最大，最小值\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 << \"=========================统计数据======================\" << endl;\r\n\t cout << \"3D点云数据数目: \" << pointData.size() << endl;\r\n\r\n\t // 统计边界\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 // 统计各个网格内的数据，网格化\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// 键为网格坐标，键值为该网格内的点云\r\n\tmap<Point3D, vector<Point3D>> meshData;\r\n\tPoint3D tempData;\r\n\tfor (auto & pointData : pointDatas) {\r\n\t\t// 值减去最小值再除以区间间隔值，判断属于哪个区间\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// 边界处理\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// 数据存储\r\n\t\tmeshData[tempData].push_back(pointData);\r\n\t}\r\n\tint pointSum = 0;\r\n\tcout << \"网格数量：\" << 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": "//==============================================================================\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 <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の逆元\ninline long long mod_inv(long long n, long long mod) {\n\treturn mod_pow(n, mod - 2, mod);\n}\n\n// エラトステネスの篩\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// 素数リスト\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// 素因数分解(素数表を用いる)\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の要素すべての最小公倍数をmodで割った余りを返す\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": "// 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    ½ 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": "//  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": "/**\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": "//////////////////////////////////////////////////////////////////////////////\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": "#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+=\"↑↓|\";\n  std::string not_occ=\"|\";\n  for(i=0;i<ne;i++)\n    not_occ+=\"↑|\";\n  for(i=0;i<ne;i++)\n    not_occ+=\"↓|\";\n  std::string antiferro=\"|\";\n  for(i=0;i<ne;i++)\n    antiferro+=\"↑|↓|\";\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änkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// Written by 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": "#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 \"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 * @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 * Polygon.cpp\n *\n *  Created on: Nov 7, 2014\n *      Author: Péter 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": "// 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 #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": "//  (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) ≈ .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": "// 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": "#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": "/* ----------------------------------------------------------------------------\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": "#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": "/*!@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": "// 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 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øgh 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// Copyright © 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": "#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": "\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": "/*(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": "#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": "/**\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": "#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 <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 * 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 φ(x) = log(x-x₀), where x₀ 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 φ: (a,b) → ℝ,  φ(x) = tanh⁻¹((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 φ: (a,b) → ℝ,  φ(x) = tanh⁻¹(((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": "\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": "//#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": "#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": "#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": "/* 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": "//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": "\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// 包含的文件与  step-37  中的基本相同，只是用有限元类FE_DGQHermite代替了FE_Q。所有对面积分进行无矩阵计算的功能已经包含在`fe_evaluation.h`中。\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// 和 step-37 一样，为了简单起见，我们在程序顶部将维数和多项式程度收集为常数。与 step-37 不同的是，这次我们选择了一个真正的高阶方法，度数为8，任何不使用和因式分解的实现都会变得非常慢，而使用MatrixFree的实现则提供了与度数为2或3时基本相同的效率。此外，本教程程序中的所有类都是模板化的，因此，通过在`main()`函数中添加适当度数的实例，可以很容易地在运行时从输入文件或命令行参数中选择度数。\n\n  const unsigned int degree_finite_element = 8; \n  const unsigned int dimension             = 3; \n// @sect3{Equation data}  \n\n// 与 step-7 相类似，我们定义了一个分析解，我们试图用离散化重现这个分析解。由于本教程的目的是展示无矩阵方法，我们选择了一个最简单的可能性，即一个余弦函数，其导数对我们来说足够简单，可以通过分析计算。再往下看，我们在这里选择的波数2.4将与 $x$ -方向的域范围即2.5相匹配，这样我们在 $x = 2.5$ 得到一个周期性的解，包括 $6pi$ 或余弦的三个整波转。第一个函数定义了解和它的梯度，分别用于表达Dirichlet和Neumann边界条件的解析解。此外，一个代表解的负拉普拉斯的类被用来表示右手边（强制）函数，我们用它来匹配离散化版本中的给定分析解（制造解）。\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`类与  step-37  中的相应类类似。一个重要的区别是，我们没有从  MatrixFreeOperators::Base  派生出这个类，因为我们想呈现  MatrixFree::loop()  的一些额外特性，这些特性在通用类  MatrixFreeOperators::Base.  中是不可用的。我们从Subscriptor类派生出这个类，以便能够在Chebyshev预处理程序中使用该操作符，因为该预处理程序通过SmartPointer存储基础矩阵。\n\n// 鉴于我们手工实现了一个完整的矩阵接口，我们需要添加一个`initialize()`函数，一个`m()`函数，一个`vmult()`函数和一个`Tvmult()`函数，这些都是之前由  MatrixFreeOperators::Base.  我们的LaplaceOperator还包含一个成员函数`get_penalty_factor()`，根据  step-39  集中选择对称内部惩罚方法中的惩罚参数 。\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`类定义了我们对这个问题的自定义预处理程序。与基于矩阵对角线的 step-37 不同，我们在这里通过使用介绍中讨论的所谓快速对角线化方法来计算非连续Galerkin方法中对角线块的近似反演。\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//这个独立的函数在`LaplaceOperator'和`%PreconditionBlockJacobi'类中都被用来调整鬼魂范围。这个函数是必要的，因为`vmult()`函数所提供的一些向量没有用包括正确的鬼魂条目布局的 `LaplaceOperator::initialize_dof_vector` 来正确初始化，而是来自MGTransferMatrixFree类，该类对无矩阵类的鬼魂选择没有概念。为了避免索引混乱，我们必须在对这些向量进行实际操作之前调整鬼域。由于向量在多网格平滑器和传输类中被保留下来，一个曾经被调整过重影范围的向量在对象的整个生命周期中都会保持这种状态，所以我们可以在函数的开始使用一个快捷方式来查看分布式向量的分区器对象（以共享指针的形式存储）是否与MatrixFree所期望的布局相同，它被存储在一个由 MatrixFree::get_dof_info(0),  访问的数据结构中 ]，其中的0表示从中提取的DoFHandler编号；我们在MatrixFree中只使用一个DoFHandler，所以这里唯一有效的编号是0。\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// 接下来的五个函数用于清除和初始化`LaplaceOperator`类，返回持有MatrixFree数据容器的共享指针，以及正确初始化向量和运算符大小，与 step-37 或者说 MatrixFreeOperators::Base. 的内容相同。\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// 这个函数在向量`src`上实现了LaplaceOperator的动作，并将结果存储在向量`dst`中。与 step-37 相比，这个调用有四个新特性。\n\n// 第一个新特性是上面提到的`adjust_ghost_range_if_necessary`函数，该函数需要使向量符合单元和面函数中FEEvaluation和FEFaceEvaluation所期望的布局。\n\n// 第二个新特征是我们没有像 step-37 中那样实现`vmult_add()`函数（通过虚拟函数 MatrixFreeOperators::Base::vmult_add()), ，而是直接实现`vmult()`功能。由于单元和面的积分都将和到目的向量中，我们当然必须在某处将向量归零。对于DG元素，我们有两个选择&ndash；一个是使用 FEEvaluation::set_dof_values() 而不是下面`apply_cell`函数中的 FEEvaluation::distribute_local_to_global() 。这是因为MatrixFree中的循环布局是这样的：单元积分总是在面积分之前接触到一个给定的向量条目。然而，这实际上只适用于完全不连续的基数，其中每个单元都有自己的自由度，不与邻近的结果共享。另一种设置，即这里选择的设置，是让 MatrixFree::loop() 来处理向量的归零问题。这可以被认为是在代码的某个地方简单地调用`dst = 0;`。对于像 `LinearAlgebra::distributed::Vector`, 这样的支持性向量来说，实现起来就比较麻烦了，因为我们的目标是不要一次性将整个向量清零。在足够小的几千个向量项上进行归零操作的好处是，在 FEEvaluation::distribute_local_to_global() 和 FEFaceEvaluation::distribute_local_to_global(). 中再次访问之前，被归零的向量项会保留在缓存中，因为无矩阵运算符的评估真的很快，仅仅归零一个大的向量就会相当于运算符评估时间的25%，我们显然希望避免这种代价。对于 MatrixFree::cell_loop 和连续基数来说，也可以使用这种将向量归零的选项，尽管在 step-37 或 step-48 的教程程序中没有使用它。\n\n// 第三个新特征是我们提供了在单元格、内面和边界面进行计算的函数方式。MatrixFree类有一个叫做`loop`的函数，它接收三个函数指针，用于三种情况，允许分开实现不同的东西。正如在 step-37 中所解释的，这些函数指针可以是 `std::function` 对象或类的成员函数。在这种情况下，我们使用指向成员函数的指针。\n\n// 最后的新特征是可以给 MatrixFree::DataAccessOnFaces 类型的最后两个参数，这个类将面积分的数据访问类型传递给并行向量的MPI数据交换例程 LinearAlgebra::distributed::Vector::update_ghost_values() 和 LinearAlgebra::distributed::Vector::compress() 。其目的是不发送相邻元素的所有自由度，而是将数据量减少到手头计算真正需要的程度。数据交换是一个真正的瓶颈，特别是对于高自由度的DG方法来说，因此一个更严格的交换方式往往是有益的。枚举字段 MatrixFree::DataAccessOnFaces 可以取值`none`，这意味着根本不做面的积分，这类似于 MatrixFree::cell_loop(), 的值`values`，意味着只使用面的形状函数值（但不使用导数），而值`gradients`时，除了值之外还访问面的第一导数。值`unspecified`意味着所有的自由度将被交换给位于处理器边界的面，并指定在本地处理器上进行处理。\n\n// 为了了解数据是如何被减少的，想想节点元素FE_DGQ的情况，节点点在元素表面，在一个单元的 $(k+1)^d$ 个自由度中，只有 $(k+1)^{d-1}$ 个自由度对 $d$ 个空间维度的多项式程度的面的值有贡献。类似的减少也可以用于内部惩罚方法，该方法评估面的值和一导数。当在一维中使用类Hermite基时，最多只有两个基函数对数值和导数有贡献。FE_DGQHermite类实现了这一概念的张量乘积，在介绍中已经讨论过。因此，每个面只需交换 $2(k+1)^{d-1}$ 个自由度，一旦 $k$ 个自由度大于4或5个，这显然是一种胜利。请注意，FE_DGQHermite的这种减少的交换在具有弯曲边界的网格上也是有效的，因为导数是在参考元素上取的，而几何体只在内部混合它们。因此，这与试图用连续的Hermite型形状函数获得 $C^1$ 的连续性不同，在这种情况下，非笛卡尔的情况会大大改变情况。显然，在非笛卡尔网格上，导数还包括超出法向导数的形状函数的切向导数，但这些也只需要元素表面的函数值。如果元素不提供任何压缩，循环会自动交换受影响单元的所有条目。\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// 由于拉普拉斯是对称的，`Tvmult()`（多网格平滑界面需要）操作被简单地转发给`vmult()`的情况。\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//单元格的操作与 step-37 非常相似。不过我们在这里没有使用系数。第二个区别是，我们用一个单一的函数调用 FEEvaluation::gather_evaluate() 代替了 FEEvaluation::read_dof_values() 后面的 FEEvaluation::evaluate() 这两个步骤，在内部调用这两个单独方法的序列。同样， FEEvaluation::integrate_scatter() 实现了 FEEvaluation::integrate() 之后的 FEEvaluation::distribute_local_to_global(). 的序列。 在这种情况下，这些新函数只是节省了两行代码。然而，我们用它们来与FEFaceEvaluation进行类比，在那里它们更重要，如下所述。\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// 面部操作实现了与 step-39 类似的内部惩罚方法的条款，正如介绍中所解释的。我们需要两个评估器对象来完成这个任务，一个用于处理来自内部面的两边之一的单元格的解，另一个用于处理来自另一边的解。面积分的评价器被称为FEFaceEvaluation，并在构造函数的第二个槽中接受一个布尔参数，以指示评价器应属于两边中的哪一边。在FEFaceEvaluation和MatrixFree中，我们称两边中的一边为 \"内部\"，另一边为 \"外部\"。`外部'这个名字是指两边的评价器将返回相同的法向量。对于 \"内部 \"一侧，法向量指向外部，而另一侧则指向内部，并且与该单元的外部法向量相对应。除了新的类名之外，我们再次得到了一系列的项目，与 step-37 中讨论的类似，但在这种情况下是针对内部面的。请注意，MatrixFree的数据结构形成了面的批次，类似于单元积分的单元批次。一批中的所有面涉及不同的单元格编号，但在参考单元格中具有相同的面编号，具有相同的细化配置（无细化或相同的子面）和相同的方向，以保持SIMD操作的简单和高效。\n\n// 注意，除了法线方向的逻辑决定外，内部与外部没有任何隐含的意义，这在内部是相当随机的。我们绝对不能依赖分配内部与外部标志的某种模式，因为这个决定是为了MatrixFree设置例程中的访问规则性和统一性而做出的。由于大多数正常的DG方法都是保守的，也就是说，通量在接口的两边看起来都是一样的，所以如果内部/外部标志被调换，法线向量得到相反的符号，那么数学就不会有任何改变。\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// 在给定的一批面孔上，我们首先更新指向当前面孔的指针，然后访问矢量。如上所述，我们把访问向量和评估结合起来。在面积分的情况下，对于FE_DGQHermite基础的特殊情况，可以减少对向量的数据访问，正如上面解释的数据交换。由于 $2(k+1)^{d-1}$ 个单元自由度中只有 $(k+1)^d$ 个单元自由度被非零值或形状函数的导数所乘，这种结构可以被用于评估，大大减少了数据访问。减少数据访问不仅是有益的，因为它减少了飞行中的数据，从而有助于缓存，而且当从单元格索引列表中相距较远的单元格收集数值时，对面的数据访问往往比单元格积分更不规则。\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// 接下来的两个语句是计算内部惩罚法的惩罚参数。正如在介绍中所解释的，我们希望有一个像 $\\frac{1}{h_\\text{i}}$ 这样的长度 $h_\\text{i}$ 法线到面的缩放比例。对于一般的非笛卡尔网格，这个长度必须由反雅各布系数乘以实坐标的法向量的乘积来计算。从这个 \"dim \"分量的向量中，我们必须最终挑选出与参考单元的法线方向一致的分量。在MatrixFree中存储的几何数据中，雅各布式中的分量被应用，使得后一个方向总是最后一个分量`dim-1`（这很有利，因为参考单元的导数排序可以与面的方向无关）。这意味着我们可以简单地访问最后一个分量`dim-1`，而不必在`data.get_face_info(face).internal_face_no`和`data.get_face_info(face).exterior_face_no`中查找局部面的编号。最后，我们还必须取这些因素的绝对值，因为法线可能指向正或负的方向。\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// 在正交点的循环中，我们最终计算了对内部惩罚方案的所有贡献。根据介绍中的公式，测试函数的值被乘以解决方案中的跳跃乘以惩罚参数和实空间中的法向导数的平均值的差值。由于内侧和外侧的两个评估器由于跳跃而得到不同的符号，我们在这里用不同的符号传递结果。测试函数的正态导数会被内侧和外侧的解决方案中的负跳跃所乘。这个术语，被称为邻接一致性术语，根据其与原始一致性术语的关系，在代码中还必须包括 $\\frac{1}{2}$ 的系数，由于测试函数槽中的平均数，它得到了二分之一的系数。\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// 一旦我们完成了正交点的循环，我们就可以对面的积分循环进行和因子化操作，并将结果加到结果向量中，使用`integrate_scatter`函数。`scatter'这个名字反映了使用与`gather_evaluate'相同的模式将矢量数据分布到矢量中的分散位置。像以前一样，整合+写操作的组合允许我们减少数据访问。\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// 边界面函数大体上沿用了内部面函数。唯一的区别是，我们没有一个单独的FEFaceEvaluation对象为我们提供外部值  $u^+$  ，但我们必须从边界条件和内部值  $u^-$  来定义它们。正如介绍中所解释的，我们在Dirichlet边界上使用 $u^+ = -u^- + 2 g_\\text{D}$ 和 $\\mathbf{n}^-\\cdot \\nabla u^+ = \\mathbf{n}^-\\cdot \\nabla u^-$ ，在Neumann边界上使用 $u^+=u^-$ 和 $\\mathbf{n}^-\\cdot \\nabla u^+ = -\\mathbf{n}^-\\cdot \\nabla u^- + 2 g_\\text{N}$  。由于这个操作实现了同质部分，即矩阵-向量乘积，我们必须在这里忽略边界函数 $g_\\text{D}$ 和 $g_\\text{N}$ ，并在 `LaplaceProblem::compute_rhs()`. 中把它们加到右侧。 ] 注意，由于通过 $u^+$ 将解 $u^-$ 扩展到外部，我们可以保持所有因子 $0.5$ 与内面函数相同，也可参见 step-39 中的讨论。\n\n// 在这一点上有一个问题。下面的实现使用一个布尔变量`is_dirichlet`来切换Dirichlet和Neumann情况。然而，我们解决了一个问题，我们还想在一些边界上施加周期性的边界条件，即沿着 $x$ 方向的边界。人们可能会问，这里应该如何处理这些条件。答案是MatrixFree会自动将周期性边界视为技术上的边界，即两个相邻单元的解值相遇的内面，必须用适当的数值通量来处理。因此，周期性边界上的所有面将出现在`apply_face()`函数中，而不是这个函数中。\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// 接下来我们来看看预处理程序的初始化。正如介绍中所解释的，我们想从一维质量和拉普拉斯矩阵的乘积中构造一个（近似的）单元矩阵的逆。我们的首要任务是计算一维矩阵，我们通过首先创建一个一维有限元来实现。在这里，我们没有预见到FE_DGQHermite<1>，而是从DoFHandler获得有限元的名称，用1替换 @p dim 参数（2或3）来创建一个一维名称，并通过使用FETools来构造一维元素。\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// 至于在单位元素上计算一维矩阵，我们简单地写下在矩阵的行和列以及正交点上的典型装配程序会做什么。我们一劳永逸地选择相同的拉普拉斯矩阵，对内部面使用系数0.5（但可能由于网格的原因，在不同方向上的缩放比例不同）。因此，我们在Dirichlet边界（正确的系数应该是导数项为1，惩罚项为2，见 step-39 ）或在Neumann边界（系数应该为0）犯了一个小错误。由于我们只在多网格方案中使用这个类作为平滑器，这个错误不会有任何重大影响，只是影响平滑质量。\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// 接下来两个语句组装的左右边界项似乎有一些任意的符号，但这些都是正确的，可以通过查看 step-39 并插入1D情况下的法向量的值-1和1来验证。\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// 接下来，我们通过单元格，将缩放后的矩阵传递给TensorProductMatrixSymmetricSum，以实际计算代表逆的广义特征值问题。由于矩阵的近似构造为 $A\\otimes M + M\\otimes A$ ，并且每个元素的权重是恒定的，我们可以在拉普拉斯矩阵上应用所有的权重，并简单地保持质量矩阵不被缩放。在单元格的循环中，我们要利用MatrixFree类提供的几何体压缩，并检查当前的几何体是否与上一批单元格上的几何体相同，在这种情况下就没有什么可做的。一旦调用了`reinit()`，就可以通过 FEEvaluation::get_mapping_data_index_offset() 访问这种压缩。\n\n// 一旦我们通过FEEvaluation访问函数访问了反雅各布系数（我们取第4个正交点的，因为它们在笛卡尔单元的所有正交点上都应该是一样的），我们检查它是对角线的，然后提取原始雅各布系数的行列式，即反雅各布系数的行列式，并根据质量矩阵的一维拉普拉斯乘以 $d-1$ 份，设置权重为 $\\text{det}(J) / h_d^2$  。\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// 一旦我们知道了拉普拉斯矩阵的比例系数，我们就将这个权重应用于未被缩放的DG拉普拉斯矩阵，并将数组发送到TensorProductMatrixSymmetricSum类，以计算介绍中提到的广义特征值问题。\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// 在DG背景下，用于近似块状Jacobi预处理的vmult函数非常简单。我们只需要读取当前单元格批次的值，对张量积矩阵阵列中的给定条目进行逆运算，并将结果写回。在这个循环中，我们覆盖了`dst`中的内容，而不是首先将条目设置为零。这对于DG方法来说是合法的，因为每个单元都有独立的自由度。此外，我们手动写出所有单元批的循环，而不是通过 MatrixFree::cell_loop(). 我们这样做是因为我们知道我们在这里不需要通过MPI网络进行数据交换，因为所有的计算都是在每个处理器上的本地单元上完成的。\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类的定义与  step-37  非常相似。一个区别是我们将元素度作为模板参数添加到类中，这将允许我们通过在`main()`函数中创建不同的实例，更容易在同一个程序中包含多个度。第二个区别是选择了FE_DGQHermite这个元素，它是专门用于这种方程的。\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// 设置函数在两个方面与  step-37  不同。首先是我们不需要为不连续的Ansatz空间插值任何约束，而只是将一个假的AffineConstraints对象传入 Matrixfree::reinit().  第二个变化是因为我们需要告诉MatrixFree同时初始化面的数据结构。我们通过为内部面和边界面分别设置更新标志来做到这一点。在边界面，我们需要函数值、它们的梯度、JxW值（用于积分）、法向量和正交点（用于边界条件的评估），而对于内部面，我们只需要形状函数值、梯度、JxW值和法向量。只要`mapping_update_flags_inner_faces`或`mapping_update_flags_boundary_faces`中的一个与UpdateFlags的默认值`update_default`不同，MatrixFree中的面数据结构总是被建立的。\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// 右手边的计算比  step-37  中的计算要复杂一些。现在的单元项包括分析解的负拉普拉斯，`RightHandSide'，为此我们需要首先将VectorizedArray字段的Point，即一批点，通过分别评估VectorizedArray中的所有通道，拆成一个点。请记住，通道的数量取决于硬件；对于不提供矢量化的系统（或deal.II没有本征），它可能是1，但在最近的Intel架构的AVX-512上也可能是8或16。\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// 其次，我们还需要应用Dirichlet和Neumann边界条件。一旦Dirichlet边界上的外部求解值 $u^+ = -u^- + 2 g_\\text{D}$ 和 $\\mathbf{n}^-\\cdot \\nabla u^+ = \\mathbf{n}^-\\cdot \\nabla u^-$ 以及Neumann边界上的 $u^+=u^-$ 和 $\\mathbf{n}^-\\cdot \\nabla u^+ = -\\mathbf{n}^-\\cdot \\nabla u^- + 2 g_\\text{N}$ 被插入并以边界函数 $g_\\text{D}$ 和 $g_\\text{N}$ 展开，这个函数就是到函数 `LaplaceOperator::apply_boundary()` 所缺的部分。需要记住的一点是，我们把边界条件移到右手边，所以符号与我们强加在解的部分相反。\n\n// 我们可以通过 MatrixFree::loop 部分发出单元格和边界部分，但我们选择手动写出所有面的完整循环，以了解MatrixFree中面的索引布局是如何设置的：内部面和边界面都共享索引范围，所有批次的内部面的数字都比批次的边界单元格低。两种变体的单一索引使我们可以很容易地在两种情况下使用相同的数据结构FEFaceEvaluation，它附着在同一个数据域上，只是位置不同。内层面的批次（其中一个批次是由于将几个面合并成一个面进行矢量化）的数量由 MatrixFree::n_inner_face_batches(), 给出，而边界面的批次数量由 MatrixFree::n_boundary_face_batches(). 给出。\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类让我们查询当前面批的边界_id。请记住，MatrixFree为矢量化设置了批次，使一个批次中的所有面孔都有相同的属性，其中包括它们的`边界_id'。因此，我们可以在这里为当前面的索引`face`查询该id，并在Dirichlet情况下（我们在函数值上添加一些东西）或Neumann情况下（我们在法线导数上添加一些东西）施加。\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// 由于我们手动运行了单元格的循环，而不是使用 MatrixFree::loop(), ，我们不能忘记与MPI进行数据交换。\n\n// 或者说，对于DG元素来说，我们不需要这样做，因为每个单元都有自己的自由度，单元和边界积分只对本地拥有的单元进行评估。与相邻子域的耦合只通过内表面积分来实现，我们在这里没有做这个。也就是说，在这里调用这个函数并没有什么坏处，所以我们这样做是为了提醒大家在 MatrixFree::loop(). 里面发生了什么。\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()`函数几乎逐字复制自  step-37  。我们设置了相同的多网格成分，即水平转移、平滑器和粗略的网格求解器。唯一不同的是，我们没有使用拉普拉斯的对角线作为用于平滑的切比雪夫迭代的预处理，而是使用我们新解决的类`%PreconditionBlockJacobi`。不过，机制是一样的。\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// 由于我们已经用分析法解决了一个问题，我们想通过计算数值结果与分析法的L2误差来验证我们实现的正确性。\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()`函数设置了初始网格，然后以常规方式运行多网格程序。作为一个域，我们选择一个矩形，在 $x$ -方向上有周期性的边界条件，在 $y$ 方向上的正面（即索引号为2的面，边界id等于0）有迪里希特条件，在背面以及 $z$ 方向上的两个面为三维情况（边界id等于1）有纽曼条件。与 $y$ 和 $z$ 方向相比， $x$ 方向的域的范围有些不同（考虑到 \"解决方案 \"的定义，我们希望在这里实现周期性的解决方案）。\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()`函数中没有任何意外。我们通过`MPI_Init()`类调用`MPI_InitFinalize`，传入文件顶部设置的关于维度和度的两个参数，然后运行拉普拉斯问题。\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": "\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になるときに以下の関数を消す。\r\n\tdouble unbiasedVar()　→kstatboostのものを推奨。\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　GSL'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> &); // 非推奨。deprecated. \r\ndouble boostMean( const std::vector <double> &); // 非推奨。deprecated. \r\ndouble sum( const double *, int);\r\ndouble mean( const double *, int);\r\ndouble unbiasedVar( const double *, int);\r\n\r\n// このファイル内でよいのか？\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// 基本的に離散変数用。\r\n// doubleなどに使う場合、等値判断のための\r\n// toleranceは0か非常に小さい値である、\r\n// という前提がある。そうでないとカテゴリ間の\r\n// 重なりが生じてしまう。\r\n// 連続変数に用いる場合には、特定の機能を使うべし。\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のTOriginとして、doubleを指定してしまっている。\r\n\t// ここに柔軟性を持たせたいならば、rtablepがないクラスをつくり、\r\n\t// それを基底クラスにして、派生クラスでテンプレート引数を増やしてrtablepを持たせるのが、素直だろう。\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要素はRecodeTableの1行分\r\n\tstd::vector <CodeType> codes; \r\n\r\n\t// \"else\"の場合の処理方法　（スコープを持つ列挙型）\r\n\tenum class ElseType { Copy, AssignValue};\r\n\t\r\n\tElseType toDoForElse; // \"else\"の場合の処理方法\r\n\tTCode codeForElse; // \"else\"の場合に値を埋める場合の値（NaN以外）\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// 等値判断のためのファンクタクラス：==演算子で判断する。\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// 等値判断のためのファンクタクラス：Toleranceを含んで判断する。\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// ==演算子を用いて、ユニークな値が何個あるかを返す。\r\n// var0に欠損値は含まないと仮定して、ケース数を算出している。\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 非推奨\r\n// このアルゴリズムでは精度が落ちるときがあるらしい。\r\n// kstatboostのものを推奨する。\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 非推奨\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// 長さnの配列へのポインタpを得て、合計を返す。\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// 長さnの配列へのポインタpを得て、平均を返す。\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// 長さnの配列へのポインタpを得て、不偏分散を返す。\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); // ここでfindを使う。areEqualを使っていない。\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// 頻度総計が偶数で、「累積頻度50%」が2値の間になっており、\r\n\t\t\t\t// 大きい方を待っていた状態のとき\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// 本来は、Datasetに入れて表示したいが、また今度。\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// 各階級の左端と右端のVectorを得る。\r\n// RecodeTypeがない場合には空のVectorが返る。\r\n// Note that obtained vectors should be\r\n// parallel to those obtained by getVectors() above\r\n// これも、上記のprintPadding()と同様に、\r\n// 本来はDatasetに入れて処理したいが、また今度。\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// 自動で階級を作成する。\r\n// Nから階級の数を設定する。Stataの方式で。\r\n// 最小値と最大値の幅を出して、そこから階級幅を出す。\r\n// 各階級は、左端点を含み、右端点を含まない。\r\n// 有効ケース数が1未満のとき、エラー。\r\n// 有効ケース数が1のとき、階級数は1。\r\n// 最大値と最小値の差がゼロの場合、次のように最大・最小を修正。\r\n// 　値がゼロなら、最小値を-1に、最大値を1にする。\r\n// 　値が正なら、最小値を0に、最大値をそのままにする。\r\n// 　値が負なら、最大値を0に、最小値をそのままにする。\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になりうる値のvectorを返す。\r\n// ソートして返す。\r\n// ただし、Elseの場合のcodeは含めない。\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に対応するコードを返す。\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に対応するleftとrightを返す。\r\n// code0に対応する範囲が登録されていなければ、nanを返す。\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に対応するラベルを返す。\r\n// code0に対応する範囲が登録されていなければ、空のstringを返す。\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// ストリームに出力する。\r\n// スペースでパディングはしない。sepで区切る。\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": "#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": "#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// 像素坐标转相机归一化坐标\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    //-- 读取图像\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<<\"一共找到了\"<<matches.size() <<\"组匹配点\"<<endl;\n\n    // 建立3D点\n    Mat d1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );       // 深度图为16位无符号数，单通道图像\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 ); // 调用OpenCV 的 PnP 求解，可选择EPNP，DLS等方法\n    Mat R;\n    cv::Rodrigues ( r, R ); // r为旋转向量形式，用Rodrigues公式转换为矩阵\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    //-- 初始化\n    Mat descriptors_1, descriptors_2;\n    // used in OpenCV3\n    Ptr<FeatureDetector> detector = ORB::create();\n    Ptr<DescriptorExtractor> descriptor = ORB::create();\n    // use this if you are in OpenCV2\n    // Ptr<FeatureDetector> detector = FeatureDetector::create ( \"ORB\" );\n    // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( \"ORB\" );\n    Ptr<DescriptorMatcher> matcher  = DescriptorMatcher::create ( \"BruteForce-Hamming\" );\n    //-- 第一步:检测 Oriented FAST 角点位置\n    detector->detect ( img_1,keypoints_1 );\n    detector->detect ( img_2,keypoints_2 );\n\n    //-- 第二步:根据角点位置计算 BRIEF 描述子\n    descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n    descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n\n    //-- 第三步:对两幅图像中的BRIEF描述子进行匹配，使用 Hamming 距离\n    vector<DMatch> match;\n    // BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( descriptors_1, descriptors_2, match );\n\n    //-- 第四步:匹配点对筛选\n    double min_dist=10000, max_dist=0;\n\n    //找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        double dist = match[i].distance;\n        if ( dist < min_dist ) min_dist = dist;\n        if ( dist > max_dist ) max_dist = dist;\n    }\n\n    printf ( \"-- Max dist : %f \\n\", max_dist );\n    printf ( \"-- Min dist : %f \\n\", min_dist );\n\n    //当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        if ( match[i].distance <= max ( 2*min_dist, 30.0 ) )\n        {\n            matches.push_back ( match[i] );\n        }\n    }\n}\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    // 初始化g2o\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose 维度为 6, landmark 维度为 3\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // 线性方程求解器\n    Block* solver_ptr = new Block ( linearSolver );     // 矩阵块求解器\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm ( solver );\n\n    // 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 中必须设置 marg 参见第十讲内容\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ù 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 à 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ètres dans Schur >= Nombre de paramètre dans le problème\");\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": "// 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  // 从这里看，参数块应该是[q,t]，且q是[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 不需要归一化吗？\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  // 这是全局参数到局部参数的雅可比矩阵。全局是trans,quat，因此是7维，局部则是se3,因此是6维。\n  // 答案中提到了J1*J2,其中J1是参数块对[t,q]求导来自于evaluate或者AD，J2则是这里的到李代数的参数化。\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": "// 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": "// 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 <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": "#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": "//\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": "﻿#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(\"重新计算\"),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(\"重量(g)\");\n    tableWidget->setHorizontalHeaderLabels(HHeadList);\n\n    QStringList VHeadList;\n    VHeadList<<\"1#\"<<\"2#\"<<\"3#\"<<\"4#\"<<\"5#\"<<QStringLiteral(\"混合后元素含量\");\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(\"点击重新计算按钮\");\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 ++){ //按列顺序优先遍历\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(\"提示\"), QStringLiteral(\"无解\"),\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 ++){ //按列顺序优先遍历\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; //未知数个数\n    int free_num = Gauss(tableWidget->columnCount()-1,var);\n    if (free_num == -1) {\n\n        QMessageBox::information(NULL, QStringLiteral(\"提示\"), QStringLiteral(\"无解\"),\n                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);\n\n    }\n    else if (free_num == -2){\n\n        QMessageBox::information(NULL, QStringLiteral(\"提示\"), QStringLiteral(\"有浮点解,无整数解\"),\n                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);\n\n    }\n    else if (free_num > 0)\n    {\n//        printf(\"无穷多解! 自由变元个数为%d\\n\", free_num);\n//        for (i = 0; i < var; i++)\n//        {\n//            if (free_x[i]) printf(\"x%d 是不确定的\\n\", i + 1);\n//            else printf(\"x%d: %d\\n\", i + 1, x[i]);\n//        }\n        QMessageBox::information(NULL, QStringLiteral(\"提示\"), QStringLiteral(\"无穷多解！\"),\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(\"单元格改变\");\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;//先除后乘防溢出\n}\n\n// 高斯消元法解方程组(Gauss-Jordan elimination).(-2表示有浮点数解，但无整数解，\n//-1表示无解，0表示唯一解，大于0表示无穷解，并返回自由变元的个数)\n//有equ个方程，var个变元。增广矩阵行数为equ,分别为0到equ-1,列数为var+1,分别为0到var.\nint Custom::Gauss(int equ,int var)\n{\n    int i,j,k;\n    int max_r;// 当前这列绝对值最大的行.\n    int col;//当前处理的列\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    //转换为阶梯阵.\n    col=0; // 当前处理的列\n    for(k = 0; k < equ && col < var; k++,col++)\n    {\n        // 枚举当前处理的行.\n// 找到该col列元素绝对值最大的那行与第k行交换.(为了在除法时减小误差)\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            // 与第k行交换.\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            // 说明该col列第k行以下全是0了，则处理当前行的下一列.\n            k--;\n            continue;\n        }\n        for(i=k+1; i<equ; i++)\n        {\n            // 枚举要删去的行.\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;//异号的情况是相加\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. 无解的情况: 化简的增广阵中存在(0, 0, ..., a)这样的行(a != 0).\n    for (i = k; i < equ; i++)\n    {\n        // 对于无穷解来说，如果要判断哪些是自由变元，那么初等行变换中的交换就会影响，则要记录交换.\n        if (a[i][col] != 0) return -1;\n    }\n    // 2. 无穷解的情况: 在var * (var + 1)的增广阵中出现(0, 0, ..., 0)这样的行，即说明没有形成严格的上三角阵.\n    // 且出现的行数即为自由变元的个数.\n    if (k < var)\n    {\n        // 首先，自由变元有var - k个，即不确定的变元至少有var - k个.\n        for (i = k - 1; i >= 0; i--)\n        {\n            // 第i行一定不会是(0, 0, ..., 0)的情况，因为这样的行是在第k行到第equ行.\n            // 同样，第i行一定不会是(0, 0, ..., a), a != 0的情况，这样的无解的.\n            free_x_num = 0; // 用于判断该行中的不确定的变元的个数，如果超过1个，则无法求解，它们仍然为不确定的变元.\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; // 无法求解出确定的变元.\n            // 说明就只有一个不确定的变元free_index，那么可以求解出该变元，且该变元是确定的.\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]; // 求出该变元.\n            free_x[free_index] = 0; // 该变元是确定的.\n        }\n        return var - k; // 自由变元有var - k个.\n    }\n    // 3. 唯一解的情况: 在var * (var + 1)的增广阵中形成严格的上三角阵.\n    // 计算出Xn-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; // 说明有浮点数解，但无整数解.\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": "// 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": "////////////////////////////////////////////\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": "// 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*  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// 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": "// 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": "/* 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 <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///   ┌────────────┰──────┐\n///   │     A      ┃ B    │\n///   ┝━━━━━━━━━━━━╋━━━━━━┥ j\n///   │            ┃      │\n///   │     C      ┃ D    │\n///   │            ┃      │\n///   └────────────┸──────┘\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": "#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": "//---------------------------------------------------------------------------//\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": "//  (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 * 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**\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": "/**\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": "#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 Τεχνολογίες Υλοποίησης Αλγορίθμων/Τελική Άσκηση/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 Τεχνολογίες Υλοποίησης Αλγορίθμων/Τελική Άσκηση/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 Τεχνολογίες Υλοποίησης Αλγορίθμων/Τελική Άσκηση/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": "/* 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": "//==================================================================================================\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": "#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#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": "/* -*- 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 <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": "// 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": "#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": "#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é, 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": "/* 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": "/* \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": "#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": "/* \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": "#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": "#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 * 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ána 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.Å^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*Å^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*Å^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": "/* -*- 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": "// 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  // 这里对应的应该是公式2下边那片,代码中只有7个,论文中是11个,\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  // 这个才是八邻域\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// 这里的type就是上边八邻域那个\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  // 这个就是一个八邻域的TXYR数组\n  using Hypotheses = std::array<Hypothesis, kNumHypotheses>;\n\n  static constexpr Hypotheses GenerateCenteredHypotheses(const Hypothesis &null_hypothesis) {\n    Hypotheses hypotheses;\n    // 一个假设变成了11个假设\n    for (size_t i = 0; i < kNumHypotheses; ++i) {// TODO null hypothesis could be avoided\n    // 这个+被重载了，这一层套一层的，真费劲\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 <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    //随机选取 g<-X\n    int ng=std::abs(GetRandom());\n    ng%=n;\n    /*\n     ********************************\n     */\n    Genf=f;\n    //此处得到了一个f\n    NTL::ZZ gtmp= ring[ng];\n    SetCoeff(g,ng,gtmp);\n    //保存一份f\n    NTL::ZZX prevf(f);\n    prevf=ReversePoly(f);\n    \n    prevf=2*prevf*g;\n    ZZXmod(prevf);\n    \n    \n    //已经存在了 f g\n    //对f取mod\n    \n    return prevf;\n}\n\n\n NTL::ZZX ntru::ReversePoly( NTL::ZZX &f)\n{\n    NTL::ZZ r(1);//比较结果\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次到 n-1的一个多项式环\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": "//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": "/* -*- 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": "\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ät München, \n *         Scott T. Miller, The Pennsylvania State University, 2013 \n */ \n\n\n// @sect3{Include files}  \n\n// 大多数deal.II的include文件已经在前面的例子中涉及到了，没有注释。\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// 然而，我们确实有一些新的包括在这个例子中。第一个定义了三角形面的有限元空间，我们把它称为 \"骨架\"。这些有限元在元素内部没有任何支持，它们代表的是在每个模数一的表面上有一个单一的值的多项式，但在模数二的表面上允许有不连续。\n\n#include <deal.II/fe/fe_face.h> \n\n// 我们包含的第二个新文件定义了一种新的稀疏矩阵类型。 常规的 <code>SparseMatrix</code> 类型存储了所有非零条目的索引。  <code>ChunkSparseMatrix</code> 则是利用了DG解的耦合性。 它存储了一个指定大小的矩阵子块的索引。 在HDG背景下，这个子块大小实际上是由骨架解场定义的每个面的自由度数量。这使得矩阵的内存消耗减少了三分之一，并且在求解器中使用矩阵时也会有类似的速度提升。\n\n#include <deal.II/lac/chunk_sparse_matrix.h> \n\n// 这个例子的最后一个新的包括涉及到数据输出。 由于我们在网格的骨架上定义了一个有限元场，我们希望能够直观地看到这个解决方案的实际情况。DataOutFaces正是这样做的；它的接口与我们熟悉的DataOut几乎一样，但输出的数据只有模拟的二维1数据。\n\n#include <deal.II/numerics/data_out_faces.h> \n\n#include <iostream> \n\n// 我们首先将所有的类放入自己的命名空间。\n\nnamespace Step51 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n//分析解的结构与 step-7 中相同。有两个例外情况。首先，我们也为3D情况创建了一个解决方案，其次，我们对解决方案进行了缩放，使其在解决方案的所有宽度值上的规范是统一的。\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// 这个类实现了一个函数，标量解和它的负梯度被收集在一起。这个函数在计算HDG近似的误差时使用，它的实现是简单地调用Solution类的值和梯度函数。\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// 接下来是对流速度的实现。如介绍中所述，我们选择的速度场在二维是 $(y, -x)$ ，在三维是 $(y, -x, 1)$ 。这就得到了一个无发散的速度场。\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// 我们实现的最后一个函数是用于制造解决方案的右手边。它与 step-7 非常相似，不同的是我们现在有一个对流项而不是反应项。由于速度场是不可压缩的，即 $\\nabla \\cdot \\mathbf{c} =0$ ，对流项简单读作  $\\mathbf{c} \\nabla u$  。\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的求解过程与  step-7  的求解过程非常相似。主要区别在于使用了三套不同的DoFHandler和FE对象，以及ChunkSparseMatrix和相应的解决方案向量。我们还使用WorkStream来实现多线程的本地求解过程，该过程利用了本地求解器的尴尬的并行性质。对于WorkStream，我们定义了对单元格的本地操作和复制到全局矩阵和向量的函数。我们这样做既是为了装配（装配要运行两次，一次是在我们生成系统矩阵时，另一次是在我们从骨架值计算元素内部解时），也是为了后处理，在后处理中我们提取一个在高阶收敛的解。\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// 用于组装和解决原始变量的数据。\n\n    struct PerTaskData; \n    struct ScratchData; \n\n// 对解决方案进行后处理以获得  $u^*$  是一个逐个元素的过程；因此，我们不需要组装任何全局数据，也不需要声明任何 \"任务数据 \"供WorkStream使用。\n\n    struct PostProcessScratchData; \n\n// 以下三个函数被 WorkStream 用来完成程序的实际工作。\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// \"局部 \"解是每个元素的内部。 这些代表了原始解场  $u$  以及辅助场  $\\mathbf{q}$  。\n\n    FESystem<dim>   fe_local; \n    DoFHandler<dim> dof_handler_local; \n    Vector<double>  solution_local; \n\n// 新的有限元类型和相应的 <code>DoFHandler</code> 被用于耦合元素级局部解的全局骨架解。\n\n    FE_FaceQ<dim>   fe; \n    DoFHandler<dim> dof_handler; \n    Vector<double>  solution; \n    Vector<double>  system_rhs; \n\n// 如介绍中所述，HDG解可以通过后处理达到  $\\mathcal{O}(h^{p+2})$  的超收敛率。 后处理的解是一个不连续的有限元解，代表每个单元内部的原始变量。 我们定义了一个程度为 $p+1$ 的FE类型来表示这个后处理的解，我们只在构造后用于输出。\n\n    FE_DGQ<dim>     fe_u_post; \n    DoFHandler<dim> dof_handler_u_post; \n    Vector<double>  solution_u_post; \n\n// 与骨架相对应的自由度强烈地执行Dirichlet边界条件，就像在连续Galerkin有限元方法中一样。我们可以通过AffineConstraints对象以类似的方式强制执行边界条件。此外，悬挂节点的处理方式与连续有限元的处理方式相同。对于只在面定义自由度的面元素，这个过程将精炼面的解设置为与粗略面的表示相吻合。\n\n// 请注意，对于HDG来说，消除悬空节点并不是唯一的可能性，就HDG理论而言，我们也可以使用精炼侧的未知数，通过精炼侧的跟踪值来表达粗略侧的局部解。然而，这样的设置在deal.II循环方面并不容易实现，因此没有进一步分析。\n\n    AffineConstraints<double> constraints; \n\n// ChunkSparseMatrix类的用法与通常的稀疏矩阵类似。你需要一个ChunkSparsityPattern类型的稀疏模式和实际的矩阵对象。在创建稀疏模式时，我们只需要额外传递局部块的大小。\n\n    ChunkSparsityPattern      sparsity_pattern; \n    ChunkSparseMatrix<double> system_matrix; \n\n// 与  step-7  相同。\n\n    const RefinementMode refinement_mode; \n    ConvergenceTable     convergence_table; \n  }; \n// @sect3{The HDG class implementation}  \n// @sect4{Constructor}  该构造函数与其他例子中的构造函数类似，除了处理多个DoFHandler和FiniteElement对象。请注意，我们为局部DG部分创建了一个有限元系统，包括梯度/通量部分和标量部分。\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解决方案的系统是以类似于其他大多数教程程序的方式设置的。 我们小心翼翼地用我们所有的DoFHandler对象来分配道夫。  @p solution 和 @p system_matrix 对象与全局骨架解决方案一起。\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// 在创建块状稀疏模式时，我们首先创建通常的动态稀疏模式，然后设置块状大小，该大小等于一个面的道夫数，当把它复制到最终的稀疏模式时。\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}  接下来是定义并行装配的本地数据结构。第一个结构 @p PerTaskData 包含了被写入全局矩阵的本地向量和矩阵，而ScratchData包含了我们在本地装配中需要的所有数据。这里有一个变量值得注意，即布尔变量 @p  trace_reconstruct。正如介绍中提到的，我们分两步解决HDG系统。首先，我们为骨架系统创建一个线性系统，通过舒尔补码 $D-CA^{-1}B$  将局部部分浓缩到其中。然后，我们用骨架的解来解决局部部分。对于这两个步骤，我们需要两次元素上的相同矩阵，我们希望通过两个装配步骤来计算。由于大部分的代码是相似的，我们用相同的函数来做这件事，但只是根据我们在开始装配时设置的一个标志在两者之间切换。因为我们需要把这个信息传递给本地的工作程序，所以我们把它存储在任务数据中一次。\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  包含WorkStream中每个线程的持久化数据。 FEValues、矩阵和矢量对象现在应该很熟悉了。 有两个对象需要讨论。  `std::vector<std::vector<unsigned  int> > fe_local_support_on_face` 和  `std::vector<std::vector<unsigned  int> > fe_support_on_face`。 这些用于指示所选择的有限元是否在与 @p fe_local 相关的局部部分和骨架部分 @p fe. 的参考单元的特定面上有支持（非零值）。 我们在构造函数中提取这一信息，并为我们工作的所有单元存储一次。 如果我们不存储这一信息，我们将被迫在每个单元上装配大量的零项，这将大大降低程序的速度。\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  包含WorkStream在对本地解决方案进行后处理时使用的数据  $u^*$  。 它与  @p ScratchData.  类似，但要简单得多。\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 函数与 Step-32 上的函数类似，其中正交公式和更新标志被设置，然后 <code>WorkStream</code> 被用来以多线程的方式进行工作。  @p trace_reconstruct  输入参数用于决定我们是求全局骨架解（false）还是局部解（true）。\n\n// 对于汇编的多线程执行，有一点值得注意的是，`assemble_system_one_cell()`中的局部计算会调用BLAS和LAPACK函数，如果这些函数在deal.II中可用。因此，底层的BLAS/LAPACK库必须支持同时来自多个线程的调用。大多数实现都支持这一点，但有些库需要以特定方式构建以避免问题。例如，在BLAS/LAPACK调用内部没有多线程的情况下编译的OpenBLAS需要在构建时将一个名为`USE_LOCKING'的标志设置为true。\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程序的实际工作由  @p assemble_system_one_cell.  组装局部矩阵  $A, B, C$  在这里完成，同时还有全局矩阵的局部贡献  $D$  。\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//为Dof_handler_local构建迭代器，用于FEValues的reinit函数。\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// 我们首先计算对应于局部-局部耦合的 @p ll_matrix 矩阵（在介绍中称为矩阵 $A$ ）的单元内部贡献，以及局部右手向量。 我们在每个正交点存储基函数、右手边值和对流速度的值，以便快速访问这些场。\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// 脸部条款是在所有元素的所有面上集合起来的。这与更传统的DG方法相反，在组装过程中，每个面只被访问一次。\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// 在求解局部变量时需要已经得到的  $\\hat{u}$  值。\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// 这里我们计算介绍中讨论的稳定参数：由于扩散是1，并且扩散长度尺度被设定为1/5，它只是导致扩散部分的贡献为5，而对流部分的贡献是通过元素边界的居中方案中的对流大小。\n\n            const double tau_stab = (5. + std::abs(convection * normal)); \n\n// 我们存储非零通量和标量值，利用我们在 @p ScratchData. 中创建的 support_on_face 信息。\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// 当  @p trace_reconstruct=false,  我们准备为骨架变量  $\\hat{u}$  组装系统。如果是这种情况，我们必须组装所有与问题相关的局部矩阵：局部-局部、局部-面部、面部-局部和面部-面部。 面-面矩阵被存储为 @p TaskData::cell_matrix, ，这样就可以通过 @p copy_local_to_global将其组装到全局系统中。\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// 注意face_no-local矩阵的符号。 我们在组装时否定了这个符号，这样我们就可以在计算舒尔补时使用 FullMatrix::mmult 的加法。\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// 这最后一个项将 $\\left<w,\\tau u_h\\right>_{\\partial \\mathcal T}$ 项的贡献加入到本地矩阵中。相对于上面的脸部矩阵，我们在两个装配阶段都需要它。\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// 当 @p trace_reconstruct=true, 时，我们在逐个元素的基础上求解局部解。 局部右手边的计算是通过用计算值 @p trace_values替换 @p 计算中的基函数 @p tr_phi。 当然，现在矩阵的符号是减号，因为我们已经把所有的东西移到了方程的另一边。\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// 一旦完成所有局部贡献的组装，我们必须：（1）组装全局系统；（2）计算局部贡献。(1)组装全局系统，或者(2)计算局部解值并保存。无论哪种情况，第一步都是对局部-局部矩阵进行反转。\n\n    scratch.ll_matrix.gauss_jordan(); \n\n// 对于(1)，我们计算舒尔补码，并将其添加到 @p  cell_matrix，介绍中的矩阵 $D$ 。\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// 对于(2)，我们只是求解(ll_matrix). (solution_local) = (l_rhs)。因此，我们用 @p l_rhs 乘以我们已经倒置的局部-局部矩阵，并用 <code>set_dof_values</code> 函数来存储结果。\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// 如果我们处于解题的第一步，即 @sect4{HDG::copy_local_to_global} ，那么我们就把局部矩阵组装到全局系统中。\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}  骨架解是通过使用带有身份预处理程序的BiCGStab求解器来解决的。\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// 一旦我们求出了骨架解，我们就可以以逐个元素的方式求出局部解。 我们通过重新使用相同的 @p assemble_system 函数来做到这一点，但将 @p trace_reconstruct 切换为真。\n\n    assemble_system(true); \n  } \n\n//  @sect4{HDG::postprocess}  \n\n// 后处理方法有两个目的。首先，我们要在度数为 $p+1$ 的元素空间中构造一个后处理的标量变量，我们希望它能在阶 $p+2$ 上收敛。这也是一个逐个元素的过程，只涉及标量解以及局部单元上的梯度。为了做到这一点，我们引入了已经定义好的从头开始的数据以及一些更新标志，并运行工作流来并行地完成这一工作。\n\n// 第二，我们要计算离散化误差，就像我们在  step-7  中做的那样。整个过程与调用 VectorTools::integrate_difference. 相似，区别在于我们如何计算标量变量和梯度变量的误差。在 step-7 中，我们通过计算 @p L2_norm 或 @p H1_seminorm 的贡献来做到这一点。在这里，我们有一个DoFHandler，计算了这两个贡献，并按其矢量分量排序， <code>[0, dim)</code> 为梯度， @p dim 为标量。为了计算它们的值，我们用一个ComponentSelectFunction来计算它们中的任何一个，再加上上面介绍的 @p SolutionAndGradient类，它包含了它们中任何一个的分析部分。最终，我们还计算了后处理的解决方案的L2-误差，并将结果添加到收敛表中。\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// 这是为后处理所做的实际工作。根据介绍中的讨论，我们需要建立一个系统，将DG解的梯度部分投影到后处理变量的梯度上。此外，我们还需要将新的后处理变量的平均值设置为等于标量DG解在单元上的平均值。\n\n// 从技术上讲，梯度的投影是一个有可能填满我们的 @p dofs_per_cell 乘以 @p dofs_per_cell 矩阵的系统，但它是单数（所有行的总和为零，因为常数函数的梯度为零）。因此，我们拿掉一行，用它来强加标量值的平均值。我们为标量部分挑选第一行，尽管我们可以为 $\\mathcal Q_{-p}$ 元素挑选任何一行。然而，如果我们使用FE_DGP元素，第一行将对应常数部分，删除例如最后一行将得到一个奇异系统。这样一来，我们的程序也可以用于这些元素。\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// 集合了所有条款后，我们又可以继续解决这个线性系统。我们对矩阵进行反转，然后将反转结果乘以右手边。另一种方法（数字上更稳定）是只对矩阵进行因式分解，然后应用因式分解。\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}  我们有三组我们想输出的结果：局部解决方案，后处理的局部解决方案，以及骨架解决方案。前两个结果都 \"活 \"在元素体积上，而后者则活在三角形的一维表面上。 我们的 @p output_results 函数将所有的局部解决方案写入同一个vtk文件，尽管它们对应于不同的DoFHandler对象。 骨架变量的图形输出是通过使用DataOutFaces类完成的。\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// 我们首先定义本地解决方案的名称和类型，并将数据添加到  @p data_out.  中。\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// 我们添加的第二个数据项是后处理的解决方案。在这种情况下，它是一个属于不同DoFHandler的单一标量变量。\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> 类的工作原理与 <code>DataOut</code> class when we have a <code>DoFHandler</code> 类似，后者定义了三角形骨架上的解决方案。 我们在此将其视为如此，代码与上面类似。\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// 我们为HDG实现了两种不同的细化情况，就像在 <code>Step-7</code> 中一样：adaptive_refinement和global_refinement。 global_refinement选项每次都会重新创建整个三角形。这是因为我们想使用比一个细化步骤更细的网格序列，即每个方向2、3、4、6、8、12、16...个元素。\n\n// adaptive_refinement模式使用 <code>KellyErrorEstimator</code> 对标量局部解中的非规则区域给出一个体面的指示。\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// 就像在 step-7 中一样，我们将其中两个面的边界指标设置为1，在这里我们要指定诺伊曼边界条件而不是迪里希特条件。由于我们每次都会为全局细化重新创建三角形，所以在每个细化步骤中都会设置标志，而不仅仅是在开始时。\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}  这里的功能与 <code>Step-7</code>  基本相同。我们在10个周期中循环，在每个周期中细化网格。 在最后，收敛表被创建。\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// 与 step-7 相比，收敛表有一个微小的变化：由于我们没有在每个周期内以2的系数细化我们的网格（而是使用2，3，4，6，8，12，...的序列），我们需要告诉收敛率评估这一点。我们通过设置单元格数量作为参考列，并额外指定问题的维度来实现这一目的，这为单元格数量和网格大小之间的关系提供了必要的信息。\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// 现在是对主类的三次调用，完全类似于  step-7  。\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": "#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": "// 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": "\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": "#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        // 使用直接法计算相机运动\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": "// [[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": "#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 * @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// 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": "#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": "#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": "#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": "//          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": "#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": "//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 <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*\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 <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": "// 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–66, 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": "#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 <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": "#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#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": "// // [[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": "#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 * 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änkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_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 * @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": "/* 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": "#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": "/*\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": "#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évy _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": "#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//  GPUTSDFVolume.hpp\n//  A GPU Based TSDF\n//\n//  Created by Dave on 11/03/2016.\n//  Copyright © 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 * @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": "#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": "/*\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": "// 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": "/******************************************************************************\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 * 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": "#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": "#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": "// 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": "/* 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": "#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// 辺\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// グラフ 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// 最短経路探索(非負閉路)\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 _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": "// 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": "#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": "/*\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": "/* 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": "/*  calculate CMB related observables, depends on Cosmology calculator(s).\n    \n    Shift parameter: R = (1+z*) * DA(z�6�5) * 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//  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": "// #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": "#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": "#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": "#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// 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": "/****************************************************************************\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": "/* -*- 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": "#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": "/* 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 <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": "// 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": "#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": "#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": "#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": "\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": "// 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 * @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": "// \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": "#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/*!\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": "//==================================================================================================\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": "#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\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// 这些第一个包含文件在前面的例子中都已经处理过了，所以我们不再解释其中的内容。\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// 在这个例子中，我们将不使用DoFHandler类默认使用的编号方案，而是使用Cuthill-McKee算法对其进行重新编号。正如在 step-2 中已经解释过的，必要的函数被声明在以下文件中。\n\n#include <deal.II/dofs/dof_renumbering.h> \n\n// 然后我们将展示一个小技巧，如何确保对象在仍在使用时不被删除。为此，deal.II有一个SmartPointer辅助类，它被声明在这个文件中。\n\n#include <deal.II/base/smartpointer.h> \n\n// 接下来，我们要使用介绍中提到的函数 VectorTools::integrate_difference() ，我们要使用一个ConvergenceTable，在运行过程中收集所有重要的数据，并在最后以表格形式打印出来。这些来自于以下两个文件。\n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/base/convergence_table.h> \n\n// 最后，我们需要使用FEFaceValues类，它与FEValues类在同一个文件中声明。\n\n#include <deal.II/fe/fe_values.h> \n\n#include <array> \n#include <fstream> \n#include <iostream> \n\n// 在我们继续实际执行之前的最后一步是打开一个命名空间 <code>Step7</code> ，我们将把所有的东西放进去，正如在介绍的最后所讨论的，并把命名空间 <code>dealii</code> 的成员导入其中。\n\nnamespace Step7 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n// 在实现实际求解的类之前，我们首先声明和定义一些代表右手边和求解类的函数类。由于我们要将数值得到的解与精确的连续解进行比较，我们需要一个代表连续解的函数对象。另一方面，我们需要右手边的函数，而这个函数当然与解共享一些特征。为了减少如果我们必须同时改变两个类中的某些东西而产生的依赖性，我们将两个函数的共同特征移到一个基类中。\n\n// 解（正如介绍中所解释的，我们选择三个指数之和）和右手边的共同特征是：指数的数量，它们的中心，以及它们的半宽。我们在以下类别中声明它们。由于指数的数量是一个编译时的常数，我们使用一个固定长度的 <code>std::array</code> 来存储中心点。\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// 表示指数中心和宽度的变量刚刚被声明，现在我们还需要给它们赋值。在这里，我们可以展示另一个小小的模板魔法，即我们如何根据维度给这些变量分配不同的值。我们将在程序中只使用2维的情况，但我们展示1维的情况是为了说明一个有用的技术。\n\n// 首先我们为1d情况下的中心赋值，我们将中心等距离地放在-1/3、0和1/3处。这个定义的<code>template &lt;&gt;</code>头显示了一个明确的专业化。这意味着，这个变量属于一个模板，但是我们并没有向编译器提供一个模板，让它通过用一些具体的值来替代 <code>dim</code> 来专门化一个具体的变量，而是自己提供一个专门化，在这个例子中是 <code>dim=1</code>  。如果编译器在模板参数等于1的地方看到了对这个变量的引用，它就知道它不需要通过替换 <code>dim</code> 从模板中生成这个变量，而是可以立即使用下面的定义。\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// 同样地，我们可以为 <code>dim=2</code> 提供一个明确的特殊化。我们将2d情况下的中心放置如下。\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// 还需要给指数的半宽指定一个值。我们希望对所有维度使用相同的数值。在这种情况下，我们只需向编译器提供一个模板，它可以通过用一个具体的值替换 <code>dim</code> 来生成一个具体的实例。\n\n  template <int dim> \n  const double SolutionBase<dim>::width = 1. / 8.; \n\n// 在声明和定义了解和右手的特征后，我们可以声明代表这两者的类。它们都代表连续函数，所以它们都派生于Function&lt;dim&gt;基类，它们也继承了SolutionBase类中定义的特征。\n\n// 实际的类是在下面声明的。请注意，为了计算数值解与连续解在L2和H1（半）准则下的误差，我们必须提供精确解的值和梯度。这比我们在以前的例子中所做的要多，在以前的例子中，我们所提供的只是一个或一列点的值。幸运的是，Function类也有用于梯度的虚拟函数，所以我们可以简单地重载Function基类中各自的虚拟成员函数。请注意，一个函数在 <code>dim</code> 空间维度上的梯度是一个大小为 <code>dim</code> 的向量，即一个等级为1、维度为 <code>dim</code> 的张量。就像其他很多东西一样，该库提供了一个合适的类。这个类的一个新特点是，它明确地使用了张量对象，之前在  step-3  和  step-4  中作为中间词出现。张量是标量（等级为零的张量）、向量（等级为一的张量）和矩阵（等级为二的张量）以及高维对象的概括。张量类需要两个模板参数：张量等级和张量维度。例如，在这里我们使用等级为一的张量（向量），维度为 <code>dim</code> (so they have <code>dim</code> 项）。虽然这比使用Vector的灵活性要差一些，但当编译时知道向量的长度时，编译器可以生成更快的代码。此外，指定一个秩为1、维数为 <code>dim</code> 的张量，可以保证张量具有正确的形状（因为它是内置于对象本身的类型中的），所以编译器可以为我们抓住大多数与尺寸有关的错误。\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//精确解类的值和梯度的实际定义是根据其数学定义，不需要过多解释。\n\n// 唯一值得一提的是，如果我们访问一个依赖模板的基类的元素（在本例中是SolutionBase&lt;dim&gt;的元素），那么C++语言会强迫我们写  <code>this-&gt;source_centers</code>  ，对于基类的其他成员也是如此。如果基类不依赖模板，C++就不需要 <code>this-&gt;</code> 的限定。这一点的原因很复杂，C++书籍会在<i>two-stage (name) lookup</i>这句话下进行解释，在deal.II FAQs中也有很长的描述。\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// 同样，这也是对解的梯度的计算。 为了从指数的贡献中积累梯度，我们分配了一个对象  <code>return_value</code>  ，它表示秩  <code>1</code>  和维  <code>dim</code>  的张量的数学量。它的默认构造函数将其设置为只包含零的向量，所以我们不需要明确关心它的初始化。\n\n// 注意，我们也可以把对象的类型定为Point&lt;dim&gt;，而不是Tensor&lt;1,dim&gt;。等级1的张量和点几乎是可以交换的，而且只有非常细微的数学含义不同。事实上，Point&lt;dim&gt;类是由Tensor&lt;1,dim&gt;类派生出来的，这就弥补了它们的相互交换能力。它们的主要区别在于它们在逻辑上的含义：点是空间中的点，比如我们要评估一个函数的位置（例如，见这个函数的第一个参数的类型）。另一方面，秩1的张量具有相同的变换属性，例如，当我们改变坐标系时，它们需要以某种方式旋转；然而，它们不具有点所具有的相同内涵，只是比坐标方向所跨越的空间更抽象的对象。事实上，梯度生活在 \"对等 \"的空间中，因为它们的分量的维度不是长度，而是长度上的一个）。\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// 对于梯度，注意它的方向是沿着（x-x_i），所以我们把这个距离向量的倍数加起来，其中的因子是由指数给出。\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// 除了代表精确解的函数外，我们还需要一个函数，在组装离散方程的线性系统时，我们可以将其作为右手。这可以通过下面的类和其函数的定义来实现。请注意，这里我们只需要函数的值，而不是它的梯度或高阶导数。\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// 右手边的值是由解的负拉普拉斯加上解本身给出的，因为我们要解决亥姆霍兹方程的问题。\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// 第一个贡献是拉普拉斯的。\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// 而第二个是解决方案本身。\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// 然后我们需要做所有工作的类。除了它的名字，它的接口与前面的例子基本相同。\n\n// 其中一个不同点是，我们将在几种模式下使用这个类：用于不同的有限元，以及用于自适应细化和全局细化。全局细化还是自适应细化的决定是通过在类的顶部声明的枚举类型传达给该类的构造函数的。构造函数接收一个有限元对象和细化模式作为参数。\n\n// 除了 <code>process_solution</code> 函数外，其余的成员函数与之前一样。在解被计算出来后，我们对它进行一些分析，比如计算各种规范的误差。为了实现一些输出，它需要细化周期的编号，因此得到它作为一个参数。\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// 现在是这个类的数据元素。在我们以前的例子中已经使用过的变量中，只有有限元对象不同。这个类的对象所操作的有限元被传递给这个类的构造函数。它必须存储一个指向有限元的指针，供成员函数使用。现在，对于本类来说，这没有什么大不了的，但由于我们想在这些程序中展示技术而不是解决方案，我们将在这里指出一个经常出现的问题--当然也包括正确的解决方案。\n\n// 考虑以下在所有示例程序中出现的情况：我们有一个三角形对象，我们有一个有限元对象，我们还有一个DoFHandler类型的对象，它同时使用前两个对象。这三个对象的寿命与其他大多数对象相比都相当长：它们基本上是在程序开始时或外循环时设置的，并在最后被销毁。问题是：我们能否保证DoFHandler使用的两个对象的寿命至少与它们被使用的时间相同？这意味着DoFHandler必须对其他对象的销毁情况有一定的了解。\n\n// 我们将在这里展示库如何设法找出对一个对象仍有活动的引用，并且从使用对象的角度来看，该对象仍然活着。基本上，该方法是沿着以下思路进行的：所有受到这种潜在危险的指针的对象都来自一个叫做Subscriptor的类。例如，Triangulation、DoFHandler和FiniteElement类的一个基类都派生于Subscriptor。后面这个类并没有提供太多的功能，但是它有一个内置的计数器，我们可以订阅这个计数器，因此这个类的名字就叫 \"订阅器\"。每当我们初始化一个指向该对象的指针时，我们可以增加它的使用计数器，而当我们移开指针或不再需要它时，我们再减少计数器。这样，我们就可以随时检查有多少个对象还在使用该对象。此外，该类需要知道一个指针，它可以用来告诉订阅对象它的无效性。\n\n// 如果一个从Subscriptor类派生出来的对象被销毁，它也必须调用Subscriptor类的析构函数。在这个析构器中，我们使用存储的指针告诉所有订阅的对象该对象的无效性。当对象出现在移动表达式的右侧时，也会发生同样的情况，也就是说，在操作后它将不再包含有效的内容。在试图访问被订阅的对象之前，订阅类应该检查存储在其相应指针中的值。\n\n// 这正是SmartPointer类正在做的事情。它基本上就像一个指针一样，也就是说，它可以被取消引用，可以被分配给其他指针，等等。除此之外，当我们试图解除引用这个类所代表的指针时，它使用上面描述的机制来找出这个指针是否是悬空的。在这种情况下，会抛出一个异常。\n\n// 在本例程序中，我们希望保护有限元对象，避免因某种原因导致所指向的有限元在使用中被破坏。因此，我们使用了一个指向有限元对象的SmartPointer；由于有限元对象在我们的计算中实际上从未改变，我们传递了一个const FiniteElement&lt;dim&gt;作为SmartPointer类的模板参数。请注意，这样声明的指针是在构造求解对象时被分配的，并在销毁时被销毁，所以对有限元对象销毁的锁定贯穿了这个HelmholtzProblem对象的生命周期。\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// 倒数第二个变量存储了传递给构造函数的细化模式。由于它只在构造函数中设置，我们可以声明这个变量为常数，以避免有人不由自主地设置它（例如在一个 \"if \"语句中，==偶然被写成=）。\n\n    const RefinementMode refinement_mode; \n\n// 对于每个细化级别，一些数据（比如单元格的数量，或者数值解的L2误差）将被生成，并在之后打印出来。TableHandler可以用来收集所有这些数据，并在运行结束后以简单文本或LaTeX格式的表格输出。这里我们不仅使用TableHandler，还使用了派生类ConvergenceTable，它还可以评估收敛率。\n\n    ConvergenceTable convergence_table; \n  }; \n// @sect3{The HelmholtzProblem class implementation}  \n// @sect4{HelmholtzProblem::HelmholtzProblem constructor}  \n\n// 在这个类的构造函数中，我们只设置作为参数传递的变量，并将DoF处理程序对象与三角形（不过目前是空的）相关联。\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// 下面的函数设置了自由度、矩阵和向量的大小等。它的大部分功能在前面的例子中已经展示过了，唯一不同的是在第一次分配自由度后立即进行重新编号的步骤。\n\n// 重编自由度并不难，只要你使用库中的一种算法。它只需要一行代码。这方面的更多信息可以在  step-2  中找到。\n\n// 但是请注意，当你对自由度进行重新编号时，你必须在分配自由度后立即进行，因为诸如悬空节点、稀疏模式等都取决于重新编号后的绝对数。\n\n// 我们在这里介绍重新编号的原因是，这是一个相对便宜的操作，但往往有一个有利的效果。虽然CG迭代本身与自由度的实际排序无关，但我们将使用SSOR作为一个预处理程序。SSOR会经过所有的自由度，并做一些取决于之前发生的操作；因此，SSOR操作并不独立于自由度的编号，而且众所周知，它的性能会通过使用重新编号技术得到改善。一个小实验表明，确实如此，例如，用这里使用的Q1程序进行自适应细化的第五个细化周期的CG迭代次数，在没有重编号的情况下为40次，而在重编号的情况下为36次。对于这个程序中的所有计算，一般都可以观察到类似的节省。\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// 为手头的问题组装方程组，主要是像之前的例子程序一样。然而，无论如何，有些东西已经改变了，所以我们对这个函数进行了相当广泛的评论。\n\n// 在该函数的顶部，你会发现通常的各种变量声明。与以前的程序相比，重要的是我们希望解决的问题也是双二次元的，因此必须使用足够精确的正交公式。此外，我们需要计算面的积分，即 <code>dim-1</code> 维的对象。那么，面的正交公式的声明就很直接了。\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// 然后我们需要一些对象来评估正交点上的形状函数的值、梯度等。虽然看起来用一个对象来做域积分和面积分应该是可行的，但是有一个微妙的区别，因为域积分的权重包括域中单元的度量，而面积分的正交需要低维流形中面的度量。在内部，这两个类都根植于一个共同的基类，它完成了大部分工作，并为域积分和面积分提供了相同的接口。\n\n// 对于亥姆霍兹方程的双线性形式的域积分，我们需要计算值和梯度，以及正交点的权重。此外，我们需要实细胞上的正交点（而不是单位细胞上的正交点）来评估右手边的函数。我们用来获取这些信息的对象是之前讨论过的FEValues类。\n\n// 对于面积分，我们只需要形状函数的值以及权重。我们还需要实心单元上的法向量和正交点，因为我们要从精确解对象中确定Neumann值（见下文）。给我们提供这些信息的类被称为FEFaceValues。\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// 然后我们需要一些从以前的例子中已经知道的对象。一个表示右侧函数的对象，它在单元格上正交点的值，单元格矩阵和右侧，以及单元格上自由度的指数。\n\n// 请注意，我们对右手边对象的操作只是查询数据，绝不会改变该对象。因此我们可以声明它  <code>const</code>  。\n\n    const RightHandSide<dim> right_hand_side; \n    std::vector<double>      rhs_values(n_q_points); \n\n// 最后我们定义一个表示精确解函数的对象。我们将用它来计算边界上的诺伊曼值。通常情况下，我们当然会使用一个单独的对象来计算，特别是由于精确解通常是未知的，而诺伊曼值是规定的。然而，我们将有点偷懒，使用我们已经有的信息。当然，现实生活中的程序会在这里采取其他方式。\n\n    Solution<dim> exact_solution; \n\n// 现在是所有单元格的主循环。这与之前的例子基本没有变化，所以我们只对有变化的地方进行评论。\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// 第一件改变的事情是双线性形式。它现在包含了亥姆霍兹方程的附加项。\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// 然后是右手边的第二项，即等高线积分。首先我们要找出这个单元格的面与边界部分Gamma2的交点是否为非零。为此，我们对所有面进行循环，检查其边界指示器是否等于 <code>1</code> ，这是我们在下面的 <code>run()</code> 函数中为组成Gamma2的边界部分指定的值。(边界指示器的默认值是 <code>0</code> ，所以只有在我们明确设置的情况下，面的指示器才能等于 <code>1</code> 。)\n\n        for (const auto &face : cell->face_iterators()) \n          if (face->at_boundary() && (face->boundary_id() == 1)) \n            { \n\n// 如果我们来到这里，那么我们已经找到了一个属于Gamma2的外部面。接下来，我们必须计算形状函数的值和其他数量，这些都是我们在计算轮廓积分时需要的。这是用 <code>reinit</code> 函数完成的，我们已经从FEValue类中知道了。\n\n              fe_face_values.reinit(cell, face); \n\n// 然后，我们可以通过在所有的正交点上进行循环来进行积分。        在每个正交点上，我们首先计算法线导数的值。我们使用精确解的梯度和从 <code>fe_face_values</code> 对象中获得的当前正交点处的面的法向量来进行计算。然后用它来计算这个面对右手边的额外贡献。\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// 现在我们有了本单元的贡献，我们可以把它转移到全局矩阵和右手边的向量，就像之前的例子一样。\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\n// 然而，我们注意到，现在我们插值边界值的边界指标（由 <code>interpolate_boundary_values</code> 的第二个参数表示）不再代表整个边界了。相反，它是我们没有指定其他指标的那部分边界（见下文）。因此，边界上不属于Gamma1的自由度被排除在边界值的插值之外，就像我们希望的那样。\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// 解方程组的方法与之前一样。\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// 现在是做网格细化的函数。根据传递给构造函数的细化模式，我们进行全局或适应性细化。\n\n// 全局细化很简单，所以没有什么可评论的。 在适应性细化的情况下，我们使用的函数和类与前面的例子程序相同。请注意，我们可以将诺伊曼边界与迪里切特边界区别对待，事实上在这里也应该这样做，因为我们在部分边界上有诺伊曼边界条件，但是由于我们在这里没有描述诺伊曼值的函数（我们只是在组装矩阵时从精确解中构造这些值），我们省略了这个细节，尽管以严格正确的方式做这些并不难添加。\n\n// 在开关的最后，我们有一个看起来稍微有点奇怪的默认情况：一个 <code>Assert</code> statement with a <code>false</code> 条件。由于 <code>Assert</code> 宏在条件为假的时候会引发一个错误，这意味着只要我们碰到这个语句，程序就会被中止。这是故意的。现在我们只实现了两种细化策略（全局性和适应性），但有人可能想增加第三种策略（例如，具有不同细化标准的适应性），并在决定细化模式的枚举中增加第三个成员。如果不是switch语句的默认情况，这个函数会简单地运行到结束而不做任何事情。这很可能不是原意。因此，在deal.II库中，你会发现一个防御性的编程技术，那就是总是有默认的中止案例，以确保在switch语句中列出案例时没有考虑的值最终被抓住，并迫使程序员添加代码来处理它们。我们还将在下面的其他地方使用同样的技术。\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// 最后，我们想在计算出解决方案后对其进行处理。为此，我们用各种（半）准则对误差进行积分，并生成表格，这些表格以后将被用来以漂亮的格式显示对连续解的收敛情况。\n\n  template <int dim> \n  void HelmholtzProblem<dim>::process_solution(const unsigned int cycle) \n  { \n\n// 我们的第一个任务是计算误差准则。为了整合计算出的数值解和连续解之间的差异（由本文件顶部定义的Solution类描述），我们首先需要一个向量来保存每个单元的误差准则。由于16位数的精度对这些数量来说并不那么重要，我们通过使用 <code>float</code> 而不是 <code>double</code> 值来节省一些内存。\n\n// 下一步是使用库中的一个函数来计算每个单元的L2准则的误差。 我们必须将DoF处理程序对象、保存数值解的节点值的向量、作为函数对象的连续解、它应将每个单元上的误差规范放入的向量、计算该规范的正交规则，以及要使用的规范类型传递给它。这里，我们使用高斯公式，在每个空间方向上有三个点，并计算L2规范。\n\n// 最后，我们想得到全局L2准则。这当然可以通过对每个单元格上的规范的平方求和，然后取该值的平方根来得到。这相当于取每个单元格上的规范向量的l2（小写 <code>l</code>  ）规范。\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// 通过同样的程序，我们可以得到H1半正态。我们重新使用 <code>difference_per_cell</code> 向量，因为在计算了上面的 <code>L2_error</code> 变量后，它不再被使用。全局 $H^1$ 半正态误差的计算方法是：取每个单元格上的误差的平方和，然后取其平方根--这个操作由 VectorTools::compute_global_error. 方便地执行。\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// 最后，我们计算出最大法线。当然，我们实际上不能计算域中*所有*点上的真正的最大误差，而只能计算有限的评估点上的最大误差，为了方便起见，我们仍然称之为 \"正交点\"，并用一个正交类型的对象来表示，尽管我们实际上没有进行任何积分。\n\n// 然后是我们想在哪些点上精确地进行评估的问题。事实证明，我们得到的结果相当敏感地取决于所使用的 \"正交 \"点。还有一个超融合的问题。在某些网格上，对于多项式程度 $k\\ge 2$ ，有限元解决方案在节点点以及Gauss-Lobatto点上特别精确，比随机选择的点要精确得多。(参见 @cite Li2019 和第1.2节的讨论和参考文献，以了解更多这方面的信息)。换句话说，如果我们有兴趣找到最大的差值 $u(\\mathbf x)-u_h(\\mathbf x)$ ，那么我们应该看一下 $\\mathbf x$ ，这些点特别不属于这种 \"特殊 \"的点，而且我们特别不应该用`QGauss(fe->degree+1)`来定义我们评估的地方。相反，我们使用一个特殊的正交规则，该规则是通过梯形规则迭代有限元的度数乘以2再加上每个空间方向的1而得到的。请注意，QIterated类的构造函数需要一个一维正交规则和一个数字，这个数字告诉它在每个空间方向重复这个规则的频率。\n\n// 使用这个特殊的正交规则，我们就可以尝试找到每个单元的最大误差。最后，我们通过调用 VectorTools::compute_global_error. 来计算每个单元上的L无穷大误差的全局L无穷大误差。\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// 在所有这些错误被计算出来之后，我们最终写出一些输出。此外，我们通过指定列的键和值将重要的数据添加到TableHandler中。 注意，没有必要事先定义列的键 -- 只需添加值即可，列将按照第一次添加值的顺序被引入到表中。\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// 和前面的例子程序一样， <code>run</code> 函数控制执行的流程。基本布局与前面的例子一样：在连续细化的网格上有一个外循环，在这个循环中首先是问题的设置，组装线性系统，求解，和后处理。\n\n// 主循环的第一个任务是创建和细化网格。这和前面的例子一样，唯一的区别是我们想把边界的一部分标记为诺伊曼型，而不是迪里希型。\n\n// 为此，我们将使用以下惯例。属于Gamma1的面将有边界指示器 <code>0</code> （这是默认的，所以我们不需要明确设置），属于Gamma2的面将使用 <code>1</code> 作为边界指示器。 为了设置这些值，我们在所有单元格上循环，然后在给定单元格的所有面上循环，检查它是否是我们想用Gamma2表示的边界的一部分，如果是，则将其边界指示器设置为 <code>1</code>  。在本程序中，我们认为左边和底部的边界是Gamma2。我们通过询问一个面的中点的x或y坐标（即向量分量0和1）是否等于-1来确定一个面是否是该边界的一部分，但我们必须给出一些小的回旋余地，因为比较在中间计算中会有四舍五入的浮点数是不稳定的。\n\n// 值得注意的是，我们必须在这里对所有的单元格进行循环，而不仅仅是活动单元格。原因是在细化时，新创建的面会继承其父面的边界指标。如果我们现在只设置活动面的边界指示器，粗化一些单元并在以后细化它们，它们将再次拥有我们没有修改的父单元的边界指示器，而不是我们想要的那个。因此，我们必须改变Gamma2上所有单元的面的边界指标，无论它们是否处于活动状态。另外，我们当然也可以在最粗的网格上完成这项工作（即在第一个细化步骤之前），之后才细化网格。\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// 接下来的步骤在前面的例子中已经知道了。这主要是每个有限元程序的基本设置。\n\n        setup_system(); \n\n        assemble_system(); \n        solve(); \n\n// 在这一连串的函数调用中，最后一步通常是对自己感兴趣的数量的计算解进行评估。这在下面的函数中完成。由于该函数产生的输出显示了当前细化步骤的编号，我们将这个编号作为一个参数传递。\n\n        process_solution(cycle); \n      } \n// @sect5{Output of graphical data}  \n\n// 在最后一次迭代后，我们在最细的网格上输出解决方案。这是用下面的语句序列完成的，我们在以前的例子中已经讨论过了。第一步是生成一个合适的文件名（这里称为 <code>vtk_filename</code> ，因为我们想以VTK格式输出数据；我们添加前缀以区分该文件名与下面其他输出文件的文件名）。在这里，我们通过网格细化算法来增加名称，和上面一样，我们要确保在增加了另一种细化方法而没有通过下面的switch语句来处理的情况下，中止程序。\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// 我们用一个后缀来增加文件名，表示我们在计算中使用的有限元。为此，有限元基类将每个坐标变量中形状函数的最大多项式程度存储为一个变量 <code>degree</code> ，我们在切换语句中使用（注意，双线性形状函数的多项式程度实际上是2，因为它们包含术语 <code>x*y</code> ；但是，每个坐标变量的多项式程度仍然只有1）。我们再次使用同样的防御性编程技术来防止多项式阶数具有意外值的情况，在switch语句的默认分支中使用 <code>Assert (false, ExcNotImplemented())</code> 这个成语。\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// 一旦我们有了输出文件的基本名称，我们就为VTK输出添加一个合适的扩展名，打开一个文件，并将解决方案的向量添加到将进行实际输出的对象中。\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// 现在像以前一样建立中间格式是下一步。我们在这里再介绍一下deal.II的一个特点。其背景如下：在这个函数的一些运行中，我们使用了双二次元的有限元。然而，由于几乎所有的输出格式都只支持双线性数据，所以数据只写成了双线性，信息因此而丢失。 当然，我们不能改变图形程序接受其输入的格式，但我们可以用不同的方式来写数据，这样我们就能更接近于四次方近似中的信息。例如，我们可以把每个单元写成四个子单元，每个子单元都有双线数据，这样我们在三角图中的每个单元都有九个数据点。当然，图形程序显示的这些数据仍然只是双线性的，但至少我们又给出了一些我们拥有的信息。\n\n// 为了允许在每个实际单元中写入多个子单元， <code>build_patches</code> 函数接受一个参数（默认为 <code>1</code>  ，这就是为什么你在之前的例子中没有看到这个参数）。这个参数表示每个空间方向上的每个单元应被细分为多少个子单元来输出。例如，如果你给出  <code>2</code>  ，这将导致二维的4个单元和三维的8个单元。对于二次元元素，每个空间方向的两个子单元显然是正确的选择，所以这就是我们所选择的。一般来说，对于多项式阶的元素 <code>q</code>, we use <code>q</code> 细分，元素的顺序也是按照上述方式确定的。\n\n// 有了这样生成的中间格式，我们就可以实际写入图形输出了。\n\n    data_out.build_patches(fe->degree); \n    data_out.write_vtk(output); \n// @sect5{Output of convergence tables}  \n\n// 在图形输出之后，我们还想从我们在  <code>process_solution</code>  中进行的误差计算中生成表格。在那里，我们用每个细化步骤的单元格数量以及不同规范的误差来填充一个表格对象。\n\n// 为了使这些数据有更好的文本输出，我们可能想设置输出时写入数值的精度。我们使用3位数，这对误差规范来说通常是足够的。默认情况下，数据是以定点符号写入的。然而，对于人们想看到的科学符号的列，另一个函数调用设置了 <code>scientific_flag</code> to <code>true</code>  ，导致数字的浮点表示。\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// 对于输出到LaTeX文件的表格，默认的列的标题是作为参数给 <code>add_value</code> 函数的键。要想拥有不同于默认的TeX标题，你可以通过以下函数调用来指定它们。注意，`\\\\'被编译器简化为`\\'，这样，真正的TeX标题就是，例如，` $L^\\infty$  -error'。\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// 最后，表格中每一列的默认LaTeX格式是`c'（居中）。要指定一个不同的（如`右'），可以使用以下函数。\n\n    convergence_table.set_tex_format(\"cells\", \"r\"); \n    convergence_table.set_tex_format(\"dofs\", \"r\"); \n\n// 在这之后，我们终于可以把表写到标准输出流 <code>std::cout</code> （在多写一行空行之后，使事情看起来更漂亮）。请注意，文本格式的输出是非常简单的，标题可能不会直接打印在特定的列上面。\n\n    std::cout << std::endl; \n    convergence_table.write_text(std::cout); \n\n// 该表也可以写成LaTeX文件。 在调用 \"latex filename \"和例如 \"xdvi filename \"后，可以查看（很好的）格式化的表格，其中filename是我们现在要写入输出的文件名。我们构建文件名的方法和以前一样，但有一个不同的前缀 \"error\"。\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// 在全局细化的情况下，输出收敛率也可能是有意义的。这可以通过ConvergenceTable提供的比常规TableHandler的功能来实现。然而，我们只为全局细化做这件事，因为对于自适应细化来说，确定像收敛顺序这样的事情是比较麻烦的。在此，我们还展示了一些可以用表来做的其他事情。\n\n    if (refinement_mode == global_refinement) \n      { \n\n// 第一件事是，人们可以将单个列组合在一起，形成所谓的超级列。从本质上讲，这些列保持不变，但被分组的那些列将得到一个贯穿一组中所有列的标题。例如，让我们把 \"周期 \"和 \"单元格 \"两列合并成一个名为 \"n单元格 \"的超级列。\n\n        convergence_table.add_column_to_supercolumn(\"cycle\", \"n cells\"); \n        convergence_table.add_column_to_supercolumn(\"cells\", \"n cells\"); \n\n// 接下来，没有必要总是输出所有的列，或者按照它们在运行过程中最初添加的顺序。选择和重新排列列的工作方式如下（注意，这包括超级列）。\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// 对于在这之前发生在ConvergenceTable上的一切，使用一个简单的TableHandler就足够了。事实上，ConvergenceTable是由TableHandler派生出来的，但它提供了自动评估收敛率的额外功能。例如，下面是我们如何让表计算减少率和收敛率（收敛率是减少率的二进制对数）。\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// 这些函数的每一次调用都会产生一个额外的列，与原来的列（在我们的例子中是 \"L2 \"和 \"H1 \"列）合并成一个超级列。\n\n// 最后，我们想再次写下这个收敛图，首先写到屏幕上，然后以LaTeX格式写到磁盘上。文件名还是按照上面的方法构建。\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// 在进入 <code>main()</code> 之前的最后一步是关闭命名空间 <code>Step7</code> ，我们已经把这个程序所需要的一切都放在这个命名空间里。\n\n} // namespace Step7 \n// @sect3{Main function}  \n\n// 主函数主要和以前一样。唯一不同的是，我们解了三次，一次是Q1和适应性细化，一次是Q1元素和全局细化，一次是Q2元素和全局细化。\n\n// 由于我们在下面为两个空间维度实例化了几个模板类，我们通过在函数的开头声明一个常数来表示空间维度的数量，使之更加通用。如果你想在1d或2d中运行程序，那么你只需要改变这个实例，而不是下面的所有用法。\n\nint main() \n{ \n  const unsigned int dim = 2; \n\n  try \n    { \n      using namespace dealii; \n      using namespace Step7; \n\n// 现在是对主类的三次调用。每个调用都被封锁在大括号中，以便在区块结束时和我们进入下一个运行之前销毁各自的对象（即有限元和HelmholtzProblem对象）。这就避免了变量名称的冲突，也确保了在三次运行中的一次运行结束后立即释放内存，而不是只在 <code>try</code> 块的末尾释放。\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": "/**\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": "#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": "#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 – this 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": "// 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": "\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": "//============================================================================\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": "// -----------------------------------------------------------------------\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": "// 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 <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": "/* =========================================================================\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": "/* 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\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 \"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": "//==================================================================================================\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": "/*\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": "#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": "#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": "#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": "/**\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": "#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// © 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": "#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": "/*\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": "#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": "// 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": "/*\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": "// Author: Henrique Mendonça <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 <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": "//-----------------------------------------------------------------------------\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": "/*! \\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": "// -*- 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": "//==============================================================================\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": "//\n//  Jacobian.cpp\n//  Eigen_test\n//\n//  Created by Emil Iliev on 18.10.19.\n//  Copyright © 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 \"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": "#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": "/*\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// 我们首先包括所有必要的deal.II头文件和一些C++相关的文件。这第一个头文件将使我们能够访问一个数据结构，使我们能够在其中存储任意的数据。\n\n#include <deal.II/algorithms/general_data_storage.h> \n\n// 接下来是一些核心类，包括一个提供时间步进的实现。\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// 然后是一些标题，定义了一些有用的坐标变换和运动学关系，这些关系在非线性弹性中经常出现。\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// 下面两个标头提供了我们进行自动微分所需的所有功能，并使用deal.II可以利用的符号计算机代数系统。所有自动微分和符号微分封装类的头文件，以及任何需要的辅助数据结构，都被收集在这些统一的头文件中。\n\n#include <deal.II/differentiation/ad.h> \n#include <deal.II/differentiation/sd.h> \n\n// 包括这个头文件使我们有能力将输出写入文件流中。\n\n#include <fstream> \n\n// 按照惯例，整个教程程序被定义在它自己独特的命名空间中。\n\nnamespace Step71 \n{ \n  using namespace dealii; \n// @sect3{An introductory example: The fundamentals of automatic and symbolic differentiation}  \n\n// 自动和象征性的区分有一些神奇和神秘的特质。尽管在一个项目中使用它们会因多种原因而受益，但了解如何使用这些框架或如何利用它们的障碍可能会超过试图将它们（可靠地）整合到工作中的开发者的耐心。\n\n// 尽管作者希望能够成功地说明这些工具是如何被整合到有限元建模的工作流程中的，但最好还是先退一步，从基础开始。因此，一开始，我们先看看如何使用这两个框架来区分一个 \"简单 \"的数学函数，这样就可以牢固地建立和理解基本的操作（包括它们的顺序和功能），并使其复杂程度降到最低。在本教程的第二部分，我们将把这些基本原理付诸实践，并在此基础上进一步发展。\n\n// 伴随着对使用框架的算法步骤的描述，我们将对它们*可能在后台做的事情有一个简化的看法。这种描述在很大程度上是为了帮助理解，我们鼓励读者查看 @ref auto_symb_diff 模块文档，以获得对这些工具实际工作的更正式描述。\n\n//  @sect4{An analytical function}  \n  namespace SimpleExample \n  { \n\n// 为了让读者相信这些工具在实践中确实有用，让我们选择一个函数，用手计算分析导数并不难。只是它的复杂程度足以让你考虑是否真的要去做这个练习，也可能让你怀疑你是否完全确定你对其导数的计算和实现是正确的。当然，问题的关键在于，函数的微分在某种意义上是相对公式化的，应该是计算机擅长的事情--如果我们能在现有的软件基础上理解这些规则，我们就不必费力地自己做了。\n\n// 我们为此选择了双变量三角函数 $f(x,y) = \\cos\\left(\\frac{y}{x}\\right)$ 。注意，这个函数是以数字类型为模板的。这样做是因为我们经常（但不总是）可以使用特殊的自动微分和符号类型来替代实数或复数类型，然后这些类型将执行一些基本的计算，例如评估一个函数值及其导数。我们将利用这一特性，确保我们只需要定义一次我们的函数，然后就可以在我们希望对其进行微分操作的任何情况下重新使用。\n\n    template <typename NumberType> \n    NumberType f(const NumberType &x, const NumberType &y) \n    { \n      return std::cos(y / x); \n    } \n\n// 我们没有立即揭示这个函数的导数，而是向前声明返回导数的函数，并将它们的定义推迟到以后。正如函数名称所暗示的，它们分别返回导数  $\\frac{df(x,y)}{dx}$  。\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// 最后是  $\\frac{d^{2}f(x,y)}{dy^{2}}$  。\n\n    double d2f_dy_dy(const double x, const double y); \n// @sect4{Computing derivatives using automatic differentiation}  \n\n// 首先，我们将使用AD作为工具，为我们自动计算导数。我们将用参数`x`和`y`来评估函数，并期望得到的值和所有的导数都能在给定的公差范围内匹配。\n\n    void \n    run_and_verify_ad(const double x, const double y, const double tol = 1e-12) \n    { \n\n// 我们的函数 $f(x,y)$ 是一个标量值函数，其参数代表代数计算或张量计算中遇到的典型输入变量。由于这个原因， Differentiation::AD::ScalarFunction 类是合适的包装类，可以用来做我们需要的计算。(作为比较，如果函数参数代表有限元单元的自由度，我们会希望以不同的方式处理它们)。问题的空间维度是不相关的，因为我们没有矢量或张量值的参数需要容纳，所以`dim`模板参数被任意分配为1的值。 第二个模板参数规定了将使用哪个AD框架（deal.II支持几个外部AD框架），以及这个框架提供的基础数字类型将被使用。这个数字类型影响了微分运算的最大顺序，以及用于计算它们的基础算法。鉴于其模板性质，这个选择是一个编译时的决定，因为许多（但不是全部）AD库利用编译时的元编程，以有效的方式实现这些特殊的数字类型。第三个模板参数说明了结果类型是什么；在我们的例子中，我们要处理的是 \"双数\"。\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// 我们有必要在我们的 @p ADHelper 类中预先登记函数 $f(x,y)$ 有多少个参数（我们将称之为 \"独立变量\"）。这些参数是`x`和`y`，所以显然有两个。\n\n      constexpr unsigned int n_independent_variables = 2; \n\n// 我们现在有足够的信息来创建和初始化一个辅助类的实例。我们还可以得到具体的数字类型，它将在所有后续计算中使用。这很有用，因为我们可以从这里开始通过引用这个类型来编写一切，如果我们想改变使用的框架或数字类型（例如，如果我们需要更多的微分运算），那么我们只需要调整`ADTypeCode`模板参数。\n\n      ADHelper ad_helper(n_independent_variables); \n      using ADNumberType = typename ADHelper::ad_type; \n\n// 下一步是在辅助类中注册自变量的数值。这样做是因为函数和它的导数将正好针对这些参数进行评估。由于我们按照`{x,y}`的顺序注册它们，变量`x`将被分配到分量号`0`，而`y`将是分量号`1`--这个细节将在接下来的几行中使用。\n\n      ad_helper.register_independent_variables({x, y}); \n\n// 我们现在要求辅助类向我们提供自变量及其自动区分的表示。这些被称为 \"敏感变量\"，因为从现在开始，我们对组件`独立变量_ad`所做的任何操作都会被AD框架跟踪和记录，并且在我们要求计算它们的导数时，会被考虑。帮助器返回的是一个可自动微分的 \"向量\"，但是我们可以确定，第2个元素代表 \"x\"，第1个元素代表 \"y\"。为了完全确保这些变量的数字类型没有任何歧义，我们给所有的自动微分变量加上`ad'的后缀。\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// 我们可以立即将自变量的敏感表示法传递给我们的模板函数，计算出  $f(x,y)$  。这也会返回一个可自动微分的数字。\n\n      const ADNumberType f_ad = f(x_ad, y_ad); \n\n// 所以现在要问的自然是，我们把这些特殊的`x_ad`和`y_ad`变量传递给函数`f`，而不是原来的`double`变量`x`和`y`，实际上计算了什么？换句话说，这一切与我们想要确定的导数的计算有什么关系？或者，更简洁地说。这个返回的`ADNumberType`对象有什么特别之处，使它有能力神奇地返回导数？\n\n// 从本质上讲，这*可以*做的是以下几点。这个特殊的数字可以被看作是一个数据结构，它存储了函数值，以及规定的导数数量。对于一个期望有两个参数的一次可导数，它可能看起来像这样。\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// 对于我们的自变量`x_ad`，`x_ad.value`的起始值只是它的赋值（即这个变量代表的实值）。导数`x_ad.derivatives[0]`将被初始化为`1'，因为`x'是第2个独立变量和 $\\frac{d(x)}{dx} = 1$  。导数`x.derivatives[1]`将被初始化为零，因为第一个自变量是`y`和 $\\frac{d(x)}{dy} = 0$  。\n\n// 为了使函数导数有意义，我们必须假设这个函数不仅在分析意义上是可微的，而且在评估点`x,y`也是可微的。我们可以利用这两个假设：当我们在数学运算中使用这种数字类型时，AD框架可以**的\n//重载操作（例如，`%operator+()`, `%operator*()`以及`%sin()`, `%exp()`, 等等），使返回的结果具有预期值。同时，它将通过对被重载的确切函数的了解和对连锁规则的严格应用来计算导数。因此，`%sin()`函数（其参数`a`本身是自变量`x`和`y`的一个函数 *可能*被定义如下。\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// 当然，所有这些也可以用于二阶甚至高阶导数。\n\n// 所以现在很明显，通过上述表示，`ADNumberType`携带了一些额外的数据，这些数据代表了可微调函数相对于原始（敏感）自变量的各种导数。因此应该注意到，使用它们会产生计算开销（因为我们在做导数计算时要计算额外的函数），以及存储这些结果的内存开销。因此，规定的微分运算的级数最好保持在最低水平，以限制计算成本。例如，我们可以自己计算第一级导数，然后使用 Differentiation::AD::VectorFunction 辅助类来确定依赖函数集合的梯度，这将是原始标量函数的第二级导数。\n\n// 还值得注意的是，由于链式规则是无差别应用的，我们只看到计算的起点和终点`{x,y}`  $\\rightarrow$  `f(x,y)`，我们永远只能查询到`f`的总导数；部分导数（上例中的`a.导数[0]`和`a.导数[1]`）是中间值，对我们是隐藏的。\n\n// 好的，既然我们现在至少知道了`f_ad'代表什么，以及它的编码是什么，让我们把所有的东西用于实际的用途。为了获得那些隐藏的派生结果，我们将最终结果注册到帮助类中。在这之后，我们不能再改变`f_ad`的值，也不能让这些变化反映在帮助者类返回的结果中。\n\n      ad_helper.register_dependent_variable(f_ad); \n\n// 下一步是提取导数（特别是函数梯度和Hessian）。为此，我们首先创建一些临时数据结构（结果类型为`double`）来存储导数（注意，所有的导数都是一次性返回的，而不是单独返回）...\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// ... 然后我们要求助手类计算这些导数，以及函数值本身。就这样了。我们得到了我们想得到的一切。\n\n      const double computed_f = ad_helper.compute_value(); \n      ad_helper.compute_gradient(Df); \n      ad_helper.compute_hessian(D2f); \n\n// 我们可以通过与分析方案的比较来说服自己，AD框架是正确的。(或者，如果你像作者一样，你会做相反的事情，宁愿验证你对分析方案的实现是正确的！)\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// 因为我们知道自变量的排序，所以我们知道梯度的哪个部分与哪个导数有关......。\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// .......对于Hessian也是如此。\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// 这很不错。在计算这个三角函数的二阶导数时并没有太多的工作。\n\n//  @sect4{Hand-calculated derivatives of the analytical solution}  \n\n// 既然我们现在知道了让AD框架为我们计算这些导数需要多少 \"执行工作\"，让我们把它与手工计算并在几个独立的函数中实现的同样的导数进行比较。\n\n// 这里是 $f(x,y) = \\cos\\left(\\frac{y}{x}\\right)$ 的两个一阶导数。\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// 这里是 $f(x,y)$ 的四个二次导数。\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))$  （正如预期的那样，根据[施瓦茨定理]（https:en.wikipedia.org/wiki/Symmetry_of_second_derivatives））。\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// 嗯......上面有很多地方我们可以引入错误，特别是在应用链式规则的时候。虽然它们不是银弹，但至少这些AD框架可以作为一个验证工具，确保我们没有犯任何错误（无论是计算还是执行），从而对我们的结果产生负面影响。\n\n// 当然，这个例子的重点是，我们可能选择了一个相对简单的函数 $f(x,y)$ ，我们可以手工验证AD框架计算的导数是否正确。但是AD框架并不关心这个函数是否简单。它可能是一个复杂得多的表达式，或者取决于两个以上的变量，它仍然能够计算出导数--唯一的区别是，*我们*不能再想出导数来验证AD框架的正确性。\n\n//  @sect4{Computing derivatives using symbolic differentiation}  \n\n// 我们现在要用符号微分法重复同样的练习。术语 \"符号微分 \"有点误导，因为微分只是计算机代数系统（CAS）（即符号框架）提供的一个工具。然而，在有限元建模和应用的背景下，它是CAS最常见的用途，因此将是我们关注的重点。再一次，我们将提供参数值`x`和`y`来评估我们的函数 $f(x,y) = \\cos\\left(\\frac{y}{x}\\right)$ 和它的导数，并提供一个公差来测试返回结果的正确性。\n\n    void \n    run_and_verify_sd(const double x, const double y, const double tol = 1e-12) \n    { \n\n// 我们需要做的第一步是形成符号变量，代表我们希望对其进行微分的函数参数。同样，这些将是我们问题的独立变量，因此在某种意义上是原始变量，与其他变量没有任何关系。我们通过初始化一个符号类型 Differentiation::SD::Expression, 来创建这些类型的（独立）变量，这个符号类型是对符号框架所使用的一组类的包装，有一个唯一的标识。在这种情况下，这个标识符，一个 `std::string`, 对于 $x$ 的参数来说，是简单的 \"x\"，同样，对于依赖函数的 $y$ 参数来说，也是 \"y\"。像以前一样，我们将用`sd`作为符号变量名称的后缀，这样我们就可以清楚地看到哪些变量是符号性的（而不是数字性的）。\n\n      const Differentiation::SD::Expression x_sd(\"x\"); \n      const Differentiation::SD::Expression y_sd(\"y\"); \n\n// 使用计算 $f(x,y)$ 的模板化函数，我们可以将这些独立变量作为参数传递给该函数。返回的结果将是另一个符号类型，代表用于计算  $\\cos\\left(\\frac{y}{x}\\right)$  的操作序列。\n\n      const Differentiation::SD::Expression f_sd = f(x_sd, y_sd); \n\n// 在这一点上，打印出表达式`f_sd`是合法的，如果我们这样做的话 \n// @code\n//  std::cout << \"f(x,y) = \" << f_sd << std::endl;\n//  @endcode \n//我们会看到`f(x,y) = cos(y/x)`打印到控制台。\n\n// 你可能会注意到，我们在构建我们的符号函数`f_sd`时，没有说明我们可能要如何使用它。与上面显示的AD方法相比，我们从调用`f(x_sd, y_sd)`返回的不是函数`f`在某个特定点的评价，而实际上是在一个通用的、尚未确定的点的评价的符号表示。这是使符号框架（CAS）不同于自动区分框架的关键点之一。每个变量`x_sd`和`y_sd`，甚至复合依赖函数`f_sd`，在某种意义上分别是数值的 \"占位符 \"和操作的组合。事实上，用于组成函数的各个组件也是占位符。操作序列被编码成一个树状的数据结构（概念上类似于[抽象语法树](https:en.wikipedia.org/wiki/Abstract_syntax_tree)）。\n\n// 一旦我们形成了这些数据结构，我们就可以把我们可能想对它们进行的任何操作推迟到以后的某个时间。这些占位符中的每一个都代表了一些东西，但我们有机会在任何方便的时间点上定义或重新定义它们所代表的东西。因此，对于这个特定的问题，我们想把 \"x \"和 \"y \"与*一些*数值（类型尚未确定）联系起来是有道理的，但我们可以在概念上（如果有意义的话）给 \"y/x \"这个比率赋值，而不是单独给 \"x \"和 \"y \"这些变量赋值。我们还可以将 \"x \"或 \"y \"与其他一些符号函数`g(a,b)`联系起来。这些操作中的任何一个都涉及到对所记录的操作树的操作，以及用其他东西替换树上的突出节点（以及该节点的子树）。这里的关键词是 \"替换\"，事实上，在 Differentiation::SD 命名空间中有许多函数的名称中都有这个词。\n\n// 这种能力使框架完全通用。在有限元模拟的背景下，我们通常会对我们的符号类型进行的操作类型是函数组合、微分、替换（部分或完全）和评估（即符号类型向其数字对应物的转换）。但如果你需要，一个CAS的能力往往不止这些。它可以形成函数的反导数（积分），对形成函数的表达式进行简化（例如，用 $1$ 替换 $(\\sin a)^2 + (\\cos a)^2$ ；或者，更简单：如果函数做了像`1+2`这样的运算，CAS可以用`3`替换它），等等。变量所代表的*表达式是从函数 $f$ 的实现方式中得到的，但CAS可以对其进行任何功能的操作。\n\n// 具体来说，为了计算因果函数相对于各个自变量的一阶导数的符号表示，我们使用 Differentiation::SD::Expression::differentiate() 函数，自变量作为其参数。每次调用都会导致CAS通过组成`f_sd`的运算树，并对表达式树的每个节点进行相对于给定符号参数的微分。\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// 为了计算二阶导数的符号表示，我们只需对自变量的一阶导数进行微分。所以要计算高阶导数，我们首先需要计算低阶导数。由于调用 \"differentiate() \"的返回类型是一个表达式，我们原则上可以通过将两个调用连在一起，直接从标量上执行双倍微分。但是在这个特殊的情况下，这是不需要的，因为我们手头有中间结果）。)\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// 使用语句\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//  打印由CAS计算的第一和第二导数的表达式，得到以下输出。\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//  这与前面介绍的这些导数的分析表达式相比，效果很好。\n\n// 现在我们已经形成了函数及其导数的符号表达式，我们想对函数的主要参数`x`和`y`的数字值进行评估。为了达到这个目的，我们构造了一个*替代图*，它将符号值映射到它们的数字对应值。\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// 这个过程的最后一步是将所有的符号变量和操作转换成数值，并产生这个操作的数值结果。为了做到这一点，我们在上面已经提到的步骤中，将替换图与符号变量结合起来。\"替换\"。\n\n// 一旦我们把这个替换图传递给CAS，它就会把符号变量的每个实例（或者更一般的，子表达式）替换成它的数字对应物，然后把这些结果在操作树上传播，如果可能的话，简化树上的每个节点。如果运算树被简化为一个单一的值（也就是说，我们已经将所有的独立变量替换成了它们的数字对应值），那么评估就完成了。\n\n// 由于C++的强类型特性，我们需要指示CAS将其对结果的表示转换为内在的数据类型（本例中为`double'）。这就是 \"评估 \"步骤，通过模板类型我们定义了这个过程的返回类型。方便的是，如果我们确定我们已经进行了完整的替换，这两个步骤可以一次完成。\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// 我们可以对第一个导数做同样的处理......\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// ...以及二阶导数。请注意，我们可以在这些操作中重复使用相同的替换图，因为我们希望针对相同的`x`和`y`值评估所有这些函数。修改置换图中的值，就可以得到相同的符号表达式的评估结果，同时给自变量分配不同的值。我们也可以很高兴地让每个变量在一次中代表一个实值，在下一次中代表一个复值。\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// 用来驱动这些初始例子的函数是直接的。我们将任意选择一些值来评估该函数（尽管知道`x = 0`是不允许的），然后将这些值传递给使用AD和SD框架的函数。\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// 现在我们已经介绍了自动分化和符号分化背后的原理，我们将通过制定两个耦合的磁力学构成法将其付诸实施：一个是与速率无关的，另一个则表现为与速率有关的行为。\n\n// 正如你在介绍中记得的那样，我们将考虑的材料构成法则要比上面的简单例子复杂得多。这不仅仅是因为我们将考虑的函数 $\\psi_{0}$ 的形式，而且特别是因为 $\\psi_{0}$ 不仅仅取决于两个标量变量，而是取决于一大堆*张量，每个张量都有几个组成部分。在某些情况下，这些是*对称*张量，对于这些张量来说，只有一个分量子集实际上是独立的，我们必须考虑计算 $\\frac{\\partial\\psi_{0}}{\\partial \\mathbf{C}}$ 这样的导数的实际意义，其中 $\\mathbf C$ 是一个对称张量。希望这一切将在下面变得清晰。我们也将清楚地看到，用手来做这件事，在最好的情况下，将是非常*繁琐，而在最坏的情况下，充满了难以发现的错误。\n\n  namespace CoupledConstitutiveLaws \n  { \n// @sect4{Constitutive parameters}  \n\n// 我们先描述一下能量函数描述中出现的各种材料参数  $\\psi_{0}$  。\n\n// ConstitutiveParameters类被用来保存这些数值。所有参数的值（包括构成参数和流变参数）都来自于  @cite Pelteret2018a  ，并给出了能够产生大致代表真实的、实验室制造的磁活性聚合物的构成响应的值，当然，这里使用的具体数值对本程序的目的没有影响。\n\n// 前四个构成参数分别代表\n\n// 弹性剪切模量 $\\mu_{e}$  。\n\n// --磁饱和时的弹性剪切模量  $\\mu_{e}^{\\infty}$  。\n\n// - 弹性剪切模量的饱和磁场强度  $h_{e}^{\\text{sat}}$  ，以及\n\n// 泊松比  $\\nu$  。\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// 接下来的四个，只与速率相关的材料有关，是以下的参数\n\n// - 粘弹性剪切模量  $\\mu_{v}$  。\n\n// - 磁饱和时的粘弹性剪切模量  $\\mu_{v}^{\\infty}$  。\n\n// 粘弹性剪切模量的饱和磁场强度 $h_{v}^{\\text{sat}}$  ，以及\n\n// --特征松弛时间  $\\tau$  。\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// 最后一个参数是相对磁导率  $\\mu_{r}$  。\n\n      double mu_r = 6.0; \n\n      bool initialized = false; \n    }; \n\n// 参数是通过ParameterAcceptor框架初始化的，该框架在  step-60  中有详细讨论。\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// 由于我们将为同一类材料制定两种构成法，因此定义一个基类以确保它们有统一的接口是有意义的。\n\n// 类的声明从构造函数开始，它将接受一组构成参数，这些参数与材料定律本身一起决定了材料的响应。\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// 我们将在一个方法中计算和存储这些值，而不是随意计算和返回动力学变量或其线性化。然后这些缓存的结果将在请求时返回。我们将把为什么要这样做的精确解释推迟到以后的阶段。现在重要的是看到这个函数接受所有的场变量，即磁场矢量 $\\boldsymbol{\\mathbb{H}}$ 和右Cauchy-Green变形张量 $\\mathbf{C}$ ，以及时间离散器。除了 @p constitutive_parameters, 之外，这些都是计算材料响应所需的基本量。\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// 接下来的几个函数提供了探测材料响应的接口，这些响应是由于施加的变形和磁荷载引起的。\n\n// 由于该类材料可以用自由能 $\\psi_{0}$ 来表示，我们可以计算出......\n\n      virtual double get_psi() const = 0; \n\n// ... 以及两个动力学量。\n\n// 磁感应矢量  $\\boldsymbol{\\mathbb{B}}$  ，和\n\n// --皮奥拉-基尔霍夫总应力张量 $\\mathbf{S}^{\\text{tot}}$  。\n      virtual Tensor<1, dim> get_B() const = 0; \n\n      virtual SymmetricTensor<2, dim> get_S() const = 0; \n\n// .......以及动力学量的线性化，它们是。\n\n// --磁静力学正切张量  $\\mathbb{D}$  。\n\n// - 总的参考性磁弹性耦合张量 $\\mathfrak{P}^{\\text{tot}}$  ，以及\n\n// --总的参考弹性正切张量 $\\mathcal{H}^{\\text{tot}}$  。\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// 我们还将定义一个方法，为这个类实例提供一个机制，在进入下一个时间段之前做任何额外的任务。同样，这样做的原因将在稍后变得清晰。\n\n      virtual void update_end_of_timestep() \n      {} \n\n// 在该类的`保护'部分，我们存储了一个对支配材料响应的构成参数实例的引用。为了方便起见，我们还定义了一些函数来返回各种构成参数（包括明确定义的，以及计算的）。\n\n与材料的弹性响应有关的参数依次是：//。\n\n// - 弹性剪切模量。\n\n// - 饱和磁场下的弹性剪切模量。\n\n// - 弹性剪切模量的饱和磁场强度。\n\n// - 泊松比。\n\n// 泊松比、Lam&eacute;参数，以及\n\n// 体积模量。\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// 与材料的弹性响应有关的参数依次是\n\n// - 粘弹性剪切模量。\n\n// -- 磁饱和时的粘弹性剪切模量。\n\n// - 粘弹性剪切模量的饱和磁场强度，以及\n\n粘弹性剪切模量的饱和磁场强度，和//--特征松弛时间。\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// 与材料的磁响应有关的参数依次是：。\n\n// 相对磁导率，以及\n\n// - 磁导率常数 $\\mu_{0}$ （其实不是一个材料常数，而是一个普遍的常数，为了简单起见，我们在这里分组）。\n\n// 我们还将实现一个函数，从时间离散性中返回时间步长。\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// 在下文中，让我们从实现刚才定义的类的几个相对琐碎的成员函数开始。\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// 我们将首先考虑一种非耗散性材料，即受磁超弹性构成法则支配的材料，在浸入磁场时表现出僵硬。正如介绍中所述，这种材料的储能密度函数可能由\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//  和\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//  给出。\n\n// 现在来看看实现这种行为的类。由于我们希望这个类能完全描述一种材料，所以我们将它标记为 \"final\"，这样继承树就在这里终止了。在类的顶部，我们定义了辅助类型，我们将在标量能量密度函数的AD计算中使用它。请注意，我们希望它能返回 \"double \"类型的值。我们还必须指定空间维度的数量，`dim'，以便建立矢量、张量和对称张量场与它们所含分量数量之间的联系。用于ADHelper类的具体的`ADTypeCode`将在实际使用该类的时候作为模板参数提供。\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// 由于基类的公共接口是纯 \"虚拟 \"的，这里我们将声明这个类将覆盖所有这些基类方法。\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`部分，我们需要定义一些提取器，这些提取器将帮助我们设置自变量，随后得到与因变量相关的计算值。如果这个类是在有限元问题的背景下使用，那么这些提取器中的每一个都（很可能）与解场的一个分量（在本例中，位移和磁标势）的梯度有关。正如你现在可能推断的那样，这里 \"C \"表示右Cauchy-Green张量，\"H \"表示磁场向量。\n\n    private: \n      const FEValuesExtractors::Vector             H_components; \n      const FEValuesExtractors::SymmetricTensor<2> C_components; \n\n// 这是一个自动微分助手的实例，我们将设置它来完成与构成法则有关的所有微分计算......\n\n      ADHelper ad_helper; \n\n// ... 以下三个成员变量将存储来自 @p ad_helper. 的输出。  @p ad_helper 一次性返回关于所有场变量的导数，因此我们将保留完整的梯度向量和Hessian矩阵。我们将从中提取我们真正感兴趣的单个条目。\n\n      double             psi; \n      Vector<double>     Dpsi; \n      FullMatrix<double> D2psi; \n    }; \n\n// 在设置字段组件提取器时，对于它们的顺序是完全任意的。但重要的是，这些提取器没有重叠的索引。这些提取器的组件总数定义了 @p ad_helper 需要跟踪的独立变量的数量，并且我们将对其进行导数。由此产生的数据结构 @p Dpsi 和 @p D2psi 也必须有相应的大小。一旦 @p ad_helper 被配置好（它的输入参数是 $\\mathbf{C}$ 和 $\\boldsymbol{\\mathbb{H}}$ 的组件总数），我们就可以直接询问它使用多少个独立变量。\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// 如前所述，由于自动微分库的工作方式， @p ad_helper 将总是同时返回能量密度函数相对于所有场变量的导数。由于这个原因，在函数`get_B()`、`get_S()`等中计算导数是没有意义的，因为我们会做很多额外的计算，然后直接丢弃。因此，处理这个问题的最好方法是用一个单一的函数调用来完成所有的前期计算，然后我们在需要时提取存储的数据。这就是我们在 \"update_internal_data() \"方法中要做的。由于材料是与速率无关的，我们可以忽略DiscreteTime参数。\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// 由于我们在每个时间步骤中都会重复使用 @p ad_helper 数据结构，所以我们需要在使用前清除它的所有陈旧信息。\n\n      ad_helper.reset(); \n\n// 下一步是设置所有字段组件的值。这些定义了 \"点\"，我们将围绕这个点计算函数梯度及其线性化。我们之前创建的提取器提供了字段和 @p ad_helper 中的注册表之间的关联 -- 它们将被反复使用，以确保我们对哪个变量对应于`H`或`C`的哪个分量有正确的解释。\n\n      ad_helper.register_independent_variable(H, H_components); \n      ad_helper.register_independent_variable(C, C_components); \n\n// 现在我们已经完成了最初的设置，我们可以检索我们字段的AD对应关系。这些是真正的能量函数的独立变量，并且对用它们进行的计算是 \"敏感的\"。请注意，AD数被视为一种特殊的数字类型，可以在许多模板化的类中使用（在这个例子中，作为Tensor和SymmetricTensor类的标量类型）。\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// 我们还可以在许多以标量类型为模板的函数中使用它们。因此，对于我们需要的这些中间值，我们可以进行张量运算和一些数学函数。由此产生的类型也将是一个自动可分的数字，它对这些函数中的操作进行编码。\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// 接下来我们将计算出在磁场影响下导致剪切模量变化（增加）的比例函数......\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// ...然后我们就可以定义材料的储能密度函数。我们将在后面看到，这个例子足够复杂，值得使用AD，至少可以验证一个无辅助的实现。\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// 储存的能量密度函数实际上是这个问题的因变量，所以作为 \"配置 \"阶段的最后一步，我们用 @p ad_helper. 注册其定义。\n      ad_helper.register_dependent_variable(psi_ad); \n\n// 最后，我们可以检索存储的能量密度函数的结果值，以及它相对于输入字段的梯度和Hessian，并将它们缓存起来。\n\n      psi = ad_helper.compute_value(); \n      ad_helper.compute_gradient(Dpsi); \n      ad_helper.compute_hessian(D2psi); \n    } \n\n// 下面的几个函数可以查询 $\\psi_{0}$ 的存储值，并提取梯度向量和Hessian矩阵的所需成分。我们再次利用提取器来表达我们希望检索的总梯度向量和Hessian矩阵的哪些部分。它们只返回能量函数的导数，所以对于我们的动能变量的定义和它们的线性化，还需要进行一些操作来形成所需的结果。\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// 请注意，对于耦合项来说，提取器参数的顺序特别重要，因为它决定了定向导数的提取顺序。因此，如果我们在调用`extract_hessian_component()`时颠倒了提取器的顺序，那么我们实际上是在检索  $\\left[ \\mathfrak{P}^{\\text{tot}} \\right]^{T}$  的一部分。\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// 我们要考虑的第二个材料定律将是一个代表具有单一耗散机制的磁涡弹材料。我们将考虑这种材料的自由能密度函数定义为\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//  ，其中\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//  与内部粘性变量\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//  的演化规律相结合，该演化规律采用一阶后向差分近似法进行离散。\n\n// 再一次，让我们看看在一个具体的类中是如何实现的。我们现在将利用SD方法，而不是之前类中使用的AD框架。为了支持这一点，这个类的构造函数不仅接受 @p constitutive_parameters, ，而且还接受两个额外的变量，这些变量将被用来初始化一个 Differentiation::SD::BatchOptimizer. 我们将在后面给出更多的背景。\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// 和自动区分助手一样， Differentiation::SD::BatchOptimizer 将一次性返回一个结果集合。因此，为了只做一次，我们将利用与之前类似的方法，在`update_internal_data()`函数中做所有昂贵的计算，并将结果缓存起来，以便分层提取。\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// 因为我们要处理的是一个与速率有关的材料，所以我们必须在适当的时候更新历史变量。这将是这个函数的目的。\n\n      virtual void update_end_of_timestep() override; \n\n// 在该类的`private`部分，我们将希望跟踪内部的粘性变形，所以下面两个（实值的，非符号的）成员变量分别持有\n\n// - 内部变量时间步长（如果嵌入非线性求解器框架，则为牛顿步长）的值，以及\n\n// - 内部变量在前一个时间步长的值。\n\n// （我们将这些变量标记为 \"Q\"，以便于识别；在计算的海洋中，不一定容易将`Cv`或`C_v`与`C`区分开来）。\n\n    private: \n      SymmetricTensor<2, dim> Q_t; \n      SymmetricTensor<2, dim> Q_t1; \n\n// 由于我们将使用符号类型，我们需要定义一些符号变量，以便与框架一起使用。(它们都以 \"SD \"为后缀，以方便区分符号类型或表达式与实值类型或标量。) 这可以在前面做一次（甚至有可能作为 \"静态 \"变量），以尽量减少与创建这些变量相关的开销。为了实现通用编程的终极目标，我们甚至可以用符号来描述构成参数，*有可能*允许一个类的实例在这些值的不同输入下被重复使用。\n\n// 这些是代表弹性、粘性和磁性材料参数的符号标量（定义的顺序与它们在 @p ConstitutiveParameters 类中出现的顺序基本相同）。我们还存储了一个符号表达式， @p delta_t_sd, ，表示时间步长）。)\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// 接下来我们定义一些代表独立场变量的张量符号变量，在此基础上，能量密度函数被参数化。\n\n      const Tensor<1, dim, Differentiation::SD::Expression>          H_sd; \n      const SymmetricTensor<2, dim, Differentiation::SD::Expression> C_sd; \n\n// 同样，我们也有内部粘性变量的符号表示（包括它的当前值和它在前一个时间段的值）。\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// 我们还应该存储从属表达式的定义。虽然我们只计算一次，但我们需要它们从下面声明的 @p optimizer 中检索数据。此外，当序列化一个像这样的材料类时（不是作为本教程的一部分），我们要么需要把这些表达式也序列化，要么需要在重新加载时重建它们。\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// 然后，下一个变量是用于评估从属函数的优化器。更具体地说，它提供了加速评估符号依赖表达式的可能性。这是一个重要的工具，因为对冗长表达式的本地评估（不使用加速方法，而是直接对符号表达式进行评估）会非常慢。 Differentiation::SD::BatchOptimizer 类提供了一种机制，可以将符号表达式树转化为另一种代码路径，例如，在各种从属表达式之间共享中间结果（意味着这些中间值每次评估只计算一次）和/或使用即时编译器编译代码（从而检索评估步骤的接近原生性能）。\n\n// 执行这种代码转换在计算上是非常昂贵的，所以我们存储了优化器，使其在每个类实例中只做一次。这也进一步促使我们决定将构成参数本身变成符号化。这样我们就可以在几种材料（当然是相同的能量函数）和潜在的多个连续体点（如果嵌入到有限元模拟中）中重复使用这个 @p optimizer 的单一实例。\n\n// 正如模板参数所指定的，数值结果将是<tt>double</tt>类型。\n\n      Differentiation::SD::BatchOptimizer<double> optimizer; \n\n// 在评估阶段，我们必须将符号变量映射到它们的实值对应物。下一个方法将提供这个功能。\n\n// 这个类的最后一个方法将配置  @p optimizer.  。\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// 由于静止变形状态是材料被认为是完全松弛的状态，内部粘性变量被初始化为同一张量，即  $\\mathbf{C}_{v} = \\mathbf{I}$  。代表构成参数、时间步长、场和内部变量的各种符号变量都有一个唯一的标识符。优化器被传递给两个参数，这两个参数声明了应该应用哪种优化（加速）技术，以及CAS应该采取哪些额外步骤来帮助提高评估期间的性能。\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// 替换图只是将以下所有数据配对在一起。\n\n// - 构成参数（从基类中获取的值）。\n\n// - 时间步长（从时间离散器中获取其值）。\n\n// 场值（其值由调用该 @p Magnetoviscoelastic_Constitutive_Law_SD 实例的外部函数规定），以及\n\n// 当前和之前的内部粘性变形（其值存储在这个类实例中）。\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// 由于符号表达式的 \"自然 \"使用，配置 @p optimizer 的大部分过程看起来与构建自动区分帮助器的过程非常相似。尽管如此，我们还是要再次详细说明这些步骤，以强调这两个框架的不同之处。\n\n// 该函数从符号化编码变形梯度行列式的表达式开始（用右Cauchy-Green变形张量表示，即我们的主要场变量），以及 $\\mathbf{C}$ 本身的逆。\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// 接下来是自由能密度函数的弹性部分的饱和函数的符号表示，然后是自由能密度函数的磁弹性贡献。这一切都与我们之前看到的结构相同。\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// 此外，我们还定义了自由能密度函数的磁-粘弹性贡献。实现这一点所需的第一个组件是一个缩放函数，它将使粘性剪切模量在磁场影响下发生变化（增加）（见 @cite Pelteret2018a  ，公式29）。此后，我们可以计算能量密度函数的耗散分量；其表达式见 @cite Pelteret2018a （公式28），这是对 @cite Linder2011a （公式46）中提出的能量密度函数的直接扩展。\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// 从这些构件中，我们可以定义材料的总自由能密度函数。\n\n      psi_sd = psi_ME_sd + psi_MVE_sd; \n\n// 目前，对中科院来说，变量 @p Q_t_sd 似乎是独立于 @p C_sd. 的，我们的张量符号表达式 @p Q_t_sd 只是有一个与之相关的标识符，没有任何东西将其与另一个张量符号表达式 @p C_sd. 联系起来。因此，相对于 @p C_sd 的任何导数将忽略这种内在的依赖关系，正如我们从进化规律可以看到的，实际上是 $\\mathbf{C}_{v} = \\mathbf{C}_{v} \\left( \\mathbf{C}, t \\right)$  。这意味着，相对于 $\\mathbf{C}$ 推导任何函数 $f = f(\\mathbf{C}, \\mathbf{Q})$ 将返回部分导数 $\\frac{\\partial f(\\mathbf{C}, \\mathbf{Q})}{\\partial \\mathbf{C}}\n//  \\Big\\vert_{\\mathbf{Q}}$ ，而不是总导数 $\\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}}$  。\n\n// 相比之下，在当前的AD库中，总导数将总是被返回。这意味着对于这类材料模型来说，计算出的动能变量是不正确的，这使得AD成为从能量密度函数中推导出（连续点水平）这种耗散性材料的构成法的不正确工具。\n\n// 正是这种特定的控制水平描述了SD和AD框架之间的一个决定性差异。在几行中，我们将对内部变量 @p Q_t_sd 的表达式进行操作，使其产生正确的线性化。\n//但是，\n//首先，我们将计算动能变量的符号表达式，即磁感应向量和Piola-Kirchhoff应力张量。执行微分的代码相当接近于模仿理论中所述的定义。\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// 因为下一步是对上述内容进行线性化，所以现在是告知CAS  @p Q_t_sd  对  @p C_sd,  的明确依赖性的适当时机，即说明  $\\mathbf{C}_{v} = \\mathbf{C}_{v} \\left( \\mathbf{C}, t\\right)$  。这意味着未来所有关于 @p C_sd 的微分运算将考虑到这种依赖关系（即计算总导数）。换句话说，我们将转换一些表达式，使其内在参数化从 $f(\\mathbf{C}, \\mathbf{Q})$ 变为 $f(\\mathbf{C}, \\mathbf{Q}(\\mathbf{C}))$  .\n\n// 为了做到这一点，我们考虑时间离散的演化规律。由此，我们有了内部变量在其历史上的明确表达，以及主要场变量。这就是它在这个表达式中描述的内容。\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// 接下来我们产生一个中间替换图，它将在一个表达式中找到 @p Q_t_sd （我们的标识符）的每个实例，并用 @p Q_t_sd_explicit. 中的完整表达式来替换它。\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// 我们可以在两个动力学变量上进行这种替换，并立即将替换后的结果与场变量进行区分。(如果你愿意，这可以分成两步进行，中间的结果储存在一个临时变量中)。同样，如果你忽略了代换所产生的 \"复杂性\"，这些将运动变量线性化并产生三个切向张量的调用与理论中所述的非常相似。\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// 现在我们需要告诉 @p optimizer 我们需要提供哪些条目的数值，以便它能成功地进行计算。这些基本上充当了 @p optimizer 必须评估的所有从属函数的输入参数。它们统称为问题的自变量、历史变量、时间步长和构成参数（因为我们没有在能量密度函数中硬编码它们）。\n\n// 因此，我们真正想要的是为它提供一个符号集合，我们可以这样完成。\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//  但这实际上都已经被编码为替换图的键。这样做还意味着我们需要在两个地方（这里和构建替换图时）管理这些符号，这很烦人，而且如果这个材料类被修改或扩展，可能会出现错误。由于我们此时对数值不感兴趣，所以如果替换图中与每个键项相关的数值被填入无效的数据也没有关系。所以我们将简单地创建一个假的替换图，并从中提取符号。请注意，任何传递给 @p optimizer 的替换图都必须至少包含这些符号的条目。\n\n      optimizer.register_symbols( \n        Differentiation::SD::Utilities::extract_symbols( \n          make_substitution_map({}, {}, 0))); \n\n// 然后我们通知优化器我们想要计算哪些数值，在我们的情况下，这包括所有的因变量（即能量密度函数及其各种导数）。\n\n      optimizer.register_functions(psi_sd, B_sd, S_sd, BB_sd, PP_sd, HH_sd); \n\n// 最后一步是最终确定优化器。通过这个调用，它将确定一个等价的代码路径，一次性评估所有的从属函数，但计算成本比直接评估符号表达式时要低。注意：这是一个昂贵的调用，所以我们希望尽可能少地执行它。我们在类的构造函数中完成了这一过程，实现了每个类实例只被调用一次的目标。\n\n      optimizer.optimize(); \n    } \n\n// 由于 @p optimizer 的配置是在前面完成的，所以每次我们想计算动能变量或它们的线性化（导数）时，要做的事情就很少了。\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// 为了更新内部历史变量，我们首先需要计算一些基本量，这一点我们之前已经看到了。我们还可以向时间离散器询问用于从上一个时间步长迭代到当前时间步长的时间步长。\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// 现在，我们可以按照演化规律给出的定义，结合所选择的时间离散化方案，更新（实值）内部粘性变形张量。\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// 接下来我们向优化器传递我们希望自变量、时间步长和（本调用隐含的）构成参数所代表的数值。\n\n      const auto substitution_map = make_substitution_map(C, H, delta_t); \n\n// 在进行下一次调用时，用于（数值）评估从属函数的调用路径要比字典替换更快。\n\n      optimizer.substitute(substitution_map); \n    } \n\n// 在调用了`update_internal_data()`之后，从优化器中提取数据就有效了。在进行评估时，我们需要从优化器中提取数据的确切符号表达式。这意味着我们需要在优化器的生命周期内存储所有因变量的符号表达式（自然，对输入变量也有同样的暗示）。\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// 当在时间上向前移动时，内部变量的 \"当前 \"状态瞬间定义了 \"前 \"时间段的状态。因此，我们记录历史变量的值，作为下一个时间步长的 \"过去值 \"使用。\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// 现在我们已经看到了AD和SD框架如何在定义这些构成法则方面做了大量的工作，为了验证，我们将手工实现相应的类，并对框架与本地实现做一些初步的基准测试。\n\n// 为了保证作者的理智，下面记录的（希望是准确的）是动能变量和它们的切线的完整定义，以及一些中间计算过程。由于构成法则类的结构和设计已经在前面概述过了，我们将略过它，只是在 \"update_internal_data() \"方法的定义中对各阶段的计算进行划分。将导数计算（及其适度表达的变量名）与出现在类描述中的文档定义联系起来应该是很容易的。然而，我们将借此机会介绍两种实现构成法类的不同范式。第二种将比第一种提供更多的灵活性（从而使其更容易扩展，在作者看来），但要牺牲一些性能。\n\n//  @sect4{Magnetoelastic constitutive law (hand-derived)}  \n\n// 从前面提到的储存能量中，对于这种磁弹性材料，定义为\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//  与\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//  ，对应于磁感应向量和总Piola-Kirchhoff应力张量的第一导数是\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//  与\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] 。\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//  在上面的一个推导中使用对称算子 $\\text{sym} \\left( \\bullet \\right)$ 有助于确保所产生的秩-4张量，由于 $\\mathbf{C}$ 的对称性而持有小的对称性，仍然将秩-2对称张量映射为秩-2对称张量。参见SymmetricTensor类文档和 step-44 的介绍，并进一步解释在四阶张量的背景下对称性的含义。\n\n//每个运动学变量相对于其参数的线性化是\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//  与\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// 好吧，很快就升级了--尽管 $\\psi_{0}$ 和 $f_{\\mu_e}$ 的定义可能已经给出了一些提示，说明计算动能场和它们的线性化需要一些努力，但最终的定义可能比最初想象的要复杂一些。了解了我们现在所做的，也许可以说我们真的不想计算这些函数相对于其参数的一、二次导数--不管我们在微积分课上做得如何，或者我们可能是多么好的程序员。\n\n// 在最终实现这些的类方法定义中，我们以稍微不同的方式组成这些计算。一些中间步骤也被保留下来，以便从另一个角度说明如何系统地计算导数。此外，一些计算被分解得更少或更进一步，以重用一些中间值，并希望能帮助读者跟随导数的操作。\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// 对于这个类的更新方法，我们将简单地预先计算一个中间值的集合（用于函数求值、导数计算等），并 \"手动 \"安排它们的顺序，以使其重复使用最大化。这意味着我们必须自己管理，并决定哪些值必须在其他值之前计算，同时保持代码本身的某种秩序或结构的模样。这很有效，但也许有点乏味。它对类的未来扩展也没有太大的帮助，因为所有这些值都是这个单一方法的局部。\n\n// 有趣的是，这种预先计算在多个地方使用的中间表达式的基本技术有一个名字：[共同子表达式消除（CSE）]（https：en.wikipedia.org/wiki/Common_subexpression_elimination）。它是计算机代数系统在承担评估类似表达式的任务时用来减少计算费用的一种策略。\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// 磁弹性能的饱和函数。\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// 饱和函数的一阶导数，注意到  $\\frac{d \\tanh(x)}{dx} = \\text{sech}^{2}(x)$  。\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// 饱和度函数的二阶导数，注意  $\\frac{d \\text{sech}^{2}(x)}{dx} = -2 \\tanh(x) \\text{sech}^{2}(x)$  。\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// 从场/运动学变量中直接获得的一些中间量。\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// 中间量的一阶导数。\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// 中间量的二阶导数。\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// 储存的能量密度函数。\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// 动能量。\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// 动能量的线性化。\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// 如前所述，我们将考虑的具有一种耗散机制的磁涡流材料的自由能密度函数定义为 \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] 。\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//  与\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//  和演变规律\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] ，\n//  其本身是以 $\\mathbf{C}$ 为参数的。根据设计，能量 $\\psi_{0}^{ME} \\left( \\mathbf{C}, \\boldsymbol{\\mathbb{H}} \\right)$ 的磁弹性部分与前面介绍的磁弹性材料的磁弹性部分是相同的。因此，对于源于这部分能量的各种贡献的导数，请参考前面的章节。我们将继续强调来自这些条款的具体贡献，用 $ME$ 对突出的条款进行上标，而来自磁弹性部分的贡献则用 $MVE$ 上标。此外，阻尼项的磁饱和函数 $f_{\\mu_{v}}^{MVE} \\left( \\boldsymbol{\\mathbb{H}} \\right)$ 具有与弹性项相同的形式（即 $f_{\\mu_{e}}^{ME} \\left( \\boldsymbol{\\mathbb{H}} \\right)$ ），因此其导数的结构与之前看到的相同；唯一的变化是三个构成参数，现在与粘性剪切模量 $\\mu_{v}$ 而非弹性剪切模量 $\\mu_{e}$ 相关。\n\n// 对于这种磁-粘弹性材料，对应于磁感应矢量和Piola-Kirchhoff总应力张量的第一导数是\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//  ，其中粘性贡献为\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//  和\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//  时间微缩的演化规律，\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//  也将决定内部变量相对于场变量的线性化是如何构成的。\n\n// 注意，为了获得这种耗散材料的磁感应矢量和总Piola-Kirchhoff应力张量的*正确表达式，我们必须严格遵守应用Coleman-Noll程序的结果：我们必须取*部分导数*。\n//自由能密度函数与场变量的关系。(对于我们的非耗散性磁弹性材料，取部分导数或全部导数都会有同样的结果，所以之前没有必要提请大家注意这一点)。操作的关键部分是冻结内部变量 $\\mathbf{C}_{v}^{(t)} \\left( \\mathbf{C} \\right)$ ，同时计算 $\\psi_{0}^{MVE} \\left( \\mathbf{C}, \\mathbf{C}_{v} \\left( \\mathbf{C} \\right), \\boldsymbol{\\mathbb{H}} \\right)$ 相对于 $\\mathbf{C}$ 的导数-- $\\mathbf{C}_{v}^{(t)}$ 对 $\\mathbf{C}$ 的依赖性不被考虑。当决定是使用AD还是SD来执行这个任务时，选择是很清楚的--只有符号框架提供了一个机制来完成这个任务；如前所述，AD只能返回总导数，所以它不适合这个任务。\n\n// 为了对事情进行总结，我们将介绍这种速度依赖性耦合材料的材料切线。两个动能变量相对于其参数的线性化是 \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//  其中粘性贡献的切线为\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//  与\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//  ，从演化定律来看，\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//  注意，只是 $\\mathcal{H}^{\\text{tot}, MVE}$ 的最后一项包含内部变量的切线。这个特殊演化规律的线性化是线性的。关于非线性演化定律的例子，这种线性化必须以迭代的方式求解，见 @cite Koprowski  -Theiss2011a。\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// 一个用于存储所有中间计算的数据结构。我们很快就会准确地看到如何利用这一点来使我们实际进行计算的那部分代码变得干净和容易（好吧，至少是更容易）遵循和维护。但是现在，我们可以说，它将允许我们把计算中间量的导数的那部分代码从使用它们的地方移开。\n\n      mutable GeneralDataStorage cache; \n\n// 接下来的两个函数是用来更新场和内部变量的状态的，在我们进行任何详细的计算之前会被调用。\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// 该类接口的其余部分专门用于计算自由能密度函数及其所有导数所需的组件的方法。\n\n// 运动学变量，或称场变量。\n\n      const Tensor<1, dim> &get_H() const; \n\n      const SymmetricTensor<2, dim> &get_C() const; \n\n// 饱和度函数的一般化表述，所需的构成参数作为参数传递给每个函数。\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// 饱和度函数一阶导数的一般化表述，所需的构成参数作为参数传递给每个函数。\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// 饱和度函数二阶导数的广义公式，所需的构成参数作为参数传递给每个函数。\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// 从场/运动学变量中直接获得的中间量。\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// 中间量的一阶导数。\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// 内部变量相对于场变量的导数。注意，我们只需要内部变量的这个导数，因为这个变量只是作为动力学变量线性化的一部分而被微分。\n\n      const SymmetricTensor<4, dim> & \n      get_dQ_t_dC(const DiscreteTime &time) const; \n\n// 中间量的二阶导数。\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// 记录应用的变形状态以及磁载荷。此后，根据新的变形状态更新内部（粘性）变量。\n\n      set_primary_variables(C, H); \n      update_internal_variable(time); \n\n// 根据当前磁场获取弹性和粘性饱和函数的值...\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// ... 以及它们的一阶导数...\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// ...以及它们的二阶导数。\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// 中间量。请注意，由于我们是从一个缓存中获取这些值，而这个缓存的寿命比这个函数调用的寿命长，所以我们可以对结果进行别名，而不是从缓存中复制这个值。\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// 中间值的第一导数，以及内部变量相对于右Cauchy-Green变形张量的那部分。\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// 中间值的二阶导数。\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// 由于线性化的定义变得特别冗长，我们将把自由能密度函数分解成三个相加的部分。\n\n// --类似 \"新胡克 \"的项。\n\n// -- 与速度有关的项，以及\n\n// --类似于储存在磁场中的能量的项。\n\n// 为了保持一致，这些贡献中的每一个都将被单独加入到我们想要计算的变量中，其顺序也是如此。\n\n// 所以，首先这是能量密度函数本身。\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// ...然后是磁感应强度和Piola-Kirchhoff应力。\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// ...... 最后是由于动能变量的线性化而产生的切线。\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// 现在我们已经用完了存储在缓存中的所有临时变量，我们可以把它清除掉，以释放一些内存。\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// 接下来的几个函数实现了饱和度函数的广义表述，以及它的各种导数。\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// 一个比例函数，它将使剪切模量在磁场的影响下发生变化（增加）。\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// 缩放函数的一阶导数\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// 对于我们为这个材料类采用的缓存计算方法，所有计算的根基是场变量，以及不可改变的辅助数据，如构成参数和时间步长。因此，我们需要以与其他变量不同的方式将它们输入缓存，因为它们是由类本身之外规定的输入。这个函数只是将它们从输入参数中直接添加到缓存中，同时检查那里是否有等效的数据（我们希望每个时间步长或牛顿迭代只调用一次`update_internal_data()`方法）。\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// 设置  $\\boldsymbol{\\mathbb{H}}$  的值。\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// 设置  $\\mathbf{C}$  的值。\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// 此后，我们可以在任何时间点从缓存中获取它们。\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// 当我们需要主要变量时，保证它们在缓存中，我们不能从它们中计算出所有的中间值（无论是直接，还是间接）。\n\n// 如果缓存中还没有存储我们要找的值，那么我们就快速计算，把它存储在缓存中，然后返回刚刚存储在缓存中的值。这样我们就可以把它作为一个引用返回，避免复制对象。同样的道理也适用于复合函数可能依赖的任何值。换句话说，如果在我们目前感兴趣的计算之前有一个依赖链，那么在我们继续使用这些值之前，我们可以保证解决这些依赖关系。尽管从缓存中获取数据是有成本的，但 \"已解决的依赖关系 \"的概念可能足够方便，使其值得看一下这个额外的成本。如果这些材料定律被嵌入到有限元框架中，那么额外的成本甚至可能不会被注意到。\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 类是用来驱动数值实验的，这些实验将在我们已经实现了构成法则的耦合材料上进行。\n\n    class RheologicalExperimentParameters : public ParameterAcceptor \n    { \n    public: \n      RheologicalExperimentParameters(); \n\n// 这些是要模拟的流变学试样的尺寸。它们有效地定义了我们虚拟实验的测量点。\n\n      double sample_radius = 0.01; \n      double sample_height = 0.001; \n\n// 三个稳态负载参数分别是\n\n// - 轴向拉伸。\n\n// -- 剪切应变振幅，和\n\n// - 轴向磁场强度。\n\n      double lambda_2 = 0.95; \n      double gamma_12 = 0.05; \n      double H_2      = 60.0e3; \n\n// 此外，随时间变化的流变学负载条件的参数为\n\n// --加载周期的频率。\n\n// - 负载周期的数量，以及\n\n// - 每个周期的离散时间步数。\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// 我们还声明了一些不言自明的参数，这些参数与用速率依赖型和速率非依赖型材料进行的实验所产生的输出数据有关。\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// 接下来的几个函数将计算与时间有关的实验参数...\n\n      double start_time() const; \n\n      double end_time() const; \n\n      double delta_t() const; \n\n// ...... 而下面两个则规定了任何时候的机械和磁力负载......\n\n      Tensor<1, 3> get_H(const double time) const; \n\n      Tensor<2, 3> get_F(const double time) const; \n\n// ...... 而这最后一个是将实验的状态输出到控制台。\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// 施加的磁场总是与流变仪转子的旋转轴对齐。\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// 根据流变仪和样品的几何形状、采样点和实验参数，计算出应用的变形（梯度）。根据介绍中记录的位移曲线，变形梯度可以用直角坐标表示为 \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] 。\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// 这是将驱动数值实验的函数。\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// 我们可以利用手工实现的构成法，将我们用它达到的结果与用AD或SD得到的结果进行比较。通过这种方式，我们可以验证它们产生了相同的结果（这表明要么两种实现方式都有很大的可能性是正确的，要么就是它们都有相同的缺陷而不正确）。无论哪种方式，对于完全自我实现的变体来说，这都是一个很好的理智检查，当发现结果之间的差异时，当然可以作为一种调试策略）。)\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// 我们将把材料的构成性响应输出到文件中进行后处理，所以在这里我们声明一个`stream`，它将作为这个输出的缓冲区。我们将使用一个简单的CSV格式来输出结果。\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// 使用DiscreteTime类，我们使用一个固定的时间步长来迭代每个时间段。\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// 我们获取并计算在这个时间步长中应用于材料的负载...\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// ...然后我们更新材料的状态...\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// ...并测试两者之间的差异。\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// 接下来我们要做的是收集一些结果进行后处理。所有的数量都在 \"当前配置 \"中（而不是 \"参考配置\"，所有由构成法则计算的数量都在这个框架中）。\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// 最后，我们将应变应力和磁载荷历史输出到文件中。\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// 这个驱动函数的目的是读取文件中的所有参数，并在此基础上创建每个构成法则的代表性实例，并调用函数对其进行流变学实验。\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// 我们开始实际工作，使用我们与速率无关的构成法配置和运行实验。这里的自动可微调数类型是硬编码的，但是通过一些巧妙的模板设计，可以在运行时选择使用哪种框架（例如，通过参数文件选择）。我们将同时用完全手工实现的反面材料法进行实验，并检查它与我们的辅助实现的计算结果。\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// 接下来我们对与速率相关的构成法则做同样的处理。如果SymEngine被设置为使用LLVM即时编译器，则默认选择最高性能的选项，该编译器（结合一些积极的编译标志）产生所有可用选项中最快的代码评估路径。作为后备措施，所谓的 \"lambda \"优化器（它只需要一个兼容C++11的编译器）将被选中。同时，我们将要求CAS进行普通子表达式的消除，以尽量减少评估过程中使用的中间计算的数量。我们将记录在SD实现的构造器内执行 \"初始化 \"步骤所需的时间，因为这正是上述转换发生的地方。\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// 主函数只调用两组要执行的例子的驱动函数。\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": "#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": "///\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": "#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’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../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": "\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": "\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": "/* -*- 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–33\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#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 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": "#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": "/*\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": "/*--------------------------------------------------------------------------\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": "#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 − 1, k − 2, . . . , k − m§\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 − m, k − m + 1, . . . , k − 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 = {}, ‖g‖_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": "#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\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 \"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": "/*************************************************\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": "// 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": "// ===============================================================================================================\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": "/********************************************************************************\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 <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": "/*\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[]){eeeeeeeeeeee\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": "//  (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": "/*\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": "/**\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": "#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 \"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 \"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ücker 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": "// 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’Souza, 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çois 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\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/*!\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": "// 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 \"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 <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": "// 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": "#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": "/*\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íduos: \");\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ções 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ções necessárias\" <<endl<<endl;\n\n    Xa.raw_print(out,\" vetor Xa (pré-normalização)\");\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íduos: \");\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ções 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ções necessárias\" <<endl<<endl;\n\n    Xa.raw_print(out,\"parametros ajustados (r,XC,YC,ZC)\");\n    out<<endl;\n\n    V.raw_print(out,\"resíduos: \");\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ções 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ão é 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ório de Saída do Processamento da \";\n    out<< \"determinação dos parâmetros de orientação relativa\"   <<endl;\n    out<<\"do Sistema de Mapeamento Móvel 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âmera Esquerda\"<<endl;\n    out << \"X(m): \" <<LcamLA(0)<< \" | Y(m): \" <<LcamLA(1)<< \" | Z(m): \" <<LcamLA(2)<<endl<<endl;\n\n    out<< \"IMU -> Câmera 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âmeras: \"<<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âmera Esquerda (BF)\");\n    out<<endl;\n    Rimu_RC.raw_print(out,\"IMU (BF) -> Câmera Direita (BF)\");\n    out<<endl<<endl;\n\n    out<< \"Matrizes do Boresight (cossenos diretores, mesma convenção da IMU): \"<<endl<<endl;\n    Rimu_LC2.raw_print(out,\"IMU (BF) -> Câmera Esquerda (BF)\");\n    out<<endl;\n    Rimu_RC2.raw_print(out,\"IMU (BF) -> Câmera Direita (BF)\");\n    out<<endl<<endl;\n\n    out<<\"no último caso, os angulos formados com os eixos do BF da IMU: \"<<endl<<endl;\n\n    out<<\"IMU (BF) -> Câmera Esquerda (BF)\"<<endl<<arma::acos(Rimu_LC2)*(180/datum::pi)<<endl<<endl;\n    out<<\"IMU (BF) -> Câmera Direita (BF)\"<<endl<<arma::acos(Rimu_RC2)*(180/datum::pi)<<endl;\n\n    out<<endl<<\"testes de consistência dos resultados\"<<endl;\n    out<<\"as matrizes de rotação deverão, 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": "/**\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 * 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": "﻿// 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//    μ⁻ - μ⁺\n//\n// where\n//         Σ_p (H(d(p)+w) - H(d(p))) I(p)\n//    μ⁻ = ------------------------------\n//           Σ_p (H(d(p)+w) - H(d(p)))\n//\n//         Σ_p (H(d(p)+w) - H(d(p))) I(p)\n//    μ⁺ = ------------------------------\n//           Σ_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 <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": "//  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": "#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": "\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    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 \"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    //-- 读取图像\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<<\"一共找到了\"<<matches.size() <<\"组匹配点\"<<endl;\n\n\n    // 建立3D点\n    Mat d1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );       // 深度图为16位无符号数，单通道图像\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        //计算3D坐标\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        //调用计数坐标函数\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 ); // 调用OpenCV 的 PnP 求解，可选择EPNP，DLS等方法\n    //solvePnPRansac ( pts_3d, pts_2d, K, Mat(), r, t, false );\n    Mat R;\n    //旋转向量到旋转矩阵\n    cv::Rodrigues ( r, R ); // r为旋转向量形式，用Rodrigues公式转换为矩阵\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;      // 因为要删除跟踪失败的点，使用list\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 ); //将坐标放入keypoints链表中\n    }\n\n\n//    for ( auto kp:keypoints )\n//    {\n//        prev_keypoints.push_back(kp); //prev_keypoints 赋值为keypoints\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：\"<<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    // 把跟丢的点删掉，keypoint 放当前帧\n\n//    int i=0;\n//    for ( auto iter=keypoints.begin(); iter!=keypoints.end(); i++)\n//    {\n//        if ( status[i] == 0 ) //表示状态\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//        //计算3D坐标\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//        //调用计数坐标函数\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 ); // 调用OpenCV 的 PnP 求解，可选择EPNP，DLS等方法\n//    //solvePnPRansac ( pts_3d, pts_2d, K, Mat(), r, t, false );\n//    Mat R2;\n//    //旋转向量到旋转矩阵\n//    cv::Rodrigues ( r2, R2 ); // r为旋转向量形式，用Rodrigues公式转换为矩阵\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    //-- 初始化\n    Mat descriptors_1, descriptors_2;\n    // used in OpenCV3\n    Ptr<FeatureDetector> detector = ORB::create();\n    Ptr<DescriptorExtractor> descriptor = ORB::create();\n    // use this if you are in OpenCV2\n    // Ptr<FeatureDetector> detector = FeatureDetector::create ( \"ORB\" );\n    // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( \"ORB\" );\n    Ptr<DescriptorMatcher> matcher  = DescriptorMatcher::create ( \"BruteForce-Hamming\" );\n    //-- 第一步:检测 Oriented FAST 角点位置\n    detector->detect ( img_1,keypoints_1 );\n    detector->detect ( img_2,keypoints_2 );\n\n    //-- 第二步:根据角点位置计算 BRIEF 描述子\n    descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n    descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n\n    //-- 第三步:对两幅图像中的BRIEF描述子进行匹配，使用 Hamming 距离\n    vector<DMatch> match;\n    // BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( descriptors_1, descriptors_2, match );\n\n    //-- 第四步:匹配点对筛选\n    double min_dist=10000, max_dist=0;\n\n    //找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        double dist = match[i].distance;\n        if ( dist < min_dist ) min_dist = dist;\n        if ( dist > max_dist ) max_dist = dist;\n    }\n\n    printf ( \"-- Max dist : %f \\n\", max_dist );\n    printf ( \"-- Min dist : %f \\n\", min_dist );\n\n    //当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        if ( match[i].distance <= max ( 2*min_dist, 30.0 ) )\n        {\n            matches.push_back ( match[i] );\n        }\n    }\n}\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": "#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éfinit Dev comme fonction à minimiser\n\n\t/* Les paramètres sont dans l'ordre (cf Fraser et al. 2011) :\n\n\t- La proba d'échappement 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'échappement à une infection antérieure Q_prior\n\t- Hétérogénéité des infectivités 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": "#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": "#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çois 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": "/* -*- 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": "//    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": "#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": "/* 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": "// 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": "/*\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": "//\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": "/* \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 << \"|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|\" << endl;\n        cout << \"|Compressible computation.|\" << endl;\n        cout << \" ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ \" << 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 << \"∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨\" << endl;\n            cout << \">> Process diverged at iteration #\" << itCnt + 1 << \"!\" << endl;\n            cout << \"∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧\";\n            cout << ANSI_COLOR_RESET << endl << endl;\n        }\n        else {\n            cout << ANSI_COLOR_GREEN;\n            cout << \"∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨∨\" << endl;\n            cout << \">> Process converged in \" << itCnt << \" iteration(s)!\" << endl;\n            cout << \"∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧∧\";\n            cout << ANSI_COLOR_RESET << endl << endl;\n        }\n    }\n    // Panel Method\n    else {\n        cout << \"|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|\" << endl;\n        cout << \"|Incompressible computation.|\" << endl;\n        cout << \" ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ \" << 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ébert-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/* --------------------------------------------------------------------- \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// 前面几个文件已经在前面的例子中讲过了，因此不再做进一步的评论。\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// 这些是我们需要的新文件。第一个和第二个提供了FECollection和<i>hp</i>版本的FEValues类，如本程序介绍中所述。下一个文件提供了自动 $hp$ 适应的功能，为此我们将使用基于衰减系列扩展系数的估计算法，这是最后两个文件的一部分。\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// 最后一组包含文件是标准的C++头文件。\n\n#include <fstream> \n#include <iostream> \n\n// 最后，这和以前的程序一样。\n\nnamespace Step27 \n{ \n  using namespace dealii; \n// @sect3{The main class}  \n\n// 这个程序的主类看起来非常像前几个教程程序中已经使用过的，例如  step-6  中的那个。主要的区别是我们将refine_grid和output_results函数合并为一个，因为我们还想输出一些用于决定如何细化网格的量（特别是估计的解决方案的平滑度）。\n\n// 就成员变量而言，我们使用与 step-6 中相同的结构，但我们需要集合来代替单个的有限元、正交和面状正交对象。我们将在类的构造函数中填充这些集合。最后一个变量， <code>max_degree</code> ，表示所用形状函数的最大多项式程度。\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// 接下来，让我们为这个问题定义右手边的函数。它在1d中是 $x+1$ ，在2d中是 $(x+1)(y+1)$ ，以此类推。\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// 这个类的构造函数是相当直接的。它将DoFHandler对象与三角形相关联，然后将最大多项式度数设置为7（在1d和2d中）或5（在3d及以上）。我们这样做是因为使用高阶多项式度数会变得非常昂贵，尤其是在更高的空间维度上。\n\n// 在这之后，我们填充有限元、单元和面的四分法对象集合。我们从二次元开始，每个正交公式的选择都是为了适合 hp::FECollection 对象中的匹配有限元。\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// 解构器与我们在  step-6  中已经做过的没有变化。\n\n  template <int dim> \n  LaplaceProblem<dim>::~LaplaceProblem() \n  { \n    dof_handler.clear(); \n  } \n// @sect4{LaplaceProblem::setup_system}  \n\n// 这个函数又是对我们在  step-6  中已经做过的事情的逐字复制。尽管函数调用的名称和参数完全相同，但内部使用的算法在某些方面是不同的，因为这里的dof_handler变量是在  $hp$  -mode。\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// 这是一个从每个单元的局部贡献中集合全局矩阵和右侧向量的函数。它的主要工作与之前许多教程中描述的一样。重要的差异是<i>hp</i>有限元方法所需要的。特别是，我们需要使用FEValues对象的集合（通过 hp::FEValues 类实现），并且在将局部贡献复制到全局对象时，我们必须消除受限自由度。这两点在本程序的介绍中都有详细解释。\n\n// 还有一个小问题是，由于我们在不同的单元格中使用了不同的多项式度数，持有局部贡献的矩阵和向量在所有单元格中的大小不尽相同。因此，在所有单元的循环开始时，我们每次都必须将它们的大小调整到正确的大小（由 <code>dofs_per_cell</code> 给出）。因为这些类的实现方式是减少矩阵或向量的大小不会释放当前分配的内存（除非新的大小为零），所以在循环开始时调整大小的过程只需要在最初几次迭代中重新分配内存。一旦我们在一个单元中找到了最大的有限元度，就不会再发生重新分配，因为所有后续的 <code>reinit</code> 调用只会将大小设置为适合当前分配的内存。这一点很重要，因为分配内存是很昂贵的，而且每次我们访问一个新的单元时都这样做会花费大量的计算时间。\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// 解决线性系统的函数与之前的例子完全没有变化。我们只是试图将初始残差（相当于右手边的 $l_2$ 准则）减少一定的系数。\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// 解完线性系统后，我们要对解进行后处理。在这里，我们所做的就是估计误差，估计解的局部平滑度，如介绍中所述，然后写出图形输出，最后根据之前计算的指标细化 $h$ 和 $p$ 中的网格。我们在同一个函数中完成这一切，因为我们希望估计的误差和平滑度指标不仅用于细化，而且还包括在图形输出中。\n\n  template <int dim> \n  void LaplaceProblem<dim>::postprocess(const unsigned int cycle) \n  { \n\n// 让我们开始计算估计的误差和平滑度指标，这两个指标对于我们三角测量的每个活动单元来说都是一个数字。对于误差指标，我们一如既往地使用KellyErrorEstimator类。\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// 估计平滑度是用介绍中所述的衰减膨胀系数的方法进行的。我们首先需要创建一个对象，能够将每一个单元上的有限元解转化为一串傅里叶级数系数。SmoothnessEstimator命名空间为这样一个 FESeries::Fourier 对象提供了一个工厂函数，它为估计平滑度的过程进行了优化。然后在最后一个函数中实际确定每个单独单元上的傅里叶系数的衰减情况。\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// 接下来我们要生成图形输出。除了上面得出的两个估计量之外，我们还想输出网格上每个元素所使用的有限元的多项式程度。\n\n// 要做到这一点，我们需要在所有单元上循环，用  <code>cell-@>active_fe_index()</code>  轮询它们的活动有限元索引。然后我们使用这个操作的结果，在有限元集合中查询具有该索引的有限元，最后确定该元素的多项式程度。我们将结果放入一个矢量，每个单元有一个元素。DataOut类要求这是一个 <code>float</code> or <code>double</code> 的向量，尽管我们的值都是整数，所以我们就用这个向量。\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// 现在有了所有的数据向量--解决方案、估计误差和平滑度指标以及有限元度--我们创建一个用于图形输出的DataOut对象并附加所有数据。\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// 生成输出的最后一步是确定一个文件名，打开文件，并将数据写入其中（这里，我们使用VTK格式）。\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// 在这之后，我们想在 $h$ 和 $p$ 两个地方实际细化网格。我们要做的是：首先，我们用估计的误差来标记那些误差最大的单元，以便进行细化。这就是我们一直以来的做法。\n\n    { \n      GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                      estimated_error_per_cell, \n                                                      0.3, \n                                                      0.03); \n\n// 接下来我们要弄清楚哪些被标记为细化的单元格实际上应该增加 $p$ 而不是减少 $h$ 。我们在这里选择的策略是，我们查看那些被标记为细化的单元格的平滑度指标，并为那些平滑度大于某个相对阈值的单元格增加 $p$ 。换句话说，对于每一个(i)细化标志被设置，(ii)平滑度指标大于阈值，以及(iii)我们在有限元集合中仍有一个多项式度数高于当前度数的有限元的单元，我们将分配一个未来的FE指数，对应于一个比当前度数高一的多项式。下面的函数正是能够做到这一点。在没有更好的策略的情况下，我们将通过在标记为细化的单元上的最小和最大平滑度指标之间进行插值来设置阈值。由于角部奇点具有很强的局部性，我们将支持 $p$ 。\n\n// - 而不是 $h$  - 精细化的数量。我们通过设置0.2的小插值系数，以低门槛实现这一点。用同样的方法，我们处理那些要被粗化的单元，当它们的平滑度指标低于在要粗化的单元上确定的相应阈值时，减少它们的多项式程度。\n\n      hp::Refinement::p_adaptivity_from_relative_threshold( \n        dof_handler, smoothness_indicators, 0.2, 0.2); \n\n// 上面的函数只决定了多项式程度是否会通过未来的FE指数发生变化，但并没有操作 $h$  -细化标志。因此，对于被标记为两个细化类别的单元格，我们更倾向于 $p$  。\n\n// 而不是 $h$  -细化。下面的函数调用确保只有 $p$ 中的一个\n\n// - 或  $h$  - 精炼中的一种，而不是同时实施两种。\n\n      hp::Refinement::choose_p_over_h(dof_handler); \n\n// 对于网格自适应细化，我们通过调用 Triangulation::prepare_coarsening_and_refinement(). 将相邻单元的细化水平差限制为1来确保2:1的网格平衡。 我们希望对相邻单元的p水平实现类似的效果：未来有限元的水平差不允许超过指定的差。通过其默认参数，调用 hp::Refinement::limit_p_level_difference() 可以确保它们的级差被限制在1以内。这不一定会减少域中的悬挂节点的数量，但可以确保高阶多项式不会被限制在面的低得多的多项式上，例如五阶多项式到二阶多项式。\n\n      triangulation.prepare_coarsening_and_refinement(); \n      hp::Refinement::limit_p_level_difference(dof_handler); \n\n// 在这个过程结束后，我们再细化网格。在这个过程中，正在进行分割的单元的子单元会继承其母单元的有限元索引。此外，未来的有限元指数将变成活动的，因此新的有限元将在下一次调用 DoFHandler::distribute_dofs(). 后被分配给单元。\n      triangulation.execute_coarsening_and_refinement(); \n    } \n  } \n// @sect4{LaplaceProblem::create_coarse_grid}  \n\n// 在创建初始网格时，会用到下面这个函数。我们想要创建的网格实际上与 step-14 中的网格类似，即中间有方孔的方形域。它可以由完全相同的函数生成。然而，由于它的实现只是2d情况下的一种特殊化，我们将介绍一种不同的方法来创建这个域，它是独立于维度的。\n\n// 我们首先创建一个有足够单元的超立方体三角形，这样它就已经包含了我们想要的域 $[-1,1]^d$ ，并细分为 $4^d$ 单元。然后，我们通过测试每个单元上顶点的坐标值来移除域中心的那些单元。最后，我们像往常一样对如此创建的网格进行全局细化。\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// 这个函数实现了程序的逻辑，就像以前大多数程序中的相应函数一样，例如见  step-6  。\n\n// 基本上，它包含了自适应循环：在第一次迭代中创建一个粗略的网格，然后建立线性系统，对其进行组合，求解，并对解进行后处理，包括网格细化。然后再重新开始。同时，也为那些盯着屏幕试图弄清楚程序是干什么的人输出一些信息。\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// 主函数仍然是我们之前的版本：将创建和运行一个主类的对象包装成一个 <code>try</code> 块，并捕捉任何抛出的异常，从而在出现问题时产生有意义的输出。\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": "// Copyright 2006. Peter Gottschling, Matthias Troyer, Rolf Bonderer\n// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MATH_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 <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// 相机内参\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    // 读入左右双目图像\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    // 最小视差\n    int mindisparity = 0;\n    // 视差搜索范围长度\n\tint ndisparities = 64;  \n    // SAD代价计算窗口大小\n\tint SADWindowSize = 11; \n\t//SGBM\n\tcv::Ptr<cv::StereoSGBM> sgbm = cv::StereoSGBM::create(mindisparity, ndisparities, SADWindowSize);\n\n    // 能量函数参数\n\tint P1 = 8 * imgLeft.channels() * SADWindowSize* SADWindowSize;\n    // 能量函数参数\n\tint P2 = 32 * imgRight.channels() * SADWindowSize* SADWindowSize;\n\n    // 下面就是各种配置了\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    // 对原始图像进行预处理\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);                //除以16得到真实视差值\n\tMat disp8U = Mat(disp.rows, disp.cols, CV_8UC1);       //显示\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    // 生成相机内参数矩阵\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    // 准备深度着色\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    // ================================== 准备可视化 =================================\n    pangolin::CreateWindowAndBind(\n        \"PointClouds\",     //窗口标题\n        IMG_W,        //窗口尺寸\n        IMG_H);       //窗口尺寸\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,            //相机图像的长和宽\n            L_FX,L_FY,L_CX,L_CY,    //相机的内参,fu fv u0 v0\n            0.2,1000),           //相机所能够看到的最浅和最深的像素\n        pangolin::ModelViewLookAt(\n            -2,2,-2,            //相机光心位置,NOTICE z轴不要设置为0\n            0,0,0,              //相机要看的位置\n            pangolin::AxisY)    //和观察的方向有关\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,     //表示整个窗口都可以观测到\n                -IMG_W/IMG_H)         //窗口的比例\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        //尝试按照谢晓佳的视频中给出的代码绘制\n        // pangolin::glDrawAxis(3);\n\n        glPointSize(1.0f);\n        glBegin(GL_POINTS);\n        \n\n        // 绘制当前帧点云\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                        // 画点\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        //不要忘记了这个东西!!!\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     //颜色环初始化\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": "/* ============================================================================\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 \"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": "#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": "#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": "#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#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": "#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": "\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": "/**\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": "#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": "//\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": "#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": "#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": "#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": "/**********************************************************************\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": "/*\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": "/* 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": "#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 <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": "/*    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": "//==================================================================================================\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": "#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": "/*\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\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": "/**\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": "\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": "#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": "#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// 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": "/*\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": "/********************************************************************************\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": "// 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": "///////////////////////////////////////////////////////////////////////////////\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 (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\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": "//          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": "#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": "#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//         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": "/**********************\n规定 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和angles_boundary是按逆时针顺序排列的边缘点信息\nstd::vector<double> ranges_boundary; \nstd::vector<double> angles_boundary;\n\nint corner = 0;\n\n//g2o图优化顶点：位姿\nclass BoundaryPoseVertex: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    // 重置\n    virtual void setToOriginImpl() \n    {\n        _estimate << 0,0,0;\n    }\n     // 更新\n    virtual void oplusImpl( const double* update )\n    {\n        _estimate += Eigen::Vector3d(update);\n    }\n    // 存盘和读盘：留空\n    virtual bool read( std::istream& in ) {}\n    virtual bool write( std::ostream& out ) const {}\n};\n// 误差模型 模板参数：观测值维度，类型，连接顶点类型\n//_measurement是角度和距离的二维向量\n//场地下边的点所构成的图优化边\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    // 计算曲线模型误差\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)其实和point_theta是一样的，measurement(1)其实和point_range是一样的\n};\n//场地左边的点所构成的图优化边\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    // 计算曲线模型误差\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)其实和point_theta是一样的，measurement(1)其实和point_range是一样的\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    // 计算曲线模型误差\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)其实和point_theta是一样的，measurement(1)其实和point_range是一样的\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    // 计算曲线模型误差\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)其实和point_theta是一样的，measurement(1)其实和point_range是一样的\n};\n\n//计算提取出来的边界点的曲率的平方的25倍，由于是为了比较大小，不在开方以及乘以倍数，注意不能提取最靠两边的四个点，否则会出现错误\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//将角度限制在-π到π之间\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//提取边缘点信息到ranges_boundary和angles_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//找到第一个不符合距离要求的点\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//找到满足距离要求的最大连续点集,以判断两个直角边位置,从第一个不满足距离要求的点开始，循环一圈，防止重复遗漏，以及vector起始终止处连续点集判断错误的情况\n\tfor (int i = first_negative + 1; i < available_number; i++) {\n\t\tif (distance[i]) {\n\t\t\t//如果上一个点远，这一个点近，则取当前点作为当前连续点集起始边界，由于是从first_negative+1开始，到available结束的，所以不会判断初始集外的位置\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//如果上一个点远，这一个点近，则取当前点作为当前连续点集起始边界，由于是从first_negative+1开始，到available结束的，所以不会判断初始集外的位置\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//根据距离算坐标，根据曲率算角点，corner_number是曲率最大点\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//距离边缘最近的距离分别是lidar位置x,y，alpha是x=0线到lidar的angle_min的基准线的角度 theta是中间变量\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 维度为 3, landmark 维度为 1\n\ttypedef g2o::BlockSolver< g2o::BlockSolverTraits<3, 1> > Block;\n\t// 线性方程求解器\n\tBlock::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>();\n\t// 矩阵块求解器\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// 设置连接的顶点\n\t\t\t\tedge->setMeasurement(point);\n\t\t\t\t// 观测数值\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// 信息矩阵：协方差矩阵之逆\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// 设置连接的顶点\n\t\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t\t// 观测数值\n\t\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t\t// 信息矩阵：协方差矩阵之逆\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// 设置连接的顶点\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// 观测数值\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// 信息矩阵：协方差矩阵之逆\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// 设置连接的顶点\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// 观测数值\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// 信息矩阵：协方差矩阵之逆\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// 设置连接的顶点\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// 观测数值\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// 信息矩阵：协方差矩阵之逆\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// 设置连接的顶点\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// 观测数值\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// 信息矩阵：协方差矩阵之逆\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// 设置连接的顶点\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// 观测数值\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// 信息矩阵：协方差矩阵之逆\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// 设置连接的顶点\n\t\t\t\tedge->setMeasurement(point);      \n\t\t\t\t// 观测数值\n\t\t\t\tedge->setInformation(Information_Matrix);\n\t\t\t\t// 信息矩阵：协方差矩阵之逆\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//去除遮挡点，保留有效雷达点信息，ranges_raw是range信息，increment是有效点顺序信息（用于后续生成角度信息）\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": "//\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": "/* 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": "\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// 以下第一个include文件现在可能已经众所周知，不需要进一步解释。\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// 这个包含文件是新的。即使我们在本教程中不求解PDE，我们也要使用FE_Nothing类提供的自由度为零的假有限元。\n\n#include <deal.II/fe/fe_nothing.h> \n\n// 下面的头文件也是新的：在其中，我们声明了MappingQ类，我们将使用该类来处理任意阶的多项式映射。\n\n#include <deal.II/fe/mapping_q.h> \n\n// 这又是一个C++的文件。\n\n#include <iostream> \n#include <fstream> \n#include <cmath> \n\n// 最后一步和以前的程序一样。\n\nnamespace Step10 \n{ \n  using namespace dealii; \n\n// 现在，由于我们要计算 $\\pi$ 的值，我们必须与一些东西进行比较。这些是 $\\pi$ 的前几个数字，我们事先定义好，以便以后使用。由于我们想计算两个数字的差值，而这两个数字是相当精确的，计算出的 $\\pi$ 的近似值的精度在一个双数变量可以容纳的数字范围内，所以我们宁可将参考值声明为 <code>long double</code> ，并给它增加一些数字。\n\n  const long double pi = 3.141592653589793238462643L; \n\n// 然后，第一个任务将是生成一些输出。由于这个程序非常小，我们在其中没有采用面向对象的技术，也没有声明类（当然，我们使用了库的面向对象的功能）。相反，我们只是将功能打包成独立的函数。我们使这些函数成为空间维数的模板，以符合使用deal.II时的通常做法，尽管我们只对两个空间维数使用这些函数，当试图对任何其他空间维数使用时，会出现异常。\n\n// 这些函数中的第一个只是生成一个圆的三角形（hyperball），并输出 $Q_p$ 的不同值的单元的映射。然后，我们细化一次网格，再做一次。\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//因此，\n//首先生成一个圆的粗略三角剖分，并将一个合适的边界描述与之关联。默认情况下， GridGenerator::hyper_ball 将SphericalManifold附加到边界上（内部使用FlatManifold），所以我们简单地调用该函数并继续前进。\n\n    Triangulation<dim> triangulation; \n    GridGenerator::hyper_ball(triangulation); \n\n// 然后在当前网格上交替生成 $Q_1$ 、 $Q_2$ 和 $Q_3$ 映射的输出，以及（在循环体的末端）对网格进行一次全局细化。\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// 为此，首先建立一个描述映射的对象。这是用MappingQ类来完成的，该类在构造函数中采用了它应使用的多项式程度作为参数。\n\n            const MappingQ<dim> mapping(degree); \n\n// 顺便提一下，对于一个片状线性映射，你可以给MappingQ的构造函数一个 <code>1</code> 的值，但也有一个MappingQ1类可以达到同样的效果。历史上，它以比MappingQ更简单的方式做了很多事情，但今天只是后者的一个包装。然而，如果你没有明确指定另一个映射，它仍然是库中许多地方隐含使用的类。\n\n// 为了真正用这个映射写出现在的网格，我们设置了一个对象，我们将用它来输出。我们将生成Gnuplot输出，它由一组描述映射的三角图的线条组成。默认情况下，三角剖分的每个面只画一条线，但由于我们想明确地看到映射的效果，所以我们想更详细地了解这些面。这可以通过传递给输出对象一个包含一些标志的结构来实现。在目前的情况下，由于Gnuplot只能画直线，我们在面孔上输出了一些额外的点，这样每个面孔就由30条小线来画，而不是只有一条。这足以让我们看到一条弯曲的线，而不是一组直线的印象。\n\n            GridOut               grid_out; \n            GridOutFlags::Gnuplot gnuplot_flags(false, 60); \n            grid_out.set_flags(gnuplot_flags); \n\n// 最后，生成一个文件名和一个用于输出的文件。\n\n            std::string filename = \n              filename_base + \"_mapping_q_\" + std::to_string(degree) + \".dat\"; \n            std::ofstream gnuplot_file(filename); \n\n// 然后把三角图写到这个文件里。该函数的最后一个参数是一个指向映射对象的指针。这个参数有一个默认值，如果没有给出值，就会取一个简单的MappingQ1对象，我们在上面简单介绍过。这样就会在输出中产生一个真实边界的片状线性近似。\n\n            grid_out.write_gnuplot(triangulation, gnuplot_file, &mapping); \n          } \n        std::cout << std::endl; \n\n// 在循环结束时，对网格进行全局细化。\n\n        triangulation.refine_global(); \n      } \n  } \n\n// 现在我们进行代码的主要部分，即 $\\pi$ 的近似。圆的面积当然是由 $\\pi r^2$ 给出的，所以有一个半径为1的圆，面积代表的只是被搜索的数字。面积的数值计算是通过在整个计算域中积分值为1的常数函数来进行的，即通过计算面积 $\\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)$ ，其中总和延伸到三角形中所有活动单元上的所有正交点， $w(x_i)$ 是正交点的重量 $x_i$ 。每个单元上的积分都是通过数字正交来逼近的，因此我们唯一需要的额外成分是建立一个FEValues对象，提供每个单元的相应`JxW`值。注意`JxW`是指<i>Jacobian determinant\n// times weight</i>的缩写；因为在数字正交中，两个因子总是出现在相同的地方，所以我们只提供合并的数量，而不是两个单独的数量）。我们注意到，在这里我们不会在其最初的目的中使用FEValues对象，即用于计算特定正交点上的特定有限元的基函数值。相反，我们只用它来获得正交点的 \"JxW\"，而不考虑我们将给FEValues对象的构造者的（假）有限元。给予FEValues对象的实际有限元根本不使用，所以我们可以给任何。\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// 对于所有单元的数字正交，我们采用足够高的正交规则。我们选择8阶的QGauss（4点），以确保数字正交引起的误差比由于边界近似的阶数，即所采用的映射的阶数（最大6）要高。请注意，积分，雅各布行列式，不是一个多项式函数（相反，它是一个有理函数），所以我们不使用高斯正交来获得积分的精确值，就像在有限元计算中经常做的那样，但也可以使用任何类似阶数的正交公式来代替。\n\n    const QGauss<dim> quadrature(4); \n\n// 现在开始在多项式映射度=1...4的基础上进行循环。\n\n    for (unsigned int degree = 1; degree < 5; ++degree) \n      { \n        std::cout << \"Degree = \" << degree << std::endl; \n\n// 首先生成三角形、边界和映射对象，正如已经看到的那样。\n\n        Triangulation<dim> triangulation; \n        GridGenerator::hyper_ball(triangulation); \n\n        const MappingQ<dim> mapping(degree); \n\n// 我们现在创建一个有限元。与其他的例子程序不同，我们实际上不需要用形状函数做任何计算；我们只需要FEValues对象的`JxW`值。因此，我们使用特殊的有限元类FE_Nothing，它的每个单元的自由度正好为零（顾名思义，每个单元的局部基础为空集）。FE_Nothing的一个比较典型的用法见  step-46  。\n\n        const FE_Nothing<dim> fe; \n\n// 同样地，我们需要创建一个DoFHandler对象。我们实际上并没有使用它，但是它将为我们提供`active_cell_iterators'，这是重新初始化三角形的每个单元上的FEValues对象所需要的。\n\n        DoFHandler<dim> dof_handler(triangulation); \n\n// 现在我们设置FEValues对象，向构造函数提供Mapping、假有限元和正交对象，以及要求只在正交点提供`JxW`值的更新标志。这告诉FEValues对象在调用 <code>reinit</code> 函数时不需要计算其他数量，从而节省计算时间。\n\n// 与之前的例子程序相比，FEValues对象的构造最重要的区别是，我们传递了一个映射对象作为第一个参数，它将被用于计算从单元到实数单元的映射。在以前的例子中，这个参数被省略了，结果是隐含地使用了MappingQ1类型的对象。\n\n        FEValues<dim> fe_values(mapping, fe, quadrature, update_JxW_values); \n\n// 我们使用一个ConvergenceTable类的对象来存储所有重要的数据，如 $\\pi$ 的近似值和与 $\\pi$ 的真实值相比的误差。我们还将使用ConvergenceTable类提供的函数来计算 $\\pi$ 的近似值的收敛率。\n\n        ConvergenceTable table; \n\n// 现在我们在三角形的几个细化步骤上循环。\n\n        for (unsigned int refinement = 0; refinement < 6; \n             ++refinement, triangulation.refine_global(1)) \n          { \n\n// 在这个循环中，我们首先将当前三角形的活动单元的数量添加到表格中。这个函数会自动创建一个上标为 \"cells \"的表格列，以防这个列之前没有被创建。\n\n            table.add_value(\"cells\", triangulation.n_active_cells()); \n\n// 然后我们为虚拟有限元分配自由度。严格来说，在我们的特殊情况下，我们不需要这个函数的调用，但我们调用它是为了让DoFHandler高兴 -- 否则它将在下面的 FEValues::reinit 函数中抛出一个断言。\n\n            dof_handler.distribute_dofs(fe); \n\n// 我们将变量面积定义为 \"长双\"，就像我们之前为 \"pi \"变量所做的那样。\n\n            long double area = 0; \n\n// 现在我们循环所有的单元格，重新初始化每个单元格的FEValues对象，并将该单元格的所有`JxW`值加到`area`上......\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// ...并将得到的区域值和错误存储在表中。我们需要静态转换为双数，因为没有实现add_value(string, long double)函数。请注意，这也涉及到第二个调用，因为 <code>std</code> 命名空间中的 <code>fabs</code> 函数在其参数类型上是重载的，所以存在一个获取并返回 <code>long double</code> 的版本，而全局命名空间中只有一个这样的函数被声明（获取并返回一个双数）。\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// 我们想计算`error`列的收敛率。因此我们需要在调用`evaluate_all_convergence_rates`之前，将其他列从收敛率评估中省略。\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// 最后我们设置一些量的输出精度和科学模式...\n\n        table.set_precision(\"eval.pi\", 16); \n        table.set_scientific(\"error\", true); \n\n// ...并将整个表格写到  std::cout.  。\n        table.write_text(std::cout); \n\n        std::cout << std::endl; \n      } \n  } \n\n// 下面的第二个函数也是计算 $\\pi$ 的近似值，但这次是通过域的周长 $2\\pi r$ 而不是面积。这个函数只是前一个函数的一个变体。因此，我们主要是给出不同之处的文件。\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// 我们采取同样的正交顺序，但这次是`dim-1`维正交，因为我们将在（边界）线上而不是在单元上积分。\n\n    const QGauss<dim - 1> quadrature(4); \n\n// 我们在所有度数上循环，创建三角形、边界、映射、假有限元和DoFHandler对象，如之前所见。\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// 然后我们创建一个FEFaceValues对象，而不是像前一个函数中的FEValues对象。同样，我们传递一个映射作为第一个参数。\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// 现在我们在所有单元和每个单元的所有面上运行。只有边界面上的`JxW`值的贡献被添加到长双变量`周长`中。\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// 我们用单元格迭代器和面的编号重新启动FEFaceValues对象。\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// 然后将评估后的数值存储在表中...\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// ......然后像前一个函数那样结束这个函数。\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// 下面的主函数只是按照上述函数的出现顺序来调用它们。除此以外，它看起来就像以前的教程程序的主函数一样。\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": "// 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": "/**\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": "#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": "/* 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 * 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": "#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": "//==================================================================================================\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": "// 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": "#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": "#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": "/* 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": "/**\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": "#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 <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 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": "/* ---------------------------------------------------------------------\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": "#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": "#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": "/******************************************************************************\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//输入左右相机类,左相机像素坐标,归一化坐标,估计的深度,特征点所在的金字塔层,外参\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);// 特征点在左相机坐标中的位置\n  //这个是一半块的大小,在不同的金子塔层patch的大小也是需要缩放的\n  float d_unit = halfpatch_size * (1 << level_ref);\n  //这里在算以px_ref为原点,uv的方向\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  //反投影\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    //初始深度\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      // 利用外参把这三点变换到右相机坐标系下\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        //如果都投影成功的话,计算仿射变换(每列就是某轴变换以后的方向)\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// 找到合适金字塔层\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  //行列式小于3为止\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//将左相机图像特征点中心的图像块warp到右相机图像坐标系中\n// Compute acc squared patch that is *warperd* from img_ref with A_cur_ref.\n//输入之前得到的粗略的仿射矩阵,左相机特征点所在所在金字塔图像,左特征点像素坐标,左特征的金字塔层，右相机需要搜索的金字塔层,\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//变换到对应的金字塔层坐标上\n  for (int y = 0; y < patch_size; ++y)\n  {\n    for (int x = 0; x < patch_size; ++x, ++patch_ptr)// // 以建立patch坐标系\n    {\n      Vector2f px_patch(x - halfpatch_size, y - halfpatch_size);\n      px_patch *= (1 << level_cur);//缩放\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]);//将左相机图像warp到右相机图像坐标系中\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": "// Copyright (c) 2021 Marcus Valtonen Örnhag\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": "/**\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": "// 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": "#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": "#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": "// 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#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//  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": "/*\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": "#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": "//==================================================================================================\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 *\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 <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": "#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": "#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>ρ</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": "/*\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º\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ón.\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": "//=======================================================================\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 \"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": "// 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": "/* -*- 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\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// 以上是相当常见的包含文件。这些文件还包括稀疏直接类的文件 SparseDirectUMFPACK。这不是解决大型线性问题的最有效的方法，但现在可以了。\n\n// 像往常一样，我们把所有的东西都放到一个共同的命名空间里。然后，我们开始声明一些常数的符号名称，这些常数将在本教程中使用。具体来说，我们在这个程序中有*多的变量（当然是密度和位移，但也有未过滤的密度和相当多的拉格朗日乘数）。我们很容易忘记这些变量在求解向量中的哪个位置，而且试图用数字来表示这些向量分量是一个错误的处方。相反，我们定义的静态变量可以在所有这些地方使用，而且只需初始化一次。在实践中，这将导致一些冗长的表达式，但它们更具可读性，而且不太可能出错。\n\n// 一个类似的问题出现在系统矩阵和向量中块的排序上。矩阵中有 $9\\times 9$ 块，而且很难记住哪个是哪个。对这些块也使用符号名称要容易得多。\n\n// 最后，我们为我们将要使用的边界指标引入符号名称，与  step-19  中的精神相同。\n\n// 在所有这些情况下，我们将这些变量声明为命名空间中的成员。在求解组件的情况下，这些变量的具体数值取决于空间维度，因此我们使用[模板变量](https:en.cppreference.com/w/cpp/language/variable_template)来使变量的数值取决于模板参数，就像我们经常使用模板函数一样。\n\nnamespace SAND \n{ \n  using namespace dealii; \n\n// 这个命名空间记录了我们的有限元系统中与每个变量相对应的第一个组件。\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// 这是一个命名空间，它记录了哪个区块对应于哪个变量。\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// 接下来是这个问题的主类。大多数函数都遵循教程程序的常规命名方式，不过有几个函数因为长度问题被从通常称为`setup_system()`的函数中分离出来，还有一些函数是处理优化算法的各个方面的。\n\n// 作为额外的奖励，该程序将计算出的设计写成STL文件，例如，可以将其发送给3D打印机。\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// 大部分的成员变量也是标准的。但是，有一些变量是专门与优化算法有关的（比如下面的各种标量因子），以及过滤器矩阵，以确保设计保持平稳。\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// 我们初始化一个由2  $\\times$  dim `FE_Q(1)`元素组成的FES系统，用于位移变量及其拉格朗日乘数，以及7 `FE_DGQ(0)`元素。 这些片状常数函数用于与密度相关的变量：密度本身、未过滤的密度、用于未过滤的密度的下限和上限的松弛变量，然后是用于过滤和未过滤的密度之间的连接以及不等式约束的拉格朗日乘子。\n\n// 这些元素出现的顺序在上面有记载。\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// 然后，第一步是创建与介绍中的问题描述相匹配的三角形--一个6乘1的矩形（或者一个6乘1乘1的3D盒子），在这个盒子的顶部中心将施加一个力。然后，这个三角形被均匀地细化若干次。\n\n// 与本程序的其他部分相比，这个函数特别假定我们是在2D中，如果我们想转到3D模拟，就需要进行修改。我们通过函数顶部的断言来确保没有人试图不经修改就意外地在三维中运行。\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// 第二步是将边界指标应用于边界的一部分。下面的代码分别为盒子的底部、顶部、左侧和右侧的边界分配了边界指示器。顶部边界的中心区域被赋予一个单独的边界指示器。这就是我们要施加向下力的地方。\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// 接下来，确定由于边界值而产生的约束。 域的底角在 $y$ 方向保持不变--左下角也在 $x$ 方向。deal.II通常认为边界值是附着在边界的片段上的，即面，而不是单个顶点。的确，从数学上讲，对于无穷大的偏微分方程，我们不能把边界值分配给单个点。但是，由于我们试图重现一个广泛使用的基准，我们还是要这样做，并牢记我们有一个有限维的问题，在单个节点上施加边界条件是有效的。\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// 检查当前面是否在底层边界上，如果是，则检查其顶点之一是否可能是左底层或右底层顶点。\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// 下一个函数制作了一个巨大的9乘9的块状矩阵，并且还设置了必要的块状向量。 这个矩阵的稀疏度模式包括滤波矩阵的稀疏度模式。它还初始化了我们将使用的任何块向量。\n\n// 设置块本身并不复杂，并且遵循诸如  step-22  等程序中已经完成的工作，例如。\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// 该函数的大部分内容是设置这些块中哪些将实际包含任何内容，即哪些变量与哪些其他变量相耦合。这很麻烦，但也是必要的，以确保我们不会为我们的矩阵分配大量的条目，而这些条目最终会变成零。\n\n// 你在下面看到的具体模式可能需要在纸上画一次，但是从我们在每次非线性迭代中必须组装的双线性形式的许多项来看，它是相对直接的方式。\n\n// 使用命名空间 \"SolutionComponents \"中定义的符号名称有助于理解下面每个项所对应的内容，但它也使表达式变得冗长而不流畅。像 `coupling[SolutionComponents::density_upper_slack_multiplier<dim>][SolutionComponents::density<dim>]` 这样的术语读起来就不太顺口，要么必须分成几行，要么几乎跑到每个屏幕的右边缘。因此，我们打开了一个大括号封闭的代码块，在这个代码块中，我们通过说 \"使用命名空间SolutionComponents\"，暂时使命名空间`SolutionComponents'中的名字可用，而不需要命名空间修饰语。\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      /*位移的联结  */ \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      /*松弛变量的耦合 */ \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// 在创建稀疏模式之前，我们还必须设置约束。由于这个程序没有自适应地细化网格，我们唯一的约束是将所有的密度变量耦合在一起，强制执行体积约束。这将最终导致矩阵的密集子块，但我们对此没有什么办法。\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// 现在我们终于可以为矩阵创建稀疏模式了，考虑到哪些变量与哪些其他变量耦合，以及我们对密度的约束。\n\n    DoFTools::make_sparsity_pattern(dof_handler, coupling, dsp, constraints); \n\n// 矩阵中唯一没有处理的部分是过滤矩阵和它的转置。这些都是非局部（积分）运算符，目前deal.II还没有相关的函数。我们最终需要做的是遍历所有单元，并将此单元上的未过滤密度与小于阈值距离的相邻单元的所有过滤密度联系起来，反之亦然；目前，我们只关心建立与这种矩阵相对应的稀疏模式，所以我们执行等效循环，以后我们将写进矩阵的一个条目，现在我们只需向稀疏矩阵添加一个条目。\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// 在生成了 \"动态 \"稀疏度模式之后，我们终于可以将其复制到用于将矩阵与稀疏度模式联系起来的结构中。由于稀疏模式很大很复杂，我们还将其输出到一个自己的文件中，以达到可视化的目的--换句话说，是为了 \"可视化调试\"。\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// 剩下的就是正确确定各种向量及其块的大小，以及为（非线性）解向量的一些分量设置初始猜测。我们在这里使用解向量各个区块的符号分量名称，为了简洁起见，使用与上面的 \"使用命名空间 \"相同的技巧。\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// 接下来是一个在程序开始时使用一次的函数。它创建了一个矩阵 $H$ ，使过滤后的密度向量等于 $H$ 乘以未过滤的密度。 这个矩阵的创建是非同小可的，它在每次迭代中都会被使用，因此，与其像我们对牛顿矩阵那样对其进行改造，不如只做一次并单独存储。\n\n// 这个矩阵的计算方式遵循上面已经使用过的大纲，以形成其稀疏模式。我们在这里对这个单独形成的矩阵的稀疏性模式重复这个过程，然后实际建立矩阵本身。你可能想看看本程序介绍中关于这个矩阵的定义。\n\n  template <int dim> \n  void SANDTopOpt<dim>::setup_filter_matrix() \n  { \n\n// 滤波器的稀疏模式已经在setup_system()函数中确定并实现。我们从相应的块中复制该结构，并在这里再次使用它。\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// 在建立了稀疏模式之后，现在我们重新做所有这些循环，以实际计算矩阵项的必要值。\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// 最后一步是对矩阵进行标准化处理，使每一行的条目之和等于1。\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// 这个函数用于建立过滤矩阵。我们创建一个输入单元的一定半径内的所有单元迭代器的集合。这些是与过滤器有关的邻近单元。\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函数建立了一个只要网格不改变就不变的矩阵（在这个程序中我们反正不改变），而下一个函数建立了每次迭代都要解决的矩阵。这就是奇迹发生的地方。描述牛顿求解KKT条件的方法的线性方程组的组成部分在这里实现。\n\n// 这个函数的顶部与大多数此类函数一样，只是设置了实际装配所需的各种变量，包括一大堆提取器。如果你以前看过  step-22  ，整个设置应该看起来很熟悉，尽管有些冗长。\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// 在这一点上，我们对未过滤的密度进行过滤，并对未过滤的密度乘法器进行邻接（转置）操作，都是对当前非线性解决方案的最佳猜测。后来我们用它来告诉我们，我们过滤的密度与应用于未过滤密度的过滤器有多大的偏差。这是因为在非线性问题的解中，我们有 $\\rho=H\\varrho$ ，但在中间迭代中，我们一般有 $\\rho^k\\neq H\\varrho^k$ ，然后 \"残差\" $\\rho^k-H\\varrho^k$ 将出现在我们下面计算的牛顿更新方程中的右边。\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// 作为构建系统矩阵的一部分，我们需要从我们目前对解决方案的猜测中获取数值。以下几行代码将检索出所需的值。\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// 我们还需要几个与来自拉格朗日的第一导数的测试函数相对应的数值，也就是 $d_{\\bullet}$ 函数。这些都是在这里计算的。\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// 最后，我们需要来自拉格朗日的第二轮导数的数值，即 $c_{\\bullet}$ 函数。这些是在这里计算的。\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// 这就是实际工作的开始。在下文中，我们将建立矩阵的所有项--它们数量众多，而且不完全是不言自明的，也取决于之前的解和它的导数（我们已经在上面评估了这些导数，并将其放入名为`old_*`的变量中）。为了理解这些条款的每一个对应的内容，你要看一下上面介绍中这些条款的明确形式。                    被驱动到0的方程的右边给出了寻找局部最小值的所有KKT条件--每个单独方程的描述都是随着右边的计算给出的。\n\n                    /* 方程1  */ \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                    /* 方程2  */ \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                   /*方程3，这与过滤器有关 */ \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                     /* 方程4：原始可行性  */ \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                   /*等式5：原始可行性  */ \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                  /* 等式6：原始可行性  */ \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// 现在我们已经把所有的东西都组装好了，我们要做的就是处理（Dirichlet）边界条件的影响和其他约束。我们将前者与当前单元的贡献结合在一起，然后让AffineConstraint类来处理后者，同时将当前单元的贡献复制到全局线性系统中。\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// 在积累了所有属于牛顿矩阵的项之后，我们现在还必须计算右手边的项（即负残差）。我们已经在另一个函数中做了这个工作，所以我们在这里调用它。\n\n    system_rhs = calculate_test_rhs(nonlinear_solution); \n\n// 这里我们使用我们已经构建好的过滤器矩阵。我们只需要整合这个应用于测试函数的过滤器，它是片状常数，所以整合变成了简单的乘以单元格的度量。 遍历预制的过滤器矩阵可以让我们使用哪些单元格在过滤器中或不在过滤器中的信息，而不需要再次重复检查邻居单元格。\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// 我们将需要在每次迭代中解决一个线性系统。我们暂时使用一个直接求解器--对于一个有这么多非零值的矩阵来说，这显然不是一个有效的选择，而且它不会扩展到任何有趣的地方。对于 \"真正的 \"应用，我们将需要一个迭代求解器，但系统的复杂性意味着一个迭代求解器的算法将需要大量的工作。因为这不是当前程序的重点，所以我们简单地坚持使用我们在这里的直接求解器--该函数遵循与 step-29 中使用的相同结构。\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// 接下来的几个函数处理优化算法的具体部分，最主要的是决定通过求解线性化（牛顿）系统计算出的方向是否可行，如果可行，我们要在这个方向上走多远。\n\n//  @sect4{Computing step lengths}  \n\n// 我们先用一个函数进行二进制搜索，找出符合对偶可行性的最大步骤--也就是说，我们能走多远，使  $s>0$  和  $z>0$  。该函数返回一对数值，分别代表 $s$ 和 $z$ 的松弛变量。\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// 下一个函数计算一个围绕 \"测试解向量 \"线性化的右手向量，我们可以用它来观察KKT条件的大小。 然后，这将用于在缩小障碍大小之前测试收敛性，以及计算 $l_1$ 的优点。\n\n// 这个函数冗长而复杂，但它实际上只是复制了上面`assemble_system()`函数的右侧部分的内容。\n\n  template <int dim> \n  BlockVector<double> SANDTopOpt<dim>::calculate_test_rhs( \n    const BlockVector<double> &test_solution) const \n  { \n\n// 我们首先创建一个零向量，其大小和阻塞为system_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                /* 方程1：这个方程以及方程\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                /*方程2；边界项将被进一步添加。\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               /* 方程3  */ \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               /* 方程4；边界项将再次被处理。with 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                /* 方程5：该方程设定了下限的松弛量， 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                /* 方程6：该方程设定了上层松弛量variable 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                /*等式7：这是在\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                /*方程8：这与方程9一起给出了\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                /*方程9  */ \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  // 我们在这里使用的算法使用一个 \"看门狗 \"策略来确定从当前迭代的位置和程度。 我们将看门狗策略建立在一个精确的 $l_1$ 功绩函数上。这个函数计算一个给定的、假定的、下一个迭代的精确 $l_1$ 功绩。\n\n  //优点函数由目标函数的总和（简单来说就是外力的积分（在域的边界上）乘以测试解的位移值（通常是当前解加上牛顿更新的某个倍数），以及残差向量的拉格朗日乘数分量的 $l_1$ 准则组成。下面的代码依次计算这些部分。\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    // 从计算目标函数开始。\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    //然后\n    //计算残差，并取对应于拉格朗日多边形的组件的 $l_1$ 准则。我们把这些加到上面计算的目标函数中，并在底部返回总和。\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  // 接下来是实际计算从当前状态（作为第一个参数传递）开始的搜索方向并返回结果向量的函数。为此，该函数首先调用与牛顿系统相对应的线性系统的组合函数，并对其进行求解。\n\n  // 这个函数还更新了优点函数中的惩罚乘数，然后返回最大比例的可行步骤。它使用`calculate_max_step_sizes()`函数来找到满足  $s>0$  和  $z>0$  的最大可行步骤。\n\n  template <int dim> \n  BlockVector<double> SANDTopOpt<dim>::find_max_step() \n  { \n    assemble_system(); \n    BlockVector<double> step = solve(); \n\n    // 接下来我们要更新punice_multiplier。 从本质上讲，更大的惩罚乘数使我们更多考虑约束条件。 观察与我们的决策变量有关的Hessian和梯度，并将其与我们的约束误差的规范相比较，可以确保我们的优点函数是 \"精确的\"\n\n    // 也就是说，它在与目标函数相同的位置有一个最小值。 由于我们的优点函数对任何超过某个最小值的惩罚乘数都是精确的，所以我们只保留计算值，如果它增加了惩罚乘数。\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    // 基于所有这些，我们现在可以计算出原始变量和对偶变量（拉格朗日乘数）的步长。一旦我们有了这些，我们就可以对解向量的分量进行缩放，这就是这个函数的回报。\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  // 下一个函数接着实现了直线搜索的反向跟踪算法。它不断缩小步长，直到找到一个优点减少的步长，然后根据当前的状态向量，以及要进入的方向，乘以步长，返回新的位置。\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  // 本块中的最后一个辅助函数是检查是否充分满足KKT条件，以便整个算法可以降低障碍物的大小。它通过计算残差的 $l_1$ 准则来实现，这就是`calculate_test_rhs()`的计算。\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  // 后处理函数中的第一个函数在VTU文件中输出信息，用于可视化。它看起来很长，但实际上与  step-22  中所做的一样，例如，只是增加了（很多）解决方案的变量。\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  // 其中第二个函数将解决方案输出为`.stl`文件，用于3D打印。STL](https:en.wikipedia.org/wiki/STL_(file_format))文件是由三角形和法线向量组成的，我们将用它来显示所有那些密度值大于0的单元，首先将网格从 $z$ 值挤出到 $z=0.25$  ，然后为密度值足够大的单元的每个面生成两个三角形。当从外面看时，三角形节点必须逆时针走，法向量必须是指向外部的单位向量，这需要进行一些检查。\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            // 我们现在已经找到了一个密度值大于0的单元。让我们先写出底部和顶部的面。由于上面提到的排序问题，我们必须确保了解一个单元的坐标系是右旋的还是左旋的。我们通过询问从顶点0开始的两条边的方向以及它们是否形成一个右手坐标系来做到这一点。\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               /*在z=0处写出一个边。  */ \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               /*在z=高度处写下一个边。  */  \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               /* 在z=0处写出一边。  */ \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               /*在z=高度处写出一个边。  */ \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            // 接下来我们需要处理单元格的四个面，扩展到 $z$ 方向。然而，我们只需要写这些面，如果该面在域的边界上，或者它是密度大于0.5的单元和密度小于0.5的单元之间的界面。\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  // 这个函数最终提供了整体的驱动逻辑。从总体上看，这是一个相当复杂的函数，主要是因为优化算法很困难：它不仅仅是像 step-15 中那样找到一个牛顿方向，然后在这个方向上再走一个固定的距离，而是要（i）确定当前步骤中的最佳对数障碍惩罚参数应该是什么，（ii）通过复杂的算法来确定我们要走多远，还有其他成分。让我们看看如何在下面的文件中把它分解成小块。\n\n  // 该函数一开始就很简单，首先设置了网格、DoFHandler，然后是下面所需的各种线性代数对象。\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  // 然后，我们设置一些影响优化算法的对数屏障和直线搜索部分的参数。\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    // 现在开始进行主迭代。整个算法通过使用一个外循环来工作，在这个外循环中，我们一直循环到（i）对数障碍参数变得足够小，或者（ii）我们已经达到收敛。在任何情况下，如果最终的迭代次数过多，我们就会终止。这个整体结构被编码为一个 \"do{ ... } while (...)`循环，其中收敛条件在底部。\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        // 在这个外循环中，我们有一个内循环，在这个内循环中，我们试图使用介绍中描述的看门狗算法找到一个更新方向。\n\n        // 看门狗算法本身的总体思路是这样的。对于最大的`max_uphill_steps`（即上述 \"内循环 \"中的一个循环）的尝试，我们使用`find_max_step()`来计算牛顿更新步骤，并在`nonlinear_solution`向量中加上这些。 在每一次尝试中（从上一次尝试结束时到达的地方开始），我们检查我们是否已经达到了上述优点函数的目标值。目标值是根据本算法的起始位置（看门狗循环开始时的`nonlinear_solution'，保存为`看门狗_state'）和本循环第一个回合中`find_max_step()'提供的第一个建议方向（`k=0'情况）计算的。\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            //然后\n            //算法的下一部分取决于上面的看门狗循环是否成功。如果成功了，那么我们就满意了，不需要进一步的行动。我们只是停留在原地。然而，如果我们在上面的循环中采取了最大数量的不成功的步骤，那么我们就需要做一些别的事情，这就是下面的代码块所做的。    具体来说，从上述循环的最后（不成功的）状态开始，我们再寻找一个更新方向，并采取所谓的 \"伸展步骤\"。如果该拉伸状态满足涉及优点函数的条件，那么我们就去那里。另一方面，如果拉伸状态也是不可接受的（就像上面所有的看门狗步骤一样），那么我们就放弃上面所有的看门狗步骤，在我们开始看门狗迭代的地方重新开始--那个地方被存储在上面的`看门狗_状态`变量中。更具体地说，下面的条件首先测试我们是否从`看门狗_state`方向的`first_step`走了一步，或者我们是否可以从拉伸状态再做一次更新来找到一个新的地方。有可能这两种情况实际上都不比我们在看门狗算法开始时的状态好，但即使是这样，那个地方显然是个困难的地方，离开后从另一个地方开始下一次迭代可能是一个有用的策略，最终收敛。    我们不断重复上面的看门狗步骤以及下面的逻辑，直到这个内部迭代最终收敛（或者如果我们遇到最大的迭代次数--在这里我们把线性求解的次数算作迭代次数，并在每次调用`find_max_step()`时增加计数器，因为这就是线性求解实际发生的地方）。在任何情况下，在这些内部迭代的每一次结束时，我们也会以适合可视化的形式输出解决方案。\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                // 如果我们没有得到一个成功的看门狗步骤，我们现在需要决定是回到我们开始的地方，还是使用最终状态。 我们比较这两个位置的优劣，然后从哪个位置取一个按比例的步长。 由于按比例的步长可以保证降低优点，所以我们最终会保留这两个位置中的一个。\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        // 在外循环结束时，我们必须更新屏障参数，为此我们使用以下公式。该函数的其余部分只是检查外循环的收敛条件，如果我们决定终止计算，就把最终的 \"设计 \"写成STL文件，用于3D打印，并输出一些时间信息。\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// 余下的代码，即`main()`函数，和平常一样。\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": "#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": "/**\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": "/* -*- 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": "//---------------------------------------------------------------------------//\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": "\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) 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 <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": "// 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 <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": "/*=============================================================================================================\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 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": "//\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// 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": "#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 Сергей Кривонос 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 <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": "#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        // 内部保持パラメータ\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用のパラメータ -> スマートポインタで保持し、それをパラメータのリストに格納\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作成 -> スマートポインタで実装(コンストラクタを抜けた時に、実体が消されないようにするため)\n        // 左辺の型はautoにしてはいけない(BaseLayerで統一し、コンテナに格納する ※ポリモーフィズムの実現)\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ではaffine2の出力、lossではlastlayerの出力を使うので分ける\n\n        // 生のポインタを格納すると実体がスコープ外となり解放されてしまうので、shared_ptrで対処\n        _layers[\"Affine1\"] = affine1;\n        _layers[\"ReLU1\"] = relu1;\n        _layers[\"Affine2\"] = affine2;\n        _last_layer = last_layer;\n\n        // 各パラメータへのポインタを格納\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では追加順が保存されないので、別途順番通り名称を格納したコンテナを用意\n        _layer_list.push_back(\"Affine1\");\n        // _layer_list.push_back(\"BatchNorm\"); // for batchnorm debug 21/03/21追加\n        _layer_list.push_back(\"ReLU1\");\n        _layer_list.push_back(\"Affine2\");\n\n        // ------------------------------------------------\n        // for batchnorm debug 21/03/21追加\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のバリデーションをしておくか？\n        vector<MatrixXd> X = inputs; // 入力もvectorなので、そのまま受ければOK\n        vector<MatrixXd> tmp_X;\n\n        // mapのrange-forは内部的にstd::pairが返される\n        for (auto layer : _layer_list)\n        {\n            // cout << layer << endl;\n            tmp_X = _layers[layer]->forward(X);\n            X.swap(tmp_X); // 中身入れ替え\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 -> 逆伝播計算に必要な情報を各レイヤにキャッシュ\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        // 逆順ループ → Boostライブラリのboost::adaptors::reverse()を使う方がEasyではある\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に格納している変数はBaseLayerにアップキャストしているので、ダウンキャストが必要 -> nullptrのときは実行しないようにする\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追加\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    //     // [&]は、スコープ外の変数を参照するというキャプチャー(ここではthisポインタを使うために指定)\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    //     // 直接内部のレイヤのパラメータにアクセスするので、ダウンキャストが必要\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 の検証用\n    // 【21/04/06】\n    // とりあえず動作することを目指すので、最初はreluで構成\n    // 後ほどsigmoid含めて動くように変更。初期値も XavierとHeの両方を選択できるようにする。\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); // パラメータも指定できるようにする？\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の変数初期化\n        this->_init_weight(weight_initializer);\n\n    }\n\n\n    void MultiLayerModel::_init_weight(string weight_initializer)\n    {\n        // weight_initializerの文字列を小文字に変換\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        // あとは Weight Decay の項も計算してLossに加える\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の検証用\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のサイズは固定\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": "//==================================================================================================\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": "/* ----------------------------------------------------------------------------\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": "/* 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": "/***************************************************************************\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": "#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": "// 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": "// 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": "#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": "#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 ‘operator*=’ (operand types are ‘arma::subview_row<double>’ and ‘arma::vec {aka arma::Col<double>}’)\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": "// 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": "#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": "#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": "/*** \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            // 构造 KD 树\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": "#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 * 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": "#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": "/* 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#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": "/* -*- 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//\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änkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n// #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": "/*\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": "#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/*                                                                           */\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": "#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": "#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": "#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": "#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ção de paridade original\n*\n* Ht_long: Referência de onde guardar o array em que cada elemento é uma linha de Ht\n* \n* Erros_1: Referência de onde guardar o\n    array em que cada elemento é um erro de peso=1 (mas só a porção de informação desse erro)\n*   exemplo: se há 5 bits na palavra-código e os 2 primeiros são de informação, então um elemento \n*   de Erros_1 pode ser 3=0b11, significando erro em cada um dos 2 bits de informação\n*\n* n_linhas, n_colunas, n_informacao: Quantas linhas e colunas tem Ht, e quantos bits são de informação\n*   na palavra código (assume-se que são correspondem às 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ó necessários os ulongs correspondentes a cada síndrome\n    */\n    for (int i = 0; i < n_linhas; ++i)\n    {\n        Ht_long[i] = Ht[i].to_ulong();\n    }\n\n    /** \n    * Porção de informação dos erros associados a cada síndrome\n    * (por isso só importam os erros em bits de informação)\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á que só se coletam os erros de informação\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írgula e \\n, sem espaços\n*\n* M: Matriz onde armazenar a leitura. \n*   Restrição: linha/coluna pode ter, no máximo (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índromes*/; ++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índrome->erro\"\n*\n* Ht: Matriz de verificação de paridade (transposta). Assume-se que suas últimas linhas\n* correspondem aos bits de informação (identidade em cima, outras linhas embaixo)\n*\n* n_linhas, n_colunas, n_informacao: Quantas linhas e colunas tem Ht, e quantos bits são de informação\n*   na palavra código (assume-se que são correspondem às primeiras linhas de Ht)\n*\n* peso_maximo: O peso dos maiores erros de informação 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ª linha de Ht -> erro só no 1º bit de info\n    assert(dict.at(1064615018496) == 17179869184); // 2ª linha de Ht -> erro só no 2º bit de info\n    assert(dict.at(34896576512) == 51539607552); // 1ª+2ª linhas de Ht -> erros nos 2 MSB de info\n    assert(dict.at(1052568944640) == 55834574848); // 1ª+2ª+4ª linhas de Ht -> erros nos 1º,2º,4º bits de info\n    assert(dict.at(549755813888) == 0); // erro composto só pela 37ª linha de Ht não aparece nos bits de info\n    assert(dict.at(481038172167) == 1); // mas se erro for de 36ª+37ª linhas de Ht -> erro no último bit de info \n                                         // (e ignora o bit de paridade)\n}\n\n\n/**\n* Retorna nova matriz em que cada linha é 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ão 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ódigo.\n*\n* Transmitido: Assume-se que cada linha é uma palavra-código\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 ≃ \" << ((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írgulas (sem espaço)\n* \n* Ht_csv: Matriz de verificação de paridade (transposta). Mesmo formato de `amostras_informacao_csv`\n*\n* Gt_csv: Matriz de geração do código (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índrome com peso maior que isto, ela não será 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índrome [1, 0, 0, 1] com erro associado [1, 0, 1, ...]\n    *   em que as reticências indicam a parte do erro concernente aos bits de paridade (não 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ça \" << (Transmitido_informacao[i] ^ Info[i]) << std::endl;\n            //     std::cout << \"Originais: \" << Transmitido[i] << \" versus \" << mult(Gt, Info[i]) << std::endl;\n            //     std::cout << \"diferença: \" << (Transmitido[i] ^ mult(Gt, Info[i])) << std::endl;\n            //     std::cout << \"síndrome: \" << 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": "// 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": "/*\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": "// 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": "#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 * @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": "#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#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": "//\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": "#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": "//  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": "/*-------------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": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Brédif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef 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": "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// 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 <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": "#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": "/*\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": "/*\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": "/* 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//\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": "/**\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": "#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": "// 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) 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 * 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": "#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 \"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": "#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// 演算\n\tF merge;\n\t// 単位元\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// モノイド(Z,+)\n\tSegmentTree(const vector<T> a)\n\t\t: SegmentTree(a, [](T a, T b) { return a + b; }, 0) {}\n\n\t// 更新\n\t// 関数の指定がなければ置き換え\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// 一点取得\n\tT find(const size_t index) { return this->tree[index + size - 1]; }\n\n\t// 区間取得\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// 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 <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": "/****************************************************************************\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": "#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; // 用于搜索最近点\n\n\n    // sensor_msgs::PointCloud2 -> pcl::PointCloud\n    pcl::fromROSMsg(*msg, *pc);\n\n    // is_dense 用于表示点云中的所有数据是否合法\n    // 设置为 否，让后续的函数再检查一遍，把 Nan（not a number）\n    // 这种不合法的数值全部去掉\n    pc->is_dense = false;\n    pcl::removeNaNFromPointCloud(*pc, *pc, indices);\n\n    // 初始化 kd 树\n    kdtree.setInputCloud(pc);\n\n    // 提前将需要在循环中用到的变量初始化好，放置在循环中重复构造变量与析构，拖慢程序运行速度\n    const int k = 20;                           // 临近点数量，根据作业要求设置为 20\n    std::vector<int> point_idx(k);              // 用来保存临近点再原来点云中的下标\n    std::vector<float> point_sq_dis(k);         // 用来保存临近点到目标点距离的平方\n    std::vector<float> features(6);             // 用来保存六种点云特征\n    std::vector<float> e(3);                    // 用来保存 k+1 个点经过 PCA 分析后得到的三个特征值计算得到的 e，从大到小排序\n    std::ofstream file;                         // 输出计算结果的目标文件\n    Eigen::Matrix<float, 3, 21> nearest_points; // 3x(k+1) 维的矩阵，用来保存点云中的点\n    Eigen::Matrix3f covariance;                 // 用来保存协方差矩阵\n    Eigen::Vector3f m, eigen_value;             // m 为 k+1 个点的质心，eigen_value 用来保存计算好的计算好的特征值\n\n    // 打开文件，没有就凭空创建一个，如果有就删掉里面的内容，再写入新的\n    // 一般不会出错\n    file.open(\"wcm.txt\");\n\n    // pcl::PointCloud 中保存点的对象，我们用引用单独给他拿出来\n    // 方便后续写代码\n    auto& points = pc->points;\n    for (size_t i = 0; i < pc->size(); i++)\n    {\n        // 每隔五个点计算一次特征值，作业没有要求这么做\n        // 只是想这么做，希望能快点\n        if(i%5 != 0) continue;\n\n        // 重置 m，因为 m 需要累加，而其他的变量只需要赋值\n        m = m.Zero();\n\n        // 搜索目标点最近的几个点\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        // 累加搜索后的数据\n        for (size_t j = 0; j < k; j++)\n        {\n            // 矩阵的块操作，将每个点作为列向量存入 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        // 矩阵的广播操作，将每一列减去 k+1 个点的质心\n        // http://eigen.tuxfamily.org/dox/group__TutorialReductionsVisitorsBroadcasting.html\n        nearest_points.colwise() -= (m/(k+1));\n\n        // 计算协方差矩阵\n        covariance = nearest_points * nearest_points.transpose();\n\n        // 对称矩阵求特征值\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver(covariance);\n        eigen_value = solver.eigenvalues();\n\n        // 矩阵的 reduction 操作，计算矩阵所有元素的和\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        // 计算点云特征\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        // 将结果写入文件，空格分开，最有追加一个换行\n        // 这种特殊的换行有清空缓冲区的效果\n        for(auto& num : features)\n            file << num << \" \";\n        file << std::endl;\n    }\n    // 关闭文件\n    file.close();\n    \n    std::cout << \"cal done\" << std::endl;\n\n    // 关闭节点\n    // 下面是官方描述\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": "// Copyright András Vukics 2006–2020. 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": "/*\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": "/*\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 * \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": "//            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": "/******************************************************************************\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ücker 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  // ここで sagemath を使っている．\r\n  // sagemath を使わなければ，1000倍は早くなるはず．\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// 正規化（一方の permutation を(1, 2, 3, ..., n)に変換）し，perm に格納\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// -----（ここまで）出力データから二つの permutation を読み込んで正規化 -----\r\n\r\n\tcanonization(); // 標準形に変換\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": "// ----------------------------------------------------------------------------\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": "#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": "///////////////////////////////////////////////////////////////////////////////\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": "#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//         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": "// 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": "#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": "// 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": "// 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": "/**\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": "/*\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": "// 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": "#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": "#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    // 寻优参数x的初始值，为5\n    double initial_x = 5.0;\n    double x = initial_x;\n\n    // 第二部分：构建寻优问题\n    Problem problem;\n    CostFunction* cost_function =\n            new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor); //使用自动求导，将之前的代价函数结构体传入，第一个1是输出维度，即残差的维度，第二个1是输入维度，即待寻优参数x的维度。\n    problem.AddResidualBlock(cost_function, NULL, &x); //向问题中添加误差项，本问题比较简单，添加一个就行。\n\n    //第三部分： 配置并运行求解器\n    Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_QR; //配置增量方程的解法\n    options.minimizer_progress_to_stdout = true;//输出到cout\n    Solver::Summary summary;//优化信息\n    ceres::Solve(options, &problem, &summary);//求解!!!\n\n    std::cout << summary.BriefReport() << \"\\n\";//输出优化的简要信息\n    //最终结果\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": "// 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": "#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": "// 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": "/**\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": "/* @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": "\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": "/* ----------------------------------------------------------------------------\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": "/* ----------------------------------------------------------------------------\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//                                                                //\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 <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": "#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// 这些公式参考这些：https://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// 从这往后新加的代码\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/* 实现的功能：\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// 参数含义： N：元素个数 left：   right：     X：   Y：\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)); // 看绝对值超过1，置1，否则为0\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///*## 我写的量化公式 start ---- ####################################################################*/\n///*\n//bit_width:量化的位宽\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///*## 我写的量化公式 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": "\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": "/*\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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_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 <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": "#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": "#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}; // 激光雷达间相对位姿关系 \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，其中法向量为(a, b, c)\n    // std::cout<<\"平面参数：\"<<std::endl;\n    // std::cout<<\"a：\"<<coefficients->values[0]<<std::endl;\n    // std::cout<<\"b：\"<<coefficients->values[1]<<std::endl;\n    // std::cout<<\"c：\"<<coefficients->values[2]<<std::endl;\n    // std::cout<<\"d：\"<<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，其中法向量为(a, b, c)\n    // std::cout<<\"平面参数：\"<<std::endl;\n    // std::cout<<\"a：\"<<coefficients->values[0]<<std::endl;\n    // std::cout<<\"b：\"<<coefficients->values[1]<<std::endl;\n    // std::cout<<\"c：\"<<coefficients->values[2]<<std::endl;\n    // std::cout<<\"d：\"<<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                // 两平面法线的夹角作为一个损失值\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  // 接下来标平移：（之所以分开标定是因为如果平移不准，起码保证旋转是准的，平移不会影响旋转。实验发现，这样标定的话平移也挺准）\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                // 一共有三维损失值，分别代表：。。。。。。先加一维\n                // 0：质心距离\n                // 计算质心\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                    // 先将点用旋转转过去：\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<<\"======================最终标定结果======================\"<<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 * @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 <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 *\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": "/**\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": "#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": "#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 <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": "// 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#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": "/**\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": "///////////////////////////////////////////////////////////////////////////////\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": "#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": "/* -------------------------------------------------------------------------\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é Mañas Álvarez, 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": "/*\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": "#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": "// 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": "#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": "///////////////////////////////////////////////////////////////////////////////\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 * \\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": "// 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 <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 <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": "// 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": "#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": "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 * 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": "#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": "// 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": "#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": "//\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": "// 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": "/**\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 (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 \"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": "\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": "/*=============================================================================\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": "// 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   \\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 - μI) * 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        // α_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 β.\n        if (i == iter_count - 1) {\n            break;\n        }\n        // v -= α_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 -= β_{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        // β_i = ||v||\n        beta_v(i) = std::sqrt(work_states.at(2).get_squared_norm());\n        // q_{i+1} = v / β_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 λ is an eigenvalue of T and q is the eigenvector, Tq = λq.\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 = λq, VV^* AVq = Vλq, A(Vq) = λ(Vq).\n    // So, an eigenvector of A for λ 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 - μI) * 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 -= α_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 -= β_{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 / β_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": "// 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": "#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": "// 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": "/*\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": "#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": "﻿#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": "#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": "#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* @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": "/*  $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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_MATRIX_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": "/******************************************************************************\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": "#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": "// 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)ロボットのローカル座標での足配置位置\n    double y_;                  //(m)ロボットのローカル座標での足配置位置\n    bool support_foot_is_right; //支持脚がどちらか\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.左右の脚で踏み出すのを1セットで1歩とする.\n *\n * @param x_destination (m) 目標地点:X.ロボット進行方向\n * @param y_destination (m) 目標地点:Y\n * @param x_stride (m) 1歩の大きさ.遊脚が身体の前に出る長さ=x_stride/2.\n * @param support_time (s) 歩行周期.(=支持脚が支持している時間:Tsup)\n * @param steps (none) 歩数.目標地点まで何歩で進むか.0以下に指定すると最大のストライドで進む.\n * @return std::vector<FootPrint> ロボットのローカル座標で表した着地位置を返す.\n * @details 今の所x方向への直線移動しか対応していない.\n * @todo y方向の移動の実装\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; //(無) 歩数\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のワールド座標 {CoM = Center of Mass}\n    double xd = 0, yd = 0, xdi = 0, ydi = 0; // CoMの速度 v(m/s) xdot(t)\n    double px = 0.0, py = 0.0;               //(m)　着地位置のワールド座標 これは実用的にはローカルの方が良いのでは？？\n    constexpr double Tc = std::sqrt(zh / g); //微分方程式の時定数\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); //誤差を無くすため\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        //決められた次の一歩を着く地点までの遊脚の移動を行っている時のシミュレーション---------------\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ともにn歩目開始時の状態\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        //次の一歩の目標位置を計算------------------\n        static constexpr double a = 10;\n        static constexpr double b = 1;\n        C = std::cosh(Tsup / Tc); //意味は全く無いが分かりやすさのため\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; //歩行素片による位置\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;               //(無) 歩数\n    double x = 0, y = 0, xi = 0, yi = 0;     //(m) CoMのワールド座標 {CoM = Center of Mass}\n    double xd = 0, yd = 0, xdi = 0, ydi = 0; // CoMの速度 v(m/s) xdot(t)\n    double px = 0.0, py = 0.0;               //(m)　着地位置のワールド座標 これは実用的にはローカルの方が良いのでは？？\n    constexpr double Tc = std::sqrt(zh / g); //微分方程式の時定数\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        //決められた次の一歩を着く地点までの遊脚の移動を行っている時のシミュレーション---------------\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ともにn歩目開始時の状態\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        //次の一歩の目標位置を計算------------------\n        static constexpr double a = 30;\n        static constexpr double b = 1;\n        C = std::cosh(Tsup / Tc); //意味は全く無いが分かりやすさのため\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; //歩行素片による位置\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 * 状態をなるべく持たせない.\n * 取り敢えず歩ける事を示したいのでなるべく簡便な実装にする。\n * 一連の重心軌道を全て生成してしまってそこからどうにかするので良い\n * todo 速度が極大な所のtを表示させたい\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": "#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": "#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": "//\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": "\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": "\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": "#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 \"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": "//\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": "#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": "#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": "/*\n\n  Código 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án 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értice: \" << 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értice: %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értice 1: \";\n  while(!(cin >> v1)){\n    cin.clear();\n    cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n    cout << \"Entrada inválida, intenta otra vez: \";\n  }\n  if(!vertexExists(g, v1, pos1)) {\n    cout << \"El vértice con id \" << v1 << \" no existe, debe crearse antes\" << endl;\n  } else {\n      cin.ignore();\n      cout << \"Vértice 2: \";\n        while(!(cin >> v2)){\n          cin.clear();\n          cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n          cout << \"Entrada inválida, intenta otra vez: \";\n        }\n        if(!vertexExists(g, v2, pos2)) {\n          cout << \"El vértice 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álida, 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álida, 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értice: %f ms \\n\", time_taken*1000);\n      }\n    }\n  } else {\n      cout << \"El vértice 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értice 1 conectado por la arista: \";\n  while(!(cin >> v1)){\n    cin.clear();\n    cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n    cout << \"Entrada inválida, intenta otra vez: \";\n  }\n  if(vertexExists(g, v1,pos1)) {\n    cin.ignore();\n    cout << \"Id del vértice 2 conectado por la arista: \";\n    while(!(cin >> v2)){\n      cin.clear();\n      cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n      cout << \"Entrada inválida, 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értice con id \" << v2 << \" no existe \" << endl;\n      }\n  } else {\n      cout << \"El vértice 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": "/* ----------------------------------------------------------------------------\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": "/******************************************************************************\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 * \\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": "\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": "#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": "#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": "/**\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": "/*    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": "/*\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": "//==================================================================================================\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": "///////////////////////////////////////////////////////////////////////////////\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ⱼ\n * - a function t(j₁, j₂, s) which returns the time to travel from location j₁\n *   to location j₂ starting at time s\n * - a time limit tₘₐₓ\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ₘₐₓ\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": "/// @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": "/* -*-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éter 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": "// 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 \"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 *\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 §14.5.3/9: \"Friend declarations shall not declare partial\n    // specializations.\" We do access protected members in operator+=().\n    template <class OtherHandle>\n    friend class MLogRegrIRLSTransitionState;\n\npublic:\n\n\n    MLogRegrIRLSTransitionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n        rebind(static_cast<uint16_t>(mStorage[0]),static_cast<uint16_t>(mStorage[1]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the iteratively-reweighted-least-squares state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(\n        const Allocator &inAllocator, \n        uint16_t inWidthOfX, \n        uint16_t inNumCategories, uint16_t inRefCategory) {\n\n        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 §14.5.3/9: \"Friend declarations shall not declare partial\n    // specializations.\" We do access protected members in operator+=().\n    template <class OtherHandle>\n    friend class MLogRegrRobustTransitionState;\n\npublic:\n    MLogRegrRobustTransitionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n        rebind(static_cast<uint16_t>(mStorage[0]),static_cast<uint16_t>(mStorage[1]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the iteratively-reweighted-least-squares state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator, \n        uint16_t inWidthOfX, uint16_t inNumCategories, uint16_t inRefCategory) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n            dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(inWidthOfX, inNumCategories));\n        rebind(inWidthOfX, inNumCategories);\n        widthOfX = inWidthOfX;\n        numCategories = inNumCategories;\n        ref_category = inRefCategory;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle> MLogRegrRobustTransitionState &operator=(\n        const MLogRegrRobustTransitionState<OtherHandle> &inOtherState) {\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle> MLogRegrRobustTransitionState &operator+=(\n        const MLogRegrRobustTransitionState<OtherHandle> &inOtherState) {\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                \"states\");\n\n        numRows += inOtherState.numRows;\n        X_transp_AX += inOtherState.X_transp_AX;\n        meat += inOtherState.meat;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        meat.fill(0);\n        X_transp_AX.fill(0);\n    }\n\nprivate:\n    static inline uint32_t arraySize(const uint16_t inWidthOfX,\n        const uint16_t inNumCategories) {\n        return 4 + 2*inWidthOfX * inWidthOfX * inNumCategories * inNumCategories\n                                 + inWidthOfX * inNumCategories;\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX             The number of independent variables.\n     * @param inNumCategories The number of categories of the dependant var\n\n\n     * Array layout (iteration refers to one aggregate-function call):\n     * Inter-iteration components (updated in final function):\n     * - 0: widthOfX (number of independant variables)\n     * - 1: numCategories (number of categories)\n     * - 2: ref_category\n     * - 3: coef (vector of coefficients)\n     *\n     * Intra-iteration components (updated in transition step):\n     * - 3 + widthOfX*numCategories: numRows (number of rows already processed in this iteration)\n     * - 4 + widthOfX * inNumCategories: X_transp_AX (X^T A X).  \n     * - 4 + widthOfX^2*numCategories^2: meat  (The meat matrix)\n     */\n    void rebind(uint16_t inWidthOfX = 0, uint16_t inNumCategories = 0) {\n        widthOfX.rebind(&mStorage[0]);\n        numCategories.rebind(&mStorage[1]);\n        ref_category.rebind(&mStorage[2]);\n        coef.rebind(&mStorage[3], inWidthOfX * inNumCategories);\n        numRows.rebind(&mStorage[3 + inWidthOfX * inNumCategories]);\n        X_transp_AX.rebind(&mStorage[4 + inWidthOfX * inNumCategories],\n            inNumCategories * inWidthOfX, inWidthOfX * inNumCategories);\n        meat.rebind(&mStorage[4 +\n             inNumCategories * inNumCategories * inWidthOfX * inWidthOfX\n             + inWidthOfX * inNumCategories], inWidthOfX * inNumCategories, inWidthOfX * inNumCategories);\n    }\n\n    Handle mStorage;\n\npublic:\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ReferenceToUInt16 numCategories;\n\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 §14.5.3/9: \"Friend declarations shall not declare partial\n    // specializations.\" We do access protected members in operator+=().\n    template <class OtherHandle>\n    friend class 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": "#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": "//=======================================================================\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 \"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": "#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": "/* \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": "#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": "#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": "/*  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": "// 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// 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 <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 * 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 \"../../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": "// 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*       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çois 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": "/*=========================================================================\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)² + (y-yi)² + (z-zi)²) = 1 ), \n    // where x, y, and z are the indices of a pixel and xi, yi, and zi are the indeces of a neighboring pixel\n    // Iterate through all pixels of input and label images\n    */\n\n  int unmarkedLength = totalNodes - markedLength; /* Quantity of unmarked nodes */\n\n  // Define vectors to store graph data\n  std::vector<float> *nodes = new std::vector<float>(totalNodes);  /* Pixel intensity for all nodes/pixels */\n  std::vector<float> *labels = new std::vector<float>(totalNodes); /* Label of each node/pixel */\n  /*  For node 'i'. If 'i' is a marked node, previousFound->at(i) is how many unmarked nodes there are before node 'i'.\n        If 'i' is an unmarked node, previousFound->at(i) is how many marked nodes there are before node 'i'.\n        This values are needed to build ordered Lu and BT matrices.\n    */\n  std::vector<int> *previousFound = new std::vector<int>(totalNodes);\n  std::vector<int> *unmarked = new std::vector<int>(unmarkedLength); /* Indices of unmarked nodes ordered */\n  std::vector<int> *marked = new std::vector<int>(markedLength);     /* Store labels of marked nodes */\n  std::vector<int> *markedIdx = new std::vector<int>(markedLength);  /* Indices of marked nodes ordered */\n  std::vector<int> *nameLabels = new std::vector<int>();             /* Values of the different labels of the prior */\n\n  // Set bounding box image iterators\n  typedef itk::ImageRegionConstIterator<InputImageType> ConstIteratorImageType;\n  ConstIteratorImageType itImageCrop(this->GetInput(), regionCrop);\n  IteratorLabelType itLabelCrop(m_LabelImage, regionLabelCrop);\n\n  int foundMarked = 0;\n  int foundUnmarked = 0;\n  int NodeIdx = 0;\n\n  itImageCrop.GoToBegin();\n  itLabelCrop.GoToBegin();\n  while (!itImageCrop.IsAtEnd())\n  {\n    // Store intensity in a std::vector\n    nodes->at(NodeIdx) = itImageCrop.Get();\n    // Store labels in a std::vector. Each index of 'nodes' and 'labels' correspond to the same pixel\n    labels->at(NodeIdx) = itLabelCrop.Get();\n\n    if (itLabelCrop.Get() == 0)\n    {\n      // Get the index of each node that is unmarked\n      unmarked->at(foundUnmarked) = NodeIdx;\n      // Store how many marked points have been found before this unmarked node\n      previousFound->at(NodeIdx) = foundMarked;\n      ++foundUnmarked;\n    }\n    else\n    {\n      // Set to label value if label != 0\n      marked->at(foundMarked) = itLabelCrop.Get();\n      // Get the index of each node that is marked\n      markedIdx->at(foundMarked) = NodeIdx;\n      // Store how many unmarked points have been found before this marked node\n      previousFound->at(NodeIdx) = foundUnmarked;\n      ++foundMarked;\n      bool found;\n\n      // Store the different labels in a std::vector\n      found = std::find(nameLabels->begin(), nameLabels->end(), itLabelCrop.Get()) != nameLabels->end();\n      if (!found)\n      {\n        nameLabels->push_back(itLabelCrop.Get());\n      }\n    }\n    ++itImageCrop;\n    ++itLabelCrop;\n    ++NodeIdx;\n  }\n\n  // Sort labels\n  std::sort(nameLabels->begin(), nameLabels->end());\n\n  int totalLabels = nameLabels->size();\n\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": "///////////////////////////////////////////////////////////////////////////////\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      // パラメーターファイルを読み込む\n      std::ifstream ifs;\n      // 実行バイナリと同じフォルダから読み込む\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      // はみ出している線分を移動させる\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": "#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": "//# /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": "/*\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": "//=======================================================================\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": "// 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": "#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": "#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": "/*\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": "#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": "// 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": "#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": "/********************************************************************************\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 ：\"\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\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": "/*\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": "// 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 ⊕ xe, u = ul ⊕\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": "///////////////////////////////////////////////////////////////////////////////\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": "#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": "/* 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": "// 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": "#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": "/*\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": "/* ----------------------------------------------------------------------------\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 初始为true，收到vicon后设置为false\n    if(!first_frame_tag_odom)\n    { \n        // 第一次回调：发布初始值\n        if(first_frame_imu)\n        {\n            first_frame_imu = false;\n            time_now = msg->header.stamp.toSec();\n            time_last = time_now;\n            // 发布初始值\n            system_pub(msg->header.stamp);\n        }\n        else\n        {\n            time_now = msg->header.stamp.toSec();\n            // 时间差\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            // 将imu存为输入值\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            // 上一时刻姿态\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            // 使用输入更新状态\n            X_state += dt*F_model(u_gyro, u_acc);\n            // 欧拉角限制幅度\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            // 更新COV\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    // 位置\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    // 姿态\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    // 刚体的位置和姿态\n    Rr_w = q.toRotationMatrix();\n    tr_w = p_temp;\n    // imu的位置和姿态\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的位置和姿态\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    // 第一次回调\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        // 获取得到imu的位置姿态（imu和质心存在偏差）\n        VectorXd odom_pose = get_pose_from_mocap(msg);\n        // 更新测量值\n        Z_measurement.segment<3>(0) = odom_pose.segment<3>(0);\n        Z_measurement.segment<3>(3) = odom_pose.segment<3>(3);\n        // 发布测量值（即mocap的原始值）\n        cam_system_pub(msg->header.stamp);\n\n        Ct = diff_g_diff_x();\n        Wt = diff_g_diff_v();\n\n        // 更新kalman增益\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        // 使用测量值更新状态\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    // 【订阅】 IMU数据，来自PX4\n    ros::Subscriber s1 = n.subscribe(\"imu\", 100, imu_callback, ros::TransportHints().tcpNoDelay());\n    // 【订阅】 VICON数据\n    ros::Subscriber s2 = n.subscribe(\"pose\", 100, mocap_callback, ros::TransportHints().tcpNoDelay());\n    // 【发布】 融合后的odom(发布频率为imu的频率)\n    odom_pub = n.advertise<nav_msgs::Odometry>(\"ekf_odom\", 100);  \n    // 【发布】 相机odom？\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    // 初始化\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    // 测量值\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    // 状态维度 [p q pdot bg ba]  [px,py,pz, wx,wy,wz（欧拉角）, 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    // 测量维度 位置+姿态\n    measurementSize = 6;                                                            // z = [p q]\n    // 输入维度 w是角速度 a是加速度\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    // 输入\n    u_input = VectorXd::Zero(inputSize);\n    // 测量\n    Z_measurement = VectorXd::Zero(measurementSize);                                // z\n    // 状态cov\n    StateCovariance = MatrixXd::Identity(stateSize, stateSize);                     // sigma\n    // kalman增益\n    Kt_kalmanGain = MatrixXd::Identity(stateSize, measurementSize);                 // Kt\n    // Ct_stateToMeasurement = MatrixXd::Identity(stateSize, measurementSize);         // Ct\n    // ？\n    X_state_correct = X_state;\n    // ？\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° !!!!!!!!!\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": "#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": "\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": "/* 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": "\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// 前面几个文件已经在前面的例子中讲过了，因此不再做进一步的评论。\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// 这里定义了不连续的有限元。它们的使用方式与所有其他有限元相同，不过--正如你在以前的教程程序中所看到的--用户与有限元类的交互根本不多：它们被传递给 <code>DoFHandler</code> 和 <code>FEValues</code> 对象，仅此而已。\n\n#include <deal.II/fe/fe_dgq.h> \n\n// FEInterfaceValues需要这个头来计算界面上的积分。\n\n#include <deal.II/fe/fe_interface_values.h> \n\n// 我们将使用最简单的求解器，称为Richardson迭代，它代表了一个简单的缺陷修正。这与一个块状SSOR预处理器（定义在precondition_block.h中）相结合，该预处理器使用DG离散产生的系统矩阵的特殊块状结构。\n\n#include <deal.II/lac/solver_richardson.h> \n#include <deal.II/lac/precondition_block.h> \n\n// 我们将使用梯度作为细化指标。\n\n#include <deal.II/numerics/derivative_approximation.h> \n\n// 最后，新的包含文件用于使用MeshWorker框架中的Mesh_loop。\n\n#include <deal.II/meshworker/mesh_loop.h> \n\n// 像所有的程序一样，我们在完成这一部分时，要包括所需的C++头文件，并声明我们要使用dealii命名空间中的对象，不含前缀。\n\n#include <iostream> \n#include <fstream> \n\nnamespace Step12 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n// 首先，我们定义一个描述不均匀边界数据的类。由于只使用它的值，我们实现value_list()，但不定义Function的所有其他函数。\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// 考虑到流动方向，单位方块 $[0,1]^2$ 的流入边界是右边界和下边界。我们在x轴上规定了不连续的边界值1和0，在右边界上规定了值0。该函数在流出边界上的值将不会在DG方案中使用。\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// 最后，一个计算并返回风场的函数  $\\beta=\\beta(\\mathbf x)$  。正如在介绍中所解释的，在2D中我们将使用一个围绕原点的旋转场。在3D中，我们只需不设置 $z$ 分量（即为零），而这个函数在目前的实现中不能用于1D。\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// 以下对象是我们在调用 MeshWorker::mesh_loop(). 时使用的抓取和复制对象 新对象是FEInterfaceValues对象，它的工作原理类似于FEValues或FEFacesValues，只是它作用于两个单元格之间的接口，并允许我们以我们的弱形式组装接口条款。\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// 在这个准备工作之后，我们继续进行这个程序的主类，称为AdvectionProblem。\n\n// 这对你来说应该是非常熟悉的。有趣的细节只有在实现集合函数的时候才会出现。\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// 此外，我们要使用DG元素。\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// 接下来的四个成员代表要解决的线性系统。  <code>system_matrix</code> and <code>right_hand_side</code> 是由 <code>assemble_system()</code>, the <code>solution</code> 产生的，在 <code>solve()</code>. The <code>sparsity_pattern</code> 中计算，用于确定 <code>system_matrix</code> 中非零元素的位置。\n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> system_matrix; \n\n    Vector<double> solution; \n    Vector<double> right_hand_side; \n  }; \n\n// 我们从构造函数开始。 <code>fe</code> 的构造器调用中的1是多项式的度数。\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// 在设置通常的有限元数据结构的函数中，我们首先需要分配DoF。\n\n    dof_handler.distribute_dofs(fe); \n\n// 我们从生成稀疏模式开始。为此，我们首先用系统中出现的耦合物填充一个动态稀疏模式（DynamicSparsityPattern）类型的中间对象。在建立模式之后，这个对象被复制到 <code>sparsity_pattern</code> 并可以被丢弃。\n\n// 为了建立DG离散的稀疏模式，我们可以调用类似于 DoFTools::make_sparsity_pattern, 的函数，该函数被称为 DoFTools::make_flux_sparsity_pattern:  。\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_flux_sparsity_pattern(dof_handler, dsp); \n    sparsity_pattern.copy_from(dsp); \n\n// 最后，我们设置了线性系统的所有组成部分的结构。\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// 这里我们看到了与手工组装的主要区别。我们不需要在单元格和面上写循环，而是在调用 MeshWorker::mesh_loop() 时包含逻辑，我们只需要指定在每个单元格、每个边界面和每个内部面应该发生什么。这三个任务是由下面的函数里面的lambda函数处理的。\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// 这是将对每个单元格执行的函数。\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// 我们解决的是一个同质方程，因此在单元项中没有显示出右手。 剩下的就是整合矩阵条目。\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// 这是为边界面调用的函数，包括使用FEFaceValues的正常积分。新的逻辑是决定该术语是进入系统矩阵（流出）还是进入右手边（流入）。\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// 这是在内部面调用的函数。参数指定了单元格、面和子面的指数（用于自适应细化）。我们只是将它们传递给FEInterfaceValues的reinit()函数。\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// 下面的lambda函数将处理从单元格和面组件中复制数据到全局矩阵和右侧的问题。\n\n// 虽然我们不需要AffineConstraints对象，因为在DG离散中没有悬空节点约束，但我们在这里使用一个空对象，因为这允许我们使用其`copy_local_to_global`功能。\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// 在这里，我们最终处理了装配问题。我们传入ScratchData和CopyData对象，以及上面的lambda函数，并指定我们要对内部面进行一次装配。\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// 对于这个简单的问题，我们使用了最简单的求解器，称为Richardson迭代，它代表了简单的缺陷修正。这与一个块状SSOR预处理相结合，该预处理使用DG离散化产生的系统矩阵的特殊块状结构。这些块的大小是每个单元的DoF数量。这里，我们使用SSOR预处理，因为我们没有根据流场对DoFs进行重新编号。如果在流的下游方向对DoFs进行重新编号，那么块状的Gauss-Seidel预处理（见PreconditionBlockSOR类，放松=1）会做得更好。\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// 这里我们创建了预处理程序。\n\n    PreconditionBlockSSOR<SparseMatrix<double>> preconditioner; \n\n// 然后将矩阵分配给它，并设置正确的块大小。\n\n    preconditioner.initialize(system_matrix, fe.n_dofs_per_cell()); \n\n// 做完这些准备工作后，我们就可以启动线性求解器了。\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// 我们根据一个非常简单的细化标准来细化网格，即对解的梯度的近似。由于这里我们考虑的是DG(1)方法（即我们使用片状双线性形状函数），我们可以简单地计算每个单元的梯度。但是我们并不希望我们的细化指标只建立在每个单元的梯度上，而是希望同时建立在相邻单元之间的不连续解函数的跳跃上。最简单的方法是通过差分商计算近似梯度，包括考虑中的单元和其相邻的单元。这是由 <code>DerivativeApproximation</code> 类完成的，它计算近似梯度的方式类似于本教程 step-9 中描述的 <code>GradientEstimation</code> 。事实上， <code>DerivativeApproximation</code> 类是在 step-9 的 <code>GradientEstimation</code> 类之后开发的。与  step-9  中的讨论相关，这里我们考虑  $h^{1+d/2}|\\nabla_h u_h|$  。此外，我们注意到，我们不考虑近似的二次导数，因为线性平流方程的解一般不在 $H^2$ 中，而只在 $H^1$ 中（或者，更准确地说：在 $H^1_\\beta$ 中，即在方向 $\\beta$ 上的导数是可平方整除的函数空间）。\n\n  template <int dim> \n  void AdvectionProblem<dim>::refine_grid() \n  { \n\n//  <code>DerivativeApproximation</code> 类将梯度计算为浮点精度。这已经足够了，因为它们是近似的，只作为细化指标。\n\n    Vector<float> gradient_indicator(triangulation.n_active_cells()); \n\n// 现在，近似梯度被计算出来了\n\n    DerivativeApproximation::approximate_gradient(mapping, \n                                                  dof_handler, \n                                                  solution, \n                                                  gradient_indicator); \n\n//并且它们的单元格按系数 $h^{1+d/2}$ 进行缩放。\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// 最后它们作为细化指标。\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// 这个程序的输出包括一个自适应细化网格的vtk文件和数值解。最后，我们还用 VectorTools::integrate_difference(). 计算了解的L-无穷大规范。\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// 下面的 <code>run</code> 函数与前面的例子类似。\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// 下面的 <code>main</code> 函数与前面的例子也类似，不需要注释。\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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_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": "#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": "/* Copyright © 2017 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n#ifndef TURI_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": "/********************************************************************************\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": "/*\n Copyright (c) 2015-2017 Paul Lagrée, 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": "#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 * 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": "#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//四舍五入取整数\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    //在这里取到一个范围在0～2q的随机 数字\n    //在取一个矩阵的时候mod q 取四舍五入\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    //先取 e == N χ 。\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//对消息的加密\n//secret为要加密的数字\nboost::numeric::ublas::matrix<int > Enc(int secret)\n{\n    using matrix=boost::numeric::ublas::matrix<int>;\n    //密文 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    //倒置矩阵\n    MatrixA= boost::numeric::ublas::trans(MatrixA);\n    \n    //A倒置T * r\n    matrix tmp(n+1,1);\n    \n   tmp= boost::numeric::ublas::prod(MatrixA, r);\n    \n    //构建加密消息\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为密文\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": "/* 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 <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 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": "//////////////////////////////////////////////////////////////////////////////////////////////\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": "#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#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": "/* 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": "/* -*- 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": "/*    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 = Σ_{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(Σ_{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": "#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// 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": "\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": "/*\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 = ∅\n    // E'= G.E\n\n    // while E' ≠ ∅:\n    //     let (u, v) be an arbitrary edge of E'\n    //     C = C ∪ {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": "#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 \"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": "//=======================================================================\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": "#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// 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": "// 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": "//==================================================================================================\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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_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": "\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–15, 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 <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": "/* -*- 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": "// 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": "// 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": "#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": "/*\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": "//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": "#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": "/**\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": "// 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": "// 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": "// 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": "/*\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": "#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 定义了caffe 中用到的一些矩阵操作和数值计算的一些函数\n\n/* \n *功能： C=alpha*A*B+beta*C \n *A,B,C 是输入矩阵（一维数组格式） \n *CblasRowMajor :数据是行主序的（二维数据也是用一维数组储存的） \n *TransA, TransB：是否要对A和B做转置操作（CblasTrans CblasNoTrans） \n *M： A、C 的行数 \n *N： B、C 的列数 \n *K： A 的列数， B 的行数 \n *lda ： A的列数（不做转置）行数（做转置） \n *ldb： B的列数（不做转置）行数（做转置） \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功能： y=alpha*A*x+beta*y \n其中X和Y是向量，A 是矩阵 \nM：A 的行数 \nN：A 的列数 \ncblas_sgemv 中的 参数1 表示对X和Y的每个元素都进行操作 \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功能： Y=alpha*X+Y \nN：为X和Y中element的个数 \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功能：用常数 alpha 对 Y 进行初始化 \n函数 void *memset(void *buffer, char c, unsigned count) 一般为新申请的内存做初始化， \n功能是将buffer所指向内存中的每个字节的内容全部设置为c指定的ASCII值, count为块的大小, \n使用memset函数来初始化数组或者结构体比其他初始化方法更快一点 \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//功能： 给 Y 的每个 element 加上常数 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函数 void *memcpy(void *dest, void *src, unsigned int count) 把src所指向 \n的内存区域 copy到dest所指向的内存区域, count为块的大小 \n表头文件: #include <string.h> \n定义函数: void *memcpy(void *dest, const void *src, size_t n) \n函数说明: memcpy()用来拷贝src所指的内存内容前n个字节到dest所指的内存地址上。与strcpy()不同的是,memcpy()会完整的复制n个字节,不会因为遇到字符串结束'\\0'而结束 \n返回值:   返回指向dest的指针 \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功能：X = alpha*X \nN： X中element的个数 \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功能：这四个函数分别实现element-wise的加减乘除（y[i] = a[i] + - * \\ b[i]） \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功能：返回一个随机数 \n*/  \nunsigned int caffe_rng_rand() {\n  return (*caffe_rng())();\n}\n\n/* \n功能 ： 返回 b 最大方向上可以表示的最接近的数值。 \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功能： 返回 vector X 和 vector Y 的内积。 \nincx， incy ： 步长，即每隔incx 或 incy 个element 进行操作。 \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": "// ====================================================================\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": "// 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/*                                                                           */\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//         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änkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_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": "#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": "#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": "// 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’t 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": "//  (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": "/* -*-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": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\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": "#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// 这些包含文件已经为你所知。它们声明了处理三角形和自由度枚举的类。\n\n#include <deal.II/grid/tria.h> \n#include <deal.II/dofs/dof_handler.h> \n\n// 在这个文件中声明了创建网格的函数。\n\n#include <deal.II/grid/grid_generator.h> \n\n// 这个文件包含了对拉格朗日插值有限元的描述。\n\n#include <deal.II/fe/fe_q.h> \n\n// 而这个文件是创建稀疏矩阵的稀疏模式所需要的，如前面的例子中所示。\n\n#include <deal.II/dofs/dof_tools.h> \n\n// 接下来的两个文件是在每个单元上使用正交法组装矩阵所需要的。下面将对其中声明的类进行解释。\n\n#include <deal.II/fe/fe_values.h> \n#include <deal.II/base/quadrature_lib.h> \n\n// 以下是我们在处理边界值时需要的三个包含文件。\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// 我们现在几乎到了终点。第二组到最后一组include文件是用于线性代数的，我们用它来解决拉普拉斯方程的有限元离散化所产生的方程组。我们将使用向量和全矩阵在每个单元中组装方程组，并将结果转移到稀疏矩阵中。然后我们将使用共轭梯度求解器来解决这个问题，为此我们需要一个预处理程序（在这个程序中，我们使用身份预处理程序，它没有任何作用，但我们还是需要包括这个文件）。\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// 最后，这是为了输出到文件和控制台。\n\n#include <deal.II/numerics/data_out.h> \n#include <fstream> \n#include <iostream> \n\n// ...这是为了将deal.II命名空间导入到全局范围。\n\nusing namespace dealii; \n// @sect3{The <code>Step3</code> class}  \n\n// 在这个程序中，我们没有采用以前例子中的程序化编程，而是将所有东西都封装到一个类中。这个类由一些函数组成，这些函数分别执行有限元程序的某些方面，一个`main`函数控制先做什么和后做什么，还有一个成员变量列表。\n\n// 该类的公共部分相当简短：它有一个构造函数和一个从外部调用的函数`run`，其作用类似于`main`函数：它协调该类的哪些操作应以何种顺序运行。该类中的其他东西，即所有真正做事情的函数，都在该类的私有部分。\n\nclass Step3 \n{ \npublic: \n  Step3(); \n\n  void run(); \n\n// 然后，还有一些成员函数，它们主要是做它们名字所暗示的事情，在介绍中已经讨论过了。由于它们不需要从外部调用，所以它们是本类的私有函数。\n\nprivate: \n  void make_grid(); \n  void setup_system(); \n  void assemble_system(); \n  void solve(); \n  void output_results() const; \n\n// 最后我们还有一些成员变量。有一些变量描述了三角形和自由度的全局编号（我们将在这个类的构造函数中指定有限元的确切多项式程度）...\n\n  Triangulation<2> triangulation; \n  FE_Q<2>          fe; \n  DoFHandler<2>    dof_handler; \n\n// ...拉普拉斯方程离散化产生的系统矩阵的稀疏模式和数值的变量...\n\n  SparsityPattern      sparsity_pattern; \n  SparseMatrix<double> system_matrix; \n\n// .......以及用于保存右手边和解决方案向量的变量。\n\n  Vector<double> solution; \n  Vector<double> system_rhs; \n}; \n// @sect4{Step3::Step3}  \n\n// 这里是构造函数。它除了首先指定我们需要双线性元素（由有限元对象的参数表示，它表示多项式的程度），并将dof_handler变量与我们使用的三角形相关联之外，没有做更多的工作。(注意，目前三角结构并没有设置网格，但是DoFHandler并不关心：它只想知道它将与哪个三角结构相关联，只有当你使用distribution_dofs()函数试图在网格上分布自由度时，它才开始关心实际的网格。) Step3类的所有其他成员变量都有一个默认的构造函数，它可以完成我们想要的一切。\n\nStep3::Step3() \n  : fe(1) \n  , dof_handler(triangulation) \n{} \n// @sect4{Step3::make_grid}  \n\n// 现在，我们要做的第一件事是生成我们想在其上进行计算的三角形，并对每个顶点进行自由度编号。我们之前在 step-1 和 step-2 中分别看到过这两个步骤。\n\n// 这个函数做的是第一部分，创建网格。 我们创建网格并对所有单元格进行五次细化。由于初始网格（也就是正方形 $[-1,1] \\times [-1,1]$ ）只由一个单元组成，所以最终的网格有32乘以32个单元，总共是1024个。\n\n// 不确定1024是否是正确的数字？我们可以通过使用三角形上的 <code>n_active_cells()</code> 函数输出单元格的数量来检查。\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  我们调用 Triangulation::n_active_cells() 函数，而不是 Triangulation::n_cells(). 这里，<i>active</i>指的是没有进一步提炼的单元。我们强调 \"活跃 \"这个形容词，因为还有更多的单元，即最细的单元的父单元，它们的父单元等等，直到构成初始网格的一个单元为止。当然，在下一个更粗的层次上，单元格的数量是最细层次上的单元格的四分之一，即256，然后是64、16、4和1。如果你在上面的代码中调用 <code>triangulation.n_cells()</code> ，你会因此得到一个1365的值。另一方面，单元格的数量（相对于活动单元格的数量）通常没有什么意义，所以没有很好的理由去打印它。\n\n//  @sect4{Step3::setup_system}  \n\n// 接下来我们列举所有的自由度，并建立矩阵和向量对象来保存系统数据。枚举是通过使用 DoFHandler::distribute_dofs(), 来完成的，我们在 step-2 的例子中已经看到了。由于我们使用了FE_Q类，并且在构造函数中设置了多项式的度数为1，即双线性元素，这就将一个自由度与每个顶点联系起来。当我们在生成输出时，让我们也看看有多少自由度被生成。\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// 每个顶点应该有一个DoF。因为我们有一个32乘以32的网格，所以DoFs的数量应该是33乘以33，即1089。\n\n// 正如我们在前面的例子中所看到的，我们通过首先创建一个临时结构，标记那些可能为非零的条目，然后将数据复制到SparsityPattern对象中，然后可以被系统矩阵使用，来设置一个稀疏模式。\n\n  DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n  DoFTools::make_sparsity_pattern(dof_handler, dsp); \n  sparsity_pattern.copy_from(dsp); \n\n// 注意，SparsityPattern对象并不保存矩阵的值，它只保存条目所在的位置。条目本身存储在SparseMatrix类型的对象中，我们的变量system_matrix就是其中之一。\n\n// 稀疏模式和矩阵之间的区别是为了让几个矩阵使用相同的稀疏模式。这在这里似乎并不重要，但是当你考虑到矩阵的大小，以及建立稀疏模式可能需要一些时间时，如果你必须在程序中存储几个矩阵，这在大规模问题中就变得很重要了。\n\n  system_matrix.reinit(sparsity_pattern); \n\n// 在这个函数中要做的最后一件事是将右侧向量和解向量的大小设置为正确的值。\n\n  solution.reinit(dof_handler.n_dofs()); \n  system_rhs.reinit(dof_handler.n_dofs()); \n} \n// @sect4{Step3::assemble_system}  \n\n// 下一步是计算形成线性系统的矩阵和右手边的条目，我们从中计算出解决方案。这是每一个有限元程序的核心功能，我们在介绍中已经讨论了主要步骤。\n\n// 组装矩阵和向量的一般方法是在所有单元上循环，并在每个单元上通过正交计算该单元对全局矩阵和右侧的贡献。现在要认识到的一点是，我们需要实心单元上正交点位置的形状函数值。然而，有限元形状函数和正交点都只定义在参考单元上。因此，它们对我们帮助不大，事实上，我们几乎不会直接从这些对象中查询有关有限元形状函数或正交点的信息。\n\n// 相反，我们需要的是一种将这些数据从参考单元映射到实际单元的方法。能够做到这一点的类都是由Mapping类派生出来的，尽管人们常常不必直接与它们打交道：库中的许多函数都可以将映射对象作为参数，但当它被省略时，它们只是简单地诉诸于标准的双线性Q1映射。我们将走这条路，暂时不打扰它（我们将在 step-10 、 step-11 和 step-12 中再讨论这个问题）。\n\n// 所以我们现在有三个类的集合来处理：有限元、正交、和映射对象。这就太多了，所以有一种类型的类可以协调这三者之间的信息交流：FEValues类。如果给这三个对象各一个实例（或两个，以及一个隐式线性映射），它就能为你提供实心单元上正交点的形状函数值和梯度的信息。\n\n// 利用所有这些，我们将把这个问题的线性系统组装在以下函数中。\n\nvoid Step3::assemble_system() \n{ \n\n// 好的，我们开始吧：我们需要一个正交公式来计算每个单元格的积分。让我们采用一个高斯公式，每个方向有两个正交点，即总共有四个点，因为我们是在二维。这个正交公式可以准确地积分三度以下的多项式（在一维）。很容易检查出，这对目前的问题来说是足够的。\n\n  QGauss<2> quadrature_formula(fe.degree + 1); \n\n// 然后我们初始化我们在上面简单谈及的对象。它需要被告知我们要使用哪个有限元，以及正交点和它们的权重（由一个正交对象共同描述）。如前所述，我们使用隐含的Q1映射，而不是自己明确指定一个。最后，我们必须告诉它我们希望它在每个单元上计算什么：我们需要正交点的形状函数值（对于右手 $(\\varphi_i,f)$ ），它们的梯度（对于矩阵条目 $(\\nabla \\varphi_i, \\nabla \\varphi_j)$ ），以及正交点的权重和从参考单元到实际单元的雅各布变换的行列式。\n\n// 我们实际需要的信息列表是作为FEValues构造函数的第三个参数的标志集合给出的。由于这些值必须重新计算，或者说更新，每次我们进入一个新的单元时，所有这些标志都以前缀 <code>update_</code> 开始，然后指出我们想要更新的实际内容。如果我们想要计算形状函数的值，那么给出的标志是#update_values；对于梯度，它是#update_gradients。雅各布的行列式和正交权重总是一起使用的，所以只计算乘积（雅各布乘以权重，或者简称 <code>JxW</code> ）；由于我们需要它们，我们必须同时列出#update_JxW_values。\n\n  FEValues<2> fe_values(fe, \n                        quadrature_formula, \n                        update_values | update_gradients | update_JxW_values); \n\n// 这种方法的优点是，我们可以指定每个单元上究竟需要什么样的信息。很容易理解的是，这种方法可以大大加快有限元计算的速度，相比之下，所有的东西，包括二阶导数、单元的法向量等都在每个单元上计算，不管是否需要它们。\n\n//  @note  <code>update_values | update_gradients | update_JxW_values</code>的语法对于那些不习惯用C语言编程多年的位操作的人来说不是很明显。首先， <code>operator|</code> 是<i>bitwise or operator</i>，也就是说，它接受两个整数参数，这些参数被解释为比特模式，并返回一个整数，其中每个比特都被设置，因为在两个参数中至少有一个的对应比特被设置。例如，考虑操作 <code>9|10</code>. In binary, <code>9=0b1001</code> （其中前缀 <code>0b</code> 表示该数字将被解释为二进制数字）和 <code>10=0b1010</code>  。通过每个比特，看它是否在其中一个参数中被设置，我们得出 <code>0b1001|0b1010=0b1011</code> ，或者用十进制符号表示， <code>9|10=11</code>  。你需要知道的第二个信息是，各种 <code>update_*</code> 标志都是有<i>exactly one bit set</i>的整数。例如，假设  <code>update_values=0b00001=1</code>  ,  <code>update_gradients=0b00010=2</code>  ,  <code>update_JxW_values=0b10000=16</code>  。那么<code>update_values | update_gradients | update_JxW_values = 0b10011 = 19</code>。换句话说，我们得到一个数字，即<i>encodes a binary mask representing all of the operations you want to happen</i>，其中每个操作正好对应于整数中的一个位，如果等于1，意味着每个单元格上应该更新一个特定的片断，如果是0，意味着我们不需要计算它。换句话说，即使 <code>operator|</code> 是<i>bitwise OR operation</i>，它真正代表的是<i>I want this AND that AND the other</i>。这样的二进制掩码在C语言编程中很常见，但在C++这样的高级语言中也许不是这样，但对当前的目的有很好的作用。\n\n// 为了在下文中进一步使用，我们为一个将被频繁使用的值定义了一个快捷方式。也就是每个单元的自由度数的缩写（因为我们是在二维，自由度只与顶点相关，所以这个数字是4，但是我们更希望在写这个变量的定义时，不妨碍我们以后选择不同的有限元，每个单元有不同的自由度数，或者在不同的空间维度工作）。\n\n// 一般来说，使用符号名称而不是硬编码这些数字是个好主意，即使你知道它们，因为例如，你可能想在某个时候改变有限元。改变元素就必须在不同的函数中进行，而且很容易忘记在程序的另一部分做相应的改变。最好不要依赖自己的计算，而是向正确的对象索取信息。在这里，我们要求有限元告诉我们每个单元的自由度数，无论我们在程序中的其他地方选择什么样的空间尺寸或多项式程度，我们都会得到正确的数字。\n\n// 这里定义的快捷方式主要是为了讨论基本概念，而不是因为它节省了大量的输入，然后会使下面的循环更容易阅读。在大型程序中，你会在很多地方看到这样的快捷方式，`dofs_per_cell`就是一个或多或少是这类对象的传统名称。\n\n  const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n\n// 现在，我们说我们想逐个单元地组装全局矩阵和向量。我们可以将结果直接写入全局矩阵，但是这样做的效率并不高，因为对稀疏矩阵元素的访问是很慢的。相反，我们首先在一个小矩阵中计算每个单元的贡献，并在这个单元的计算结束后将其转移到全局矩阵中。我们对右手边的向量也是这样做的。所以我们首先分配这些对象（这些是局部对象，所有的自由度都与所有其他的自由度耦合，我们应该使用一个完整的矩阵对象，而不是一个用于局部操作的稀疏矩阵；以后所有的东西都将转移到全局的稀疏矩阵中）。\n\n  FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n  Vector<double>     cell_rhs(dofs_per_cell); \n\n// 在集合每个单元的贡献时，我们用自由度的局部编号（即从零到dofs_per_cell-1的编号）来做。然而，当我们将结果转移到全局矩阵时，我们必须知道自由度的全局编号。当我们查询它们时，我们需要为这些数字建立一个从头开始的（临时）数组（关于这里使用的类型， types::global_dof_index, ，见介绍末尾的讨论）。\n\n  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n// 现在是所有单元格的循环。我们之前已经看到这对一个三角形是如何工作的。DoFHandler的单元格迭代器与Triangulation的迭代器完全类似，但有关于你所使用的有限元的自由度的额外信息。在自由度处理程序的活动单元上进行循环操作的方法与三角法相同。\n\n// 注意，这次我们将单元的类型声明为`const auto &`，而不是`auto`。在第1步中，我们通过用细化指标标记来修改三角形的单元。在这里，我们只检查单元格而不修改它们，所以把`cell`声明为`const`是很好的做法，以便执行这个不变性。\n\n  for (const auto &cell : dof_handler.active_cell_iterators()) \n    { \n\n// 我们现在坐在一个单元上，我们希望计算形状函数的值和梯度，以及参考单元和真实单元之间映射的雅各布矩阵的行列式，在正交点上。由于所有这些值都取决于单元格的几何形状，我们必须让FEValues对象在每个单元格上重新计算它们。\n\n      fe_values.reinit(cell); \n\n// 接下来，在我们填充之前，将本地单元对全局矩阵和全局右手边的贡献重置为零。\n\n      cell_matrix = 0; \n      cell_rhs    = 0; \n\n// 现在是时候开始对单元进行积分了，我们通过对所有的正交点进行循环来完成，我们将用q_index来编号。\n\n      for (const unsigned int q_index : fe_values.quadrature_point_indices()) \n        { \n\n// 首先组装矩阵。对于拉普拉斯问题，每个单元格上的矩阵是形状函数i和j的梯度的积分。由于我们不进行积分，而是使用正交，所以这是在所有正交点的积分之和乘以正交点的雅各布矩阵的行列式乘以这个正交点的权重。你可以通过使用 <code>fe_values.shape_grad(i,q_index)</code> 得到形状函数 $i$ 在数字q_index的正交点上的梯度；这个梯度是一个二维向量（事实上它是张量 @<1,dim@>, 类型，这里dim=2），两个这样的向量的乘积是标量乘积，即两个shape_grad函数调用的积是点乘。这又要乘以雅各布行列式和正交点权重（通过调用 FEValues::JxW() 得到）。最后，对所有形状函数 $i$ 和 $j$ 重复上述操作。\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// 然后我们对右手边做同样的事情。在这里，积分是对形状函数i乘以右手边的函数，我们选择的是常值为1的函数（更有趣的例子将在下面的程序中考虑）。\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// 现在我们有了这个单元的贡献，我们必须把它转移到全局矩阵和右手边。为此，我们首先要找出这个单元上的自由度有哪些全局数字。让我们简单地询问该单元的信息。\n\n      cell->get_dof_indices(local_dof_indices); \n\n// 然后再次循环所有形状函数i和j，并将局部元素转移到全局矩阵中。全局数字可以用local_dof_indices[i]获得。\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// 再来，我们对右边的向量做同样的事情。\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\n// 为此，我们首先获得边界上的自由度列表以及形状函数在那里的值。为了简单起见，我们只对边界值函数进行插值，而不是将其投影到边界上。库中有一个函数正是这样做的。  VectorTools::interpolate_boundary_values(). 它的参数是（省略存在默认值而我们不关心的参数）：DoFHandler对象，用于获取边界上自由度的全局数字；边界上边界值应被内插的部分；边界值函数本身；以及输出对象。\n\n// 边界分量的含义如下：在很多情况下，你可能只想在边界的一部分施加某些边界值。例如，在流体力学中，你可能有流入和流出的边界，或者在身体变形计算中，身体的夹紧和自由部分。那么你就想用指标来表示边界的这些不同部分，并告诉interpolate_boundary_values函数只计算边界的某一部分（例如夹住的部分，或流入的边界）的边界值。默认情况下，所有的边界都有一个0的边界指标，除非另有规定。如果边界的部分有不同的边界条件，你必须用不同的边界指示器为这些部分编号。然后，下面的函数调用将只确定那些边界指标实际上是作为第二个参数指定的0的边界部分的边界值。\n\n// 描述边界值的函数是一个Function类型的对象或一个派生类的对象。其中一个派生类是 Functions::ZeroFunction, ，它描述了一个到处都是零的函数（并不意外）。我们就地创建这样一个对象，并将其传递给 VectorTools::interpolate_boundary_values() 函数。\n\n// 最后，输出对象是一对全局自由度数（即边界上的自由度数）和它们的边界值（这里所有条目都是零）的列表。这种自由度数到边界值的映射是由 <code>std::map</code> 类完成的。\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// 现在我们得到了边界DoF的列表和它们各自的边界值，让我们用它们来相应地修改方程组。这可以通过以下函数调用来实现。\n\n  MatrixTools::apply_boundary_values(boundary_values, \n                                     system_matrix, \n                                     solution, \n                                     system_rhs); \n} \n// @sect4{Step3::solve}  \n\n// 下面的函数简单地求解了离散化的方程。由于该系统对于高斯消除或LU分解等直接求解器来说是一个相当大的系统，我们使用共轭梯度算法。你应该记住，这里的变量数量（只有1089个）对于有限元计算来说是一个非常小的数字，而100.000是一个比较常见的数字。 对于这个数量的变量，直接方法已经不能使用了，你不得不使用CG这样的方法。\n\nvoid Step3::solve() \n{ \n\n// 首先，我们需要有一个对象，知道如何告诉CG算法何时停止。这是通过使用SolverControl对象来实现的，作为停止标准，我们说：在最多1000次迭代后停止（这远远超过了1089个变量的需要；见结果部分以了解真正使用了多少次），如果残差的规范低于 $10^{-12}$ 就停止。在实践中，后一个标准将是停止迭代的一个标准。\n\n  SolverControl solver_control(1000, 1e-12); \n\n// 然后，我们需要解算器本身。SolverCG类的模板参数是向量的类型，留下空的角括号将表明我们采取的是默认参数（即 <code>Vector@<double@></code>  ）。然而，我们明确地提到了模板参数。\n\n  SolverCG<Vector<double>> solver(solver_control); \n\n// 现在求解方程组。CG求解器的第四个参数是一个预处理程序。我们觉得还没有准备好深入研究这个问题，所以我们告诉它使用身份运算作为预处理。\n\n  solver.solve(system_matrix, solution, system_rhs, PreconditionIdentity()); \n\n// 现在求解器已经完成了它的工作，求解变量包含了求解函数的结点值。\n\n} \n// @sect4{Step3::output_results}  \n\n// 典型的有限元程序的最后一部分是输出结果，也许会做一些后处理（例如计算边界处的最大应力值，或者计算整个流出物的平均通量，等等）。我们这里没有这样的后处理，但是我们想把解决方案写到一个文件里。\n\nvoid Step3::output_results() const \n{ \n\n// 为了将输出写入文件，我们需要一个知道输出格式等的对象。这就是DataOut类，我们需要一个该类型的对象。\n\n  DataOut<2> data_out; \n\n// 现在我们必须告诉它从哪里获取它要写的值。我们告诉它使用哪个DoFHandler对象，以及求解向量（以及求解变量在输出文件中的名称）。如果我们有不止一个我们想在输出中查看的向量（例如右手边，每个单元格的错误，等等），我们也要把它们加进去。\n\n  data_out.attach_dof_handler(dof_handler); \n  data_out.add_data_vector(solution, \"solution\"); \n\n// 在DataOut对象知道它要处理哪些数据后，我们必须告诉它把它们处理成后端可以处理的数据。原因是我们将前端（知道如何处理DoFHandler对象和数据向量）与后端（知道许多不同的输出格式）分开，使用一种中间数据格式将数据从前端传输到后端。数据通过以下函数转换为这种中间格式。\n\n  data_out.build_patches(); \n\n// 现在我们已经为实际输出做好了一切准备。只要打开一个文件，用VTK格式把数据写进去就可以了（在我们这里使用的DataOut类中还有很多其他函数，可以把数据写成postscript、AVS、GMV、Gnuplot或其他一些文件格式）。\n\n  std::ofstream output(\"solution.vtk\"); \n  data_out.write_vtk(output); \n} \n// @sect4{Step3::run}  \n\n// 最后，这个类的最后一个函数是主函数，调用 <code>Step3</code> 类的所有其他函数。这样做的顺序类似于大多数有限元程序的工作顺序。由于这些名字大多是不言自明的，所以没有什么可评论的。\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// 这是程序的主函数。由于主函数的概念大多是C++编程之前的面向对象时代的遗留物，所以它通常不做更多的事情，只是创建一个顶层类的对象并调用其原理函数。\n\n// 最后，函数的第一行是用来启用deal.II可以生成的一些诊断程序的输出。  @p deallog 变量（代表deal-log，而不是de-allog）代表一个流，库的某些部分将输出写入其中。例如，迭代求解器将产生诊断程序（起始残差、求解器步骤数、最终残差），在运行这个教程程序时可以看到。\n\n//  @p deallog 的输出可以写到控制台，也可以写到文件，或者两者都写。两者在默认情况下都是禁用的，因为多年来我们已经知道，一个程序只应该在用户明确要求的时候才产生输出。但这是可以改变的，为了解释如何做到这一点，我们需要解释 @p deallog 是如何工作的。当库的个别部分想要记录输出时，它们会打开一个 \"上下文 \"或 \"部分\"，这个输出将被放入其中。在想要写输出的部分结束时，人们再次退出这个部分。由于一个函数可以在这个输出部分打开的范围内调用另一个函数，所以输出实际上可以分层嵌套到这些部分。LogStream类（ @p deallog 是一个变量）将这些部分中的每一个称为 \"前缀\"，因为所有的输出都以这个前缀打印在行的左端，前缀由冒号分隔。总是有一个默认的前缀叫做 \"DEAL\"（暗示了deal.II的历史，它是以前一个叫做 \"DEAL \"的库的继承者，LogStream类是被带入deal.II的少数代码之一）。\n\n// 默认情况下， @p logstream 只输出前缀为零的行--也就是说，所有的输出都是禁用的，因为默认的 \"DEAL \"前缀总是存在的。但人们可以为应该输出的行设置不同的最大前缀数，以达到更大的效果，事实上在这里我们通过调用 LogStream::depth_console(). 将其设置为两个。这意味着对于所有的屏幕输出，在默认的 \"DEAL \"之外再推一个前缀的上下文被允许将其输出打印到屏幕上（\"控制台\"），而所有进一步嵌套的部分将有三个或更多的前缀被激活，会写到 @p deallog, ，但 @p deallog 并不转发这个输出到屏幕。因此，运行这个例子（或者看 \"结果 \"部分），你会看到解算器的统计数据前缀为 \"DEAL:CG\"，这是两个前缀。这对于当前程序的上下文来说已经足够了，但是你将在以后看到一些例子（例如，在 step-22 中），其中求解器嵌套得更深，你可能通过设置更高的深度来获得有用的信息。\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": "#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 \"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": "#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": "#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// 比特串转化为字节的长度\n\tsize_t i;\n\tunsigned char triBytes[3];\t\t// 存储三个字节\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 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 <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// 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  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": "#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": "// 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 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": "#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": "/* 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": "#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": "/* 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": "#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": "/**\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": "\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": "/********************************************************************************\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": "\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//  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": "// [[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": "\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": "/*\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/*!\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": "///////////////////////////////////////////////////////////////////////////////\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": "// Copyright © 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ée \" << 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 \"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": "#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": "/*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 <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": "//\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": "\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": "﻿/*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": "//=======================================================================\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": "\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": "#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": "#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": "#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": "/*!\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 * 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": "// 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 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 \"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": "\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": "//# /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": "//=======================================================================\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": "/**\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": "////////////////////////////////////////////////////////////////////////////////\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 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 <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": "// 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": "/**\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": "// 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": "/*\n * Copyright (c) 2020-2021, Marco Sánchez Beeckman\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#include <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 \"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": "\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// 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": "/*\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": "#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": "#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": "#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": "// 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": "#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": "// 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": "\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": "/*\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 * 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\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": "#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": "//=======================================================================\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": "//=======================================================================\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": "/// \\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": "//==================================================================================================\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ᵗ then Σ=(Lᵗ)⁻¹L⁻¹.\n\t\t// We assume the log-likelihood looks like this:\n\t\t// f(x) = s(Lᵗ(x-x₀)) + O((x-x₀)³)\n\t\t// near the true maximum x₀, where s is the standard multivariate normal\n\t\t// log-density.  Then\n\t\t// f'(x) = -L Lᵗ (x-x₀) + O((x-x₀)²)   (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⁻¹ f'(x) = -Lᵗ(x-x₀) + O((x-x₀)²)\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": "\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": "#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'échantillons\nfloat deltaWaveLength = 4.;               //(En nm, espacement des échantillons)\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éparer 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ées sphériques (plus simple)\n//Utilisé 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ées de Boyer Lindquist au coordonnées cartésienne (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é pour l'intégration */\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 à partir des coord de BL (y) et de leurs dérivées (dydx)\n//Retourne un vecteur normé\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érations\n    int k = 0; //nombre de collision\n\n    float oldtheta; //pour detecter le passage à 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ée 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é 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écise\n            if (diskCollision)\n            {\n                if (k < rdr.maxtransparency)\n                {\n\n                    float phi = atan2(coll_y / r, coll_x / r); //Coordonné du point d'impact (en sphérique)\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ères 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és)\n                    //- à cause du sens des rayons\n\n                    //Temperature du disque à cet endroit\n                    float Temp = disk.Temp(r);\n\n                    //Décalage en fréquence égal à décalage en temperature, valable aussi pour l'intensité\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 à 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ération\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ée\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ération\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 étoiles)\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é de passer de cartesien à 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é sur la direction du rayon principal, qui contient les autres rayons (tjrs en terme de direction)\n            //Calcul en coord cartesienne pour éviter les discontinuités liées 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 échappés, on regarde quels étoiles sont dans le cercle formé 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écupere 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 égal à 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ées\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ètres ont été initialisés\"<<endl;\n        if (adisk == NULL)\n        {\n            cout<<\"L'image de départ n'a pas été trouvée\"<< endl;\n            exit(0);\n        }\n\n        /*rdr.height = 1080 / 8;\n        rdr.width = 1920 / 8;\n        rdr.R_inf = 21.5; //distance à partir de laquelle on considere etre a l'infini */\n\n        rdr.ChunkSizeHeight = 15; //Blocs de 15 par 15 pixels traités en parallele\n        rdr.ChunkSizeWidth = 15; //Blocs de 15 par 15 pixels traités 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ême faisceau\n\n        //bh.a = 0.5;   //spin (adimensionné,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épéter la texture du dique (en longeur pour ne pas qu'elle soit pixelisée)\n\n        rdr.precalc(bh.a2); //quelques calculs pour avoir les carrés de certaines qtité 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": "// 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 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": "/*\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 <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": "#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 <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(\"オプション\");\n  options.add_options()\n    (\"help,h\",    \"ヘルプを表示\")\n    (\"input,i\", boost::program_options::value<std::string>(),  \"入力ファイル\")\n    (\"output,o\", boost::program_options::value<std::string>(),  \"出力ファイル\")\n    (\"envelope,e\", boost::program_options::value<std::string>(),  \"エンベロープ\")\n    (\"note,n\", boost::program_options::value<int>()->default_value(60),  \"音階\")\n    (\"width,w\", boost::program_options::value<int>()->default_value(1024),  \"幅\")\n    (\"resolution,r\", boost::program_options::value<int>()->default_value(13),  \"分解能\")\n    (\"interval,j\", boost::program_options::value<int>()->default_value(100),  \"間隔\");\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": "#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 * @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": "#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": "// 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": "////////////////////////////////////////////////////////////////////////////////\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": "#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": "#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": "// 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": "#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": "/***********************************************************************\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 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": "/**\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": "/*=============================================================================\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’s horizon\n *\n * Azimuth\n * THe Azimuth, is in the range of 0◦ to 360◦ and indicates how far an object\n * in the sky is from the north as measured along an observer’s horizon.\n *\n * Altitude\n * The Altitude, represented by the symbol h, and ranges from −90◦ to +90◦.\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 \"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": "#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": "/*-----------------------------------------------------------------------------+\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": "#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": "#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": "/* -*- 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": "#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": "/*\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": "/**\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// 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": "#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": "/* 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": "#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 <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": "#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)²] 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₀² + 3x₀*x₁², 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öfberg, 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": "#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": "#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 * 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ürlich nur jeweils für 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ört) -- zuerst die eigenen DoF!\n\t\t *   Es ist garantiert, dass die DoF der Nachbarn in sich auch jeweils zusammenhängen (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üssen 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ür jeden Nachbarn: Ich schicke dem Nachbarn meine dofRecvFromNeighbor (das sind globale Indizes), die er mit regelmäßig 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ür 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ängt 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ür Arrays von Elementvektoren.\n\t\t// Dafür gehe ich für 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änger die\n\t\t// gleiche Sortierung haben, können Sender und Empfänger ohne weitere Kommunikation einen\n\t\t// \"Austauschplan\" für 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ängt 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ßend 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ür 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ür 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 überflüssig, 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ätzlich* an den i-ten Knoten gesendet werden müssen und wem sie gehören.\n\t\t\t// Iteriere dazu über die Elemente, die uns gehören und notiere alle Knoten, die nicht unsere sind.\n\t\t\t// Passe dabei aber auf, keine DoF doppelt hinzuzufügen!\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ören zusammenhängen.\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ür, dass die DoF für 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ür hypersurfaceDoFIndex=\" << hypersurfaceDoFIndex << \" von Hypersurface \" << _surfaceIndex <<\n\t\t\t\t//\t\t\" ist elementDoFIndex=\" << result << std::endl;\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tclass HypersurfaceDoFT {\n\t\t\tprivate:\n\t\t\t\tuint _hypersurfaceIndex;\n\t\t\t\tuint _elementIndex;\n\n\t\t\tpublic:\n\t\t\t\tHypersurfaceDoFT(uint hypersurfaceIndex, index_t elementIndex) : _hypersurfaceIndex(hypersurfaceIndex), _elementIndex(elementIndex) {}\n\n\t\t\t\toperator uint() const {\n\t\t\t\t\treturn _hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tuint index() const {\n\t\t\t\t\treturn _hypersurfaceIndex;\n\t\t\t\t}\n\n\t\t\t\tuint elementDoFIndex() const {\n\t\t\t\t\treturn _elementIndex;\n\t\t\t\t}\n\n\t\t\t\tbool operator==(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex == other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator!=(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex != other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator<(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex < other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator<=(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex <= other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator>(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex > other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t\tbool operator>=(HypersurfaceDoFT const& other) const {\n\t\t\t\t\treturn _hypersurfaceIndex >= other._hypersurfaceIndex;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\ttypename 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": "// 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 * 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": "#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": "\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/*!\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": "#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": "//          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": "/* ---------------------------------------------------------------------\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": "// 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": "/**\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": "//  (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": "#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üchler, P. Heitjans, A. Payer, and R. Schöllhorn, \"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": "/**\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": "#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 \"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": "\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包括的文件已经在前面的例子中介绍过了，因此不再做进一步的评论。\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// 而这又是C++。\n\n#include <array> \n#include <iostream> \n#include <fstream> \n\n// 最后一步和以前所有的程序一样。\n\nnamespace Step30 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n// 描述方程数据的类和单个术语的实际装配几乎完全照搬自  step-12  。我们将对差异进行评论。\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//流场选择为逆时针方向的四分之一圆，原点为域的右半部分的中点，数值为正 $x$ ，而在域的左边部分，流速只是向左走，与从右边进来的流速一致。在圆形部分，流速的大小与离原点的距离成正比。这与 step-12 不同，在该定义中，到处都是1。新定义导致 $\\beta$ 沿单元的每个给定面的线性变化。另一方面， $u(x,y)$ 的解决方案与之前完全相同。\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// 这个类的声明完全不受我们目前的变化影响。\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// 同样地，该类的构造函数以及组装对应于单元格内部和边界面的术语的函数与之前没有变化。装配单元间面术语的函数也没有改变，因为它所做的只是对两个FEFaceValuesBase类型的对象进行操作（它是FEFaceValues和FESubfaceValues的基类）。这些对象从何而来，即它们是如何被初始化的，对这个函数来说并不重要：它只是假设这两个对象所代表的面或子面上的正交点与物理空间中的相同点相对应。\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// 这个声明很像  step-12  的声明。然而，我们引入了一个新的例程（set_anisotropic_flags）并修改了另一个例程（refine_grid）。\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// 我们再次希望使用程度为1的DG元素（但这只在构造函数中指定）。如果你想使用不同程度的DG方法，请在构造函数中用新的程度替换1。\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// 这是新的，在介绍中解释的各向异性跳跃指标的评估中使用的阈值。它的值在构造函数中被设置为3.0，但它可以很容易地被改变为一个大于1的不同值。\n\n    const double anisotropic_threshold_ratio; \n\n// 这是一个指示是否使用各向异性细化的bool标志。它由构造函数设置，构造函数需要一个同名的参数。\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// 对于不同程度的DG方法，在这里进行修改。\n\n    degree(1) \n    , fe(degree) \n    , dof_handler(triangulation) \n    , anisotropic_threshold_ratio(3.) \n    , anisotropic(anisotropic) \n    , \n\n// 由于β是一个线性函数，我们可以选择正交的度数，对于这个度数，所得的积分是正确的。因此，我们选择使用  <code>degree+1</code>  高斯点，这使我们能够准确地积分度数为  <code>2*degree+1</code>  的多项式，足以满足我们在本程序中要进行的所有积分。\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// 我们继续使用 <code>assemble_system</code> 函数来实现DG离散化。这个函数与 step-12 中的 <code>assemble_system</code> 函数的作用相同（但没有MeshWorker）。 一个单元的邻居关系所考虑的四种情况与各向同性的情况相同，即a)单元在边界上，b)有更细的邻居单元，c)邻居既不粗也不细，d)邻居更粗。 然而，我们决定哪种情况的方式是按照介绍中描述的方式进行修改的。\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// 情况(a)。该面在边界上。\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// 情况(b)。这是一个内部面，邻居是精炼的（我们可以通过询问当前单元格的面是否有孩子来测试）。在这种情况下，我们需要对 \"子面 \"进行整合，即当前单元格的面的子女。            (有一个稍微令人困惑的角落案例。如果我们是在1d中--诚然，当前的程序和它对各向异性细化的演示并不特别相关--那么单元间的面总是相同的：它们只是顶点。换句话说，在1d中，我们不希望对不同层次的单元之间的面进行不同的处理。我们在这里检查的条件`face->has_children()`确保了这一点：在1d中，这个函数总是返回`false`，因此在1d中我们不会进入这个`if`分支。但我们将不得不在下面的情况（c）中回到这个角落。\n\n                if (face->has_children()) \n                  { \n\n// 我们需要知道，哪个邻居的面朝向我们单元格的方向。使用  @p  neighbor_face_no 函数，我们可以得到粗邻和非粗邻的这些信息。\n\n                    const unsigned int neighbor2 = \n                      cell->neighbor_face_no(face_no); \n\n// 现在我们对所有的子脸进行循环，也就是当前脸的子脸和可能的孙子脸。\n\n                    for (unsigned int subface_no = 0; \n                         subface_no < face->n_active_descendants(); \n                         ++subface_no) \n                      { \n\n// 为了得到当前子面后面的单元，我们可以使用 @p neighbor_child_on_subface 函数。它照顾到了所有各向异性细化和非标准面的复杂情况。\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// 这个案例的其余部分没有变化。\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//情况(c)。如果这是一个内部面，并且邻居没有进一步细化，我们就会得到这里（或者，如上所述，我们是在1d中，在这种情况下，我们对每个内部面都会得到这里）。然后我们需要决定是否要对当前面进行整合。如果邻居实际上更粗，那么我们就忽略这个面，而是在访问邻居单元并查看当前面的时候处理它（除了在1d中，如上所述，这不会发生）。\n\n                    if (dim > 1 && cell->neighbor_is_coarser(face_no)) \n                      continue; \n\n// 另一方面，如果邻居是更精细的，那么我们已经处理了上面(b)情况下的脸（1d除外）。所以对于2d和3d，我们只需要决定是要处理来自当前一侧的同一层次的单元格之间的面，还是来自邻接一侧的面。 我们通过引入一个平局来做到这一点。          我们只取索引较小的单元格（在当前细化级别内）。在1d中，我们取较粗的单元，或者如果它们在同一层次，则取该层次中指数较小的单元。这就导致了一个复杂的条件，希望在上面的描述中可以理解。\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// 这里我们知道，邻居不是更粗的，所以我们可以使用通常的  @p neighbor_of_neighbor  函数。然而，我们也可以使用更通用的 @p neighbor_face_no 函数。\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// 我们不需要考虑情况(d)，因为这些面在情况(b)中被 \"从另一侧 \"处理。\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// 对于这个简单的问题，我们再次使用简单的Richardson迭代法。该求解器完全不受我们各向异性变化的影响。\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// 我们根据 step-12 中使用的相同的简单细化标准来细化网格，即对解的梯度的近似。\n\n  template <int dim> \n  void DGMethod<dim>::refine_grid() \n  { \n    Vector<float> gradient_indicator(triangulation.n_active_cells()); \n\n// 我们对梯度进行近似计算。\n\n    DerivativeApproximation::approximate_gradient(mapping, \n                                                  dof_handler, \n                                                  solution2, \n                                                  gradient_indicator); \n\n//并对其进行缩放，以获得一个误差指标。\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// 然后我们用这个指标来标记误差指标最高的30%的单元格来进行精炼。\n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    gradient_indicator, \n                                                    0.3, \n                                                    0.1); \n\n// 现在，细化标志被设置为那些具有大误差指标的单元。如果不做任何改变，这些单元将被等向细化。如果给这个函数的 @p anisotropic 标志被设置，我们现在调用set_anisotropic_flags()函数，该函数使用跳转指标将一些细化标志重置为各向异性细化。\n\n    if (anisotropic) \n      set_anisotropic_flags(); \n\n// 现在执行考虑各向异性以及各向同性的细化标志的细化。\n\n    triangulation.execute_coarsening_and_refinement(); \n  } \n\n// 一旦错误指标被评估，误差最大的单元被标记为细化，我们要再次循环这些被标记的单元，以决定它们是否需要各向同性的细化或各向异性的细化更为合适。这就是在介绍中解释的各向异性跳跃指标。\n\n  template <int dim> \n  void DGMethod<dim>::set_anisotropic_flags() \n  { \n\n// 我们想在被标记的单元格的面上评估跳跃，所以我们需要一些对象来评估面上的解决方案的值。\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// 现在我们需要对所有活动单元进行循环。\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n\n// 我们只需要考虑那些被标记为细化的单元。\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// 在汇编例程中看到的四种不同的邻居关系的情况在这里以同样的方式重复。\n\n                  if (face->has_children()) \n                    { \n\n// 邻居被完善。 首先，我们存储信息，即邻居的哪个面指向我们当前单元的方向。这个属性将被继承给子代。\n\n                      unsigned int neighbor2 = cell->neighbor_face_no(face_no); \n\n// 现在我们对所有的子面进行循环。\n\n                      for (unsigned int subface_no = 0; \n                           subface_no < face->n_active_descendants(); \n                           ++subface_no) \n                        { \n\n//得到一个迭代器，指向当前子面后面的单元格...\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// ...并重新启动各自的FEFaceValues和FESSubFaceValues对象。\n\n                          fe_v_subface.reinit(cell, face_no, subface_no); \n                          fe_v_face_neighbor.reinit(neighbor_child, neighbor2); \n\n// 我们获得了函数值\n\n                          fe_v_subface.get_function_values(solution2, u); \n                          fe_v_face_neighbor.get_function_values(solution2, \n                                                                 u_neighbor); \n\n//以及正交权重，乘以雅各布行列式。\n\n                          const std::vector<double> &JxW = \n                            fe_v_subface.get_JxW_values(); \n\n// 现在我们在所有的正交点上循环。\n\n                          for (unsigned int x = 0; \n                               x < fe_v_subface.n_quadrature_points; \n                               ++x) \n                            { \n\n//并整合解决方案的跳跃的绝对值，即分别从当前单元和邻近单元看到的函数值的绝对值。我们知道，前两个面与单元格上的第一个坐标方向正交，后两个面与第二个坐标方向正交，以此类推，所以我们将这些值累积成具有 <code>dim</code> 成分的向量。\n\n                              jump[face_no / 2] += \n                                std::abs(u[x] - u_neighbor[x]) * JxW[x]; \n\n// 我们还将缩放后的权重相加，以获得脸部的量度。\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// 我们的当前单元和邻居在所考虑的面有相同的细化。除此以外，我们的做法与上述情况下的一个子单元的做法基本相同。\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// 现在邻居实际上更粗了。这种情况是新的，因为它没有出现在汇编程序中。在这里，我们必须考虑它，但这并不太复杂。我们只需使用  @p  neighbor_of_coarser_neighbor 函数，它再次自行处理各向异性的细化和非标准面的方向。\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// 现在我们分析一下平均跳动的大小，我们用跳动除以各面的度量得到。\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// 现在我们在单元格的 <code>dim</code> 坐标方向上进行循环，并比较与该方向正交的面的平均跳跃和与其余方向正交的面的平均跳跃。如果前者比后者大一个给定的系数，我们只沿帽轴进行细化。否则，我们不改变细化标志，导致各向同性的细化。\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// 程序的其余部分非常遵循之前教程程序的方案。我们以VTU格式输出网格（就像我们在 step-1 中所做的那样，例如），并以VTU格式输出可视化，我们几乎总是这样做。\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// 创建矩形域。\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// 调整不同方向的单元数，以获得原始网格的完全各向同性的单元。\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// 如果你想以3D方式运行程序，只需将下面一行改为 <code>const unsigned int dim = 3;</code>  。\n\n      const unsigned int dim = 2; \n\n      { \n\n// 首先，我们用各向同性的细化方法进行一次运行。\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// 现在我们进行第二次运行，这次是各向异性的细化。\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": "//| 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            /// β1\n            BO_PARAM(double, b1, 0.9);\n\n            /// @ingroup opt_defaults\n            /// β2\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; η to α)\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": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_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": "#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": "/*  $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": "/**\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": "//==============================================================================\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": "/*\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": "//\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": "/*\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": "// --------------------------------------------------------------------------\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": "#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": "/*\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": "///////////////////////////////////////////////////////////////\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": "/* 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": "/**\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": "#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": "//==============================================================================\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#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 ∇xA\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// ∫∇x(φj)(p) = Σ_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//     ┏                    ┓\n\t//     ┃ φj(pi) ... 1 xi yi ┃\n\t// A = ┃   ┊        ┊  ┊  ┊ ┃ ∊ ℝ^{#S x (#K+1+dim)}\n\t//     ┃   ┊        ┊  ┊  ┊ ┃\n\t//     ┗                    ┛\n\t//     ┏                    ┓^⊤\n\t// w = ┃ wj ... a00 a10 a01 ┃   ∊ ℝ^{#K+1+dim}\n\t//     ┗                    ┛\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 ∫f over the rest of the mesh.\n\t// We write down the constraint as:\n\t//\n\t// ∫_{p ∊ E} Σ_j wj ∇x(φj)(p) + ∇x(a^⊤·p + c) dp = lb       (1)\n\t// (1) ⇔ ∫_{p ∊ E} Σ_j wj ∇x(φj)(p) + ax dp = lb\n\t//     ⇔ lb - Σ_j wj ∫_{p ∊ E} ∇x(φj)(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] ∊ ℝ^{#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//     ┏                      ┓^⊤\n\t// t = ┃ 0  ┈  ┈  0 0 lbx lby ┃   / Vol(E) ∊ ℝ^{#K+1+dim}\n\t//     ┗                      ┛\n\t//\n\t//     ┏                  ┓\n\t//     ┃   1              ┃\n\t//     ┃       1          ┃\n\t//     ┃          ·       ┃\n\t// L = ┃             ·    ┃ ∊ ℝ^{ (#K+1+dim) x (#K+1}) }\n\t//     ┃                1 ┃\n\t//     ┃ Lx_j  ┈        0 ┃\n\t//     ┃ Ly_j  ┈        0 ┃\n\t//     ┗                  ┛\n\t// Where Lx_j = -∫∇xφj / Vol(E) = -∫_{p ∊ E} ∇x(φj)(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": "/**\n *  Copyright (C) 2012  \n *    Ekaterina Potapova\n *    Automation and Control Institute\n *    Vienna University of Technology\n *    Gusshausstraße 25-29\n *    1040 Vienna, Austria\n *    potapova(at)acin.tuwien.ac.at\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see http://www.gnu.org/licenses/\n */\n\n#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": "//==================================================================================================\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 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}}
