{"text": "#ifndef __PAR_EQUILIBRIUM_IC_H__\n#define __PAR_EQUILIBRIUM_IC_H__\n\n\n\n#include \"GAMER.h\"\n#include \"TestProb.h\"\n#include \"vector\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\nusing namespace std;\n\n//gsl library\n#ifdef SUPPORT_GSL\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_roots.h>\n#endif\n\n\ntypedef struct Filename_Parameter{\n   int Cloud_Num;\n   vector<string> Params_Filenames;\n}FP;\ntypedef struct Physical_Parameter{\n   int      Cloud_Num;\n\n   string Params_Filenames;\n\n   char     Cloud_Type[MAX_STRING];\n   char     Density_Table_Name[MAX_STRING];\n   int      AddExtPot;\n   char     ExtPot_Table_Name[MAX_STRING];\n   int      Cloud_RSeed;\n   double   Cloud_Rho0;\n   double   Cloud_R0;\n   double   Cloud_MaxR;\n   double*  Cloud_Center;\n   double*  Cloud_BulkVel;\n   double   Cloud_Einasto_Power_Factor;\n   double   Cloud_Par_Num;\n\n   int      Cloud_MassProfNBin;\n}PhysP;\n\n\nclass Par_EquilibriumIC\n{\n   public:\n      Par_EquilibriumIC();\n      virtual ~Par_EquilibriumIC();\n      void Read_Filenames( const char *filename_para);\n      void Load_Physical_Params(const FP filenames,const int cloud_idx, const long NPar_AllRank);\n      void Init();\n      void Par_SetEquilibriumIC(real *Mass_AllRank, real *Pos_AllRank[3], real *Vel_AllRank[3],const long Par_Idx);\n\n\n      PhysP params;\n      FP   filenames;\n   protected:\n\n   private:\n      // Derive physical attributes for particles\n      double Set_Mass( double x );\n      double Set_Density( double x );\n      double Set_Velocity(const double x);\n\n      // Initialize physical parameter tables\n      void Init_Mass();\n      void Init_Pot();\n      void Init_Prob_Dens();\n\n      //  Initialization through Table\n      void Init_Mass_Table();\n      void Init_Pot_Table();\n\n      //  Add External Potential\n      void Add_Ext_Pot();\n\n      // Auxiliary functions\n      int Aux_CountRow( const char *filename );\n      int Aux_Countcolumn( const char *filename );\n      int GetParams( const char *filename,const char *keyword,const int para_num,const char *para_type,vector <string> &container);\n      void Check_InputFileName();\n      void RanVec_FixRadius( const double r, double RanVec[] );\n\n      // Solve Eddington's equation\n      double potential(const double x);\n      double inverse_psi_to_index (double psi);\n      double integration_eng_base(double eng);\n\n      double delta;\n      double eng_min;\n      double *prob_dens;\n      double *int_prob_dens;\n      double *psi;\n\n      // statistics\n      double slope(double* a,double* b,int start,int fin);\n      void smooth_all(double* x,int start,int fin);\n      double ave(double* a,int start,int fin);\n      double var_n(double* a,int start,int fin);\n      double cor(double* x,double* y,int start,int fin);\n      void mask(double* x,int start,int fin);\n      void add_num(double* x,int start,int fin);\n\n      // Tables of particles' attributes\n      double *Table_r;\n      double *Table_Enclosed_Mass;\n      double *Table_Density;\n      double *Table_dRho_dr;\n      double *Table_dRho_dx;\n      double *Table_Gravity_Field;\n      double *Table_Gravity_Potential;\n\n      // Random number generator\n      RandomNumber_t *Random_Num_Gen ;\n};\n\n\n\n#endif //__PAR_EQUILIBRIUM_IC_H__\n", "meta": {"hexsha": "c67bccd5c71f7f2b4c66f25cb8ab0e5097767904", "size": 3257, "ext": "h", "lang": "C", "max_stars_repo_path": "include/Par_EquilibriumIC.h", "max_stars_repo_name": "CrazyAncestor/gamer", "max_stars_repo_head_hexsha": "4feb2c8efe3b4dc92391b0b2a03b2c1c39aaa384", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T13:43:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-29T13:43:35.000Z", "max_issues_repo_path": "include/Par_EquilibriumIC.h", "max_issues_repo_name": "CrazyAncestor/gamer", "max_issues_repo_head_hexsha": "4feb2c8efe3b4dc92391b0b2a03b2c1c39aaa384", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Par_EquilibriumIC.h", "max_forks_repo_name": "CrazyAncestor/gamer", "max_forks_repo_head_hexsha": "4feb2c8efe3b4dc92391b0b2a03b2c1c39aaa384", "max_forks_repo_licenses": ["BSD-3-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.056, "max_line_length": 131, "alphanum_fraction": 0.6852932146, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3999975276654782}}
{"text": "/* specfunc/bessel_zero.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_airy.h>\n#include <gsl/gsl_sf_pow_int.h>\n#include <gsl/gsl_sf_bessel.h>\n\n#include \"error.h\"\n\n#include \"bessel_olver.h\"\n\n/* For Chebyshev expansions of the roots as functions of nu,\n * see [G. Nemeth, Mathematical Approximation of Special Functions].\n * This gives the fits for all nu and s <= 10.\n * I made the fits for other values of s myself [GJ].\n */\n\n/* Chebyshev expansion: j_{nu,1} = c_k T_k*(nu/2), nu <= 2 */\nstatic const double coef_jnu1_a[] = {\n  3.801775243633476,\n  1.360704737511120,\n -0.030707710261106,\n  0.004526823746202,\n -0.000808682832134,\n  0.000159218792489,\n -0.000033225189761,\n  0.000007205599763,\n -0.000001606110397,\n  0.000000365439424,\n -0.000000084498039,\n  0.000000019793815,\n -0.000000004687054,\n  0.000000001120052,\n -0.000000000269767,\n  0.000000000065420,\n -0.000000000015961,\n  0.000000000003914,\n -0.000000000000965,\n  0.000000000000239,\n -0.000000000000059,\n  0.000000000000015,\n -0.000000000000004,\n  0.000000000000001\n};\n\n\n/* Chebyshev expansion: j_{nu,1} = nu c_k T_k*((2/nu)^(2/3)), nu >= 2 */\nstatic const double coef_jnu1_b[] = {\n  1.735063412537096,\n  0.784478100951978,\n  0.048881473180370,\n -0.000578279783021,\n -0.000038984957864,\n  0.000005758297879,\n -0.000000327583229,\n -0.000000003853878,\n  0.000000002284653,\n -0.000000000153079,\n -0.000000000000895,\n  0.000000000000283,\n  0.000000000000043,\n  0.000000000000010,\n -0.000000000000003\n};\n\n\n/* Chebyshev expansion: j_{nu,2} = c_k T_k*(nu/2), nu <= 2 */\nstatic const double coef_jnu2_a[] = {\n  6.992370244046161,\n  1.446379282056534,\n -0.023458616207293,\n  0.002172149448700,\n -0.000246262775620,\n  0.000030990180959,\n -0.000004154183047,\n  0.000000580766328,\n -0.000000083648175,\n  0.000000012317355,\n -0.000000001844887,\n  0.000000000280076,\n -0.000000000042986,\n  0.000000000006658,\n -0.000000000001039,\n  0.000000000000163,\n -0.000000000000026,\n  0.000000000000004,\n -0.000000000000001\n};\n\n\n/* Chebyshev expansion: j_{nu,2} = nu c_k T_k*((2/nu)^(2/3)), nu >= 2 */\nstatic const double coef_jnu2_b[] = {\n  2.465611864263400,\n  1.607952988471069,\n  0.138758034431497,\n -0.003687791182054,\n -0.000051276007868,\n  0.000045113570749,\n -0.000007579172152,\n  0.000000736469208,\n -0.000000011118527,\n -0.000000011919884,\n  0.000000002696788,\n -0.000000000314488,\n  0.000000000008124,\n  0.000000000005211,\n -0.000000000001292,\n  0.000000000000158,\n -0.000000000000004,\n -0.000000000000003,\n  0.000000000000001\n};\n\n\n/* Chebyshev expansion: j_{nu,3} = c_k T_k*(nu/3), nu <= 3 */\nstatic const double coef_jnu3_a[] = {\n  10.869647065239236,\n   2.177524286141710,\n  -0.034822817125293,\n   0.003167249102413,\n  -0.000353960349344,\n   0.000044039086085,\n  -0.000005851380981,\n   0.000000812575483,\n  -0.000000116463617,\n   0.000000017091246,\n  -0.000000002554376,\n   0.000000000387335,\n  -0.000000000059428,\n   0.000000000009207,\n  -0.000000000001438,\n   0.000000000000226,\n  -0.000000000000036,\n   0.000000000000006,\n  -0.000000000000001\n};\n\n\n/* Chebyshev expansion: j_{nu,3} = nu c_k T_k*((3/nu)^(2/3)), nu >= 3 */\nstatic const double coef_jnu3_b[] = {\n  2.522816775173244,\n  1.673199424973720,\n  0.146431617506314,\n -0.004049001763912,\n -0.000039517767244,\n  0.000048781729288,\n -0.000008729705695,\n  0.000000928737310,\n -0.000000028388244,\n -0.000000012927432,\n  0.000000003441008,\n -0.000000000471695,\n  0.000000000025590,\n  0.000000000005502,\n -0.000000000001881,\n  0.000000000000295,\n -0.000000000000020,\n -0.000000000000003,\n  0.000000000000001\n};\n\n\n/* Chebyshev expansion: j_{nu,4} = c_k T_k*(nu/4), nu <= 4 */\nstatic const double coef_jnu4_a[] = {\n  14.750310252773009,\n   2.908010932941708,\n  -0.046093293420315,\n   0.004147172321412,\n  -0.000459092310473,\n   0.000056646951906,\n  -0.000007472351546,\n   0.000001031210065,\n  -0.000000147008137,\n   0.000000021475218,\n  -0.000000003197208,\n   0.000000000483249,\n  -0.000000000073946,\n   0.000000000011431,\n  -0.000000000001782,\n   0.000000000000280,\n  -0.000000000000044,\n   0.000000000000007,\n  -0.000000000000001\n};\n\n\n/* Chebyshev expansion: j_{nu,4} = nu c_k T_k*((4/nu)^(2/3)), nu >= 4 */\nstatic const double coef_jnu4_b[] = {\n  2.551681323117914,\n  1.706177978336572,\n  0.150357658406131,\n -0.004234001378590,\n -0.000033854229898,\n  0.000050763551485,\n -0.000009337464057,\n  0.000001029717834,\n -0.000000037474196,\n -0.000000013450153,\n  0.000000003836180,\n -0.000000000557404,\n  0.000000000035748,\n  0.000000000005487,\n -0.000000000002187,\n  0.000000000000374,\n -0.000000000000031,\n -0.000000000000003,\n  0.000000000000001\n};\n\n\n\n/* Chebyshev expansion: j_{nu,5} = c_k T_k*(nu/5), nu <= 5 */\nstatic const double coef_jnu5_a[] = {\n  18.632261081028211,\n   3.638249012596966,\n  -0.057329705998828,\n   0.005121709126820,\n  -0.000563325259487,\n   0.000069100826174,\n  -0.000009066603030,\n   0.000001245181383,\n  -0.000000176737282,\n   0.000000025716695,\n  -0.000000003815184,\n   0.000000000574839,\n  -0.000000000087715,\n   0.000000000013526,\n  -0.000000000002104,\n   0.000000000000330,\n  -0.000000000000052,\n   0.000000000000008,\n  -0.000000000000001\n};\n\n\n/* Chebyshev expansion: j_{nu,5} = nu c_k T_k*((5/nu)^(2/3)), nu >= 5 */\n/* FIXME: There is something wrong with this fit, in about the\n * 9th or 10th decimal place.\n */\nstatic const double coef_jnu5_b[] = {\n  2.569079487591442,\n  1.726073360882134,\n  0.152740776809531,\n -0.004346449660148,\n -0.000030512461856,\n  0.000052000821080,\n -0.000009713343981,\n  0.000001091997863,\n -0.000000043061707,\n -0.000000013779413,\n  0.000000004082870,\n -0.000000000611259,\n  0.000000000042242,\n  0.000000000005448,\n -0.000000000002377,\n  0.000000000000424,\n -0.000000000000038,\n -0.000000000000002,\n  0.000000000000002\n};\n\n\n/* Chebyshev expansion: j_{nu,6} = c_k T_k*(nu/6), nu <= 6 */\nstatic const double coef_jnu6_a[] = {\n  22.514836143374042,\n   4.368367257557198,\n  -0.068550155285562,\n   0.006093776505822,\n  -0.000667152784957,\n   0.000081486022398,\n  -0.000010649011647,\n   0.000001457089679,\n  -0.000000206105082,\n   0.000000029894724,\n  -0.000000004422012,\n   0.000000000664471,\n  -0.000000000101140,\n   0.000000000015561,\n  -0.000000000002416,\n   0.000000000000378,\n  -0.000000000000060,\n   0.000000000000009,\n  -0.000000000000002\n};\n\n\n/* Chebyshev expansion: j_{nu,6} = nu c_k T_k*((6/nu)^(2/3)), nu >= 6 */\nstatic const double coef_jnu6_b[] = {\n  2.580710285494837,\n  1.739380728566154,\n  0.154340696401691,\n -0.004422028860168,\n -0.000028305272624,\n  0.000052845975269,\n -0.000009968794373,\n  0.000001134252926,\n -0.000000046841241,\n -0.000000014007555,\n  0.000000004251816,\n -0.000000000648213,\n  0.000000000046728,\n  0.000000000005414,\n -0.000000000002508,\n  0.000000000000459,\n -0.000000000000043,\n -0.000000000000002,\n  0.000000000000002\n};\n\n\n/* Chebyshev expansion: j_{nu,7} = c_k T_k*(nu/7), nu <= 7 */\nstatic const double coef_jnu7_a[] = {\n  26.397760539730869,\n   5.098418721711790,\n  -0.079761896398948,\n   0.007064521280487,\n  -0.000770766522482,\n   0.000093835449636,\n  -0.000012225308542,\n   0.000001667939800,\n  -0.000000235288157,\n   0.000000034040347,\n  -0.000000005023142,\n   0.000000000753101,\n  -0.000000000114389,\n   0.000000000017564,\n  -0.000000000002722,\n   0.000000000000425,\n  -0.000000000000067,\n   0.000000000000011,\n  -0.000000000000002\n};\n\n\n/* Chebyshev expansion: j_{nu,7} = nu c_k T_k*((7/nu)^(2/3)), nu >= 7 */\nstatic const double coef_jnu7_b[] = {\n  2.589033335856773,\n  1.748907007612678,\n  0.155488900387653,\n -0.004476317805688,\n -0.000026737952924,\n  0.000053459680946,\n -0.000010153699240,\n  0.000001164804272,\n -0.000000049566917,\n -0.000000014175403,\n  0.000000004374840,\n -0.000000000675135,\n  0.000000000050004,\n  0.000000000005387,\n -0.000000000002603,\n  0.000000000000485,\n -0.000000000000047,\n -0.000000000000002,\n  0.000000000000002\n};\n\n\n/* Chebyshev expansion: j_{nu,8} = c_k T_k*(nu/8), nu <= 8 */\nstatic const double coef_jnu8_a[] = {\n  30.280900001606662,\n   5.828429205461221,\n  -0.090968381181069,\n   0.008034479731033,\n  -0.000874254899080,\n   0.000106164151611,\n  -0.000013798098749,\n   0.000001878187386,\n  -0.000000264366627,\n   0.000000038167685,\n  -0.000000005621060,\n   0.000000000841165,\n  -0.000000000127538,\n   0.000000000019550,\n  -0.000000000003025,\n   0.000000000000472,\n  -0.000000000000074,\n   0.000000000000012,\n  -0.000000000000002\n};\n\n\n/* Chebyshev expansion: j_{nu,8} = nu c_k T_k*((8/nu)^(2/3)), nu >= 8 */\nstatic const double coef_jnu8_b[] = {\n  2.595283877150078,\n  1.756063044986928,\n  0.156352972371030,\n -0.004517201896761,\n -0.000025567187878,\n  0.000053925472558,\n -0.000010293734486,\n  0.000001187923085,\n -0.000000051625122,\n -0.000000014304212,\n  0.000000004468450,\n -0.000000000695620,\n  0.000000000052500,\n  0.000000000005367,\n -0.000000000002676,\n  0.000000000000505,\n -0.000000000000050,\n -0.000000000000002,\n  0.000000000000002\n};\n\n\n/* Chebyshev expansion: j_{nu,9} = c_k T_k*(nu/9), nu <= 9 */\nstatic const double coef_jnu9_a[] = {\n  34.164181213238386,\n   6.558412747925228,\n  -0.102171455365016,\n   0.009003934361201,\n  -0.000977663914535,\n   0.000118479876579,\n  -0.000015368714220,\n   0.000002088064285,\n  -0.000000293381154,\n   0.000000042283900,\n  -0.000000006217033,\n   0.000000000928887,\n  -0.000000000140627,\n   0.000000000021526,\n  -0.000000000003326,\n   0.000000000000518,\n  -0.000000000000081,\n   0.000000000000013,\n  -0.000000000000002\n};\n\n\n/* Chebyshev expansion: j_{nu,9} = nu c_k T_k*((9/nu)^(2/3)), nu >= 9 */\nstatic const double coef_jnu9_b[] = {\n  2.600150240905079,\n  1.761635491694032,\n  0.157026743724010,\n -0.004549100368716,\n -0.000024659248617,\n  0.000054291035068,\n -0.000010403464334,\n  0.000001206027524,\n -0.000000053234089,\n -0.000000014406241,\n  0.000000004542078,\n -0.000000000711728,\n  0.000000000054464,\n  0.000000000005350,\n -0.000000000002733,\n  0.000000000000521,\n -0.000000000000052,\n -0.000000000000002,\n  0.000000000000002\n};\n\n\n/* Chebyshev expansion: j_{nu,10} = c_k T_k*(nu/10), nu <= 10 */\nstatic const double coef_jnu10_a[] = {\n  38.047560766184647,\n   7.288377637926008,\n  -0.113372193277897,\n   0.009973047509098,\n  -0.001081019701335,\n   0.000130786983847,\n  -0.000016937898538,\n   0.000002297699179,\n  -0.000000322354218,\n   0.000000046392941,\n  -0.000000006811759,\n   0.000000001016395,\n  -0.000000000153677,\n   0.000000000023486,\n  -0.000000000003616,\n   0.000000000000561,\n  -0.000000000000095,\n   0.000000000000027,\n  -0.000000000000013,\n   0.000000000000005\n};\n\n\n/* Chebyshev expansion: j_{nu,10} = nu c_k T_k*((10/nu)^(2/3)), nu >= 10 */\nstatic const double coef_jnu10_b[] = {\n  2.604046346867949,\n  1.766097596481182,\n  0.157566834446511,\n -0.004574682244089,\n -0.000023934500688,\n  0.000054585558231,\n -0.000010491765415,\n  0.000001220589364,\n -0.000000054526331,\n -0.000000014489078,\n  0.000000004601510,\n -0.000000000724727,\n  0.000000000056049,\n  0.000000000005337,\n -0.000000000002779,\n  0.000000000000533,\n -0.000000000000054,\n -0.000000000000002,\n  0.000000000000002\n};\n\n\n/* Chebyshev expansion: j_{nu,11} = c_k T_k*(nu/22), nu <= 22 */\nstatic const double coef_jnu11_a[] = {\n  49.5054081076848637,\n  15.33692279367165101,\n -0.33677234163517130,\n  0.04623235772920729,\n -0.00781084960665093,\n  0.00147217395434708,\n -0.00029695043846867,\n  0.00006273356860235,\n -0.00001370575125628,\n  3.07171282012e-6,\n -7.0235041249e-7,\n  1.6320559339e-7,\n -3.843117306e-8,\n  9.15083800e-9,\n -2.19957642e-9,\n  5.3301703e-10,\n -1.3007541e-10,\n  3.193827e-11,\n -7.88605e-12,\n  1.95918e-12,\n -4.9020e-13,\n  1.2207e-13,\n -2.820e-14,\n  5.25e-15,\n -1.88e-15,\n  2.80e-15,\n -2.45e-15\n};\n\n\n/* Chebyshev expansion: j_{nu,12} = c_k T_k*(nu/24), nu <= 24 */\nstatic const double coef_jnu12_a[] = {\n  54.0787833216641519,\n  16.7336367772863598,\n -0.36718411124537953,\n  0.05035523375053820,\n -0.00849884978867533,\n  0.00160027692813434,\n -0.00032248114889921,\n  0.00006806354127199,\n -0.00001485665901339,\n  3.32668783672e-6,\n -7.5998952729e-7,\n  1.7644939709e-7,\n -4.151538210e-8,\n  9.87722772e-9,\n -2.37230133e-9,\n  5.7442875e-10,\n -1.4007767e-10,\n  3.437166e-11,\n -8.48215e-12,\n  2.10554e-12,\n -5.2623e-13,\n  1.3189e-13,\n -3.175e-14,\n  5.73e-15,\n  5.6e-16,\n -8.7e-16,\n -6.5e-16\n};\n\n\n/* Chebyshev expansion: j_{nu,13} = c_k T_k*(nu/26), nu <= 26 */\nstatic const double coef_jnu13_a[] = {\n  58.6521941921708890,\n  18.1303398137970284,\n -0.39759381380126650,\n  0.05447765240465494,\n -0.00918674227679980,\n  0.00172835361420579,\n -0.00034800528297612,\n  0.00007339183835188,\n -0.00001600713368099,\n  3.58154960392e-6,\n -8.1759873497e-7,\n  1.8968523220e-7,\n -4.459745253e-8,\n  1.060304419e-8,\n -2.54487624e-9,\n  6.1580214e-10,\n -1.5006751e-10,\n  3.679707e-11,\n -9.07159e-12,\n  2.24713e-12,\n -5.5943e-13,\n  1.4069e-13,\n -3.679e-14,\n  1.119e-14,\n -4.99e-15,\n  3.43e-15,\n -2.85e-15,\n  2.3e-15,\n -1.7e-15,\n  8.7e-16\n};\n\n\n/* Chebyshev expansion: j_{nu,14} = c_k T_k*(nu/28), nu <= 28 */\nstatic const double coef_jnu14_a[] = {\n  63.2256329577315566,\n  19.5270342832914901,\n -0.42800190567884337,\n  0.05859971627729398,\n -0.00987455163523582,\n  0.00185641011402081,\n -0.00037352439419968,\n  0.00007871886257265,\n -0.00001715728110045,\n  3.83632624437e-6,\n -8.7518558668e-7,\n  2.0291515353e-7,\n -4.767795233e-8,\n  1.132844415e-8,\n -2.71734219e-9,\n  6.5714886e-10,\n -1.6005342e-10,\n  3.922557e-11,\n -9.66637e-12,\n  2.39379e-12,\n -5.9541e-13,\n  1.4868e-13,\n -3.726e-14,\n  9.37e-15,\n -2.36e-15,\n  6.0e-16\n};\n\n\n/* Chebyshev expansion: j_{nu,15} = c_k T_k*(nu/30), nu <= 30 */\nstatic const double coef_jnu15_a[] = {\n  67.7990939565631635,\n  20.9237219226859859,\n -0.45840871823085836,\n  0.06272149946755639,\n -0.01056229551143042,\n  0.00198445078693100,\n -0.00039903958650729,\n  0.00008404489865469,\n -0.00001830717574922,\n  4.09103745566e-6,\n -9.3275533309e-7,\n  2.1614056403e-7,\n -5.075725222e-8,\n  1.205352081e-8,\n -2.88971837e-9,\n  6.9846848e-10,\n -1.7002946e-10,\n  4.164941e-11,\n -1.025859e-11,\n  2.53921e-12,\n -6.3128e-13,\n  1.5757e-13,\n -3.947e-14,\n  9.92e-15,\n -2.50e-15,\n  6.3e-16\n};\n\n\n/* Chebyshev expansion: j_{nu,16} = c_k T_k*(nu/32), nu <= 32 */\nstatic const double coef_jnu16_a[] = {\n  72.3725729616724770,\n  22.32040402918608585,\n -0.48881449782358690,\n  0.06684305681828766,\n -0.01124998690363398,\n  0.00211247882775445,\n -0.00042455166484632,\n  0.00008937015316346,\n -0.00001945687139551,\n  4.34569739281e-6,\n -9.9031173548e-7,\n  2.2936247195e-7,\n -5.383562595e-8,\n  1.277835103e-8,\n -3.06202860e-9,\n  7.3977037e-10,\n -1.8000071e-10,\n  4.407196e-11,\n -1.085046e-11,\n  2.68453e-12,\n -6.6712e-13,\n  1.6644e-13,\n -4.168e-14,\n  1.047e-14,\n -2.64e-15,\n  6.7e-16\n};\n\n\n/* Chebyshev expansion: j_{nu,17} = c_k T_k*(nu/34), nu <= 34 */\nstatic const double coef_jnu17_a[] = {\n  76.9460667535209549,\n  23.71708159112252670,\n -0.51921943142405352,\n  0.07096442978067622,\n -0.01193763559341369,\n  0.00224049662974902,\n -0.00045006122941781,\n  0.00009469477941684,\n -0.00002060640777107,\n  4.60031647195e-6,\n -1.04785755046e-6,\n  2.4258161247e-7,\n -5.691327087e-8,\n  1.350298805e-8,\n -3.23428733e-9,\n  7.8105847e-10,\n -1.8996825e-10,\n  4.649350e-11,\n -1.144205e-11,\n  2.82979e-12,\n -7.0294e-13,\n  1.7531e-13,\n -4.388e-14,\n  1.102e-14,\n -2.78e-15,\n  7.0e-16\n};\n\n\n/* Chebyshev expansion: j_{nu,18} = c_k T_k*(nu/36), nu <= 36 */\nstatic const double coef_jnu18_a[] = {\n  81.5195728368096659,\n  25.11375537470259305,\n -0.54962366347317668,\n  0.07508565026117689,\n -0.01262524908033818,\n  0.00236850602019778,\n -0.00047556873651929,\n  0.00010001889347161,\n -0.00002175581482429,\n  4.85490251239e-6,\n -1.10539483940e-6,\n  2.5579853343e-7,\n -5.999033352e-8,\n  1.422747129e-8,\n -3.40650521e-9,\n  8.2233565e-10,\n -1.9993286e-10,\n  4.891426e-11,\n -1.203343e-11,\n  2.97498e-12,\n -7.3875e-13,\n  1.8418e-13,\n -4.608e-14,\n  1.157e-14,\n -2.91e-15,\n  7.4e-16\n};\n\n\n/* Chebyshev expansion: j_{nu,19} = c_k T_k*(nu/38), nu <= 38 */\nstatic const double coef_jnu19_a[] = {\n  86.0930892477047512,\n  26.51042598308271729,\n -0.58002730731948358,\n  0.07920674321589394,\n -0.01331283320930301,\n  0.00249650841778073,\n -0.00050107453900793,\n  0.00010534258471335,\n -0.00002290511552874,\n  5.10946148897e-6,\n -1.16292517157e-6,\n  2.6901365037e-7,\n -6.306692473e-8,\n  1.495183048e-8,\n -3.57869025e-9,\n  8.6360410e-10,\n -2.0989514e-10,\n  5.133439e-11,\n -1.262465e-11,\n  3.12013e-12,\n -7.7455e-13,\n  1.9304e-13,\n -4.829e-14,\n  1.212e-14,\n -3.05e-15,\n  7.7e-16\n};\n\n\n/* Chebyshev expansion: j_{nu,20} = c_k T_k*(nu/40), nu <= 40 */\nstatic const double coef_jnu20_a[] = {\n  90.6666144195163770,\n  27.9070938975436823,\n -0.61043045315390591,\n  0.08332772844325554,\n -0.01400039260208282,\n  0.00262450494035660,\n -0.00052657891389470,\n  0.00011066592304919,\n -0.00002405432778364,\n  5.36399803946e-6,\n -1.22044976064e-6,\n  2.8222728362e-7,\n -6.614312964e-8,\n  1.567608839e-8,\n -3.75084856e-9,\n  9.0486546e-10,\n -2.1985553e-10,\n  5.375401e-11,\n -1.321572e-11,\n  3.26524e-12,\n -8.1033e-13,\n  2.0190e-13,\n -5.049e-14,\n  1.267e-14,\n -3.19e-15,\n  8.0e-16,\n -2.0e-16\n};\n\n\nstatic const double * coef_jnu_a[] = {\n  0,\n  coef_jnu1_a,\n  coef_jnu2_a,\n  coef_jnu3_a,\n  coef_jnu4_a,\n  coef_jnu5_a,\n  coef_jnu6_a,\n  coef_jnu7_a,\n  coef_jnu8_a,\n  coef_jnu9_a,\n  coef_jnu10_a,\n  coef_jnu11_a,\n  coef_jnu12_a,\n  coef_jnu13_a,\n  coef_jnu14_a,\n  coef_jnu15_a,\n  coef_jnu16_a,\n  coef_jnu17_a,\n  coef_jnu18_a,\n  coef_jnu19_a,\n  coef_jnu20_a\n};\n\nstatic const size_t size_jnu_a[] = {\n  0,\n  sizeof(coef_jnu1_a)/sizeof(double),\n  sizeof(coef_jnu2_a)/sizeof(double),\n  sizeof(coef_jnu3_a)/sizeof(double),\n  sizeof(coef_jnu4_a)/sizeof(double),\n  sizeof(coef_jnu5_a)/sizeof(double),\n  sizeof(coef_jnu6_a)/sizeof(double),\n  sizeof(coef_jnu7_a)/sizeof(double),\n  sizeof(coef_jnu8_a)/sizeof(double),\n  sizeof(coef_jnu9_a)/sizeof(double),\n  sizeof(coef_jnu10_a)/sizeof(double),\n  sizeof(coef_jnu11_a)/sizeof(double),\n  sizeof(coef_jnu12_a)/sizeof(double),\n  sizeof(coef_jnu13_a)/sizeof(double),\n  sizeof(coef_jnu14_a)/sizeof(double),\n  sizeof(coef_jnu15_a)/sizeof(double),\n  sizeof(coef_jnu16_a)/sizeof(double),\n  sizeof(coef_jnu17_a)/sizeof(double),\n  sizeof(coef_jnu18_a)/sizeof(double),\n  sizeof(coef_jnu19_a)/sizeof(double),\n  sizeof(coef_jnu20_a)/sizeof(double)\n};\n\n\nstatic const double * coef_jnu_b[] = {\n  0,\n  coef_jnu1_b,\n  coef_jnu2_b,\n  coef_jnu3_b,\n  coef_jnu4_b,\n  coef_jnu5_b,\n  coef_jnu6_b,\n  coef_jnu7_b,\n  coef_jnu8_b,\n  coef_jnu9_b,\n  coef_jnu10_b\n};\n\nstatic const size_t size_jnu_b[] = {\n  0,\n  sizeof(coef_jnu1_b)/sizeof(double),\n  sizeof(coef_jnu2_b)/sizeof(double),\n  sizeof(coef_jnu3_b)/sizeof(double),\n  sizeof(coef_jnu4_b)/sizeof(double),\n  sizeof(coef_jnu5_b)/sizeof(double),\n  sizeof(coef_jnu6_b)/sizeof(double),\n  sizeof(coef_jnu7_b)/sizeof(double),\n  sizeof(coef_jnu8_b)/sizeof(double),\n  sizeof(coef_jnu9_b)/sizeof(double),\n  sizeof(coef_jnu10_b)/sizeof(double)\n};\n\n\n\n/* Evaluate Clenshaw recurrence for\n * a T* Chebyshev series.\n * sizeof(c) = N+1\n */\nstatic double\nclenshaw(const double * c, int N, double u)\n{\n  double B_np1 = 0.0;\n  double B_n   = c[N];\n  double B_nm1;\n  int n;\n  for(n=N; n>0; n--) {\n    B_nm1 = 2.0*(2.0*u-1.0) * B_n - B_np1 + c[n-1];\n    B_np1 = B_n;\n    B_n   = B_nm1;\n  }\n  return B_n - (2.0*u-1.0)*B_np1;\n}\n\n\n\n/* correction terms to leading McMahon expansion\n * [Abramowitz+Stegun 9.5.12]\n * [Olver, Royal Society Math. Tables, v. 7]\n * We factor out a beta, so that this is a multiplicative\n * correction:\n *   j_{nu,s} = beta(s,nu) * mcmahon_correction(nu, beta(s,nu))\n *   macmahon_correction --> 1 as s --> Inf\n */\nstatic double\nmcmahon_correction(const double mu, const double beta)\n{\n  const double eb   = 8.0*beta;\n  const double ebsq = eb*eb;\n\n  if(mu < GSL_DBL_EPSILON) {\n    /* Prevent division by zero below. */\n    const double term1 =  1.0/ebsq;\n    const double term2 = -4.0*31.0/(3*ebsq*ebsq);\n    const double term3 =  32.0*3779.0/(15.0*ebsq*ebsq*ebsq);\n    const double term4 = -64.0*6277237.0/(105.0*ebsq*ebsq*ebsq*ebsq);\n    const double term5 =  512.0*2092163573.0/(315.0*ebsq*ebsq*ebsq*ebsq*ebsq);\n    return 1.0 + 8.0*(term1 + term2 + term3 + term4 + term5);\n  }\n  else {\n    /* Here we do things in terms of 1/mu, which\n     * is purely to prevent overflow in the very\n     * unlikely case that mu is really big.\n     */\n    const double mi   = 1.0/mu;\n    const double r  = mu/ebsq;\n    const double n2 = 4.0/3.0    * (7.0 - 31.0*mi);\n    const double n3 = 32.0/15.0  * (83.0 + (-982.0 + 3779.0*mi)*mi);\n    const double n4 = 64.0/105.0 * (6949.0 + (-153855.0 + (1585743.0 - 6277237.0*mi)*mi)*mi);\n    const double n5 = 512.0/315.0 * (70197.0 + (-2479316.0 + (48010494.0 + (-512062548.0 + 2092163573.0*mi)*mi)*mi)*mi);\n    const double n6 = 2048.0/3465.0 * (5592657.0 + (-287149133.0 + (8903961290.0 + (-179289628602.0 + (1982611456181.0 - 8249725736393.0*mi)*mi)*mi)*mi)*mi);\n    const double term1 = (1.0 - mi) * r;\n    const double term2 = term1 * n2 * r;\n    const double term3 = term1 * n3 * r*r;\n    const double term4 = term1 * n4 * r*r*r;\n    const double term5 = term1 * n5 * r*r*r*r;\n    const double term6 = term1 * n6 * r*r*r*r*r;\n    return 1.0 - 8.0*(term1 + term2 + term3 + term4 + term5 + term6);\n  }\n}\n\n\n/* Assumes z >= 1.0 */\nstatic double\nolver_b0(double z, double minus_zeta)\n{\n  if(z < 1.02) {\n    const double a = 1.0-z;\n    const double c0 =  0.0179988721413553309252458658183;\n    const double c1 =  0.0111992982212877614645974276203;\n    const double c2 =  0.0059404069786014304317781160605;\n    const double c3 =  0.0028676724516390040844556450173;\n    const double c4 =  0.0012339189052567271708525111185;\n    const double c5 =  0.0004169250674535178764734660248;\n    const double c6 =  0.0000330173385085949806952777365;\n    const double c7 = -0.0001318076238578203009990106425;\n    const double c8 = -0.0001906870370050847239813945647;\n    return c0 + a*(c1 + a*(c2 + a*(c3 + a*(c4 + a*(c5 + a*(c6 + a*(c7 + a*c8)))))));\n  }\n  else {\n    const double abs_zeta = minus_zeta;\n    const double t = 1.0/(z*sqrt(1.0 - 1.0/(z*z)));\n    return -5.0/(48.0*abs_zeta*abs_zeta) + t*(3.0 + 5.0*t*t)/(24.0*sqrt(abs_zeta));\n  }\n}\n\n\ninline\nstatic double\nolver_f1(double z, double minus_zeta)\n{\n  const double b0 = olver_b0(z, minus_zeta);\n  const double h2 = sqrt(4.0*minus_zeta/(z*z-1.0)); /* FIXME */\n  return 0.5 * z * h2 * b0;\n}\n\n\nint\ngsl_sf_bessel_zero_J0_e(unsigned int s, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(s == 0){\n    result->val = 0.0;\n    result->err = 0.0;\n    GSL_ERROR (\"error\", GSL_EINVAL);\n  }\n  else {\n    /* See [F. Lether, J. Comp. Appl .Math. 67, 167 (1996)]. */\n\n    static const double P[] = { 1567450796.0/12539606369.0,\n                                8903660.0/2365861.0,\n                                10747040.0/536751.0,\n                                17590991.0/1696654.0\n                              };\n    static const double Q[] = { 1.0,\n                                29354255.0/954518.0,\n                                76900001.0/431847.0,\n                                67237052.0/442411.0\n                              };\n\n    const double beta = (s - 0.25) * M_PI;\n    const double bi2  = 1.0/(beta*beta);\n    const double R33num = P[0] + bi2 * (P[1] + bi2 * (P[2] + P[3] * bi2));\n    const double R33den = Q[0] + bi2 * (Q[1] + bi2 * (Q[2] + Q[3] * bi2));\n    const double R33 = R33num/R33den;\n    result->val = beta + R33/beta;\n    result->err = fabs(3.0e-15 * result->val);\n    return GSL_SUCCESS;\n  }\n}\n\n\nint\ngsl_sf_bessel_zero_J1_e(unsigned int s, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(s == 0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    /* See [M. Branders et al., J. Comp. Phys. 42, 403 (1981)]. */\n\n    static const double a[] = { -0.362804405737084,\n                                 0.120341279038597,\n                                 0.439454547101171e-01,\n                                 0.159340088474713e-02\n                              };\n    static const double b[] = {  1.0,\n                                -0.325641790801361,\n                                -0.117453445968927,\n                                -0.424906902601794e-02\n                              };\n\n    const double beta = (s + 0.25) * M_PI;\n    const double bi2  = 1.0/(beta*beta);\n    const double Rnum = a[3] + bi2 * (a[2] + bi2 * (a[1] + bi2 * a[0]));\n    const double Rden = b[3] + bi2 * (b[2] + bi2 * (b[1] + bi2 * b[0]));\n    const double R = Rnum/Rden;\n    result->val = beta * (1.0 + R*bi2);\n    result->err = fabs(2.0e-14 * result->val);\n    return GSL_SUCCESS;\n  }\n}\n\n\nint\ngsl_sf_bessel_zero_Jnu_e(double nu, unsigned int s, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(nu <= -1.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(s == 0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    if (nu == 0.0) {\n      GSL_ERROR (\"no zero-th root for nu = 0.0\", GSL_EINVAL);\n    }\n    return GSL_SUCCESS;\n  }\n  else if(nu < 0.0) {\n    /* This can be done, I'm just lazy now. */\n    result->val = 0.0;\n    result->err = 0.0;\n    GSL_ERROR(\"unimplemented\", GSL_EUNIMPL);\n  }\n  else if(s == 1) {\n    /* Chebyshev fits for the first positive zero.\n     * For some reason Nemeth made this different from the others.\n     */\n    if(nu < 2.0) {\n      const double * c = coef_jnu_a[s];\n      const size_t   L = size_jnu_a[s];\n      const double arg = nu/2.0;\n      const double chb = clenshaw(c, L-1, arg);\n      result->val = chb;\n      result->err = 2.0e-15 * result->val;\n    }\n    else {\n      const double * c = coef_jnu_b[s];\n      const size_t   L = size_jnu_b[s];\n      const double arg = pow(2.0/nu, 2.0/3.0);\n      const double chb = clenshaw(c, L-1, arg);\n      result->val = nu * chb;\n      result->err = 2.0e-15 * result->val;\n    }\n    return GSL_SUCCESS;\n  }\n  else if(s <= 10) {\n    /* Chebyshev fits for the first 10 positive zeros. */\n    if(nu < s) {\n      const double * c = coef_jnu_a[s];\n      const size_t   L = size_jnu_a[s];\n      const double arg = nu/s;\n      const double chb = clenshaw(c, L-1, arg);\n      result->val = chb;\n      result->err = 2.0e-15 * result->val;\n    }\n    else {\n      const double * c = coef_jnu_b[s];\n      const size_t   L = size_jnu_b[s];\n      const double arg = pow(s/nu, 2.0/3.0);\n      const double chb = clenshaw(c, L-1, arg);\n      result->val = nu * chb;\n      result->err = 2.0e-15 * result->val;\n\n      /* FIXME: truth in advertising for the screwed up\n       * s = 5 fit. Need to fix that.\n       */\n      if(s == 5) {\n        result->err *= 5.0e+06;\n      }\n    }\n    return GSL_SUCCESS;\n  }\n  else if(s > 0.5*nu && s <= 20) {\n    /* Chebyshev fits for 10 < s <= 20. */\n    const double * c = coef_jnu_a[s];\n    const size_t   L = size_jnu_a[s];\n    const double arg = nu/(2.0*s);\n    const double chb = clenshaw(c, L-1, arg);\n    result->val = chb;\n    result->err = 4.0e-15 * chb;\n    return GSL_SUCCESS;\n  }\n  else if(s > 2.0 * nu) {\n    /* McMahon expansion if s is large compared to nu. */\n    const double beta = (s + 0.5*nu - 0.25) * M_PI;\n    const double mc   = mcmahon_correction(4.0*nu*nu, beta);\n    gsl_sf_result rat12;\n    gsl_sf_pow_int_e(nu/beta, 14, &rat12);\n    result->val  = beta * mc;\n    result->err  = 4.0 * fabs(beta) * rat12.val;\n    result->err += 4.0 * fabs(GSL_DBL_EPSILON * result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    /* Olver uniform asymptotic. */\n    gsl_sf_result as;\n    const int stat_as = gsl_sf_airy_zero_Ai_e(s, &as);\n    const double minus_zeta = -pow(nu,-2.0/3.0) * as.val;\n    const double z  = gsl_sf_bessel_Olver_zofmzeta(minus_zeta);\n    const double f1 = olver_f1(z, minus_zeta);\n    result->val  = nu * (z + f1/(nu*nu));\n    result->err  = 0.001/(nu*nu*nu);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return stat_as;\n  }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_zero_J0(unsigned int s)\n{\n  EVAL_RESULT(gsl_sf_bessel_zero_J0_e(s, &result));\n}\n\ndouble gsl_sf_bessel_zero_J1(unsigned int s)\n{\n  EVAL_RESULT(gsl_sf_bessel_zero_J1_e(s, &result));\n}\n\ndouble gsl_sf_bessel_zero_Jnu(double nu, unsigned int s)\n{\n  EVAL_RESULT(gsl_sf_bessel_zero_Jnu_e(nu, s, &result));\n}\n", "meta": {"hexsha": "7ff8f7ebf0d7c0d044a7bb7a51b189ffea958a75", "size": 28806, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_zero.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_zero.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_zero.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 23.6114754098, "max_line_length": 157, "alphanum_fraction": 0.6611816983, "num_tokens": 12032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3998630067801101}}
{"text": "#include <stdlib.h>\n#include <cblas.h>\n#include <lapacke.h>\n\n#include \"../../runtime/pcp.h\"\n#include \"tasks.h\"\n#include \"utils.h\"\n\n\n#define BLOCK_SIZE 32\n#define MAX_MATRIX_SIZE 1024\n#define MAX_NUM_ITER (MAX_MATRIX_SIZE / BLOCK_SIZE)\n#define MAX_NUM_THREADS 16\n\n\n// The matrix partitioning for TRSM and SYRK in each iteration.\n//\n// A partitioning x of a range 0, ..., n - 1 over p threads is\n// represented as an array x[] of length p + 1 such that x[k] is the\n// start of the block assigned to thread k and x[k + 1] - x[k] is the\n// size of the block assigned to thread k, for k = 0, ..., p - 1. \nstruct partition\n{\n    // The matrix size. \n    int matrix_size;\n\n    // The block size.\n    int block_size;\n\n    // The number of threads.\n    int num_threads;\n\n    // The number of iterations = ceil(matrix_size, block_size).\n    int num_iter;\n\n    // The partitionings for TRSM. \n    int trsm[MAX_NUM_ITER][MAX_NUM_THREADS + 1];\n\n    // The partitionings for SYRK.\n    int syrk[MAX_NUM_ITER][MAX_NUM_THREADS + 1];\n};\n\n\n// Barrier used to synchronize the workers between iterations.\nstatic pcp_barrier_t *barrier = NULL;\n\nstatic struct partition *partition_db[MAX_MATRIX_SIZE + 1][MAX_NUM_THREADS + 1] = {NULL};\nstatic struct partition *partition = NULL;\n\nstatic double *A;\nstatic int ldA;\nstatic int n;\n#define A(i,j) A[(i) + (j) * ldA]\n\n\n\n// Initializes the partitioning for TRSM for a given iteration.\n//\n// Uses uniform row blocks. \nstatic void part_init_trsm(int iter)\n{\n    const int last = partition->matrix_size;\n    const int first = min(last, (iter + 1) * partition->block_size);\n    const int size = last - first;\n    const int p = partition->num_threads;\n    const int chunk = iceil(size, p);\n    partition->trsm[iter][0] = first;\n    partition->trsm[iter][p] = last;\n    for (int th = 1; th < p; ++th) {\n        partition->trsm[iter][th] = min(last, partition->trsm[iter][th - 1] + chunk);\n    }\n}\n\n\n// Initializes the partitioning for SYRK for a given iteration.\nstatic void part_init_syrk(int iter)\n{\n    // Balance the load by flops.\n    const int last = partition->matrix_size;\n    const int first = min(last, (iter + 1) * partition->block_size);\n    const int size = last - first;\n    const int p = partition->num_threads;\n    const int total_work = size * (size + 1) / 2;\n    const int ideal_part_work = total_work / p;\n    partition->syrk[iter][0] = first;\n    partition->syrk[iter][p] = last;\n    for (int k = 1; k < p; ++k) {\n        partition->syrk[iter][k] = partition->syrk[iter][k - 1];\n        int work = 0;\n        while (work < ideal_part_work && partition->syrk[iter][k] < last) {\n            partition->syrk[iter][k] += 1;\n            work += partition->syrk[iter][k] - first;\n        }\n        if (k == 1) {\n            partition->syrk[iter][k] = max(partition->syrk[iter][k], partition->syrk[iter][k - 1] + partition->block_size);\n            partition->syrk[iter][k] = min(partition->syrk[iter][k], last);\n        }\n    }\n}\n\n\n// Returns the start of a TRSM block. \nstatic int part_block_start_trsm(int iter, int me)\n{\n    return partition->trsm[iter][me];\n}\n\n\n// Returns the size of a TRSM block. \nstatic int part_block_size_trsm(int iter, int me)\n{\n    return part_block_start_trsm(iter, me + 1) - part_block_start_trsm(iter, me);\n}\n\n\n// Returns the start of a SYRK block. \nstatic int part_block_start_syrk(int iter, int me)\n{\n    return partition->syrk[iter][me];\n}\n\n\n// Returns the size of a SYRK block. \nstatic int part_block_size_syrk(int iter, int me)\n{\n    return part_block_start_syrk(iter, me + 1) - part_block_start_syrk(iter, me);\n}\n\n\n// Initializes the partitioning for given parameters.\n//\n// Follows this protocol:\n// 1) Re-use existing if it matches.\n// 2) Load from file if it matches.\n// 3) Create from scratch.\nstatic void part_init(int matrix_size, int block_size, int num_threads)\n{\n    // Check if the partitioning is available in the databse.\n    if (partition_db[matrix_size][num_threads] == NULL) {\n        // No, create from scratch and save in the database.\n        partition = malloc(sizeof(*partition));\n        partition->matrix_size = matrix_size;\n        partition->block_size = block_size;\n        partition->num_threads = num_threads;\n        partition->num_iter = iceil(matrix_size, block_size);\n        for (int iter = 0; iter < partition->num_iter; ++iter) {\n            part_init_trsm(iter);\n            part_init_syrk(iter);\n        }\n        partition_db[matrix_size][num_threads] = partition;\n    } else {\n        // Yes, reuse from database.\n        partition = partition_db[matrix_size][num_threads];\n    }\n}\n\n\nvoid chol_task_par_reconfigure(int nth)\n{\n    // Choose current size of the worker pool for barrier.\n    if (barrier != NULL) {\n        pcp_barrier_destroy(barrier);\n    }\n    barrier = pcp_barrier_create(nth);\n}\n\n\nvoid chol_task_par_finalize(void)\n{\n    if (barrier != NULL) {\n        pcp_barrier_destroy(barrier);\n        barrier = NULL;\n    }\n}\n\n\nstatic void krnl_chol(int iter)\n{\n    int jp      = iter * partition->block_size;\n    int n       = min(partition->matrix_size - jp, partition->block_size);\n    double *A11 = &A(jp,jp);\n\n    LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', n, A11, ldA);    \n}\n\n\nstatic void krnl_syrk(int iter, int me)\n{\n    //   j1        j2\n    // i g g g g g s\n    //   g g g g g s s \n    //   g g g g g s s s \n    //   g g g g g s s s s\n    //\n    // g = gemm\n    // s = syrk\n\n    int jp = iter * partition->block_size;\n    int i  = part_block_start_syrk(iter, me);\n    int m  = part_block_size_syrk(iter, me);\n    int j1 = jp + partition->block_size;\n    int j2 = i;\n    int n1 = j2 - j1;\n    int k  = partition->block_size;\n\n    double *A21;\n    double *A21a, *A21b;\n    double *A22;\n\n    /* SYRK */\n    if (m > 0) {\n        A22 = &A(i,j2);\n        A21 = &A(i,jp);\n        cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans,\n                    m, k, \n                    -1.0, A21, ldA,\n                     1.0, A22, ldA);\n    }\n\n    /* GEMM */\n    if (m > 0 && n1 > 0) {\n        A22  = &A(i,j1);\n        A21a = &A(i,jp);\n        A21b = &A(j1,jp);\n        cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,\n                    m, n1, k,\n                    -1.0, A21a, ldA,\n                          A21b, ldA,\n                     1.0, A22,  ldA);\n    }\n}\n\n\nstatic void krnl_trsm(int iter, int me)\n{\n    int jp      = iter * partition->block_size;\n    int i       = part_block_start_trsm(iter, me);\n    int m       = part_block_size_trsm(iter, me);\n    int n       = min(partition->matrix_size - jp, partition->block_size);\n    double *A11 = &A(jp,jp);\n    double *A21 = &A(i,jp);\n\n    if (m > 0) {\n        cblas_dtrsm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit,\n                    m, n,\n                    1.0, A11, ldA,\n                         A21, ldA);\n    }\n}\n\n\nvoid chol_task_par(void *ptr, int nth, int me)\n{\n    struct chol_task_arg *arg = (struct chol_task_arg*) ptr;\n       \n    n   = arg->n;\n    A   = arg->A;\n    ldA = arg->ldA;\n\n    if (me == 0) {\n        part_init(n, BLOCK_SIZE, nth);\n    }\n\n    if (me == 0) {\n        // chol(0)\n        krnl_chol(0);\n    }\n\n    // Synchronize.\n    pcp_barrier_wait(barrier);\n\n    // Loop over iterations.\n    for (int iter = 0; iter < partition->num_iter; ++iter) {\n        const int final_iteration = (iter == partition->num_iter - 1);\n\n        // Synchronize\n        pcp_barrier_wait(barrier);\n\n        //\n        // Phase I: trsm(iter) in //\n        //\n\n        krnl_trsm(iter, me);\n\n        // Synchronize\n        pcp_barrier_wait(barrier);\n\n        //\n        // Phase II: syrk(iter) in // plus chol(iter + 1)\n        //\n\n        krnl_syrk(iter, me);\n        if (me == 0 && !final_iteration) {\n            krnl_chol(iter + 1);\n        }\n    }\n\n    // Synchronize\n    pcp_barrier_wait(barrier);\n}\n", "meta": {"hexsha": "47225be2e9eccc0f722dbab3dfe74901ad64a9ec", "size": 7797, "ext": "c", "lang": "C", "max_stars_repo_path": "src/examples/dpotrf/task-chol-par.c", "max_stars_repo_name": "NLAFET/pcp-runtime", "max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/dpotrf/task-chol-par.c", "max_issues_repo_name": "NLAFET/pcp-runtime", "max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/dpotrf/task-chol-par.c", "max_forks_repo_name": "NLAFET/pcp-runtime", "max_forks_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_forks_repo_licenses": ["BSD-3-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.903654485, "max_line_length": 123, "alphanum_fraction": 0.5897139926, "num_tokens": 2274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.3997563042527226}}
{"text": "#if !defined (STATISTICS_H)\n#define STATISTICS_H\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include \"Rand.h\"\n#include <gsl/gsl_sf_gamma.h>\n#include <gsl/gsl_sf_bessel.h>\n\nusing namespace std;\n\nconst int         XMAX = 600;\nconst long double EXPXMAX = exp((double)XMAX);\nconst long double EXP     = exp(1.0);\n\ndouble Beta(double t, double x, double Itot); \ndouble Gaussian(double x, double mean, double var);\nlong double Poisson(int lambda, int k);\n\nvoid Statistics(const vector<double>& data, double& ave, double& squareave, double& var);\n\nvoid Statistics(const vector<double>& data, double& max, double& min, double& ave, double& var, double& error);\nvoid Statistics(const vector<int>& data, double& max, double& min, double& ave, double& var, double& error);\nvoid Statistics(const vector<int>& data, double& xmax, double& xmin, double& xave, double& xvar, double& xerror, double& x2ave);\n\n//void Statistics(const vector<int>& data, double& xmax, double& xmin, double& xave, double& xvar, double& xerror, double& x2ave, double& x1inverseave);\n\nvoid Statistics(const vector<int>& data, double& Xmin, double& Xmax, \n\t\tdouble& X1inverseave, //  <1/(X+1)>\n\t\tdouble& logXave,      //  < logX >\n\t\tdouble& Xsrave,       //  < X^0.5 > \n\t\tdouble& Xave,         //  < X > \n\t\tdouble& X2ave );      //  < x^2 > \n\nvoid moment(const vector<int>& data, double &ave, double &adev, double &sdev, double &var, double &skew, double &curt);\n\nvoid StatisticalDispersion(vector<int>& X, double& H7, double& H8, double& H9, double& H10);\n\ndouble GetXsecondmin(const vector<double>& data, double Xmin);\n\nvoid Statistics(const vector<double>& data, \n\t\tdouble& min, double& Q1, double& Q2, double& Q3, double& max, \n\t\tdouble& ave, double& var, double& error,\n\t\tofstream& fout1, ofstream& fout2);\n\nvoid Binning(const vector<double>& data, int B, vector<double>& Binsize, vector<double>& Q);\nint GetBinIndex(const double& x, const vector<double>& Q);\n\n#endif\n\n\n", "meta": {"hexsha": "d089733de2c2a07a7650ace59eb7404e53e74e0e", "size": 2006, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Gadgets/Statistics/Histogram/Statistics.h", "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Gadgets/Statistics/Histogram/Statistics.h", "max_issues_repo_name": "spxuw/RFIM", "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Gadgets/Statistics/Histogram/Statistics.h", "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8214285714, "max_line_length": 152, "alphanum_fraction": 0.6949152542, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.39975628814177094}}
{"text": "#include \"common.h\"\n#include \"dMatrix.h\"\n#include \"options.h\"\n#include \"linefile.h\"\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_statistics_double.h>\n\n\nstruct rnaBinder \n/* Name and correlation of rna binding proteins. */\n{\n    struct rnaBinder *next; /* Next in list. */\n    char *psName;           /* Name of probe set. Something like\n\t\t \t     * E@NM_XXXXXX_a_at or GXXXXXXX_a_at.*/\n    char *geneName;         /* Name of gene probed by probe\n\t\t\t     * set. Hopefully something readable. */\n    char *pfamAcc;          /* Name of pfam accession. */\n    char *pfamName;         /* Name of pfam domain. */\n    double corr;           /* Correlation between rnaBinder and cluster of interest. */\n};\n\nstruct clusterMember\n/* Member of the cluster of interest. */\n{\n    struct clusterMember *next; /* Next in list. */\n    char *geneId;               /* Gene id in cluster. */\n    char *psName;               /* Name of the probe set. */\n    char *desc;                 /* Description of the probe set. */\n};\n\nstatic struct optionSpec optionSpecs[] = \n/* Our acceptable options to be called with. */\n{\n    {\"help\", OPTION_BOOLEAN},\n    {\"sjIndexFile\", OPTION_STRING},\n    {\"psFile\", OPTION_STRING},\n    {\"clusterFile\", OPTION_STRING},\n    {\"rnaBindingFile\", OPTION_STRING},\n    {\"outputFile\", OPTION_STRING},\n    {\"antiCorrelation\", OPTION_BOOLEAN},\n    {NULL, 0}\n};\n\nstatic char *optionDescripts[] = \n/* Description of our options for usage summary. */\n{\n    \"Display this messge.\",\n    \"File with splice junction indexes.\",\n    \"File with probe set intensities.\",\n    \"File with probe sets in cluster of interest.\",\n    \"File with rna binding gene sets.\",\n    \"File to output correlation results to.\",\n    \"Sort by anti-correlation rather than correlation.\"\n};\n\nvoid usage()\n/* Print usage and quit. */\n{\nint i=0;\nwarn(\"rnaBindingClusterCorr - Program to calculate the correlation\\n\"\n     \"between rna binding protein expression data and splice junctions\\n\"\n     \"co-regulated as determined by clustering splice junction indexes.\\n\"\n     \"options are:\");\nfor(i=0; i<ArraySize(optionSpecs) -1; i++)\n    fprintf(stderr, \"  -%s -- %s\\n\", optionSpecs[i].name, optionDescripts[i]);\nerrAbort(\"\\nusage:\\n\"\n\t \"   rnaBindingClusterCorr -sjIndexFile=input/sjIndexTest.tab -psFile=input/psIntenTest.tab \\\\ \\n\"\n         \"      -clusterFile=input/clusterTest.tab -rnaBindingFile=input/rnaBinderTest.tab \\\\ \\n\"\n         \"      -outputFile=output/test.out.tab\\n\");\n}\n\n\ndouble correlation(double *X, double *Y, int count)\n/* Compute the correlation between X and Y \n   correlation(X,Y) = cov(X,Y)/ squareRt(var(X)var(Y))\n   page 332 Sheldon Ross \"A First Course in Probability\" 1998\n*/\n{\ndouble varX = gsl_stats_variance(X, 1, count);\ndouble varY = gsl_stats_variance(Y, 1, count);\ndouble covXY = gsl_stats_covariance(X, 1, Y, 1, count);\n\ndouble correlation = covXY / sqrt(varX *varY);\nreturn correlation;\n}\n\ndouble calcDistanceFromCluster(struct rnaBinder *rb, struct clusterMember *cmList,\n\t\t\t       struct dMatrix *sjIndex, struct dMatrix *psInten)\n/* Calculate the distance from the rnaBinder intensity measurement to\n   the sjIndexes of the cluster members. If no intensity present use\n   0 as it will fall in the middle of [-1,1]. */\n{\ndouble sum = 0;\nint count = 0;\nint sjIx = 0, gsIx = 0;\nstruct clusterMember *cm = NULL;\ndouble corr = 0;\nif(sjIndex->colCount != psInten->colCount)\n    errAbort(\"Splice Junction and Intensity files must have same number of columns.\");\n\n/* Get the index of the gene set in the intensity file. */\ngsIx = hashIntValDefault(psInten->nameIndex, rb->psName, -1);\nif(gsIx == -1)\n    {\n/*     warn(\"Probe Set %s not found in intensitiy file.\"); */\n    return 0;\n    }\nfor(cm = cmList; cm != NULL; cm = cm->next)\n    {\n    /* For each member get the index in the splice junction file. */\n    sjIx = hashIntValDefault(sjIndex->nameIndex, cm->psName, -1);\n    if(sjIx == -1)\n\terrAbort(\"Probe Set %s not found in SJ index file.\");\n    corr = correlation(psInten->matrix[gsIx], sjIndex->matrix[sjIx], sjIndex->colCount);\n    sum += corr;\n    count++;\n    }\nif(count == 0)\n    errAbort(\"No junctions in cluster.\");\nsum = sum / (double) count;\nreturn sum;\n}\n\nint rnaBinderCmp(const void *va, const void *vb)\n/* Compare to sort based correlation. */\n{\nconst struct rnaBinder *a = *((struct rnaBinder **)va);\nconst struct rnaBinder *b = *((struct rnaBinder **)vb);\nreturn a->corr < b->corr;\n}\n\nstruct rnaBinder *loadRnaBinders()\n/* Load the probe sets that encode genes thought to \n   bind rnas. Expected order is probeSet, geneName, pfamAcc, pfamName */\n{\nstruct rnaBinder *rbList = NULL, *rb = NULL;\nchar *words[4];\nstruct lineFile *lf = NULL;\nchar *inputFile = optionVal(\"rnaBindingFile\", NULL);\n\nassert(inputFile);\nlf = lineFileOpen(inputFile, TRUE);\nwhile(lineFileChopCharNext(lf, '\\t', words, ArraySize(words)))\n    {\n    AllocVar(rb);\n    rb->psName = cloneString(words[0]);\n    rb->geneName = cloneString(words[1]);\n    rb->pfamAcc = cloneString(words[2]);\n    rb->pfamName = cloneString(words[3]);\n    slAddHead(&rbList, rb);\n    }\nlineFileClose(&lf);\nslReverse(&rbList);\nreturn rbList; \n}\n\nstruct clusterMember *loadClusterMembers()\n/* Load the probe sets that are in our cluster of interest. */\n{\nstruct clusterMember *cmList = NULL, *cm = NULL;\nchar *words[3];\nstruct lineFile *lf = NULL;\nchar *inputFile = optionVal(\"clusterFile\", NULL);\nint wordCount = 0;\nassert(inputFile);\nlf = lineFileOpen(inputFile, TRUE);\nwhile((wordCount = lineFileChopCharNext(lf, '\\t', words, ArraySize(words))) != 0)\n    {\n    AllocVar(cm);\n    if(wordCount == 3) \n\t{\n\tcm->geneId = cloneString(words[0]);\n\tcm->psName = cloneString(words[1]);\n\tcm->desc = cloneString(words[2]);\n\t}\n    else if(wordCount == 2)\n\t{\n\tcm->psName = cloneString(words[0]);\n\tcm->desc = cloneString(words[1]);\n\t}\n    else\n\terrAbort(\"Got %d words at line %d\", wordCount, lf->lineIx);\n    slAddHead(&cmList, cm);\n    }\nlineFileClose(&lf);\nslReverse(&cmList);\nreturn cmList; \n}\n\nvoid reportRnaBinders(struct rnaBinder *rbList)\n/* Report the rnaBinder distances. */\n{\nstruct rnaBinder *rb = NULL;\nchar *fileName = optionVal(\"outputFile\", NULL);\nFILE *out = NULL;\n\nif(fileName == NULL)\n    errAbort(\"Must specify an outputFile\");\nout = mustOpen(fileName, \"w\");\nfor(rb = rbList; rb != NULL; rb = rb->next)\n    {\n    fprintf(out, \"%s\\t%s\\t%s\\t%s\\t%.4f\\n\", \n\t    rb->psName, rb->geneName, rb->pfamAcc, rb->pfamName, rb->corr);\n    }\ncarefulClose(&out);\n}\n\nvoid rnaBindingClusterCorr()\n/* Top level function to calculate correlations. */\n{\nchar *sjIndexFile = optionVal(\"sjIndexFile\", NULL);\nchar *psFile = optionVal(\"psFile\", NULL);\nstruct dMatrix *sjIndex = NULL, *psInten = NULL;\nstruct rnaBinder *rbList = NULL, *rb = NULL;\nstruct clusterMember *cmList = NULL, *cm = NULL;\n\nwarn(\"Loading Files.\");\nsjIndex = dMatrixLoad(sjIndexFile); \npsInten = dMatrixLoad(psFile); \nrbList = loadRnaBinders();\ncmList = loadClusterMembers();\n\nwarn(\"Calculating Distance.\");\n/* Calculate distance. */\nfor(rb = rbList; rb != NULL; rb = rb->next)\n    rb->corr = calcDistanceFromCluster(rb, cmList, sjIndex, psInten);\n\n/* Sort by distance (correlati2n) */\nslSort(&rbList, rnaBinderCmp);\n\n/* If we want anti-correlation reverse. */\nif(optionExists(\"antiCorrelation\"))\n    slReverse(&rbList);\n\nwarn(\"Writing out results.\");\n/* Do some outputting. */\nreportRnaBinders(rbList);\n\n/* Cleanup. */\ndMatrixFree(&sjIndex);\ndMatrixFree(&psInten);\nwarn(\"Done.\");\n}\n\nint main(int argc, char *argv[])\n{\nif(argc == 1)\n    usage();\noptionInit(&argc, argv, optionSpecs);\nif(optionExists(\"help\"))\n    usage();\nrnaBindingClusterCorr();\nreturn 0;\n}\n", "meta": {"hexsha": "3218abce5bd7a80380981fba818f2146e7e46431", "size": 7571, "ext": "c", "lang": "C", "max_stars_repo_path": "src/hg/altSplice/affySplice/rnaBindingClusterCorr.c", "max_stars_repo_name": "andypohl/kent", "max_stars_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 171.0, "max_stars_repo_stars_event_min_datetime": "2015-04-22T15:16:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T20:21:53.000Z", "max_issues_repo_path": "src/hg/altSplice/affySplice/rnaBindingClusterCorr.c", "max_issues_repo_name": "andypohl/kent", "max_issues_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 60.0, "max_issues_repo_issues_event_min_datetime": "2016-10-03T15:15:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:21:52.000Z", "max_forks_repo_path": "src/hg/altSplice/affySplice/rnaBindingClusterCorr.c", "max_forks_repo_name": "andypohl/kent", "max_forks_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 80.0, "max_forks_repo_forks_event_min_datetime": "2015-04-16T10:39:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:36:30.000Z", "avg_line_length": 29.6901960784, "max_line_length": 99, "alphanum_fraction": 0.6699247127, "num_tokens": 2106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.39969760986545144}}
{"text": "#pragma once\n\n#include <string>\n\n#include <gsl/gsl_complex.h>\n\n#include \"Expression.h\"\n#include \"UnitConversionExpression/Units.h\"\n\nclass BaseUnitExpression: public Expression {\n\n    UnitType type;\n    std::string abbr;\n    double val;\n\n    BaseUnitExpression(const std::string& unit, double val);\n    BaseUnitExpression(UnitType type, const std::string& unit, double val);\n\n    public:\n        static expression construct(const std::string& unit, double val = 1);\n        static expression construct(UnitType type, const std::string& unit, double val);\n\n        std::string repr() const override;\n        int id() const override;\n\n        EXPRESSION_OVERRIDES\n\n        friend expression operator*(const BaseUnitExpression& unit1, const BaseUnitExpression& unit2);\n        friend expression operator*(const BaseUnitExpression& unit1, const expression expr);\n        friend expression operator/(const BaseUnitExpression& unit1, const BaseUnitExpression& unit2);\n        friend expression operator/(const BaseUnitExpression& unit1, const expression expr);\n        friend expression operator^(const BaseUnitExpression& unit1, const expression expr);\n\n        friend expression convert(const BaseUnitExpression& from, const BaseUnitExpression& to);\n};\n\nclass ConvertedUnitExpression: public Expression {\n\n    UnitType type;\n    std::string abbr;\n    double val;\n\n    ConvertedUnitExpression(UnitType type, const std::string& unit, double val);\n\n    public:\n        static expression construct(UnitType type, const std::string& unit, double val);\n\n        std::string repr() const override;\n        int id() const override;\n\n        EXPRESSION_OVERRIDES\n};\n", "meta": {"hexsha": "c5950c56fe153962ba975f2f4bb589a8f88118c7", "size": 1652, "ext": "h", "lang": "C", "max_stars_repo_path": "MathEngine/Expressions/UnitExpression.h", "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathEngine/Expressions/UnitExpression.h", "max_issues_repo_name": "antoniojkim/CalcPlusPlus", "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathEngine/Expressions/UnitExpression.h", "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_forks_repo_licenses": ["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.1698113208, "max_line_length": 102, "alphanum_fraction": 0.7167070218, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3993716714886666}}
{"text": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_blas.h>\n#include \"Watershed.h\"\n#include \"math_functions.h\"\n#include \"Globals.h\"\n#include \"constitutive_equations.h\"\n#include \"dgshed_numerical_flux.h\"\n#include \"manufactured_solution.h\"\n\n/*****************************************************************************************//**\n * @file computeL.c\n *\n * This file contains code to evaluate the right hand side of the following discrete ODE obtained\n * from the DG discretization of the 2-D shallow water equations:\n * \n * \\f$\\frac{\\partial \\hat{\\mathbf{w}}}{\\partial t} = M^{-1}L(\\hat{\\mathbf{w}},t)\\f$\n *\n * *******************************************************************************************/\n\n\n/***************************************************************************/\n/************ Compute the spatial discretization of the equation ***********/\n/***************************************************************************/\nextern void GetLGLWeights(int N, double *w);\nextern double receive_floodwater(struct TwoDRegion *floodplain, int edg);\n\nvoid computeChanL(struct channel* Chan, double time, double *dt, int channelNumber, int stage, double* RHSA, double* RHSQ)\n{\n\tint fluxType = 1;\n\tint NumEdges = Chan->NumEdges;\n\tint NumEl = Chan->NumEl;\n\tint NumNodes = Chan->NumNodes;\n\tint Np = Chan->Np;\n\tint P = Chan->P;\n\n#ifdef WDON\n\t/**** Compute the mass over an element to use later for ensuring ********/\n\t/**** positive mass with the flux in a wetting and drying treatment *************/\n\tdouble* mass = xcalloc(NumEl, sizeof(double));\n\tdouble LGLWeight[Np];\n\tGetLGLWeights(P, LGLWeight);\n\n\tfor (int i = 0; i < NumEl; ++i)\n\t{\n\t\tdouble avgArea = 0;\n\t\tint begNode = i*Np + 1;\n\t\tfor (int j =0; j < Np; j++)\n\t\t{\n\t\t\tavgArea += LGLWeight[j]*Chan->A[begNode+j];\n\t\t}\n\t\tmass[i] = avgArea;\n\t}\n#endif\n\n\t/************** Compute the numerical flux at the faces *****************/\n\tdouble* Fhat1L = xcalloc(NumEdges, sizeof(double));\n\tdouble* Fhat2L = xcalloc(NumEdges, sizeof(double));\n\tdouble* Fhat1R = xcalloc(NumEdges, sizeof(double));\n\tdouble* Fhat2R = xcalloc(NumEdges, sizeof(double));\n\n\tfor (int i=0; i < NumEdges; ++i)\n\t{\n\t\tdouble A_L, Q_L, A_R, Q_R, m1val, m2val;\n\n\t\tint leftNode = i*Np;\n\t\tint rightNode = leftNode+1;\n\n\t\tm1val = Chan->m1[i];\n\t\tm2val = Chan->m2[i];\n\t\tdouble bval = Chan->b[i];\n\n\t\tdouble tmpF[2];\n\n#ifdef WDON\n\t\t// Check to see if the elements separated by this boundary are both dry\n\t\tif (i > 0 && i < NumEdges-1)\n\t\t{\n\t\t\tif (Chan->WD[i-1] == 0 && Chan->WD[i] == 0)\n\t\t\t{\n\t\t\t\t// Reflection flux for the left element\n\t\t\t\tA_L = Chan->A[leftNode];\n\t\t\t\tA_R = A_L;\n\t\t\t\tQ_L = Chan->Q[leftNode];\n\t\t\t\tQ_R = -Q_L;\n\n\t\t\t\tif (fluxType == 1)\n\t\t\t\t\tRoeFluxChan(tmpF, A_L, A_R, Q_L, Q_R,bval, m1val, m2val,0);\n\t\t\t\telse if (fluxType == 2)\n\t\t\t\t\tLFChan(tmpF, A_L, A_R, Q_L, Q_R,bval, m1val, m2val, 0);\n\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tprintf(\"Unknown flux type. Exiting now \\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\tFhat1L[i] = tmpF[0];\n\t\t\t\tFhat2L[i] = tmpF[1];\n\n\t\t\t\t// Reflection flux for the right element\n\t\t\t\tA_R = Chan->A[rightNode];\n\t\t\t\tA_L = A_R;\n\t\t\t\tQ_R = Chan->Q[rightNode];\n\t\t\t\tQ_L = -Q_R;\n\n\t\t\t\tif (fluxType == 1)\n\t\t\t\t\tRoeFluxChan(tmpF, A_L, A_R, Q_L, Q_R, bval, m1val, m2val, 0);\n\t\t\t\telse if (fluxType == 2)\n\t\t\t\t\tLFChan(tmpF, A_L, A_R, Q_L, Q_R, bval, m1val, m2val, 0);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tprintf(\"Unknown flux type. Exiting now \\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tFhat1R[i] = tmpF[0];\n\t\t\t\tFhat2R[i] = tmpF[1];\n\n\t\t\t\tif (isnan(tmpF[0]) || isnan(tmpF[1]))\n\t\t\t\t{\n\t\t\t\t\tprintf(\"both elements dry flux not a number, edge %d \\n\",i);\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\t// if the elements are not both dry\n\t\tif ((i == 0) || (i == NumEl) || Chan->WD[i-1] == 1 || Chan->WD[i] == 1)\n\t\t{\n\t\t\tA_L = Chan->A[leftNode];\n\t\t\tA_R = Chan->A[rightNode];\n\n\t\t\tQ_L = Chan->Q[leftNode];\n\t\t\tQ_R = Chan->Q[rightNode];\n\n\t\t\tif (fluxType == 1)\n\t\t\t\tRoeFluxChan(tmpF, A_L, A_R, Q_L,Q_R,bval, m1val, m2val, g);\n\t\t\telse if (fluxType == 2)\n\t\t\t\tLFChan(tmpF, A_L, A_R, Q_L,Q_R,bval, m1val, m2val, g);\n\n\t\t\telse\n\t\t\t{\n\t\t\t\tprintf(\"Unknown flux type. Exiting now \\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\tif (isnan(tmpF[0]) || isnan(tmpF[1]))\n\t\t\t{\n\t\t\t\tprintf(\"A_L = %lf A_R = %lf Q_L = %lf Q_R = %lf\\n\", A_L, A_R, Q_L, Q_R);\n\t\t\t\tprintf(\" both elements wet flux not a number, edge %d, channel %d , time = %lf\\n\",i, channelNumber, time);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t\tif (i==0 || Chan->WD[i-1] == 1)\n\t\t\t{\n\t\t\t\tFhat1L[i] = tmpF[0];\n\t\t\t\tFhat2L[i] = tmpF[1];\t\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdouble newtmpF[2];\n\t\t\t\tif (fluxType == 1)\n\t\t\t\t\tRoeFluxChan(newtmpF, A_L, A_R, Q_L, Q_R, bval, m1val, m2val, 0);\n\t\t\t\telse if (fluxType == 2)\n\t\t\t\t\tLFChan(newtmpF, A_L, A_R, Q_L, Q_R, bval, m1val, m2val, 0);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tprintf(\"Unknown flux type. Exiting now \\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tFhat1L[i] = newtmpF[0];\n\t\t\t\tFhat2L[i] = newtmpF[1];\n\t\t\t\tif (isnan(newtmpF[0]) || isnan(newtmpF[1]))\n\t\t\t\t{\n\t\t\t\t\tprintf(\"left element dry flux not a number, edge %d \\n\",i);\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif (i == NumEl || Chan->WD[i]==1)\n\t\t\t{\n\t\t\t\tFhat1R[i] = tmpF[0];\n\t\t\t\tFhat2R[i] = tmpF[1];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (fluxType == 1)\n\t\t\t\t\tRoeFluxChan(tmpF, A_L,A_R,Q_L,Q_R,bval, m1val, m2val, 0);\n\t\t\t\telse if (fluxType == 2)\n\t\t\t\t\tLFChan(tmpF, A_L,A_R,Q_L,Q_R,bval, m1val, m2val, 0);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tprintf(\"Unknown flux type. Exiting now \\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tFhat1R[i] = tmpF[0];\n\t\t\t\tFhat2R[i] = tmpF[1];\t\t\n\t\t\t\tif (isnan(tmpF[0]) || isnan(tmpF[1]))\n\t\t\t\t{\n\t\t\t\t\tprintf(\"right element dry flux not a number, edge %d \\n\",i);\n\t\t\t\t\tprintf(\"A_L = %lf A_R = %lf Q_L = %lf Q_R = %lf bval = %lf m1val = %lf m2val = %lf\\n\", A_L, A_R, Q_L, Q_R, bval, m1val, m2val);\n\t\t\t\t\tprintf(\"F = %lf\\n\", tmpF[0]);\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n#else\n\t\tA_L = Chan->A[leftNode];\n\t\tA_R = Chan->A[rightNode];\n\n\t\tQ_L = Chan->Q[leftNode];\n\t\tQ_R = Chan->Q[rightNode];\n\n\n\t\tif (fluxType == 1)\n\t\t\tRoeFluxChan(tmpF, A_L, A_R, Q_L,Q_R,bval,m1val,m2val,g);\n\t\telse if (fluxType == 2)\n\t\t\tLFChan(tmpF, A_L, A_R, Q_L,Q_R,bval,m1val,m2val,g);\n\t\telse\n\t\t{\n\t\t\tprintf(\"Unknown flux type. Exiting now \\n\");\n\t\t\texit(1);\n\t\t}\n\n\t\tif (isnan(tmpF[0]) || isnan(tmpF[1]))\n\t\t{\n\t\t\tprintf(\"flux not a number, edge %d \\n\",i);\n\n\t\t\tprintf(\"A_L = %3.16f A_R = %3.16f Q_L = %3.16f Q_R = %31.6f, b = %lf, m1 = %lf, m2 = %lf \\n\", A_L, A_R, Q_L, Q_R, Chan->b[i], m1val, m2val);\n\n\t\t\tprintf(\"Fhat = %lf Ghat = %lf\\n\", tmpF[0], tmpF[1]);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tFhat1L[i] = tmpF[0];\n\t\tFhat2L[i] = tmpF[1];\t\n\n\t\tFhat1R[i] = tmpF[0];\n\t\tFhat2R[i] = tmpF[1];\n\n#endif\n\n\t\t/**************************************************************************************************/\n\t\tdouble u_L = Q_L/A_L;\n\t\tdouble u_R = Q_R/A_R;\n\t\t//approximate c_L (exact for rectangular channels, but not for trapezoidal\n\t\tdouble c_L = sqrt(g*A_L/Chan->b[i]);\n\t\tdouble c_R = sqrt(g*A_R/Chan->b[i]);\n\n\t\tif (i==0)\n\t\t\tChan->max_lambda = fmax((fabs(u_L)+c_L), (fabs(u_R)+c_R));\t\t\t\n\t\t// Compute maximum eigenvalue for the next time step\n\t\tdouble current_max =fmax((fabs(u_L) + c_L), (fabs(u_R) + c_R));\n\t\tChan->max_lambda = max(Chan->max_lambda,current_max);\n\t}\n\n#ifdef WDON\n\tfor (int i =1; i < NumEdges-1; ++i)\n\t{\n\t\tint leftNode = i*Np;\n\t\tint rightNode = leftNode+1;\n\t\tdouble maxBetaOverAlpha = 2;\n\t\t// Check to see if this flux might possibly result in negative mass\n\t\t// If the mass will be negative on the left side\n\t\t//int cont = 1;\n\t\t//while(cont)\n\t\t//{\n\t\t\tif (Fhat1L[i]*maxBetaOverAlpha*(*dt) > mass[i-1] || -Fhat1R[i]*maxBetaOverAlpha*(*dt) > mass[i] )\n\t\t\t{\n\t\t\t\tFhat1L[i] = 0.0;\n\t\t\t\tFhat2L[i] = 0.0;\n\t\t\t\tFhat1R[i] = 0.0;\n\t\t\t\tFhat2R[i] = 0.0;\n\n\t\t\t\t//double A_L = Chan->A[leftNode];\n\t\t\t\t//double A_R = A_L;\n\t\t\t\t//double Q_L = Chan->Q[leftNode];\n\t\t\t\t//double Q_R = -Q_L;\n\t\t\t\t//double bval = Chan->NodalB[leftNode];\n\t\t\t\t//double m1val = Chan->Nodalm1[leftNode];\n\t\t\t\t//double m2val = Chan->Nodalm2[leftNode];\n\n\t\t\t\t//double tmpF[2];\n\t\t\t\t//double localG = g;\n\n\t\t\t\t//if (Chan->WD[i] == 0)\n\t\t\t\t//\tlocalG = 0;\n\n\t\t\t\t//if (fluxType == 1)\n\t\t\t\t//\tRoeFluxChan(tmpF, A_L, A_R, Q_L, Q_R, bval,m1val,m2val,localG);\n\t\t\t\t//else if (fluxType == 2)\n\t\t\t\t//\tLFChan(tmpF, A_L, A_R, Q_L, Q_R, bval,m1val,m2val,localG);\n\t\t\t\t//else\n\t\t\t\t//{\n\t\t\t\t//\tprintf(\"Unknown flux type. Exiting now \\n\");\n\t\t\t\t//\texit(1);\n\t\t\t\t//}\n\t\t\t\t//Fhat1L[i] = tmpF[0];\n\t\t\t\t//Fhat2L[i] = tmpF[1];\n\t\t\t\t//printf(\"element %d of Channel %d will be dry. Reducing dt now.\\n\", i, channelNumber);\n\t\t\t\t//(*dt) = 0.5*(*dt);\n\t\t\t}\n\t\t\t//else\n\t\t\t//\tcont = 0;\n\t\t//}\n\n\t\t//cont = 1;\n\t\t//while(cont)\n\t\t//{\n\t\t//\t// If the mass will be negative on the right side\n\t\t//\tif (-Fhat1R[i]*maxBetaOverAlpha*(*dt) > mass[i])\n\t\t//\t{\n\t\t//\t\tdouble A_R = Chan->A[rightNode];\n\t\t//\t\tdouble A_L = A_R;\n\t\t//\t\tdouble Q_R = Chan->Q[rightNode];\n\t\t//\t\tdouble Q_L = -Q_R;\n\t\t//\t\tdouble bval = Chan->NodalB[rightNode];\n\t\t//\t\tdouble m1val = Chan->Nodalm1[rightNode];\n\t\t//\t\tdouble m2val = Chan->Nodalm2[rightNode];\n\n\t\t//\t\tdouble tmpF[2];\n\t\t//\t\tdouble localG = g;\n\t\t//\t\tif (Chan->WD[i] == 0)\n\t\t//\t\t\tlocalG = 0;\n\n\t\t//\t\tif (fluxType == 1)\n\t\t//\t\t\tRoeFluxChan(tmpF, A_L, A_R, Q_L, Q_R, bval, m1val, m2val,localG);\n\t\t//\t\telse if (fluxType == 2)\n\t\t//\t\t\tLFChan(tmpF, A_L, A_R, Q_L, Q_R, bval,m1val,m2val,localG);\n\t\t//\t\telse\n\t\t//\t\t{\n\t\t//\t\t\tprintf(\"Unknown flux type. Exiting now \\n\");\n\t\t//\t\t\texit(1);\n\t\t//\t\t}\n\n\t\t//\t\tFhat1R[i] = tmpF[0];\n\t\t//\t\tFhat2R[i] = tmpF[1];\n\t\t//\t\tprintf(\"element %d of channel %d will be dry. Decreasing dt now.\\n\",i, channelNumber);\n\n\t\t//\t\t*dt = 0.5*(*dt);\n\n\t\t//\t}\n\t\t//\telse\n\t\t//\t\tcont = 0;\n\t\t//}\n\t}\n\tfree(mass);\n#endif\n\n\n\tfor (int k=0; k < NumEl; ++k) \n\t{\n\n\t\tdouble h = Chan->dh[k];\t\n\t\tgsl_vector *F1 = gsl_vector_alloc(Np);\n\t\tgsl_vector *F2 = gsl_vector_alloc(Np);\n\t\tgsl_vector *ST21 = gsl_vector_alloc(Np);\n\t\tgsl_vector *ST22 = gsl_vector_alloc(Np);\n\t\tgsl_vector *ST23 = gsl_vector_alloc(Np);\n\n\t\t//ST11 contains the qL term that comes from overland flow\n\t\tgsl_vector *ST11 = gsl_vector_calloc(Np);\n\n\t\t// ST12 contains term that takes flooding into account\n\t\tgsl_vector *ST12 = gsl_vector_calloc(Np);\n\n\t\tint begNode = k*Np;\n\t\tfor (int i = 0; i < Np; i++)\n\t\t{\n\t\t\tdouble Aval = Chan->A[begNode+i+1];\n\t\t\tdouble Qval = Chan->Q[begNode+i+1];\n\t\t\tdouble qL = Chan->qL[begNode+i];\n\t\t\tdouble qM = Chan->qM[begNode+i];\n\t\t\tdouble bval = Chan->NodalB[begNode+i];\n\t\t\tdouble S0 = Chan->dz[begNode+i];\n\t\t\tdouble m1val = Chan->Nodalm1[begNode+i];\n\t\t\tdouble m2val = Chan->Nodalm2[begNode+i];\n\t\t\tdouble dm1val = Chan->dm1[begNode+i];\n\t\t\tdouble dm2val = Chan->dm2[begNode+i];\n\t\t\tdouble dbval = Chan->db[begNode+i];\n\t\t\tdouble nval = Chan->NodalnFriction[begNode+i];\n\t\t\tdouble I1val = getI1(Aval, bval, m1val, m2val);\n\t\t\tdouble I2val = getI2(Aval, bval, dbval, m1val, dm1val, m2val, dm2val);\n\t\t\tdouble Sfval = getS_f(Aval, Qval, bval, m1val, m2val, nval);\n\t\t\tdouble beta = Chan->beta[begNode+i];\n\t\t\tdouble localG;\n#ifdef WDON\n\t\t\tif(Chan->WD[k]==1)\n\t\t\t\tlocalG = g;\n\t\t\telse\n\t\t\t\tlocalG = 0;\n#else\n\t\t\tlocalG = g;\n#endif\n\n\t\t\tgsl_vector_set(F1, i, Qval);\n\t\t\tgsl_vector_set(F2, i, beta*Qval*Qval/Aval + localG*I1val); \n\t\t\tgsl_vector_set(ST21, i, localG*I2val);\n\t\t\tgsl_vector_set(ST22, i, localG*Aval*S0);\n\t\t\tgsl_vector_set(ST23, i, localG*Aval*Sfval);\n\t\t\tgsl_vector_set(ST11, i, qL);\n\t\t\tgsl_vector_set(ST12, i, qM);\n\n\t\t}\n\n\t\t//gsl_blas_dgemv(CblasNoTrans, 2.0/h, InvM, ST, 1.0, ST11);\n\n\t\tgsl_vector *localFhat1 = gsl_vector_alloc(2);\n\t\tgsl_vector_set(localFhat1, 0, Fhat1R[k]);\n\t\tgsl_vector_set(localFhat1, 1, Fhat1L[k+1]);\n\n\t\tgsl_vector *localFhat2 = gsl_vector_alloc(2);\n\t\tgsl_vector_set(localFhat2, 0, Fhat2R[k]);\n\t\tgsl_vector_set(localFhat2, 1, Fhat2L[k+1]);\n\n\t\t// cacluate the volume integral of the flux\n\t\tgsl_vector *localRHS1 = gsl_vector_calloc(Np);\n\t\tgsl_vector *localRHS2 = gsl_vector_calloc(Np);\n\t\tgsl_blas_dgemv(CblasNoTrans, 2.0/h, VolMat, F1, 1.0, localRHS1);\n\t\tgsl_blas_dgemv(CblasNoTrans, 2.0/h, VolMat, F2, 1.0, localRHS2);\n\n\t\t// calculate the surface integral of the flux\n\t\tgsl_vector *SurfPart1 = gsl_vector_calloc(Np);\n\t\tgsl_vector *SurfPart2 = gsl_vector_calloc(Np);\n\t\tgsl_blas_dgemv(CblasNoTrans, 2.0/h, LIFT, localFhat1, 1.0, SurfPart1);\n\t\tgsl_blas_dgemv(CblasNoTrans, 2.0/h, LIFT, localFhat2, 1.0, SurfPart2);\n\n\t\t// calculate the RHS\n\t\tgsl_vector_add(localRHS1, SurfPart1);\n\t\tgsl_vector_add(localRHS1, ST11);\n\t\tgsl_vector_add(localRHS1, ST12);\n\t\tgsl_vector_add(localRHS2, SurfPart2);\n\t\tgsl_vector_add(localRHS2, ST21);\n\t\tgsl_vector_add(localRHS2, ST22);\n\t\tgsl_vector_sub(localRHS2, ST23);\n\n\t\tfor(int i = 0; i < Np; i++)\n\t\t{\n\t\t\tRHSA[begNode+i+1] = gsl_vector_get(localRHS1, i);\n\t\t\tRHSQ[begNode+i+1] = gsl_vector_get(localRHS2, i);\n\t\t}\n\n\t\tgsl_vector_free(F1);\n\t\tgsl_vector_free(F2);\n\t\tgsl_vector_free(localFhat1);\n\t\tgsl_vector_free(localFhat2);\n\t\tgsl_vector_free(SurfPart1);\n\t\tgsl_vector_free(SurfPart2);\n\t\tgsl_vector_free(ST11);\n\t\tgsl_vector_free(ST12);\n\t\tgsl_vector_free(ST21);\n\t\tgsl_vector_free(ST22);\n\t\tgsl_vector_free(ST23);\n\t\tgsl_vector_free(localRHS1);\n\t\tgsl_vector_free(localRHS2);\n\n\n\t}\n\n\tfree(Fhat1L);\n\tfree(Fhat1R);\n\tfree(Fhat2L);\n\tfree(Fhat2R);\n\n}\n\nvoid computeLKinematicEls(double time, double* RHS, int fp)\n{\n\tint NumEl = FloodplainList[fp]->NumEl;\n\t// calculate and store the flux (Q) at the downstream edge of each kinematic element\n\t// these fluxes will be used to calculate the upwinded flux values\n\tdouble *Fhat = xcalloc(NumEl, sizeof(double));\n\tfor (int i = 0; i < NumEl; ++i)\n\t{\n\t\tstruct kinematicEl *kinEl = KinematicElList[i];\n\t\tif (kinEl->isActive)\n\t\t{\n\t\t\tint Np = kinEl->Np;\n\t\t\tdouble myA = kinEl->A[Np-1];\n\t\t\tdouble myS0 = kinEl->dz[Np-1];\n\t\t\tdouble myNf = kinEl->NodalnFriction[Np-1];\n\t\t\tdouble myWeq = kinEl->weq;\n\t\t\tdouble myH = myA/myWeq;\n\n\t\t\t// using manning's N.\n\t\t\tFhat[i] = myWeq*sqrt(myS0)*pow(myH, 5.0/3)/myNf;\n\n\n\t\t\t// using chezy's relationship. nf stands for C, chezy's coefficient\n\t\t\t//Fhat[i] = myWeq*sqrt(myS0*myH)*myH*myNf;\n\t\t}\n\t}\n\n\t// now calculate the right hand side\n\tfor (int i = 0; i < NumEl; ++i)\n\t{\n\t\tstruct kinematicEl *kinEl = KinematicElList[i];\n\t\tif (kinEl->isActive)\n\t\t{\n\t\t\tdouble h_el = kinEl->dh;\n\t\t\tint Np = kinEl->Np;\n\n\t\t\tgsl_vector *F = gsl_vector_calloc(Np);\n\n\t\t\tgsl_vector *ST = gsl_vector_calloc(Np);\t\t\t // will eventually store R-I (Rainfall - Infiltration)\n\n\t\t\tdouble weq = kinEl->weq;\n\n\t\t\tfor (int j = 0; j < Np; ++j)\n\t\t\t{\n\t\t\t\tdouble A = kinEl->A[j];\n\t\t\t\tdouble nf = kinEl->NodalnFriction[j];\n\t\t\t\tdouble S0 = kinEl->dz[j];\n\t\t\t\tdouble H = A/weq;\n\n\t\t\t\t// using manning's N\n\t\t\t\tdouble myF = weq*sqrt(S0)*pow(H,5.0/3)/nf;\n\n\t\t\t\t// using Chezy's relationship (nf stands for C)\n\t\t\t\t//double myF = weq*sqrt(S0*H)*H*nf;\n\n\t\t\t\tif (S0 < 0 )\n\t\t\t\t\tprintf(\"z1 = %lf z2 = %lf\\n\", kinEl->z1, kinEl->z2);\n\t\t\t\tif (isnan(myF))\n\t\t\t\t{\n\t\t\t\t\tprintf(\"myF is nan; A = %lf, nf = %lf, S0 = %lf, H = %lf weq = %lf, kinElNum = %d\\n\", A, nf, S0, H, weq, i);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tgsl_vector_set(F, j, myF);\n\n\t\t\t\tdouble rainfall;\n\t\t\t\tif (time < 1800)\n\t\t\t\t\trainfall = 1.0/12/3600;\n\n\t\t\t\tgsl_vector_set(ST, j, weq*rainfall);\n\t\t\t\t// second parking lot case\n\t\t\t\t//if (time  <= 180)\n\t\t\t\t//\tgsl_vector_set(ST, j, weq*2.0/12/3600);\n\t\t\t\t//else if (time <= 360)\n\t\t\t\t//\tgsl_vector_set(ST, j, weq*4.0/12/3600);\n\n\t\t\t}\n\t\t\t// Now calculate total upstream flux. \n\t\t\t// If the element is at the boundary of the watershed, flux coming in will be 0.\n\t\t\tint numUpstreamEls = kinEl->numUpstreamEls;\n\t\t\tdouble Fhat1 = 0.0;\n\t\t\t//if (numUpstreamEls > 1)\n\t\t\t//\tprintf(\" i = %d UpEl1 = %d UpEl2 = %d\\n\", i, kinEl->upstreamEls[0], kinEl->upstreamEls[1]);\n\t\t\tfor (int j = 0; j < numUpstreamEls; ++j)\n\t\t\t{\n\t\t\t\tint upstreamEl = kinEl->upstreamEls[j];\n\t\t\t\t//printf(\"upstream el = %d\\t\", upstreamEl);\n\t\t\t\tFhat1 += Fhat[upstreamEl];\n\t\t\t}\n\t\t\t//printf(\"downstream el = %d\\n\", kinEl->el2);\n\t\t\tdouble Fhat2 = Fhat[i];\n\t\t\tgsl_vector *localFhat = gsl_vector_alloc(2);\n\t\t\tgsl_vector_set(localFhat, 0, Fhat1);\n\t\t\tgsl_vector_set(localFhat, 1, Fhat2);\n\n\n\t\t\tgsl_vector *localRHS = gsl_vector_calloc(Np);\n\n\t\t\t// calculate the volume integral\n\t\t\tgsl_blas_dgemv(CblasNoTrans, 2.0/h_el, VolMat, F, 1.0, localRHS);\n\n\t\t\t// calculate the surface integral\n\t\t\tgsl_vector *SurfPart = gsl_vector_calloc(Np);\n\t\t\tgsl_blas_dgemv(CblasNoTrans, 2.0/h_el, LIFT, localFhat, 1.0, SurfPart);\n\n\t\t\t// subtract the surface integral from the volume integral\n\t\t\tgsl_vector_add(localRHS, SurfPart);\n\n\t\t\t// add source term to the right hand side\n\n\t\t\tgsl_vector_add(localRHS, ST);\n\n\t\t\tfor (int j = 0; j < Np; j++)\n\t\t\t{\n\t\t\t\tRHS[i*Np+j] = gsl_vector_get(localRHS, j);\n\t\t\t\tif (isnan(RHS[i*Np+j]))\n\t\t\t\t{\n\t\t\t\t\tprintf(\"SurfPart = %lf \\n\", gsl_vector_get(SurfPart,j));\n\t\t\t\t}\n\t\t\t}\n\t\t\tgsl_vector_free(F);\n\t\t\tgsl_vector_free(localFhat);\n\t\t\tgsl_vector_free(SurfPart);\n\t\t\tgsl_vector_free(localRHS);\n\t\t\tgsl_vector_free(ST);\n\n\t\t}\n\n\t}\n\tfree(Fhat);\n\n}\n\n\n/***********************************************************************************************//**\n * Function for evaluating the right hand side of the discrete ODE obtained from the DG discretization\n * of the 2-D shallow water equations\n * @param [in] currRegion a pointer to the junction structure corresponding to the junction that is \n * currently being worked on \n * @param [in] time  a double representing the current time of the simulation\n * @param [out] RHSZeta a pointer to an array of size NumEl x 3 in which the right hand side for\n * the water surface elevation will be stored\n * @param [out] RHSQx a pointer to an array of size NumEl x 3 in which the right hand side for the\n * momentum in the x-direction is stored\n * @param [out] RHSQy a pointer to an array of size NumEl x 3 in which the right hand side for the\n * momentum in the y-direction is stored\n *\n ***************************************************************************************************/\n\nvoid compute2DL(struct TwoDRegion *currRegion, double time, double *RHSZeta, double *RHSQx, double *RHSQy, double dt)\n{\n\n\tint NumEdges = currRegion->TotalNumEdges;\n\tint NumEl = currRegion->NumEl;\n\tint Nfp = currRegion->P + 1;\n\tint Np = currRegion->Np;\n\n\n#ifdef WDON\n\t/**** Compute the mass over an element to use later for ensuring ********/\n\t/**** positive mass with the flux in a wetting and drying treatment *************/\n\tdouble* mass = xcalloc(NumEl, sizeof(double));\n\tgsl_vector *height = gsl_vector_calloc(Np);\n\tgsl_vector *tmp = gsl_vector_alloc(Np);\n\tgsl_vector *jac = gsl_vector_alloc(Np);\n\n\tfor (int i = 0; i < NumEl; ++i)\n\t{\n\t\tfor (int j = 0; j < Np; j++)\n\t\t{\n\t\t\tgsl_vector_set(height, j, currRegion->zeta[i][j] + currRegion->NodalZ[i][j]);\n\t\t\tgsl_vector_set(jac, j, currRegion->jac[i]);\n\t\t}\n\n\t\tgsl_blas_dgemv(CblasNoTrans, 1.0, MassMatrix2D, height, 0.0, tmp);\n\t\tgsl_blas_ddot(jac, tmp, &mass[i]);\n\n\t}\n\n\tgsl_vector_free(height);\n\tgsl_vector_free(tmp);\n\tgsl_vector_free(jac);\n#endif\n\n\n\n\t/********************************* Compute Roe's flux at the face **********************************************/\n\tdouble **Fhat1dotn, **Fhat2dotn, **Fhat3dotn;\n\tFhat1dotn = malloc(NumEl*sizeof(double*));\n\tFhat2dotn = malloc(NumEl*sizeof(double*));\n\tFhat3dotn = malloc(NumEl*sizeof(double*));\n\tfor (int i = 0; i < NumEl; i++)\n\t{\n\t\tFhat1dotn[i] = xcalloc(3*Nfp, sizeof(double));\n\t\tFhat2dotn[i] = xcalloc(3*Nfp, sizeof(double));\n\t\tFhat3dotn[i] = xcalloc(3*Nfp, sizeof(double));\n\t}\n\n\n\tfor (int i=0; i<NumEdges; ++i)\n\t{\n\t\tint el1 = currRegion->EdgtoEls[i*2];\n\t\tint el2 = currRegion->EdgtoEls[i*2+1];\n\n\t\tint ledg1 = currRegion->GlobaltoLocalEdg[i*2];\n\t\tint ledg2 = currRegion->GlobaltoLocalEdg[i*2+1];\n\n\t\t// take the normal from element 1 side\n\t\tdouble nx = currRegion->nx[el1*3+ledg1];\n\t\tdouble ny = currRegion->ny[el1*3+ledg1];\n\n\t\tdouble tx = -ny;\n\t\tdouble ty = nx;\n\n\t\tfor (int j = 0; j < Nfp; j++)\n\t\t{\n\t\t\tdouble zeta_in, Qx_in, Qy_in;\n\t\t\tdouble zeta_ex, Qx_ex, Qy_ex;\n\t\t\tdouble z_in, z_ex;\t\t\t// should be the same as z_ex\n\n\t\t\tint lv1 = currRegion->GlobalEdgPosNegNodes[i][2*j];\n\t\t\tint lv2 = currRegion->GlobalEdgPosNegNodes[i][2*j+1];\n\n\t\t\tint pos1 = currRegion->PosInFVec[i][2*j];\n\t\t\tint pos2 = currRegion->PosInFVec[i][2*j+1];\n\n\t\t\tdouble Fn_in[3], Fn_ex[3];\n\n\t\t\tzeta_in = currRegion->zeta[el1][lv1];\n\t\t\tQx_in = currRegion->Qx[el1][lv1];\n\t\t\tQy_in = currRegion->Qy[el1][lv1];\n\t\t\tz_in = currRegion->NodalZ[el1][lv1];\n\n\t\t\tdouble Q_T_in = Qx_in*tx + Qy_in*ty;\n\n\t\t\t// need to change this later so that the boundary condition is given per node on the edge\n\t\t\t// if the edge is an exterior edge connected to a channel \n\t\t\tint bdrypres = currRegion->BdryPrescribed[i];\n\n\n\t\t//if (el1 == 531 || el2 == 531)\n\t\t//{\n\t\t//\tprintf(\"el1 = %d, el2 = %d\\n\", el1, el2);\n\t\t//\tprintf(\"WD1 = %d, WD2 = %d\\n\", currRegion->WD[el1], currRegion->WD[el2]);\n\t\t//\tprintf(\"bdrypres = %d\\n\", bdrypres);\n\t\t//}\n\n\n\n\n\t\t\t// manufactured solution\n\t\t\tif (bdrypres == 555)\n\t\t\t\t//if (bdrypres == 555 || (el1 == el2))\n\t\t\t{\n\t\t\t\tdouble xval = currRegion->NodalX[el1][lv1];\n\t\t\t\tdouble yval = currRegion->NodalY[el1][lv1];\n\t\t\t\tzeta_ex = getmanH(xval, yval, time);\n\t\t\t\tQx_ex = getQx(xval, yval, time);\n\t\t\t\tQy_ex = getQy(xval, yval, time);\n\t\t\t}\n\t\t\t// if inflow or outflow boundary, i.e. if bdrypres = 1 or 2\n\t\t\t//for floodplains\n\t\t\telse if (bdrypres == 111)\t\n\t\t\t{\n\t\t\t\tzeta_ex = currRegion->bzeta[i];\n\t\t\t\tQx_ex = Qx_in;\n\t\t\t\tQy_ex = Qy_in;\n\t\t\t}\n\n\t\t\telse if (bdrypres == 222)\n\t\t\t{\n\t\t\t\tzeta_ex = zeta_in;\n\t\t\t\tdouble Q_N_ex = currRegion->bQn[i];\n\t\t\t\tdouble Q_T_ex = Q_T_in;\n\t\t\t\tdouble denom = 1./(nx*ty-ny*tx);\n\t\t\t\tQx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;\n\t\t\t\tQy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;\n\t\t\t}\n\n\t\t\telse if (bdrypres == 333)\n\t\t\t{\n\t\t\t\tzeta_ex = currRegion->bQn[i];\n\t\t\t\tdouble Q_N_ex = currRegion->bQn[i];\n\t\t\t\tdouble Q_T_ex = Q_T_in;\n\t\t\t\tdouble denom = 1./(nx*ty-ny*tx);\n\t\t\t\tQx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;\n\t\t\t\tQy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;\n\n\t\t\t}\n\t\t\t// for junctions\n\t\t\telse if (bdrypres == 1 || bdrypres == 2)\n\t\t\t{\n\t\t\t\tzeta_ex = currRegion->bzeta[i];\n\t\t\t\tdouble Q_N_ex = currRegion->bQn[i];\n\t\t\t\t// for the first iteration\n\t\t\t\tif (zeta_ex == -10000.0 && Q_N_ex == -10000.0)\n\t\t\t\t{\n\t\t\t\t\tzeta_ex = zeta_in;\n\t\t\t\t\tQx_ex = Qx_in;\n\t\t\t\t\tQy_ex = Qy_in;\n\t\t\t\t\tz_ex = z_in;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdouble Q_T_ex = Q_T_in;\n\t\t\t\t\tdouble denom = 1./(nx*ty-ny*tx);\n\t\t\t\t\tQx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;\n\t\t\t\t\tQy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;\n\t\t\t\t\tz_ex = z_in;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// for floodplains\n\t\t\telse if (bdrypres == 3)\n\t\t\t{\n\t\t\t\tdouble Q_N_ex = receive_floodwater(currRegion, i);\n\n\t\t\t\t// element 1\n\t\t\t\tQx_in = currRegion->Qx[el1][lv1];\n\t\t\t\tQy_in = currRegion->Qy[el1][lv1];\n\t\t\t\tzeta_in = currRegion->zeta[el1][lv1];\n\t\t\t\tz_in = currRegion->NodalZ[el1][lv1];\n\t\t\t\tzeta_ex = zeta_in;\n\t\t\t\tQ_T_in = Qx_in*tx + Qy_in*ty;\n\t\t\t\tdouble Q_T_ex = Q_T_in;\n\t\t\t\tdouble denom = 1./(nx*ty-ny*tx);\n\t\t\t\tQx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;\n\t\t\t\tQy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;\n\t\t\t\n\t\t\t\tdouble localG = g;\n\n#ifdef WDON\n\t\t\t\tif (currRegion->WD[el1] == 0)\n\t\t\t\t\tlocalG = 0;\n\t\t\t\telse\n\t\t\t\t\tlocalG = g;\n#endif\n\n\t\t\t\tdouble current_max_lam= RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex, z_in, nx, ny, localG,Fn_in);\n\n\t\t\t\t//if (el1 == 170 && fabs(Q_N_ex) > 0)\n\t\t\t\t//{\n\t\t\t\t//\tprintf(\"***************\\n\");\n\t\t\t\t//\tprintf(\"time = %lf\\n\", time);\n\t\t\t\t//\tprintf(\"j = %d el1 = %d, el2 = %d\\n\", j, el1, el2);\n\t\t\t\t//\tprintf(\"WD1 = %d, WD2 = %d\\n\", currRegion->WD[el1], currRegion->WD[el2]);\n\t\t\t\t//\tprintf(\"Q_N_ex = %lf, Qx_in = %lf, Qy_in = %lf, \\n\", Q_N_ex, Qx_in, Qy_in);\n\t\t\t\t//\tprintf(\"Fn_in = %lf, %lf, %lf\\n\", Fn_in[0], Fn_in[1], Fn_in[2]);\n\t\t\t\t//}\n\n\t\t\t\t// element 2\n\t\t\t\tnx = -nx;\n\t\t\t\tny = -ny;\n\t\t\t\ttx = -ny;\n\t\t\t\tty = nx;\n\t\t\t\tdenom = 1./(nx*ty-ny*tx);\n\t\t\t\tzeta_in = currRegion->zeta[el2][lv2];\n\t\t\t\tz_in = currRegion->NodalZ[el2][lv2];\n\t\t\t\tzeta_ex = zeta_in;\n\t\t\t\tQx_in = currRegion->Qx[el2][lv2];\n\t\t\t\tQy_in = currRegion->Qy[el2][lv2];\n\t\t\t\tQ_T_in = Qx_in*tx + Qy_in*ty;\n\t\t\t\tQ_T_ex = Q_T_in;\n\t\t\t\tdenom = 1./(nx*ty-ny*tx);\n\t\t\t\tQx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;\n\t\t\t\tQy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;\n\t\t\t\tz_ex = z_in;\n\n#ifdef WDON\n\t\t\t\tif (currRegion->WD[el2] == 0)\n\t\t\t\t\tlocalG = 0;\n\t\t\t\telse\n\t\t\t\t\tlocalG = g;\n#endif\n\n\n\t\t\t\tcurrent_max_lam= RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex, z_in, nx, ny, localG, Fn_ex);\n\n\t\t\t\tif (el2 == 170 && fabs(Q_N_ex)>0)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"***************\\n\");\n\t\t\t\t\tprintf(\"el1 = %d, el2 = %d\\n\", el1, el2);\n\n\t\t\t\t\tprintf(\"Q_N_ex = %lf\\n\", Q_N_ex);\n\t\t\t\t\tprintf(\"Fn_in = %lf, %lf, %lf\\n\", Fn_in[0], Fn_in[1], Fn_ex[2]);\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\t// if edge i is a boundary edge but not connected to a channel, implement no flux boundary condition\n\t\t\telse if (el1 == el2)\n\t\t\t{\n\t\t\t\tzeta_ex  = currRegion->zeta[el2][lv2];\n\t\t\t\t// Compute the velocity in the normal direction\n\t\t\t\tdouble Q_N_in = Qx_in*nx + Qy_in*ny;\n\t\t\t\tdouble Q_T_in = Qx_in*tx + Qy_in*ty;\n\n\t\t\t\t// Reflect the velocity in the normal direction\n\t\t\t\tdouble Q_N_ex = -Q_N_in;\n\t\t\t\tdouble Q_T_ex = Q_T_in;\n\n\t\t\t\t// Compute the x and y components of the external state flow\n\t\t\t\tdouble denom = 1./(nx*ty - ny*tx);\n\t\t\t\tQx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;\n\t\t\t\tQy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;\n\n\t\t\t\tz_ex = z_in;\n\n\t\t\t}\n\n\t\t\t// if the edge is not a boundary edge\n\t\t\telse\n\t\t\t{\n\t\t\t\tzeta_ex = currRegion->zeta[el2][lv2];\n\t\t\t\tQx_ex = currRegion->Qx[el2][lv2];\n\t\t\t\tQy_ex = currRegion->Qy[el2][lv2];\n\t\t\t\tz_ex = currRegion->NodalZ[el2][lv2];\n\t\t\t}\n\n#ifdef WDON\n\t\t\t// Check to see if both of the elements separated by this edge are dry\n\t\t\tif (currRegion->WD[el1] == 0 && currRegion->WD[el2] == 0 && (bdrypres != 3) && (bdrypres != 222) && (bdrypres != 2) && (bdrypres !=1))\n\t\t\t{\n\t\t\t\tFn_in[0] = 0.0;\n\t\t\t\tFn_in[1] = 0.0;\n\t\t\t\tFn_in[2] = 0.0;\n\t\t\t\tFn_ex[0] = 0.0;\n\t\t\t\tFn_ex[1] = 0.0;\n\t\t\t\tFn_ex[2] = 0.0;\n\n\t\t\t\t//// Reflection flux for the interior element\n\t\t\t\t//double zeta_ex_ref = zeta_in;\n\t\t\t\t//double Q_N_in = Qx_in*nx + Qy_in*ny;\n\t\t\t\t//double Q_T_in = Qx_in*tx + Qy_in*ty;\n\n\t\t\t\t//double Q_N_ex = -Q_N_in;\n\t\t\t\t//double Q_T_ex = Q_T_in;\n\t\t\t\t//\n\t\t\t\t//double denom = 1./(nx*ty - ny*tx);\n\t\t\t\t//double Qx_ex_ref = (ty*Q_N_ex - ny*Q_T_ex)*denom;\n\t\t\t\t//double Qy_ex_ref = (-tx*Q_N_ex + nx*Q_T_ex)*denom;\n\n\t\t\t\t//double max_lam_in = RoeFluxJunc(zeta_in, zeta_ex_ref, Qx_in,Qx_ex_ref,\n\t\t\t\t//\tQy_in, Qy_ex_ref, z_in, nx, ny, 0, Fn_in);\n\n\t\t\t\t//// Reflection flux for the exterior element\n\t\t\t\t//double zeta_in_ref = zeta_ex;\n\t\t\t\t//Q_N_ex = Qx_ex*nx + Qy_ex*ny;\n\t\t\t\t//Q_T_ex = Qx_ex*tx + Qy_ex*ty;\n\n\t\t\t\t//Q_N_in = -Q_N_ex;\n\t\t\t\t//Q_T_in = Q_T_ex;\n\t\t\t\t//\n\t\t\t\t//double Qx_in_ref = (ty*Q_N_in - ny*Q_T_in)*denom;\n\t\t\t\t//double Qy_in_ref = (-tx*Q_N_in + nx*Q_T_ex)*denom;\n\t\t\t\t//double max_lam_ex = RoeFluxJunc(zeta_in_ref, zeta_ex, Qx_in_ref, Qx_ex, Qy_in_ref, Qy_ex, z_in, nx, ny, 0, Fn_ex);\n\n\t\t\t\t//if (i ==0)\n\t\t\t\t//\tcurrRegion->max_lambda = max(max_lam_in, max_lam_ex);\n\t\t\t\t//else\n\t\t\t\t//{\n\t\t\t\t//\tcurrRegion->max_lambda = fmax(currRegion->max_lambda, max_lam_in);\n\t\t\t\t//\tcurrRegion->max_lambda = fmax(currRegion->max_lambda, max_lam_ex);\n\t\t\t\t//}\n\n\t\t\t}\n\t\t\telse if (bdrypres != 3 && bdrypres != 222)// if the elements aren't both dry\n\t\t\t{\n\t\t\t\tdouble Fhatdotn[3];\n\t\t\t\tdouble current_max_lam= RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex, z_in, nx, ny, g,Fhatdotn);\n\n\t\t\t\tif (isnan(Fhatdotn[0]) || isnan(Fhatdotn[1]) || isnan(Fhatdotn[2]))\n\t\t\t\t{\n\t\t\t\t\tprintf(\"2D both elements wet flux not a number, edge %d, time %e, for domain type %d \\n\",i,time, currRegion->type);\n\t\t\t\t\tprintf(\"ze_ex = %lf, ze_in = %lf, z_in = %lf, Qx_ex = %lf, Qx_in = %lf, Qy_ex = %lf, Qy_in = %lf, el_ex = %d, el_in = %d, bdrypres = %d\\n\", zeta_ex, zeta_in, z_in, Qx_ex, Qx_in, Qy_ex, Qy_in, el2, el1, bdrypres); \n\t\t\t\t\tprintf(\"wdfalg1 = %d , wdflag2 = %d\\n\", currRegion->WD[el1], currRegion->WD[el2]);\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\n\t\t\t\t// Check to see if the flux is large enough to dry up the elements\n\t\t\t\t// Calculate the sum of the length of the three edges of the interior and exterior element\n\t\t\t\tdouble edg_len_el1 = 0;\n\t\t\t\tfor (int v = 0; v < 3; v++)\n\t\t\t\t{\n\t\t\t\t\tint v1 = currRegion->EltoVert[el1*3 + v];\n\t\t\t\t\tint v2 = currRegion->EltoVert[el1*3 + (v+1)%3];\n\t\t\t\t\tedg_len_el1 += sqrt(pow(currRegion->Vx[v1] - currRegion->Vx[v2], 2) + pow(currRegion->Vy[v1] - currRegion->Vy[v2],2));\n\t\t\t\t}\n\n\t\t\t\tdouble edg_len_el2 = 0;\n\t\t\t\tfor (int v = 0; v < 3; v++)\n\t\t\t\t{\n\t\t\t\t\tint v1 = currRegion->EltoVert[el2*3 + v];\n\t\t\t\t\tint v2 = currRegion->EltoVert[el2*3 + (v+1)%3];\n\t\t\t\t\tedg_len_el2 += sqrt(pow(currRegion->Vx[v1] - currRegion->Vx[v2], 2) + pow(currRegion->Vy[v1] - currRegion->Vy[v2],2));\n\t\t\t\t}\n\n\t\t\t\tdouble maxBetaOverAlpha = 2;\n\n\t\t\t\tif ((1.01*Fhatdotn[0]*edg_len_el1*maxBetaOverAlpha*dt >= mass[el1]) || (-1.01*Fhatdotn[0]*edg_len_el2*maxBetaOverAlpha*dt >= mass[el2]))\n\t\t\t\t{\n\t\t\t\t\t//printf(\"either el %d or el %d will be dry \\n\", el1, el2);\n\t\t\t\t\tFn_in[0] = 0.0;\n\t\t\t\t\tFn_in[1] = 0.0; \n\t\t\t\t\tFn_in[2] = 0.0;\n\t\t\t\t\tFn_ex[0] = 0.0;\n\t\t\t\t\tFn_ex[1] = 0.0; \n\t\t\t\t\tFn_ex[2] = 0.0;\n\n\t\t\t\t}\n\n\t\t\t\telse // check to make sure the flux is not coming from a dry element\n\t\t\t\t{\n\t\t\t\t\tif (currRegion->WD[el1] == 1 || (el1 == el2))\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int j =0; j < 3; ++j)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFn_in[j] = Fhatdotn[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (Fhatdotn[0] > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t//printf(\"initially, el1 = %d, j = %d, Fn_ex = %lf\\n\", el1, j, Fhatdotn[0]);\n\t\t\t\t\t\tzeta_ex = currRegion->zeta[el2][lv2];\n\t\t\t\t\t\tzeta_in = zeta_ex;\n\t\t\t\t\t\tQx_ex = currRegion->Qx[el2][lv2];\n\t\t\t\t\t\tQy_ex = currRegion->Qy[el2][lv2];\n\t\t\t\t\t\tdouble Q_N_ex = Qx_ex*nx + Qy_ex*ny;\n\t\t\t\t\t\tdouble Q_N_in = -Q_N_ex;\n\t\t\t\t\t\tdouble Q_T_ex = Qx_ex*tx + Qy_ex*ty;\n\t\t\t\t\t\tQ_T_in = Q_T_ex;\n\t\t\t\t\t\tdouble denom = 1./(nx*ty-ny*tx);\n\t\t\t\t\t\tQx_in = (ty*Q_N_in - ny*Q_T_in)*denom;\n\t\t\t\t\t\tQy_in = (-tx*Q_N_in + nx*Q_T_in)*denom;\n\n\t\t\t\t\t\tdouble max_lam_in = RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex,\n\t\t\t\t\t\t\t\tz_ex, nx, ny, g, Fn_in);\n\t\t\t\t\t\tif (isnan(Fn_in[0]) || isnan(Fn_in[1]) || isnan(Fn_in[2]))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprintf(\"2D interior element dry flux not a number, edge %d, el_in = %d, el_ex = %d, domain type = %d\\n\",i, el1, el2, currRegion->type);\n\t\t\t\t\t\t\tprintf(\"ze_ex = %lf, ze_in = %lf, z_in = %lf, z_ex = %lf, Qx_ex = %lf, Qx_in = %lf, Qy_ex = %lf, Qy_in = %lf, el_ex = %d, el_in = %d, bdrypres = %d\\n\", zeta_ex, zeta_in, z_in, z_ex, Qx_ex, Qx_in, Qy_ex, Qy_in, el2, el1, bdrypres); \n\t\t\t\t\t\t\tprintf(\"wdfalg1 = %d , wdflag2 = %d\\n\", currRegion->WD[el1], currRegion->WD[el2]);\n\t\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//printf(\"after reflection, el1 = %d, Fn_ex = %lf\\n\", el1, Fn_in[0]);\n\t\t\t\t\t\tcurrent_max_lam = max(current_max_lam, max_lam_in);\n\t\t\t\t\t}\n\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble max_lam_in = RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex,\n\t\t\t\t\t\t\t\tz_in, nx, ny, 0, Fn_in);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif (currRegion->WD[el2] == 1 && (el1 != el2))\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tFn_ex[j] = Fhatdotn[j];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if ((el1 != el2) && (Fhatdotn[0] < 0))\n\t\t\t\t\t{\n\t\t\t\t\t//\tprintf(\"initially, el2 = %d, Fn_ex = %lf\\n\", el2, -Fhatdotn[0]);\n\t\t\t\t\t\tQx_in = currRegion->Qx[el1][lv1];\n\t\t\t\t\t\tQy_in = currRegion->Qy[el1][lv1];\n\t\t\t\t\t\tzeta_in = currRegion->zeta[el1][lv1];\n\t\t\t\t\t\tdouble Q_N_in = Qx_in*nx + Qy_in*ny;\n\t\t\t\t\t\tdouble Q_T_in = Qx_in*tx + Qy_in*ty;\n\t\t\t\t\t\tdouble Q_N_ex = -Q_N_in;\n\t\t\t\t\t\tdouble Q_T_ex = Q_T_in;\n\t\t\t\t\t\tdouble denom = 1.0/(nx*ty - ny*tx);\n\t\t\t\t\t\tQx_ex = (ty*Q_N_ex - ny*Q_T_ex)*denom;\n\t\t\t\t\t\tQy_ex = (-tx*Q_N_ex + nx*Q_T_ex)*denom;\n\t\t\t\t\t\tzeta_ex = zeta_in;\n\n\t\t\t\t\t\tdouble max_lam_ex = RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex,\n\t\t\t\t\t\t\t\tQy_in, Qy_ex, z_in, nx, ny, g, Fn_ex);\n\t\t\t\t\t\tcurrent_max_lam = max(current_max_lam, max_lam_ex);\n\n\t\t\t\t\t\tif (isnan(Fn_ex[0]) || isnan(Fn_ex[1]) || isnan(Fn_ex[2]))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprintf(\"2D exterior element dry flux not a number, edge %d \\n\",i);\n\t\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//printf(\"el2 = %d, Fn_ex = %lf\\n\", el2, -Fn_ex[0]);\n\n\t\t\t\t\t//\tprintf(\"after reflection, el2 = %d, Fn_ex = %lf\\n\", el2, -Fn_ex[0]);\n\t\t\t\t\t}\n\t\t\t\t\telse if (el1 != el2 )\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble max_lam_ex = RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex,\n\t\t\t\t\t\t\t\tQy_in, Qy_ex, z_in, nx, ny, 0, Fn_ex);\n\t\t\t\t\t\tcurrent_max_lam = max(current_max_lam, max_lam_ex);\n\t\t\t\t\t\n\t\t\t\t\t}\n\n\t\t\t\t\tif (i == 0)\n\t\t\t\t\t\tcurrRegion->max_lambda = current_max_lam;\n\t\t\t\t\telse\n\t\t\t\t\t\tcurrRegion->max_lambda = fmax(currRegion->max_lambda, current_max_lam);\n\t\t\t\t}\n\n\t\t\t}\n\n#else\n\n\t\t\tdouble Fhatdotn[3];\n\t\t\tdouble current_max_lam= RoeFluxJunc(zeta_in, zeta_ex, Qx_in, Qx_ex, Qy_in, Qy_ex, z_in, nx, ny, g, Fhatdotn);\n\n\t\t\tif (isnan(Fhatdotn[0]) || isnan(Fhatdotn[1]) || isnan(Fhatdotn[2]))\n\t\t\t{\n\t\t\t\tprintf(\"2D numerical flux not a number, edge %d \\n\",i);\n\t\t\t\tprintf(\"zeta_in = %e, zeta_ex = %e, z_edge = %e, BdryPrescribed = %d \\n\", zeta_in, zeta_ex, z_in, bdrypres);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t{\n\t\t\t\tFn_in[j] = Fhatdotn[j];\n\t\t\t\tFn_ex[j] = Fhatdotn[j];\n\t\t\t}\n\n\t\t\tif (i == 0)\n\t\t\t\tcurrRegion->max_lambda = current_max_lam;\n\t\t\telse\n\t\t\t\tcurrRegion->max_lambda = max(currRegion->max_lambda, current_max_lam);\n\n#endif\n\n\t\t\t// store Fhatdotn for the two elements connected by this edge\n\t\t\tFhat1dotn[el1][pos1] = Fn_in[0];\n\t\t\tFhat2dotn[el1][pos1] = Fn_in[1];\n\t\t\tFhat3dotn[el1][pos1] = Fn_in[2];\n\n\t\t\t// store the value for the exterior element, only if the edge is not a boundary edge\n\t\t\tif (el2 != el1 && (bdrypres != 3))\n\t\t\t{\n\t\t\t\tFhat1dotn[el2][pos2] = -Fn_ex[0];\n\t\t\t\tFhat2dotn[el2][pos2] = -Fn_ex[1];\n\t\t\t\tFhat3dotn[el2][pos2] = -Fn_ex[2];\n\t\t\t}\n\t\t\telse if (el2 != el1)  // for bdyrpes = 3, we have already taken sign of normals into account during flux calculation\n\t\t\t{\n\t\t\t\tFhat1dotn[el2][pos2] = Fn_ex[0];\n\t\t\t\tFhat2dotn[el2][pos2] = Fn_ex[1];\n\t\t\t\tFhat3dotn[el2][pos2] = Fn_ex[2];\n\t\t\t}\n\n\t\t} // end node loop\n\n\t}\t// end edge loop\n\n\n\tfor (int k=0; k<NumEl; ++k)\n\t{\n\t\tgsl_vector *F1x = gsl_vector_alloc(Np);\n\t\tgsl_vector *F2x = gsl_vector_alloc(Np);\n\t\tgsl_vector *F3x = gsl_vector_alloc(Np);\n\t\tgsl_vector *F1y = gsl_vector_alloc(Np);\n\t\tgsl_vector *F2y = gsl_vector_alloc(Np);\n\t\tgsl_vector *F3y = gsl_vector_alloc(Np);\n\t\tgsl_vector *ST21 = gsl_vector_calloc(Np);\n\t\tgsl_vector *ST22 = gsl_vector_calloc(Np);\n\t\tgsl_vector *ST31 = gsl_vector_calloc(Np);\n\t\tgsl_vector *ST32 = gsl_vector_calloc(Np);\n\t\t//gsl_vector *ST11 = gsl_vector_calloc(Np);\n\n\t\tdouble localG = g;\n#ifdef WDON\n\t\tif(currRegion->WD[k] == 0)\n\t\t\tlocalG = 0;\n#endif\n\n\t\tfor (int i = 0; i < Np; i++)\n\t\t{\n\t\t\tdouble zeta = currRegion->zeta[k][i];\n\t\t\tdouble Qx = currRegion->Qx[k][i];\n\t\t\tdouble Qy = currRegion->Qy[k][i];\n\t\t\tdouble z = currRegion->NodalZ[k][i];\n\t\t\tdouble H = zeta + z;\n\t\t\tdouble f2x = Qx*Qx/H + 0.5*localG*(H*H - z*z);\n\t\t\tdouble f2y = Qx*Qy/H;\n\t\t\tdouble f3x = f2y;\n\t\t\tdouble f3y = Qy*Qy/H + 0.5*localG*(H*H - z*z);\n\t\t\tgsl_vector_set(F1x, i, Qx);\n\t\t\tgsl_vector_set(F1y, i, Qy);\n\t\t\tgsl_vector_set(F2x, i, f2x);\n\t\t\tgsl_vector_set(F2y, i, f2y);\n\t\t\tgsl_vector_set(F3x, i, f3x);\n\t\t\tgsl_vector_set(F3y, i, f3y);\n\n\t\t\tdouble u = Qx/H;\n\t\t\tdouble v = Qy/H;\n\t\t\tdouble nfric = currRegion->NodalnFriction[k][i];\n\t\t\tdouble tau = localG*nfric*nfric*sqrt(u*u + v*v)/pow(H,4.0/3);\n\t\t\tdouble dzx = currRegion->Nodaldzx[k][i];\n\t\t\tdouble dzy = currRegion->Nodaldzy[k][i];\n\n\t\t\tgsl_vector_set(ST21, i, localG*zeta*dzx);\n\t\t\tgsl_vector_set(ST22, i, -tau*Qx);\n\t\t\tgsl_vector_set(ST31, i, localG*zeta*dzy);\n\t\t\tgsl_vector_set(ST32, i, -tau*Qy);\n\n\t\t\t// Source terms for manufactured solution\n\t\t\t//double xval = currRegion->NodalX[k][i];\n\t\t\t//double yval = currRegion->NodalY[k][i];\n\n\t\t\t//double st2 = getS2(xval, yval, time);\n\t\t\t//double st3 = getS3(xval, yval, time);\n\t\t\t//gsl_vector_set(ST21, i, st2);\n\t\t\t//gsl_vector_set(ST31, i, st3);\n\n#ifdef WDON\n\t\t\tif (currRegion->WD[k] == 0)\n\t\t\t{\n\t\t\t\tgsl_vector_set(F1x, i, 0);\n\t\t\t\tgsl_vector_set(F1y, i, 0);\n\t\t\t\tgsl_vector_set(F2x, i, 0);\n\t\t\t\tgsl_vector_set(F2y, i, 0);\n\t\t\t\tgsl_vector_set(F3x, i, 0);\n\t\t\t\tgsl_vector_set(F3y, i, 0);\n\t\t\t\tgsl_vector_set(ST21, i, 0);\n\t\t\t\tgsl_vector_set(ST22, i, 0);\n\t\t\t\tgsl_vector_set(ST31, i, 0);\n\t\t\t\tgsl_vector_set(ST32, i, 0);\n\t\t\t}\n#endif\n\n\t\t// rainfall\n\t\t//if (currRegion->type == 2)\n\t\t//\tgsl_vector_set(ST11, i, 0.5*12/3600);\n\n\t\t}\n\n\t\t// Calculate the volume integral of the flux\n\t\tdouble rx = currRegion->rx[k];\n\t\tdouble ry = currRegion->ry[k];\n\t\tdouble sx = currRegion->sx[k];\n\t\tdouble sy = currRegion->sy[k];\n\n\t\tgsl_vector *localRHS1 = gsl_vector_calloc(Np);\n\t\tgsl_vector *localRHS2 = gsl_vector_calloc(Np);\n\t\tgsl_vector *localRHS3 = gsl_vector_calloc(Np);\n\n\n\t\tgsl_vector *lR12 = gsl_vector_calloc(Np);\n\t\tgsl_vector *lR13 = gsl_vector_calloc(Np);\n\t\tgsl_vector *lR14 = gsl_vector_calloc(Np);\n\t\tgsl_vector *lR22 = gsl_vector_calloc(Np);\n\t\tgsl_vector *lR23 = gsl_vector_calloc(Np);\n\t\tgsl_vector *lR24 = gsl_vector_calloc(Np);\n\t\tgsl_vector *lR32 = gsl_vector_calloc(Np);\n\t\tgsl_vector *lR33 = gsl_vector_calloc(Np);\n\t\tgsl_vector *lR34 = gsl_vector_calloc(Np);\n\n\t\tgsl_blas_dgemv(CblasNoTrans, rx, Drw, F1x, 0.0, localRHS1);\n\t\tgsl_blas_dgemv(CblasNoTrans, sx, Dsw, F1x, 0.0, lR12);\n\t\tgsl_blas_dgemv(CblasNoTrans, ry, Drw, F1y, 0.0, lR13);\n\t\tgsl_blas_dgemv(CblasNoTrans, sy, Dsw, F1y, 0.0, lR14);\n\n\n\t\tgsl_vector_add(localRHS1, lR12);\n\t\tgsl_vector_add(localRHS1, lR13);\n\t\tgsl_vector_add(localRHS1, lR14);\n\n\t\tgsl_blas_dgemv(CblasNoTrans, rx, Drw, F2x, 0.0, localRHS2);\n\t\tgsl_blas_dgemv(CblasNoTrans, sx, Dsw, F2x, 0.0, lR22);\n\t\tgsl_blas_dgemv(CblasNoTrans, ry, Drw, F2y, 0.0, lR23);\n\t\tgsl_blas_dgemv(CblasNoTrans, sy, Dsw, F2y, 0.0, lR24);\n\n\t\tgsl_vector_add(localRHS2, lR22);\n\t\tgsl_vector_add(localRHS2, lR23);\n\t\tgsl_vector_add(localRHS2, lR24);\n\n\n\t\tgsl_blas_dgemv(CblasNoTrans, rx, Drw, F3x, 0.0, localRHS3);\n\t\tgsl_blas_dgemv(CblasNoTrans, sx, Dsw, F3x, 0.0, lR32);\n\t\tgsl_blas_dgemv(CblasNoTrans, ry, Drw, F3y, 0.0, lR33);\n\t\tgsl_blas_dgemv(CblasNoTrans, sy, Dsw, F3y, 0.0, lR34);\n\n\n\t\tgsl_vector_add(localRHS3, lR32);\n\t\tgsl_vector_add(localRHS3, lR33);\n\t\tgsl_vector_add(localRHS3, lR34);\n\n\n\t\t// calculate the surface integral of the flux\n\t\tgsl_vector *localFhat1dotn = gsl_vector_alloc(3*Nfp);\n\t\tgsl_vector *localFhat2dotn = gsl_vector_alloc(3*Nfp);\n\t\tgsl_vector *localFhat3dotn = gsl_vector_alloc(3*Nfp);\n\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tdouble edgJac = currRegion->edgJac[k*3+i];\n\t\t\tfor (int j = 0; j < Nfp; j++)\n\t\t\t{\n\t\t\t\tint index = i*Nfp+j;\n\t\t\t\tgsl_vector_set(localFhat1dotn, index, edgJac*Fhat1dotn[k][index]);\n\t\t\t\tgsl_vector_set(localFhat2dotn, index, edgJac*Fhat2dotn[k][index]);\n\t\t\t\t//printf(\"edgJac = %lf Fhat = %lf\\n\", edgJac, Fhat2dotn[k][index]);\n\t\t\t\tgsl_vector_set(localFhat3dotn, index, edgJac*Fhat3dotn[k][index]);\n\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t\tdouble jac = currRegion->jac[k];\n\n\t\tgsl_vector *SurfPart1 = gsl_vector_calloc(Np);\n\t\tgsl_vector *SurfPart2 = gsl_vector_calloc(Np);\n\t\tgsl_vector *SurfPart3 = gsl_vector_calloc(Np);\n\n\t\tdouble fac = 1.0/jac;\n\t\tgsl_blas_dgemv(CblasNoTrans, fac, LIFT2D, localFhat1dotn, 0.0, SurfPart1);\n\t\tgsl_blas_dgemv(CblasNoTrans, fac, LIFT2D, localFhat2dotn, 0.0, SurfPart2);\n\t\tgsl_blas_dgemv(CblasNoTrans, fac, LIFT2D, localFhat3dotn, 0.0, SurfPart3);\n\n\t\t// subtract this from the RHS\n\t\tgsl_vector_sub(localRHS1, SurfPart1);\n\t\tgsl_vector_sub(localRHS2, SurfPart2);\n\t\tgsl_vector_sub(localRHS3, SurfPart3);\n\n\t\t// add source and sink terms\n\t\t//gsl_vector_add(localRHS1, ST11);\n\t\t//\n\t\t//gsl_vector_add(localRHS1, ST11);\n\t\tgsl_vector_add(localRHS2, ST21);\n\t\tgsl_vector_add(localRHS2, ST22);\n\t\tgsl_vector_add(localRHS3, ST31);\n\t\tgsl_vector_add(localRHS3, ST32);\n\n\t\tint begNode = k*Np;\n\t\tfor(int i = 0; i < Np; i++)\n\t\t{\n\t\t\tRHSZeta[begNode+i] = gsl_vector_get(localRHS1,i);\n\t\t\tRHSQx[begNode+i] = gsl_vector_get(localRHS2,i);\n\t\t\tRHSQy[begNode+i] = gsl_vector_get(localRHS3, i);\n\n\t\t}\n\n\n\t\t// free all gsl vectors\n\t\tgsl_vector_free(localRHS1);\n\t\tgsl_vector_free(localRHS2);\n\t\tgsl_vector_free(localRHS3);\n\t\tgsl_vector_free(localFhat1dotn);\n\t\tgsl_vector_free(localFhat2dotn);\n\t\tgsl_vector_free(localFhat3dotn);\n\t\tgsl_vector_free(SurfPart1);\n\t\tgsl_vector_free(SurfPart2);\n\t\tgsl_vector_free(SurfPart3);\n\t\tgsl_vector_free(lR12);\n\t\tgsl_vector_free(lR13);\t\n\t\tgsl_vector_free(lR14);\n\t\tgsl_vector_free(lR22);\n\t\tgsl_vector_free(lR23);\n\t\tgsl_vector_free(lR24);\n\t\tgsl_vector_free(lR32);\n\t\tgsl_vector_free(lR33);\n\t\tgsl_vector_free(lR34);\n\t\tgsl_vector_free(F1x); \n\t\tgsl_vector_free(F2x); \n\t\tgsl_vector_free(F3x); \n\t\tgsl_vector_free(F1y); \t\n\t\tgsl_vector_free(F2y); \n\t\tgsl_vector_free(F3y); \n\t\t//gsl_vector_free(ST11);\n\t\tgsl_vector_free(ST21);\n\t\tgsl_vector_free(ST22);\n\t\tgsl_vector_free(ST31);\n\t\tgsl_vector_free(ST32);\n\n\t}\n\n\t// free allocated space\n\tfor (int i = 0; i < NumEl; i++)\n\t{\n\t\tfree(Fhat1dotn[i]);\n\t\tfree(Fhat2dotn[i]);\n\t\tfree(Fhat3dotn[i]);\n\t}\n\tfree(Fhat1dotn);\n\tfree(Fhat2dotn);\n\tfree(Fhat3dotn);\n\n#ifdef WDON\n\tfree(mass);\n#endif\n\n}\n", "meta": {"hexsha": "4787760dbfb621d15b3385f08b7bc4b30ad9716e", "size": 39986, "ext": "c", "lang": "C", "max_stars_repo_path": "DGSHED/computeL.c", "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_issues_repo_path": "DGSHED/computeL.c", "max_issues_repo_name": "evalseth/DG-RAIN", "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DGSHED/computeL.c", "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "avg_line_length": 29.2723279649, "max_line_length": 238, "alphanum_fraction": 0.6081878658, "num_tokens": 15278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.39935293738144817}}
{"text": "#ifndef __INTERP_2D_H__\n#define __INTERP_2D_H__\n\n#include <string.h>\n//#include <gsl/gsl_vector.h>\n//#include <gsl/gsl_matrix.h>\n//#include <gsl/gsl_math.h>\n#include <gsl/gsl_spline.h>\n\n#include \"cubic_bspline_2d_coeffs.h\"\n#include \"cubic_bspline_2d_interpol.h\"\n\nenum\n{\n    INTERP_2D_LINEAR=0,\n    INTERP_2D_CUBIC_BSPLINE=1\n};\n\ntypedef struct\n{\n    int size1;\n    int size2;\n    double * xa;\n    double * ya;\n    double * za;\n    int type;        \n}interp_2d;\n\ninterp_2d * interp_2d_alloc(int size1, int size2);\nvoid interp_2d_free(interp_2d * i2d);\n\nvoid interp_2d_init(interp_2d * i2d, const double * xa, const double * ya, const double * za, int type);\n\ndouble interp_2d_eval(interp_2d  * i2d, double x, double y, gsl_interp_accel * accx, gsl_interp_accel * accy);\nvoid interp_2d_eval_grad(interp_2d * i2d, double x, double y, double * grad, gsl_interp_accel * accx, gsl_interp_accel * accy);\ndouble interp_2d_eval_cubic_bspline(interp_2d * i2d, double x, double y, gsl_interp_accel * accx,gsl_interp_accel * accy);\n\n#endif\n\n", "meta": {"hexsha": "c254bdef8f92c50b207aaeb1f091462ae0869d5b", "size": 1028, "ext": "h", "lang": "C", "max_stars_repo_path": "galpy/util/interp_2d/interp_2d.h", "max_stars_repo_name": "fardal/galpy", "max_stars_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "galpy/util/interp_2d/interp_2d.h", "max_issues_repo_name": "fardal/galpy", "max_issues_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "galpy/util/interp_2d/interp_2d.h", "max_forks_repo_name": "fardal/galpy", "max_forks_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "max_forks_repo_licenses": ["BSD-3-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.7, "max_line_length": 127, "alphanum_fraction": 0.7315175097, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.39925626355850713}}
{"text": "#ifndef __LLVUTILS_H__\n#define __LLVUTILS_H__ 1\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <string.h>\n#include <gsl/gsl_cdf.h>\n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"EOBNRv2HMROMstruct.h\"\n#include \"EOBNRv2HMROM.h\"\n#include \"wip.h\"\n#include \"likelihood.h\"\n#include \"splinecoeffs.h\"\n#include \"LLVFDresponse.h\"\n#include \"LLVnoise.h\"\n\n/***************** Structures for parameters *****************/\n\n/* Parameters for the generation of a LLV waveform (in the form of a list of modes) */\ntypedef struct tagLLVParams {\n  double tRef;               /* reference time (s) - GPS time at the frequency representing coalescence */\n  double phiRef;             /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */\n  double m1;                 /* mass of companion 1 (solar masses) */\n  double m2;                 /* mass of companion 2 (solar masses) */\n  double distance;           /* distance of source (Mpc) */\n  double ra;                 /* right ascension of the source (rad) */\n  double dec;                /* declination of the source (rad) */\n  double inclination;        /* inclination of L relative to line of sight (rad) */\n  double polarization;       /* polarization angle (rad) */\n  int nbmode;                /* number of modes to generate (starting with 22) - defaults to 5 (all modes) */\n} LLVParams;\n\n/* Global parameters for the waveform generation and overlap computation */\ntypedef struct tagLLVGlobalParams {\n  double fRef;               /* reference frequency (Hz, default 0 which is interpreted as Mf=0.14) */\n  double minf;               /* Minimal frequency (Hz) - when set to 0 (default), use the first frequency covered by the noise data of the detector */\n  double maxf;               /* Maximal frequency (Hz) - when set to 0 (default), use the last frequency covered by the noise data of the detector */\n  int setphiRefatfRef;       /* Flag for adjusting the FD phase at phiRef at the given fRef, which depends also on tRef - if false, treat phiRef simply as an orbital phase shift (minus an observer phase shift) (default=1) */\n  int nbmodeinj;             /* number of modes to include in the injection (starting with 22) - defaults to 5 (all modes) */\n  int nbmodetemp;            /* number of modes to include in the templates (starting with 22) - defaults to 5 (all modes) */\n  int tagint;                /* Tag choosing the integrator: 0 for wip (default), 1 for linear integration */\n  int tagnetwork;            /* Tag choosing the network of detectors to use */\n  int nbptsoverlap;          /* Number of points to use in loglinear overlaps (default 32768) */\n  int constL;                /* set all logLikelihood to 0 - allows to sample from the prior for testing */\n} LLVGlobalParams;\n\ntypedef struct tagLLVPrior {\n\tdouble deltaT;             /* width of time prior centered on injected value (s) (default 0.1) */\n\tdouble comp_min;           /* minimum component mass (solar masses) (default 4) */\n\tdouble comp_max;           /* maximum component mass (solar masses) (default 50) */\n\tdouble mtot_min;           /* minimum total mass (solar masses) (default 8) */\n\tdouble mtot_max;           /* maximum total mass (solar masses) (default 100) */\n\tdouble qmax;               /* maximum asymmetric mass ratio (>=1) (default 12) */\n\tdouble dist_min;           /* minimum distance of source (Mpc) (default 1) */\n\tdouble dist_max;           /* maximum distance of source (Mpc) (default 1e4) */\n  double ra_min;            /* minimum ra (rad, default 0) - for testing */\n  double ra_max;            /* maximum ra (rad, default 2pi) - for testing */\n  double dec_min;           /* minimum dec (rad, default 0) - for testing */\n  double dec_max;           /* maximum dec (rad, default pi) - for testing */\n  double phase_min;          /* minimum phase (rad, default 0) - for testing */\n  double phase_max;          /* maximum phase (rad, default 2pi) - for testing */\n  double pol_min;            /* minimum polarization (rad, default 0) - for testing */\n  double pol_max;            /* maximum polarization (rad, default 2pi) - for testing */\n  double inc_min;            /* minimum inclination (rad, default 0) - for testing */\n  double inc_max;            /* maximum inclination (rad, default pi) - for testing */\n  double fix_m1;\n  double fix_m2;\n  double fix_time;\n  double fix_ra;\n  double fix_dec;\n  double fix_phase;\n  double fix_pol;\n  double fix_dist;\n  double fix_inc;\n  int pin_m1;\n  int pin_m2;\n  int pin_time;\n  int pin_ra;\n  int pin_dec;\n  int pin_phase;\n  int pin_pol;\n  int pin_dist;\n  int pin_inc;\n  double snr_target;\n  int rescale_distprior;\n  int flat_distprior;\n} LLVPrior;\n\ntypedef struct tagLLVRunParams {\n\tdouble eff;                /* target efficiency (default 0.1) */\n\tdouble tol;                /* logZ tolerance (default 0.5) */\n\tint    nlive;              /* number of live points (default 1000) */\n\tchar   outroot[200];       /* output root (default \"chains/LLVinference_\") */\n\tint    bambi;              /* run BAMBI? (default 0) */\n\tint    resume;             /* resume form previous run? (default 0) */\n\tint    maxiter;            /* max number of iterations (default 0 - ignore) */\n\tchar   netfile[200];       /* NN settings file (default \"LLVinference.inp\") */\n  int    mmodal;             /* use multimodal decomposition ? */\n  int    maxcls;             /* max number of modes in multimodal decomposition */\n  int    nclspar;            /* number of parameters to use for multimodal decomposition - in the order of the cube */\n  double ztol;               /* in multimodal decomposition, modes with lnZ lower than Ztol are ignored */\n  int    seed;               /* seed the inference by setting one of the live points to the injection ? */\n} LLVRunParams;\n\n/************ Structures for signals and injections ************/\n\n// typedef struct tagLLVSignal\n// {\n//   struct tagListmodesCAmpPhaseFrequencySeries* LHOSignal;   /* Signal in LHO, in the form of a list of the contribution of each mode */\n//   struct tagListmodesCAmpPhaseFrequencySeries* LLOSignal;   /* Signal in LLO, in the form of a list of the contribution of each mode */\n//   struct tagListmodesCAmpPhaseFrequencySeries* VIRGOSignal; /* Signal in VIRGO, in the form of a list of the contribution of each mode */\n//   double LHOhh;                                             /* Inner product (h|h) for LHO */\n//   double LLOhh;                                             /* Inner product (h|h) for LLO */\n//   double VIRGOhh;                                           /* Inner product (h|h) for VIRGO */\n// } LLVSignal;\n\ntypedef struct tagLLVSignalCAmpPhase\n{\n  struct tagListmodesCAmpPhaseFrequencySeries* LHOSignal;   /* Signal in LHO, in the form of a list of the contribution of each mode */\n  struct tagListmodesCAmpPhaseFrequencySeries* LLOSignal;   /* Signal in LLO, in the form of a list of the contribution of each mode */\n  struct tagListmodesCAmpPhaseFrequencySeries* VIRGOSignal; /* Signal in VIRGO, in the form of a list of the contribution of each mode */\n  double LLVhh;                                             /* Combined Inner product (h|h) for dectectors LHV */\n} LLVSignalCAmpPhase;\n\ntypedef struct tagLLVInjectionCAmpPhase\n{\n  struct tagListmodesCAmpPhaseSpline* LHOSplines;   /* Signal in LHO, in the form of a list of splines for the contribution of each mode */\n  struct tagListmodesCAmpPhaseSpline* LLOSplines;   /* Signal in LLO, in the form of a list of splines for the contribution of each mode */\n  struct tagListmodesCAmpPhaseSpline* VIRGOSplines;   /* Signal in VIRGO, in the form of a list of splines for the contribution of each mode */\n  double LLVss;                                   /* Combined Inner product (s|s) for dectectors LHV */\n} LLVInjectionCAmpPhase;\n\ntypedef struct tagLLVSignalReIm /* We don't store the SNRs here, as we will use -1/2(h-s|h-s) for the likelihood */\n{\n  struct tagReImFrequencySeries* LHOSignal;   /* Signal in LHO, in the form of a Re/Im frequency series where the modes have been summed */\n  struct tagReImFrequencySeries* LLOSignal;   /* Signal in LLO, in the form of a Re/Im frequency series where the modes have been summed */\n  struct tagReImFrequencySeries* VIRGOSignal;   /* Signal in VIRGO, in the form of a Re/Im frequency series where the modes have been summed */\n} LLVSignalReIm;\n\ntypedef struct tagLLVInjectionReIm /* Storing the vectors of frequencies and noise values - We don't store the SNRs here, as we will use -1/2(h-s|h-s) for the likelihood */\n{\n  struct tagReImFrequencySeries* LHOSignal;   /* Signal in LHO, in the form of a Re/Im frequency series where the modes have been summed */\n  struct tagReImFrequencySeries* LLOSignal;   /* Signal in LLO, in the form of a Re/Im frequency series where the modes have been summed */\n  struct tagReImFrequencySeries* VIRGOSignal;   /* Signal in VIRGO, in the form of a Re/Im frequency series where the modes have been summed */\n  gsl_vector* freq;                            /* Vector of frequencies of the injection (assumed to be the same for LHO, LLO, VIRGO) */\n  gsl_vector* noisevaluesLHO;                    /* Vector of noise values on freq LHO */\n  gsl_vector* noisevaluesLLO;                    /* Vector of noise values on freq LLO */\n  gsl_vector* noisevaluesVIRGO;                  /* Vector of noise values on freq VIRGO */\n} LLVInjectionReIm;\n\n/************ Functions for LLV parameters, injection, likelihood, prior ************/\n\n/* Parsing parameters for the generation of a LLV waveform, from the command line */\n/* Masses are input in solar masses and distances in Mpc - converted in SI for the internals */\nvoid parse_args_LLV(ssize_t argc, char **argv,\n    LLVParams* params,\n    LLVGlobalParams* globalparams,\n    LLVPrior* prior,\n    LLVRunParams* run,\n    LLVParams* addparams);\n\n/* Functions to print the parameters of the run in files for reference */\nint print_parameters_to_file_LLV(\n  LLVParams* params,\n  LLVGlobalParams* globalparams,\n  LLVPrior* prior,\n  LLVRunParams* run);\nint print_rescaleddist_to_file_LLV(\n  LLVParams* params,\n  LLVGlobalParams* globalparams,\n  LLVPrior* prior,\n  LLVRunParams* run);\n\n/* Initialization and clean-up for LLVSignal structures */\nvoid LLVSignalCAmpPhase_Cleanup(LLVSignalCAmpPhase* signal);\nvoid LLVSignalCAmpPhase_Init(LLVSignalCAmpPhase** signal);\nvoid LLVInjectionCAmpPhase_Cleanup(LLVInjectionCAmpPhase* signal);\nvoid LLVInjectionCAmpPhase_Init(LLVInjectionCAmpPhase** signal);\nvoid LLVSignalReIm_Cleanup(LLVSignalReIm* signal);\nvoid LLVSignalReIm_Init(LLVSignalReIm** signal);\nvoid LLVInjectionReIm_Cleanup(LLVInjectionReIm* signal);\nvoid LLVInjectionReIm_Init(LLVInjectionReIm** signal);\n\n/* Function generating a LLV signal as a list of modes in CAmp/Phase form, from LLV parameters */\nint LLVGenerateSignalCAmpPhase(\n  struct tagLLVParams* params,                 /* Input: set of LLV parameters of the signal */\n  struct tagLLVSignalCAmpPhase* signal);  /* Output: structure for the generated signal */\n/* Function generating a LLV injection as a list of modes, given as preinterpolated splines, from LLV parameters */\nint LLVGenerateInjectionCAmpPhase(\n  struct tagLLVParams* injectedparams,    /* Input: set of LLV parameters of the signal */\n  struct tagLLVInjectionCAmpPhase* signal);  /* Output: structure for the generated signal */\n/* Function generating a LLV signal as a frequency series in Re/Im form where the modes have been summed, from LLV parameters - takes as argument the frequencies on which to evaluate */\nint LLVGenerateSignalReIm(\n  struct tagLLVParams* params,       /* Input: set of LLV parameters of the template */\n  gsl_vector* freq,                   /* Input: frequencies on which evaluating the waveform (from the injection) */\n  struct tagLLVSignalReIm* signal);  /* Output: structure for the generated signal */\n/* Function generating a LLV injection as a frequency series in Re/Im form where the modes have been summed, from LLV parameters - frequencies on which to evaluate are to be determined internally */\nint LLVGenerateInjectionReIm(\n  struct tagLLVParams* injectedparams,       /* Input: set of LLV parameters of the injection */\n  double fLow,                                /* Input: starting frequency (from argument minf) */\n  double fHigh,                               /* Input: upper frequency (from argument maxf) */\n  int nbpts,                                  /* Input: number of frequency samples */\n  int tagsampling,                            /* Input: tag for using linear (0) or logarithmic (1) sampling */\n  struct tagLLVInjectionReIm* signal);       /* Output: structure for the generated signal */\n\n// checks prior boundaires\nint PriorBoundaryCheck(LLVPrior *prior, double *Cube);\n\n// Prior functions from Cube to physical parameters\n// x1 is min, x2 is max when specified\n// r is Cube value\ndouble CubeToFlatPrior(double r, double x1, double x2);\ndouble CubeToLogFlatPrior(double r, double x1, double x2);\ndouble CubeToPowerPrior(double p, double r, double x1, double x2);\ndouble CubeToGaussianPrior(double r, double mean, double sigma);\ndouble CubeToSinPrior(double r, double x1, double x2);\ndouble CubeToCosPrior(double r, double x1, double x2);\n\n/* Prior functions from physical parameters to Cube\n   x1 is min, x2 is max when specified\n   y is physical value */\ndouble FlatPriorToCube(double y, double x1, double x2);\ndouble LogFlatPriorToCube(double y, double x1, double x2);\ndouble PowerPriorToCube(double p, double y, double x1, double x2);\ndouble SinPriorToCube(double y, double x1, double x2);\ndouble CosPriorToCube(double y, double x1, double x2);\n\n/* log-Likelihood functions */\ndouble CalculateLogLCAmpPhase(LLVParams *params, LLVInjectionCAmpPhase* injection);\ndouble CalculateLogLReIm(LLVParams *params, LLVInjectionReIm* injection);\n\n/************ Global Parameters ************/\n\nextern LLVParams* injectedparams;\nextern LLVGlobalParams* globalparams;\nextern LLVPrior* priorParams;\ndouble logZdata;\n\n#endif\n", "meta": {"hexsha": "7af16db351b28f970c657f4917de347d4617dc1e", "size": 14013, "ext": "h", "lang": "C", "max_stars_repo_path": "LLVinference/LLVutils.h", "max_stars_repo_name": "JohnGBaker/flare", "max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "LLVinference/LLVutils.h", "max_issues_repo_name": "JohnGBaker/flare", "max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LLVinference/LLVutils.h", "max_forks_repo_name": "JohnGBaker/flare", "max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 57.6666666667, "max_line_length": 224, "alphanum_fraction": 0.6810104903, "num_tokens": 3476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.3991353238454251}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_cblas.h>\n\n#include \"tests.h\"\n\nvoid\ntest_trsv (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.995f };\n   float X[] = { 0.348f };\n   int incX = -1;\n   float x_expected[] = { 0.349749f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1150)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.995f };\n   float X[] = { 0.348f };\n   int incX = -1;\n   float x_expected[] = { 0.348f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1151)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.995f };\n   float X[] = { 0.348f };\n   int incX = -1;\n   float x_expected[] = { 0.349749f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1152)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.995f };\n   float X[] = { 0.348f };\n   int incX = -1;\n   float x_expected[] = { 0.348f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1153)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.995f };\n   float X[] = { 0.348f };\n   int incX = -1;\n   float x_expected[] = { 0.349749f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1154)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.995f };\n   float X[] = { 0.348f };\n   int incX = -1;\n   float x_expected[] = { 0.348f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1155)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.995f };\n   float X[] = { 0.348f };\n   int incX = -1;\n   float x_expected[] = { 0.349749f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1156)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.995f };\n   float X[] = { 0.348f };\n   int incX = -1;\n   float x_expected[] = { 0.348f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1157)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.793f };\n   float X[] = { 0.338f };\n   int incX = -1;\n   float x_expected[] = { 0.42623f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1158)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.793f };\n   float X[] = { 0.338f };\n   int incX = -1;\n   float x_expected[] = { 0.338f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1159)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.793f };\n   float X[] = { 0.338f };\n   int incX = -1;\n   float x_expected[] = { 0.42623f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1160)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.793f };\n   float X[] = { 0.338f };\n   int incX = -1;\n   float x_expected[] = { 0.338f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1161)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.793f };\n   float X[] = { 0.338f };\n   int incX = -1;\n   float x_expected[] = { 0.42623f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1162)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.793f };\n   float X[] = { 0.338f };\n   int incX = -1;\n   float x_expected[] = { 0.338f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1163)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.793f };\n   float X[] = { 0.338f };\n   int incX = -1;\n   float x_expected[] = { 0.42623f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1164)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.793f };\n   float X[] = { 0.338f };\n   int incX = -1;\n   float x_expected[] = { 0.338f };\n   cblas_strsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], flteps, \"strsv(case 1165)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.21 };\n   double X[] = { 0.473 };\n   int incX = -1;\n   double x_expected[] = { -2.25238095238 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1166)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.21 };\n   double X[] = { 0.473 };\n   int incX = -1;\n   double x_expected[] = { 0.473 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1167)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.21 };\n   double X[] = { 0.473 };\n   int incX = -1;\n   double x_expected[] = { -2.25238095238 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1168)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.21 };\n   double X[] = { 0.473 };\n   int incX = -1;\n   double x_expected[] = { 0.473 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1169)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.21 };\n   double X[] = { 0.473 };\n   int incX = -1;\n   double x_expected[] = { -2.25238095238 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1170)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.21 };\n   double X[] = { 0.473 };\n   int incX = -1;\n   double x_expected[] = { 0.473 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1171)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.21 };\n   double X[] = { 0.473 };\n   int incX = -1;\n   double x_expected[] = { -2.25238095238 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1172)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { -0.21 };\n   double X[] = { 0.473 };\n   int incX = -1;\n   double x_expected[] = { 0.473 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1173)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.748 };\n   double X[] = { 0.979 };\n   int incX = -1;\n   double x_expected[] = { 1.30882352941 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1174)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.748 };\n   double X[] = { 0.979 };\n   int incX = -1;\n   double x_expected[] = { 0.979 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1175)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.748 };\n   double X[] = { 0.979 };\n   int incX = -1;\n   double x_expected[] = { 1.30882352941 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1176)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.748 };\n   double X[] = { 0.979 };\n   int incX = -1;\n   double x_expected[] = { 0.979 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1177)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.748 };\n   double X[] = { 0.979 };\n   int incX = -1;\n   double x_expected[] = { 1.30882352941 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1178)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.748 };\n   double X[] = { 0.979 };\n   int incX = -1;\n   double x_expected[] = { 0.979 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1179)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.748 };\n   double X[] = { 0.979 };\n   int incX = -1;\n   double x_expected[] = { 1.30882352941 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1180)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.748 };\n   double X[] = { 0.979 };\n   int incX = -1;\n   double x_expected[] = { 0.979 };\n   cblas_dtrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[i], x_expected[i], dbleps, \"dtrsv(case 1181)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.529f, -0.348f };\n   float X[] = { -0.95f, 0.343f };\n   int incX = -1;\n   float x_expected[] = { -1.55112f, -0.372004f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1182) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1182) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.529f, -0.348f };\n   float X[] = { -0.95f, 0.343f };\n   int incX = -1;\n   float x_expected[] = { -0.95f, 0.343f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1183) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1183) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.529f, -0.348f };\n   float X[] = { -0.95f, 0.343f };\n   int incX = -1;\n   float x_expected[] = { -1.55112f, -0.372004f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1184) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1184) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.529f, -0.348f };\n   float X[] = { -0.95f, 0.343f };\n   int incX = -1;\n   float x_expected[] = { -0.95f, 0.343f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1185) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1185) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.529f, -0.348f };\n   float X[] = { -0.95f, 0.343f };\n   int incX = -1;\n   float x_expected[] = { -1.55112f, -0.372004f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1186) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1186) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.529f, -0.348f };\n   float X[] = { -0.95f, 0.343f };\n   int incX = -1;\n   float x_expected[] = { -0.95f, 0.343f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1187) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1187) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.529f, -0.348f };\n   float X[] = { -0.95f, 0.343f };\n   int incX = -1;\n   float x_expected[] = { -1.55112f, -0.372004f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1188) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1188) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.529f, -0.348f };\n   float X[] = { -0.95f, 0.343f };\n   int incX = -1;\n   float x_expected[] = { -0.95f, 0.343f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1189) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1189) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.6f, 0.041f };\n   float X[] = { 0.896f, -0.447f };\n   int incX = -1;\n   float x_expected[] = { 1.43572f, -0.843108f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1190) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1190) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.6f, 0.041f };\n   float X[] = { 0.896f, -0.447f };\n   int incX = -1;\n   float x_expected[] = { 0.896f, -0.447f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1191) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1191) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.6f, 0.041f };\n   float X[] = { 0.896f, -0.447f };\n   int incX = -1;\n   float x_expected[] = { 1.43572f, -0.843108f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1192) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1192) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.6f, 0.041f };\n   float X[] = { 0.896f, -0.447f };\n   int incX = -1;\n   float x_expected[] = { 0.896f, -0.447f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1193) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1193) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.6f, 0.041f };\n   float X[] = { 0.896f, -0.447f };\n   int incX = -1;\n   float x_expected[] = { 1.43572f, -0.843108f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1194) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1194) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.6f, 0.041f };\n   float X[] = { 0.896f, -0.447f };\n   int incX = -1;\n   float x_expected[] = { 0.896f, -0.447f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1195) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1195) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.6f, 0.041f };\n   float X[] = { 0.896f, -0.447f };\n   int incX = -1;\n   float x_expected[] = { 1.43572f, -0.843108f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1196) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1196) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.6f, 0.041f };\n   float X[] = { 0.896f, -0.447f };\n   int incX = -1;\n   float x_expected[] = { 0.896f, -0.447f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1197) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1197) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.397f, 0.683f };\n   float X[] = { 0.765f, 0.18f };\n   int incX = -1;\n   float x_expected[] = { 0.289642f, 0.951701f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1198) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1198) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.397f, 0.683f };\n   float X[] = { 0.765f, 0.18f };\n   int incX = -1;\n   float x_expected[] = { 0.765f, 0.18f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1199) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1199) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.397f, 0.683f };\n   float X[] = { 0.765f, 0.18f };\n   int incX = -1;\n   float x_expected[] = { 0.289642f, 0.951701f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1200) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1200) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.397f, 0.683f };\n   float X[] = { 0.765f, 0.18f };\n   int incX = -1;\n   float x_expected[] = { 0.765f, 0.18f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1201) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1201) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.397f, 0.683f };\n   float X[] = { 0.765f, 0.18f };\n   int incX = -1;\n   float x_expected[] = { 0.289642f, 0.951701f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1202) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1202) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.397f, 0.683f };\n   float X[] = { 0.765f, 0.18f };\n   int incX = -1;\n   float x_expected[] = { 0.765f, 0.18f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1203) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1203) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.397f, 0.683f };\n   float X[] = { 0.765f, 0.18f };\n   int incX = -1;\n   float x_expected[] = { 0.289642f, 0.951701f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1204) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1204) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   float A[] = { 0.397f, 0.683f };\n   float X[] = { 0.765f, 0.18f };\n   int incX = -1;\n   float x_expected[] = { 0.765f, 0.18f };\n   cblas_ctrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], flteps, \"ctrsv(case 1205) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, \"ctrsv(case 1205) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.977, -0.955 };\n   double X[] = { -0.627, 0.281 };\n   int incX = -1;\n   double x_expected[] = { -0.471957414573, -0.173714770642 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1206) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1206) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.977, -0.955 };\n   double X[] = { -0.627, 0.281 };\n   int incX = -1;\n   double x_expected[] = { -0.627, 0.281 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1207) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1207) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.977, -0.955 };\n   double X[] = { -0.627, 0.281 };\n   int incX = -1;\n   double x_expected[] = { -0.471957414573, -0.173714770642 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1208) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1208) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.977, -0.955 };\n   double X[] = { -0.627, 0.281 };\n   int incX = -1;\n   double x_expected[] = { -0.627, 0.281 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1209) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1209) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.977, -0.955 };\n   double X[] = { -0.627, 0.281 };\n   int incX = -1;\n   double x_expected[] = { -0.471957414573, -0.173714770642 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1210) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1210) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.977, -0.955 };\n   double X[] = { -0.627, 0.281 };\n   int incX = -1;\n   double x_expected[] = { -0.627, 0.281 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1211) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1211) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.977, -0.955 };\n   double X[] = { -0.627, 0.281 };\n   int incX = -1;\n   double x_expected[] = { -0.471957414573, -0.173714770642 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1212) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1212) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 111;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.977, -0.955 };\n   double X[] = { -0.627, 0.281 };\n   int incX = -1;\n   double x_expected[] = { -0.627, 0.281 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1213) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1213) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.076, -0.16 };\n   double X[] = { 0.3, -0.874 };\n   int incX = -1;\n   double x_expected[] = { 5.18357980622, -0.587200407955 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1214) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1214) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.076, -0.16 };\n   double X[] = { 0.3, -0.874 };\n   int incX = -1;\n   double x_expected[] = { 0.3, -0.874 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1215) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1215) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.076, -0.16 };\n   double X[] = { 0.3, -0.874 };\n   int incX = -1;\n   double x_expected[] = { 5.18357980622, -0.587200407955 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1216) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1216) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.076, -0.16 };\n   double X[] = { 0.3, -0.874 };\n   int incX = -1;\n   double x_expected[] = { 0.3, -0.874 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1217) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1217) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.076, -0.16 };\n   double X[] = { 0.3, -0.874 };\n   int incX = -1;\n   double x_expected[] = { 5.18357980622, -0.587200407955 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1218) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1218) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.076, -0.16 };\n   double X[] = { 0.3, -0.874 };\n   int incX = -1;\n   double x_expected[] = { 0.3, -0.874 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1219) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1219) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.076, -0.16 };\n   double X[] = { 0.3, -0.874 };\n   int incX = -1;\n   double x_expected[] = { 5.18357980622, -0.587200407955 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1220) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1220) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 112;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.076, -0.16 };\n   double X[] = { 0.3, -0.874 };\n   int incX = -1;\n   double x_expected[] = { 0.3, -0.874 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1221) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1221) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.372, -0.745 };\n   double X[] = { -0.085, -0.303 };\n   int incX = -1;\n   double x_expected[] = { -0.371144591432, -0.0712292456544 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1222) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1222) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.372, -0.745 };\n   double X[] = { -0.085, -0.303 };\n   int incX = -1;\n   double x_expected[] = { -0.085, -0.303 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1223) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1223) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.372, -0.745 };\n   double X[] = { -0.085, -0.303 };\n   int incX = -1;\n   double x_expected[] = { -0.371144591432, -0.0712292456544 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1224) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1224) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.372, -0.745 };\n   double X[] = { -0.085, -0.303 };\n   int incX = -1;\n   double x_expected[] = { -0.085, -0.303 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1225) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1225) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.372, -0.745 };\n   double X[] = { -0.085, -0.303 };\n   int incX = -1;\n   double x_expected[] = { -0.371144591432, -0.0712292456544 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1226) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1226) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 121;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.372, -0.745 };\n   double X[] = { -0.085, -0.303 };\n   int incX = -1;\n   double x_expected[] = { -0.085, -0.303 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1227) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1227) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 131;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.372, -0.745 };\n   double X[] = { -0.085, -0.303 };\n   int incX = -1;\n   double x_expected[] = { -0.371144591432, -0.0712292456544 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1228) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1228) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int trans = 113;\n   int uplo = 122;\n   int diag = 132;\n   int N = 1;\n   int lda = 1;\n   double A[] = { 0.372, -0.745 };\n   double X[] = { -0.085, -0.303 };\n   int incX = -1;\n   double x_expected[] = { -0.085, -0.303 };\n   cblas_ztrsv(order, uplo, trans, diag, N, A, lda, X, incX);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(X[2*i], x_expected[2*i], dbleps, \"ztrsv(case 1229) real\");\n       gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, \"ztrsv(case 1229) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "39f5083b3c9feff9c8000ab65afca9d6baadefcc", "size": 39777, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_trsv.c", "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 692.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_trsv.c", "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1096.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_trsv.c", "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "avg_line_length": 22.8603448276, "max_line_length": 82, "alphanum_fraction": 0.4972220127, "num_tokens": 16136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.39894236604101824}}
{"text": "/**\n * @file postfilter.h\n\n * @brief implementation of post-filters for a microphone array. \n\n   The following post-filters are implemented:\n   [1] Zelinski post-filter\n   [2] APAB post-filter\n   [3] McCowan's post-filter\n   [4] Lefkimmiatis's post-filter\n\n   The correspondig references are:\n   [1] C.Claude Marro et al. \"Analysis of noise reduction and dereverberation techniques based on microphone arrays with postfiltering\", IEEE Trans. ASP, vol. 6, pp 240-259, May 1998.\n   [2] M.Brandstein, \"Microphone Arrays\", Springer, ISBN 3-540-41953-5, pp.39-60.\n   [3] Iain A. Mccowan et al., \"Microphone array post-filter based on noise field coherence\", IEEE Trans. SAP, vol. 11, pp. Nov. 709--716, 2003.\n   [4] Stamatios Lefkimmiatis et al., \"A generalized estimation approach for linear and nonlinear microphone array post-filters\",  Speech Communication, 2007.\n\n  * @author Kenichi Kumatani\n*/\n#ifndef POSTFILTER_H\n#define POSTFILTER_H\n\n#include <stdio.h>\n#include <assert.h>\n#include <float.h>\n\n#include <gsl/gsl_block.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_fft_complex.h>\n#include <common/refcount.h>\n#include \"common/jexception.h\"\n\n#include \"stream/stream.h\"\n#include \"postfilter/spectralsubtraction.h\"\n#include \"postfilter/binauralprocessing.h\"\n#include \"beamformer/spectralinfoarray.h\"\n#include \"beamformer/beamformer.h\"\n\ntypedef enum {\n  TYPE_ZELINSKI1_REAL = 0x01,\n  TYPE_ZELINSKI1_ABS  = 0x02,\n  TYPE_APAB = 0x04,\n  TYPE_ZELINSKI2 = 0x08,\n  NO_USE_POST_FILTER = 0x00\n} PostfilterType;\n\nvoid ZelinskiFilter(gsl_vector_complex **arrayManifold,\n\t\t    SnapShotArrayPtr     snapShotArray, \n\t\t    bool halfBandShift, \n\t\t    gsl_vector_complex *beamformedSignal,\n\t\t    gsl_vector_complex **prevCSDs, \n\t\t    gsl_vector_complex *pfweights,\n\t\t    double alpha, int Ropt );\n\nvoid ApabFilter( gsl_vector_complex **arrayManifold,\n\t\t SnapShotArrayPtr     snapShotArray, \n\t\t int fftLen, int nChan, bool halfBandShift,\n\t\t gsl_vector_complex *beamformedSignal,\n\t\t int channelX );\n\n/**\n   @class Zelinski post-filtering\n\n   @brief filter beamformer's outputs under the assumption that noise signals between sensors are uncorrelated. \n   @usage\n   1. construct an object,\n   2. set the array snapshot and array manifold vectors with \n      either setBeamformer() or setSnapShotArray() and setArrayManifold(), \n   3. process data at each frame by caling next().\n*/\nclass ZelinskiPostFilter: public VectorComplexFeatureStream {\npublic:\n  ZelinskiPostFilter( VectorComplexFeatureStreamPtr &output, unsigned fftLen, double alpha=0.6, int type=2, int minFrames=0, const String& nm = \"ZelinskPostFilter\" );\n  ~ZelinskiPostFilter();\n\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void reset();\n\n  void set_beamformer(SubbandDSPtr &beamformer);\n  void set_snapshot_array(SnapShotArrayPtr &snapShotArray);\n  void set_array_manifold_vector(unsigned fbinX, gsl_vector_complex *arrayManifoldVector, bool halfBandShift, unsigned NC = 1);\n  const gsl_vector_complex* postfilter_weights(){\n    if( NULL == bf_weights_ )\n      return NULL;\n    return(bf_weights_->wp1());\n  }\n\n#ifdef ENABLE_LEGACY_BTK_API\n  void setBeamformer(SubbandDSPtr &beamformer){ set_beamformer(beamformer); }\n  void setSnapShotArray(SnapShotArrayPtr &snapShotArray){ set_snapshot_array(snapShotArray); }\n  void setArrayManifoldVector(unsigned fbinX, gsl_vector_complex *arrayManifoldVector, bool halfBandShift, unsigned NC = 1){ set_array_manifold_vector(fbinX, arrayManifoldVector, halfBandShift, NC); }\n  const gsl_vector_complex* getPostFilterWeights(){ return postfilter_weights(); }\n#endif\n\nprotected:\n  unsigned                      fftLen_;\n  VectorComplexFeatureStreamPtr samp_; /* output of the beamformer */\n  PostfilterType                type_; /* the type of the Zelinski-postfilters */\n  double                        alpha_; /* forgetting factor */\n  int                           min_frames_;\n  SubbandDSPtr                  bf_ptr_; /* */\n  BeamformerWeights*            bf_weights_;\n  bool                          has_bf_ptr_; /* true if bf_ptr_ is set with setBeamformer() */\n  SnapShotArrayPtr              snapshot_array_; /* multi-channel input */\n};\n\ntypedef Inherit<ZelinskiPostFilter, VectorComplexFeatureStreamPtr> ZelinskiPostFilterPtr;\n\n/**\n   @class McCowan post-filtering\n\n   @brief process the beamformer's outputs with McCowan's post-filtering\n   @usage\n   1. construct an object,\n   2. compute the noise coherence matrix through setDiffuseNoiseModel( micPositions, ssampleRate)\n   3. set the array snapshot and array manifold vectors with \n      either setBeamformer() or setSnapShotArray() and setArrayManifold(), \n   4. process data at each frame by caling next().\n*/\nclass McCowanPostFilter: public ZelinskiPostFilter {\npublic:\n  McCowanPostFilter( VectorComplexFeatureStreamPtr &output, unsigned fftLen, double alpha=0.6, int type=2, int minFrames=0, float threshold=0.99, const String& nm = \"McCowanPostFilter\" );\n  ~McCowanPostFilter();\n\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void reset();\n  /* micPositions[][x,y,z] */\n\n  const gsl_matrix_complex *noise_spatial_spectral_matrix( unsigned fbinX );\n  bool set_noise_spatial_spectral_matrix( unsigned fbinX, gsl_matrix_complex* Rnn );\n  bool set_diffuse_noise_model( const gsl_matrix* micPositions, double sampleRate, double sspeed = 343740.0 );\n  void set_all_diagonal_loading(float diagonalWeight);\n  void set_diagonal_looading(unsigned fbinX, float diagonalWeight);\n  void divide_all_nondiagonal_elements(float mu);\n  void divide_nondiagonal_elements(unsigned fbinX, float mu);\n\n#ifdef ENABLE_LEGACY_BTK_API\n  const gsl_matrix_complex *getNoiseSpatialSpectralMatrix(unsigned fbinX){ return noise_spatial_spectral_matrix(fbinX); }\n  bool setNoiseSpatialSpectralMatrix(unsigned fbinX, gsl_matrix_complex* Rnn){ return set_noise_spatial_spectral_matrix(fbinX, Rnn); }\n  bool setDiffuseNoiseModel(const gsl_matrix* micPositions, double sampleRate, double sspeed = 343740.0){ return set_diffuse_noise_model( micPositions, sampleRate, sspeed); }\n  void setAllLevelsOfDiagonalLoading(float diagonalWeight){ set_all_diagonal_loading(diagonalWeight); }\n  void setLevelOfDiagonalLoading(unsigned fbinX, float diagonalWeight){ set_diagonal_looading(fbinX, diagonalWeight); }\n  void divideAllNonDiagonalElements( float mu );\n  void divideNonDiagonalElements( unsigned fbinX, float mu );\n#endif\n\nprotected:\n  double estimate_average_clean_PSD_( unsigned fbinX, gsl_vector_complex* currCSDf );\n  virtual void post_filtering_();\n\nprotected:\n  gsl_matrix_complex**                           R_; /* Noise spatial spectral matrices */\n  float*                                         diagonal_weights_;\n  float                                          threshold_of_Rij_; /* to avoid the indeterminate solution*/\n  gsl_vector_complex*                            time_aligned_signal_f_; /* workspace */\n  bool                                           invR_computed_;\n};\n\ntypedef Inherit<McCowanPostFilter, ZelinskiPostFilterPtr> McCowanPostFilterPtr;\n\n/**\n   @class Lefkimmiatis post-filtering\n   @brief compute a Winer filter under the the diffuse noise field assumption\n   @usage\n   1. construct an object,\n   2. compute the noise coherence matrix through setDiffuseNoiseModel( micPositions, ssampleRate)\n   3. set the array snapshot and array manifold vectors with \n      either setBeamformer() or setSnapShotArray() and setArrayManifold(), \n   4. process data at each frame by caling next().\n*/\nclass LefkimmiatisPostFilter: public McCowanPostFilter {\npublic:\n  LefkimmiatisPostFilter( VectorComplexFeatureStreamPtr &output, unsigned fftLen, double minSV=1.0E-8, unsigned fbinX1=0, double alpha=0.6, int type=2, int minFrames=0, float threshold=0.99, const String& nm = \"LefkimmiatisPostFilte\" );\n  ~LefkimmiatisPostFilter();\n\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void reset();\n  /* micPositions[][x,y,z] */\n\n  void calc_inverse_noise_spatial_spectral_matrix();\n\n#ifdef ENABLE_LEGACY_BTK_API\n  void calcInverseNoiseSpatialSpectralMatrix(){ calc_inverse_noise_spatial_spectral_matrix(); }\n#endif\n\nprotected:\n  double estimate_average_noise_PSD_( unsigned fbinX, gsl_vector_complex* currCSDf );\n  virtual void post_filtering_();\n\nprivate:\n  gsl_complex calcLambda( unsigned fbinX );\n\n  gsl_matrix_complex** invR_;\n  gsl_vector_complex*  tmpH_;\n  double              minSV_;\n  unsigned            fbinX1_;\n};\n\ntypedef Inherit<LefkimmiatisPostFilter, McCowanPostFilterPtr> LefkimmiatisPostFilterPtr;\n\n/**\n   @class high pass filter\n*/\nclass HighPassFilter: public VectorComplexFeatureStream {\npublic:\n  HighPassFilter( VectorComplexFeatureStreamPtr &output, float cutOffFreq, int sampleRate, const String& nm = \"HighPassFilter\" );\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void reset();\n\nprivate:\n  VectorComplexFeatureStreamPtr src_;\n  unsigned cutoff_fbinX_;\n};\n\ntypedef Inherit<HighPassFilter, VectorComplexFeatureStreamPtr> HighPassFilterPtr;\n\n#endif\n", "meta": {"hexsha": "d5acc73398cce5940e876b4d3f193b0c8175aba2", "size": 9099, "ext": "h", "lang": "C", "max_stars_repo_path": "btk20_src/postfilter/postfilter.h", "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_issues_repo_path": "btk20_src/postfilter/postfilter.h", "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_forks_repo_path": "btk20_src/postfilter/postfilter.h", "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "avg_line_length": 41.1719457014, "max_line_length": 236, "alphanum_fraction": 0.746785361, "num_tokens": 2307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3989415677005749}}
{"text": "#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <getopt.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_rng.h>\n#include \"../fewbody.h\"\n\nint calc_units(fb_hier_t hier, fb_units_t *units)\n{\n  /* mass unit is total system mass */\n  units->m = hier.hier[hier.hi[1]+0].m + hier.hier[hier.hi[1]+1].m +\t\\\n    hier.hier[hier.hi[1]+2].m + hier.hier[hier.hi[1]+3].m +\t\t\\\n    hier.hier[hier.hi[1]+4].m;\n  /* length unit is one AU */\n  units->l = FB_CONST_AU;\n  /* everything else is derived */\n  units->E = FB_CONST_G * fb_sqr(units->m) / units->l;\n  units->v = sqrt(units->E/units->m);\n  units->t = units->l / units->v;\n  return(0);\n}\n\nint main(int argc, char *argv[])\n{\n  int j;\n  double t;\n  fb_hier_t hier;\n  fb_input_t input;\n  fb_ret_t retval;\n  fb_units_t units;\n  char string1[FB_MAX_STRING_LENGTH], string2[FB_MAX_STRING_LENGTH];\n  \n  /* set input parameters */\n  input.ks = 0; /* turn K-S regularization off */\n  input.tstop = 1.0e4; /* stopping time in units of units.t */\n  input.Dflag = 0; /* don't output dynamical info to stdout */\n  input.dt = 0.0; /* irrelevant when Dflag=0 */\n  input.tcpustop = 120.0; /* stopping CPU time in seconds */\n  input.absacc = 1.0e-9; /* integrator absolute accuracy */\n  input.relacc = 1.0e-9; /* integrator relative accuracy */\n  input.ncount = 500; /* number of integration steps between calls to fb_classify() */\n  input.tidaltol = 1.0e-6; /* tidal perturbation required to force numerical */\n                           /* integration of a binary node */\n  input.fexp = 1.0; /* radius expansion factor of merger products */\n  fb_debug = 0;\n  \n  /* initialize a few things */\n  t = 0.0;\n  hier.nstarinit = 5;\n  hier.nstar = 5;\n  fb_malloc_hier(&hier);\n  fb_init_hier(&hier);\n  \n  /* set stellar properties */\n  for (j=0; j<hier.nstar; j++) {\n    hier.hier[hier.hi[1]+j].ncoll = 1;\n    hier.hier[hier.hi[1]+j].id[0] = j;\n    snprintf(hier.hier[hier.hi[1]+j].idstring, FB_MAX_STRING_LENGTH, \"%d\", j);\n    hier.hier[hier.hi[1]+j].n = 1;\n    hier.hier[hier.hi[1]+j].obj[0] = NULL;\n    hier.hier[hier.hi[1]+j].obj[1] = NULL;\n    hier.hier[hier.hi[1]+j].Eint = 0.0;\n    hier.hier[hier.hi[1]+j].Lint[0] = 0.0;\n    hier.hier[hier.hi[1]+j].Lint[1] = 0.0;\n    hier.hier[hier.hi[1]+j].Lint[2] = 0.0;\n    hier.hier[hier.hi[1]+j].R = 1.0e-3 * FB_CONST_RSUN;\n    hier.hier[hier.hi[1]+j].m = FB_CONST_MSUN;\n    hier.hier[hier.hi[1]+j].x[2] = 0.0; /* everything in x-y plane */\n    hier.hier[hier.hi[1]+j].v[2] = 0.0; \n  }\n  \n  /* set some positions and velocities */\n  hier.hier[hier.hi[1]+0].x[0] = 10.0 * FB_CONST_AU;\n  hier.hier[hier.hi[1]+0].x[1] = 0.0 * FB_CONST_AU;\n  hier.hier[hier.hi[1]+0].v[0] = 10.0e5;\n  hier.hier[hier.hi[1]+0].v[1] = 0.0;\n  \n  hier.hier[hier.hi[1]+1].x[0] = 10.0 * FB_CONST_AU;\n  hier.hier[hier.hi[1]+1].x[1] = 10.0 * FB_CONST_AU;\n  hier.hier[hier.hi[1]+0].v[0] = -10.0e5;\n  hier.hier[hier.hi[1]+0].v[1] = 0.0;\n  \n  hier.hier[hier.hi[1]+2].x[0] = -30.0 * FB_CONST_AU;\n  hier.hier[hier.hi[1]+2].x[1] = -5.0 * FB_CONST_AU;\n  hier.hier[hier.hi[1]+0].v[0] = 0.0;\n  hier.hier[hier.hi[1]+0].v[1] = 5.0e5;\n  \n  hier.hier[hier.hi[1]+3].x[0] = 0.0 * FB_CONST_AU;\n  hier.hier[hier.hi[1]+3].x[1] = 27.0 * FB_CONST_AU;\n  hier.hier[hier.hi[1]+0].v[0] = -5.0e5;\n  hier.hier[hier.hi[1]+0].v[1] = -4.0e5;\n  \n  hier.hier[hier.hi[1]+4].x[0] = 10.0 * FB_CONST_AU;\n  hier.hier[hier.hi[1]+4].x[1] = -32.0 * FB_CONST_AU;\n  hier.hier[hier.hi[1]+0].v[0] = 5.0e5;\n  hier.hier[hier.hi[1]+0].v[1] = -1.0e5;\n  \n  /* set units with our own routine, then normalize */\n  calc_units(hier, &units);\n  fb_normalize(&hier, units);\n  \n  /* call Fewbody to evolve system */\n  retval = fewbody(input, &hier, &t);\n  \n  /* all the rest is parsing the output */\n  if (retval.retval == 1) {\n    fprintf(stderr, \"encounter complete.\\n\");\n  } else {\n    fprintf(stderr, \"encounter NOT complete.\\n\");\n  }\n  \n  fprintf(stderr, \"final configuration:  %s  (%s)\\n\",\n\t  fb_sprint_hier(hier, string1),\n\t  fb_sprint_hier_hr(hier, string2));\n  \n  fprintf(stderr, \"t_final=%.6g (%.6g yr)  t_cpu=%.6g s\\n\",\t\\\n\t  t, t*units.t/FB_CONST_YR, retval.tcpu);\n  \n  fprintf(stderr, \"DeltaL/L0=%.6g  DeltaL=%.6g\\n\", retval.DeltaLfrac, retval.DeltaL);\n  fprintf(stderr, \"DeltaE/E0=%.6g  DeltaE=%.6g\\n\", retval.DeltaEfrac, retval.DeltaE);\n  fprintf(stderr, \"Rmin=%.6g (%.6g RSUN)  Rmin_i=%d  Rmin_j=%d\\n\",\t\\\n\t  retval.Rmin, retval.Rmin*units.l/FB_CONST_RSUN, retval.Rmin_i, retval.Rmin_j);\n  fprintf(stderr, \"Nosc=%d (%s)\\n\", retval.Nosc, \n\t  (retval.Nosc>=1?\"resonance\":\"non-resonance\"));\n\n  fprintf(stderr, \"orbital parameters of outermost binaries:\\n\");\n  for (j=0; j<hier.nobj; j++) {\n    if (hier.obj[j]->n >= 2) {\n      fprintf(stderr, \"j=%d  a=%.6g AU  e=%.6g\\n\", j, \n\t      hier.obj[j]->a * units.l / FB_CONST_AU, hier.obj[j]->e);\n    }\n  }\n\n  fb_free_hier(hier);\n  return(0);\n}\n", "meta": {"hexsha": "03a7df093c76187cd9eeb54cdec70cca409d9cc1", "size": 4848, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/O/FEWBODY/doc/simple.c", "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": ["PSF-2.0"], "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/fewbod/fewbody-0.26/O/FEWBODY/doc/simple.c", "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_licenses": ["PSF-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/O/FEWBODY/doc/simple.c", "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": ["PSF-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3829787234, "max_line_length": 86, "alphanum_fraction": 0.6113861386, "num_tokens": 1910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.39894156152224086}}
{"text": "//===--- Sudoku/Location_Utilities.h                                    ---===//\n//\n// Utilities for class Sudoku::Location\n//===----------------------------------------------------------------------===//\n#pragma once\n\n#include \"Board_Section_traits.h\"\n#include \"Location.h\"\n#include \"Size.h\"\n#include \"traits.h\"\n\n#include <gsl/gsl> // index\n\n#include <vector>\n\n#include <algorithm> // minmax_element, is_sorted, all_of\n#include <iterator>  // back_inserter\n#include <limits>    // numeric_limits\n\n#include \"Board.fwd.h\" // Forward declarations\n\n\nnamespace Sudoku\n{\n//===-- function declarations ---------------------------------------------===//\ntemplate<int N>\nconstexpr void valid_dimensions() noexcept;\n\ntemplate<int N>\nconstexpr bool is_valid(Location<N>) noexcept;\ntemplate<int N>\nconstexpr bool is_valid(const std::vector<Location<N>>& locs) noexcept(true);\n\ntemplate<int N>\nconstexpr bool is_valid_size(gsl::index elem) noexcept;\ntemplate<int N>\nconstexpr bool is_valid_size(gsl::index row, gsl::index col) noexcept;\n\ntemplate<int N>\nconstexpr bool is_same_row(Location<N>, Location<N>) noexcept;\ntemplate<int N>\nconstexpr bool is_same_col(Location<N>, Location<N>) noexcept;\ntemplate<int N>\nconstexpr bool is_same_block(Location<N>, Location<N>) noexcept;\n\ntemplate<int N, typename ItrT>\nconstexpr bool is_same_row(ItrT begin, ItrT end) noexcept;\ntemplate<int N, typename ItrT>\nconstexpr bool is_same_col(ItrT begin, ItrT end) noexcept;\ntemplate<int N, typename ItrT>\nconstexpr bool is_same_block(ItrT begin, ItrT end) noexcept;\n\ntemplate<int N>\nstd::vector<Location<N>> get_same_row(\n\tconst Location<N>, const std::vector<Location<N>>&) noexcept(true);\ntemplate<int N>\nstd::vector<Location<N>> get_same_col(\n\tconst Location<N>, const std::vector<Location<N>>&) noexcept(true);\ntemplate<int N>\nstd::vector<Location<N>> get_same_block(\n\tconst Location<N>, const std::vector<Location<N>>&) noexcept(true);\n\ntemplate<int N, typename S>\nconstexpr bool is_same_section(S section, Location<N>) noexcept;\n\ntemplate<typename SectionT, int N>\nbool is_same_section(SectionT, std::vector<Location<N>>&) noexcept;\n\ntemplate<\n\tint N,\n\ttypename S,\n\ttypename = std::enable_if_t<\n\t\tBoard_Section::traits::is_Row_v<S> ||\n\t\tBoard_Section::traits::is_Col_v<S>>>\nbool intersect_block(S section, Location<N> block_loc) noexcept;\n\n//===----------------------------------------------------------------------===//\n\n\n// Compile-time only Test\ntemplate<int N>\nconstexpr void valid_dimensions() noexcept\n{\n\t// input check\n\tstatic_assert((base_size<N>) > 1, \"base_size too small\");\n\tstatic_assert(\n\t\tbase_size<N> < elem_size<N> && elem_size<N> <= full_size<N> &&\n\t\t\tbase_size<N> < std::numeric_limits<int>::max() && // <limits>\n\t\t\telem_size<N> < std::numeric_limits<int>::max() &&\n\t\t\tfull_size<N> < std::numeric_limits<int>::max(),\n\t\t\"board size out of bounds\");\n\t// logic check\n\tstatic_assert(\n\t\tbase_size<N> * base_size<N> == elem_size<N> &&\n\t\t\telem_size<N> * elem_size<N> == full_size<N>,\n\t\t\"size calculation broken\");\n}\n\n// Test if Location on Board\ntemplate<int N>\n[[nodiscard]] inline constexpr bool is_valid(const Location<N> loc) noexcept\n{\n\treturn (loc.element() >= 0 && loc.element() < full_size<N>);\n}\n\n// Test if Locations on Board and if sorted (ascending)\ntemplate<int N>\n[[nodiscard]] inline constexpr bool\n\tis_valid(const std::vector<Location<N>>& locs) noexcept(true)\n{ // std::is_sorted can throw std::bad_alloc\n\treturn (\n\t\t!locs.empty() && (std::is_sorted(locs.cbegin(), locs.cend()) &&\n\t\t\t\t\t\t  locs.cbegin()->element() >= 0 &&\n\t\t\t\t\t\t  locs.crbegin()->element() < full_size<N>));\n}\n\n// Test row/col/block-element\ntemplate<int N>\n[[nodiscard]] inline constexpr bool\n\tis_valid_size(const gsl::index elem) noexcept\n{\n\treturn (elem >= 0 && elem < elem_size<N>);\n}\n\n// Test if location on Board\ntemplate<int N>\n[[nodiscard]] inline constexpr bool\n\tis_valid_size(const gsl::index row, const gsl::index col) noexcept\n{\n\treturn is_valid_size<N>(row) && is_valid_size<N>(col);\n}\n\n\n//===----------------------------------------------------------------------===//\n\n// check\ntemplate<int N>\n[[nodiscard]] inline constexpr bool\n\tis_same_row(const Location<N> left, const Location<N> right) noexcept\n{\n\treturn (is_valid<N>(left) && is_valid<N>(right)) &&\n\t\t   left.row() == right.row();\n}\n\n// check: all in same row\ntemplate<int N, typename ItrT>\n[[nodiscard]] constexpr bool\n\tis_same_row(const ItrT begin, const ItrT end) noexcept\n{\n\t{\n\t\tstatic_assert(traits::is_forward<ItrT>);\n\t}\n\tif (begin == end)\n\t\treturn false;\n\n\tconst auto itr = begin + 1;\n\treturn std::all_of(\n\t\titr, end, [begin](Location<N> i) { return is_same_row<N>(*begin, i); });\n}\n\n// return all in same row\ntemplate<int N> // NOLINTNEXTLINE(bugprone-exception-escape)\n[[nodiscard]] std::vector<Location<N>> get_same_row(\n\tconst Location<N> left,\n\tconst std::vector<Location<N>>& right) noexcept(true)\n{ // std::copy_if could throw std::bad_alloc\n\tstd::vector<Location<N>> output{};\n\tconst auto predicate = [&left](Location<N> loc) {\n\t\treturn is_same_row(left, loc);\n\t};\n\tstd::copy_if(\n\t\tright.cbegin(), right.cend(), std::back_inserter(output), predicate);\n\treturn output;\n}\n\n// check\ntemplate<int N>\n[[nodiscard]] inline constexpr bool\n\tis_same_col(const Location<N> left, const Location<N> right) noexcept\n{\n\treturn (is_valid<N>(left) && is_valid<N>(right)) &&\n\t\t   left.col() == right.col();\n}\n\n// check: all in same col\ntemplate<int N, typename ItrT>\n[[nodiscard]] inline constexpr bool\n\tis_same_col(const ItrT begin, const ItrT end) noexcept\n{\n\t{\n\t\tstatic_assert(traits::is_forward<ItrT>);\n\t}\n\tif (begin == end)\n\t\treturn false;\n\n\tconst auto itr = begin + 1;\n\treturn std::all_of(\n\t\titr, end, [begin](Location<N> i) { return is_same_col<N>(*begin, i); });\n}\n\n// return all in same col\ntemplate<int N> // NOLINTNEXTLINE(bugprone-exception-escape)\n[[nodiscard]] std::vector<Location<N>> get_same_col(\n\tconst Location<N> left,\n\tconst std::vector<Location<N>>& right) noexcept(true)\n{ // std::copy_if could throw std::bad_alloc\n\tstd::vector<Location<N>> output{};\n\tconst auto predicate = [&left](Location<N> loc) {\n\t\treturn is_same_col(left, loc);\n\t};\n\tstd::copy_if(\n\t\tright.cbegin(), right.cend(), std::back_inserter(output), predicate);\n\treturn output;\n}\n\n// check\ntemplate<int N>\n[[nodiscard]] inline constexpr bool\n\tis_same_block(const Location<N> left, const Location<N> right) noexcept\n{\n\treturn (is_valid<N>(left) && is_valid<N>(right)) &&\n\t\t   left.block() == right.block();\n}\n\n// check all in same block\ntemplate<int N, typename ItrT>\n[[nodiscard]] inline constexpr bool\n\tis_same_block(const ItrT begin, const ItrT end) noexcept\n{\n\t{\n\t\tstatic_assert(traits::is_forward<ItrT>);\n\t}\n\tif (begin == end)\n\t\treturn false;\n\n\tconst auto itr = begin + 1;\n\treturn std::all_of(itr, end, [begin](Location<N> i) {\n\t\treturn is_same_block<N>(*begin, i);\n\t});\n}\n\n// return all in same block\ntemplate<int N> // NOLINTNEXTLINE(bugprone-exception-escape)\n[[nodiscard]] std::vector<Location<N>> get_same_block(\n\tconst Location<N> left,\n\tconst std::vector<Location<N>>& right) noexcept(true)\n{ // std::copy_if could throw std::bad_alloc\n\tstd::vector<Location<N>> output{};\n\tconst auto predicate = [&left](Location<N> loc) {\n\t\treturn is_same_block(left, loc);\n\t};\n\tstd::copy_if(\n\t\tright.cbegin(), right.cend(), std::back_inserter(output), predicate);\n\treturn output;\n}\n\n// check: [loc] is in [section]\ntemplate<int N, typename S>\n[[nodiscard]] inline constexpr bool\n\tis_same_section(const S section, const Location<N> loc) noexcept\n{\n\tstatic_assert(Board_Section::traits::is_Section_v<S>);\n\n\tif constexpr (Board_Section::traits::is_Row_v<S>)\n\t\treturn is_same_row(loc, section.cbegin().location());\n\telse if constexpr (Board_Section::traits::is_Col_v<S>)\n\t\treturn is_same_col(loc, section.cbegin().location());\n\telse\n\t{\n\t\tstatic_assert(Board_Section::traits::is_Block_v<S>);\n\t\treturn is_same_block(loc, section.cbegin().location());\n\t}\n}\n\n// check: [section] intersects block containing [loc]\ntemplate<int N, typename S, typename>\n[[nodiscard]] inline bool\n\tintersect_block(const S section, const Location<N> block_loc) noexcept\n{\n\tfor (auto itr = section.cbegin(); itr != section.cend(); ++itr)\n\t{\n\t\tif (is_same_block(block_loc, itr.location()))\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n// check: at least one [location] inside [section]\ntemplate<typename SectionT, int N>\n[[nodiscard]] inline bool is_same_section(\n\tSectionT const section, std::vector<Location<N>> const& locs) noexcept\n{\n\treturn std::any_of(locs.cbegin(), locs.cend(), [section](Location<N> L) {\n\t\treturn is_same_section(section, L);\n\t});\n}\n\n} // namespace Sudoku\n", "meta": {"hexsha": "9df5873fe59fbc00c0a9592f2f84d06e0c3a0911", "size": 8574, "ext": "h", "lang": "C", "max_stars_repo_path": "Sudoku/Sudoku/Location_Utilities.h", "max_stars_repo_name": "FeodorFitsner/fwkSudoku", "max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sudoku/Sudoku/Location_Utilities.h", "max_issues_repo_name": "FeodorFitsner/fwkSudoku", "max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sudoku/Sudoku/Location_Utilities.h", "max_forks_repo_name": "FeodorFitsner/fwkSudoku", "max_forks_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10", "max_forks_repo_licenses": ["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.4850498339, "max_line_length": 80, "alphanum_fraction": 0.681712153, "num_tokens": 2165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3988603820631224}}
{"text": "/* -*- coding: utf-8; mode: c++; tab-width: 2; -*- -------------------------\n   Interface/declaration file for GramSchmidt.cpp\n------------------------------------------------------------------------- */\n\n#ifndef GRAMSCHMIDT_H\n#define GRAMSCHMIDT_H\n\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include <cblas.h>\n#include <lapacke.h>\n#include <iostream>\n\n// TO DO: Improve performance with CBLAS/LAPACKE for large size x\n// std::vector<double> v;\n// double* a = &v[0];\n\n// int GramSchmidt(size_t, size_t, void*, void*);\nint GramSchmidt(size_t, size_t, double*, double*);\n\n// int GramSchmidt(std::vector<std::vector<double>>, std::vector<std::vector<double>>);\n\n#endif", "meta": {"hexsha": "db3caa6fb2c7e059b57529ea37df68e155fda95f", "size": 681, "ext": "h", "lang": "C", "max_stars_repo_path": "Parallel-Cpp-MPI-OpenMP/chapter2GramSchmidt/src/GramSchmidt.h", "max_stars_repo_name": "pranjal-s/cpp17", "max_stars_repo_head_hexsha": "04b5278ff4d754d6e62f955d49bddf6509f86e73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Parallel-Cpp-MPI-OpenMP/chapter2GramSchmidt/src/GramSchmidt.h", "max_issues_repo_name": "pranjal-s/cpp17", "max_issues_repo_head_hexsha": "04b5278ff4d754d6e62f955d49bddf6509f86e73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Parallel-Cpp-MPI-OpenMP/chapter2GramSchmidt/src/GramSchmidt.h", "max_forks_repo_name": "pranjal-s/cpp17", "max_forks_repo_head_hexsha": "04b5278ff4d754d6e62f955d49bddf6509f86e73", "max_forks_repo_licenses": ["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.375, "max_line_length": 87, "alphanum_fraction": 0.5932452276, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.39886037317462414}}
{"text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <dirent.h>\n#include \"hdf5.h\"\n#include <math.h>\n#include <time.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_sf_bessel.h>\n#include \"mclib_3d.h\"\n//#include \"mclib.h\"\n#include <omp.h>\n\n#define R_DIM 1260\n#define THETA_DIM 280\n#define PHI_DIM 280\n\n\nvoid read_hydro(char hydro_prefix[200], int frame, double r_inj, double **x, double **y,  double **z, double **szx, double **szy, double **r, double **theta, double **phi,\\\n  double **velx, double **vely, double **velz, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number,  int ph_inj, double min_r, double max_r, double fps, FILE *fPtr)\n{\n    FILE *hydroPtr=NULL;\n    char hydrofile[200]=\"\", file_num[200]=\"\", full_file[200]=\"\"  ;\n    char buf[10]=\"\";\n    int i=0, j=0, k=0, elem=0;\n    float buffer=0;\n    float *dens_unprc=malloc(sizeof(float)*R_DIM*THETA_DIM*PHI_DIM);\n    float *vel_r_unprc=malloc(sizeof(float)*R_DIM*THETA_DIM*PHI_DIM);\n    float *vel_theta_unprc=malloc(sizeof(float)*R_DIM*THETA_DIM*PHI_DIM);\n    float *vel_phi_unprc=malloc(sizeof(float)*R_DIM*THETA_DIM*PHI_DIM);\n    float *pres_unprc=malloc(sizeof(float)*R_DIM*THETA_DIM*PHI_DIM);\n    double ph_rmin=0, ph_rmax=0;\n    double r_in=1e10, r_ref=2e13;\n    double *r_edge=malloc(sizeof(double)*(R_DIM+1));\n    double *dr=malloc(sizeof(double)*(R_DIM));\n    double *r_unprc=malloc(sizeof(double)*R_DIM);\n    double *theta_unprc=malloc(sizeof(double)*THETA_DIM);\n    double *phi_unprc=malloc(sizeof(double)*PHI_DIM);\n    \n    if (ph_inj==0)\n    {\n        ph_rmin=min_r;\n        ph_rmax=max_r;\n    }\n    \n    \n    \n    //density\n    snprintf(hydrofile,sizeof(hydrofile),\"%s%s%d%s\",hydro_prefix,\"u0\", 1,\"-\" );\n    modifyFlashName(file_num, hydrofile, frame, 1);\n    snprintf(full_file, sizeof(full_file), \"%s%s\", file_num, \".data\");\n    \n    fprintf(fPtr,\"Reading Density: %s\\n\", full_file);\n    fflush(fPtr);\n    \n    hydroPtr=fopen(full_file, \"rb\");\n    fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran \n    fread(dens_unprc, sizeof(float)*R_DIM*THETA_DIM*PHI_DIM,R_DIM*THETA_DIM*PHI_DIM, hydroPtr); //data\n    fclose(hydroPtr);\n    \n    \n    for (i=0;i<R_DIM*THETA_DIM*PHI_DIM;i++)\n    {\n        if ((i>98784000-5) || (i<5))\n        {\n            fprintf(fPtr,\"Density %d: %0.7e\\n\", i, *(dens_unprc+i));\n            fflush(fPtr);\n        }\n    }\n     \n    \n    //velocities divided by c\n    //v_r\n    snprintf(hydrofile,sizeof(hydrofile),\"%s%s%d%s\",hydro_prefix,\"u0\", 2,\"-\" );\n    modifyFlashName(file_num, hydrofile, frame, 1);\n    snprintf(full_file, sizeof(full_file), \"%s%s\", file_num, \".data\");\n    \n    fprintf(fPtr,\"Reading v_r: %s\\n\", full_file);\n    fflush(fPtr);\n    \n    hydroPtr=fopen(full_file, \"rb\");\n    fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran \n    fread(vel_r_unprc, sizeof(float)*R_DIM*THETA_DIM*PHI_DIM,R_DIM*THETA_DIM*PHI_DIM, hydroPtr);\n    fclose(hydroPtr);\n    \n    \n    for (i=0;i<5;i++)\n    {\n        fprintf(fPtr,\"V_r %d: %e\\n\", i, *(vel_r_unprc+i));\n        fflush(fPtr);\n    }\n    \n     \n    //v_theta\n    snprintf(hydrofile,sizeof(hydrofile),\"%s%s%d%s\",hydro_prefix,\"u0\", 3,\"-\" );\n    modifyFlashName(file_num, hydrofile, frame, 1);\n    snprintf(full_file, sizeof(full_file), \"%s%s\", file_num, \".data\");\n    \n    fprintf(fPtr,\"Reading v_theta: %s\\n\", full_file);\n    fflush(fPtr);\n    \n    hydroPtr=fopen(full_file, \"rb\");\n    fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran \n    fread(vel_theta_unprc, sizeof(float)*R_DIM*THETA_DIM*PHI_DIM,R_DIM*THETA_DIM*PHI_DIM, hydroPtr);\n    fclose(hydroPtr);\n    \n    \n    for (i=0;i<5;i++)\n    {\n        fprintf(fPtr,\"V_theta %d: %e\\n\", i, *(vel_theta_unprc+i));\n        fflush(fPtr);\n    }\n     \n    \n    //v_phi\n    snprintf(hydrofile,sizeof(hydrofile),\"%s%s%d%s\",hydro_prefix,\"u0\", 4,\"-\" );\n    modifyFlashName(file_num, hydrofile, frame, 1);\n    snprintf(full_file, sizeof(full_file), \"%s%s\", file_num, \".data\");\n    \n    fprintf(fPtr,\"Reading v_phi: %s\\n\", full_file);\n    fflush(fPtr);\n    \n    hydroPtr=fopen(full_file, \"rb\");\n    fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran \n    fread(vel_phi_unprc, sizeof(float)*R_DIM*THETA_DIM*PHI_DIM,R_DIM*THETA_DIM*PHI_DIM, hydroPtr);\n    fclose(hydroPtr);\n    \n    \n    for (i=0;i<5;i++)\n    {\n        fprintf(fPtr,\"V_phi %d: %e\\n\", i, *(vel_phi_unprc+i));\n        fflush(fPtr);\n    }\n    \n    \n    //pressure (divided by c^2)\n    snprintf(hydrofile,sizeof(hydrofile),\"%s%s%d%s\",hydro_prefix,\"u0\", 8,\"-\" );\n    modifyFlashName(file_num, hydrofile, frame, 1);\n    snprintf(full_file, sizeof(full_file), \"%s%s\", file_num, \".data\");\n    \n    fprintf(fPtr,\"Reading pres: %s\\n\", full_file);\n    fflush(fPtr);\n    \n    hydroPtr=fopen(full_file, \"rb\");\n    fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran \n    fread(pres_unprc, sizeof(float)*R_DIM*THETA_DIM*PHI_DIM,R_DIM*THETA_DIM*PHI_DIM, hydroPtr);\n    fclose(hydroPtr);\n    \n    for (i=PHI_DIM-1;i<PHI_DIM;i++)\n    {\n        for (j=THETA_DIM-1;j<THETA_DIM;j++)\n        {\n            for (k=R_DIM-5;k<R_DIM;k++)\n            {\n        \n            fprintf(fPtr,\"Pres %d: %e\\n\", (i*R_DIM*THETA_DIM + j*R_DIM + k  ), *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  )));\n            fflush(fPtr);\n        \n            }\n        }\n    }\n    \n    \n    // see how many elements there are to test if reading correctly\n    /*\n    hydroPtr=fopen(full_file, \"rb\");\n    fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran \n    while (1 == fread(&buffer,sizeof(float),1,hydroPtr))\n    {\n        elem++;\n    }\n    //fread(pres_unprc, sizeof(double)*HYDRO_DIM,HYDRO_DIM, hydroPtr);\n    fclose(hydroPtr);\n    \n    fprintf(fPtr,\"Elem %d\\n\", elem);\n    */\n    \n    //R\n    if (frame<=1300)\n    {\n        snprintf(hydrofile,sizeof(hydrofile),\"%s%s%d%s\",hydro_prefix,\"grid0\", 0,\"-x1.data\" );\n    }\n    else if (frame<=2000)\n    {\n        snprintf(hydrofile,sizeof(hydrofile),\"%s%s%d%s\",hydro_prefix,\"grid0\", 1,\"-x1.data\" );\n    }\n    else\n    {\n        snprintf(hydrofile,sizeof(hydrofile),\"%s%s%d%s\",hydro_prefix,\"grid0\", 2,\"-x1.data\" );\n    }\n    \n    fprintf(fPtr,\"Reading Radius: %s\\n\", hydrofile);\n    fflush(fPtr);\n    \n    hydroPtr=fopen(hydrofile, \"r\");\n    \n    i=0;\n    while (i<R_DIM)\n    {\n        fscanf(hydroPtr, \"%lf\", (r_unprc+i));  //read value\n        fgets(buf, 3,hydroPtr); //read comma\n        \n        if (i<5)\n        {\n            fprintf(fPtr,\"R %d: %e\\n\", i, *(r_unprc+i));\n            fflush(fPtr);\n        }\n        \n        i++;\n    }\n    \n    fclose(hydroPtr);\n    \n    //calculate radial grid edges\n    *(r_edge+0)=r_in;\n    i=0;\n    for (i=1;i<R_DIM;i++)\n    {\n        *(r_edge+i)=(*(r_edge+i-1))+((*(r_edge+i-1))*(M_PI/560)/(1+((*(r_edge+i-1))/r_ref))); //r_i = r_(i-1) + Dq r_(i-1) [1 + r_(i-1)/r0]-1\n        *(dr+i-1)=(*(r_edge+i))-(*(r_edge+i-1));\n        \n        if (i<5)\n        {\n            fprintf(fPtr,\"R Edge: %d: %e Dr: %e\\n\", i, *(r_edge+i), *(dr+i-1));\n            fflush(fPtr);\n        }\n         \n    }\n    free(r_edge);\n    \n    //Theta\n    snprintf(hydrofile,sizeof(hydrofile),\"%s%s\",hydro_prefix,\"grid-x2.data\" );\n    fprintf(fPtr,\"Reading Theta: %s\\n\", hydrofile);\n    fflush(fPtr);\n    \n    hydroPtr=fopen(hydrofile, \"r\");\n    \n    i=0;\n    while (i<THETA_DIM)\n    {\n        fscanf(hydroPtr, \"%lf\", (theta_unprc+i));  //read value\n        fgets(buf, 3,hydroPtr); //read comma\n        \n        if (i<5)\n        {\n            fprintf(fPtr,\"R %d: %e\\n\", i, *(theta_unprc+i));\n            fflush(fPtr);\n        }\n        \n        i++;\n    }\n    \n    fclose(hydroPtr);\n    \n    //Phi\n    snprintf(hydrofile,sizeof(hydrofile),\"%s%s\",hydro_prefix,\"grid-x3.data\" );\n    fprintf(fPtr,\"Reading Phi: %s\\n\", hydrofile);\n    fflush(fPtr);\n    \n    hydroPtr=fopen(hydrofile, \"r\");\n    \n    i=0;\n    while (i<PHI_DIM)\n    {\n        fscanf(hydroPtr, \"%lf\", (phi_unprc+i));  //read value\n        fgets(buf, 3,hydroPtr); //read comma\n        \n        if (i<5)\n        {\n            fprintf(fPtr,\"R %d: %e\\n\", i, *(phi_unprc+i));\n            fflush(fPtr);\n        }\n        \n        i++;\n    }\n    \n    fclose(hydroPtr);\n    \n    //limit number of array elements\n    elem=0;\n    for (i=0;i<PHI_DIM;i++)\n    {\n        for (j=0;j<THETA_DIM;j++)\n        {\n            for (k=0;k<R_DIM;k++)\n            {\n                //if I have photons do selection differently than if injecting photons\n                if (ph_inj==0) \n                {\n                    //if calling this function when propagating photons, choose blocks based on where the photons are\n                    if (((ph_rmin - C_LIGHT/fps)<(*(r_unprc+k))) && (*(r_unprc+k)  < (ph_rmax + C_LIGHT/fps) ))\n                    {\n                        // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  )\n                        elem++;\n                    }\n                }\n                else\n                {\n                    //if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient \n                    if (((r_inj - C_LIGHT/fps)<(*(r_unprc+k))) && (*(r_unprc+k)  < (r_inj + C_LIGHT/fps) ))\n                    {\n                        // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  )\n                        elem++;\n                    }\n                    \n                }\n        \n            }\n        }\n    }\n    \n    fprintf(fPtr,\"Number of post restricted Elems: %d %e\\n\", elem, r_inj);\n    \n    //allocate space for new set of data\n    (*pres)=malloc (elem * sizeof (double ));\n    (*velx)=malloc (elem * sizeof (double ));\n    (*vely)=malloc (elem * sizeof (double ));\n    (*velz)=malloc (elem * sizeof (double ));\n    (*dens)=malloc (elem * sizeof (double ));\n    (*x)=malloc (elem * sizeof (double ));\n    (*y)=malloc (elem * sizeof (double ));\n    (*z)=malloc (elem * sizeof (double ));\n    (*r)=malloc (elem * sizeof (double ));\n    (*theta)=malloc (elem * sizeof (double ));\n    (*phi)=malloc (elem * sizeof (double ));\n    (*gamma)=malloc (elem * sizeof (double ));\n    (*dens_lab)=malloc (elem * sizeof (double ));\n    (*szx)=malloc (elem * sizeof (double )); //theta and phi resolution \n    (*szy)=malloc (elem * sizeof (double )); //r resolution\n    (*temp)=malloc (elem * sizeof (double ));\n    \n    //limit number of array elements\n    elem=0;\n    for (i=0;i<PHI_DIM;i++)\n    {\n        for (j=0;j<THETA_DIM;j++)\n        {\n            for (k=0;k<R_DIM;k++)\n            {\n                //if I have photons do selection differently than if injecting photons\n                if (ph_inj==0) \n                {\n                    //if calling this function when propagating photons, choose blocks based on where the photons are\n                    if (((ph_rmin - C_LIGHT/fps)<(*(r_unprc+k))) && (*(r_unprc+k)  < (ph_rmax + C_LIGHT/fps) ))\n                    {\n                        (*pres)[elem] = *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  ));\n                        (*dens)[elem] = *(dens_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  ));\n                        (*temp)[elem] =  pow(3*(*(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n                        //fprintf(fPtr, \"Selected Values: pres, %e, temp, %e\\n\",*(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  )),pow(3*(*(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0) );\n                        \n                        (*gamma)[elem] = pow(pow(1.0-(pow(*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+ pow(*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+pow(*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)),0.5),-1);\n                        (*dens_lab)[elem] = (*(dens_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  )))*pow(pow(1.0-(pow(*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+ pow(*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+pow(*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)),0.5),-1);\n                        (*r)[elem] = *(r_unprc+k);\n                        (*theta)[elem] = *(theta_unprc+j);\n                        (*phi)[elem] = *(phi_unprc+i);\n                        (*x)[elem] = (*(r_unprc+k))*sin(*(theta_unprc+j))*cos(*(phi_unprc+i));\n                        (*y)[elem] = (*(r_unprc+k))*sin(*(theta_unprc+j))*sin(*(phi_unprc+i));\n                        (*z)[elem] = (*(r_unprc+k))*cos(*(theta_unprc+j));\n                        (*szx)[elem] = M_PI/560; \n                        (*szy)[elem] =  *(dr+k);\n                        (*velx)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j))*cos(*(phi_unprc+i))) + ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))*cos(*(phi_unprc+i))) - ((*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(phi_unprc+i)));\n                        (*vely)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j))*sin(*(phi_unprc+i))) + ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))*sin(*(phi_unprc+i))) + ((*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(phi_unprc+i)));\n                        (*velz)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))) - ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j)));\n\n                        elem++;\n                        \n                    }\n                }\n                else\n                {\n                    //if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient \n                    if (((r_inj - C_LIGHT/fps)<(*(r_unprc+k))) && (*(r_unprc+k)  < (r_inj + C_LIGHT/fps) ))\n                    {\n                        (*pres)[elem] = *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  ));\n                        (*dens)[elem] = *(dens_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  ));\n                        (*temp)[elem] =  pow(3*(*(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n                        (*gamma)[elem] = pow(pow(1.0-(pow(*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+ pow(*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+pow(*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)),0.5),-1);\n                        (*dens_lab)[elem] = (*(dens_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k  )))*pow(pow(1.0-(pow(*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+ pow(*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)+pow(*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )),2)),0.5),-1);\n                        (*r)[elem] = *(r_unprc+k);\n                        (*theta)[elem] = *(theta_unprc+j);\n                        (*phi)[elem] = *(phi_unprc+i);\n                        (*x)[elem] = (*(r_unprc+k))*sin(*(theta_unprc+j))*cos(*(phi_unprc+i));\n                        (*y)[elem] = (*(r_unprc+k))*sin(*(theta_unprc+j))*sin(*(phi_unprc+i));\n                        (*z)[elem] = (*(r_unprc+k))*cos(*(theta_unprc+j));\n                        (*szx)[elem] = M_PI/560; \n                        (*szy)[elem] =  *(dr+k);\n                        (*velx)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j))*cos(*(phi_unprc+i))) + ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))*cos(*(phi_unprc+i))) - ((*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(phi_unprc+i)));\n                        (*vely)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j))*sin(*(phi_unprc+i))) + ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))*sin(*(phi_unprc+i))) + ((*(vel_phi_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(phi_unprc+i)));\n                        (*velz)[elem]=((*(vel_r_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*cos(*(theta_unprc+j))) - ((*(vel_theta_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )))*sin(*(theta_unprc+j)));\n\n                        elem++;\n                    }\n                    \n                }\n        \n            }\n        }\n    }\n    \n    *number=elem;\n    \n    free(pres_unprc); free(dens_unprc); free(r_unprc); free(theta_unprc); free(phi_unprc);free(dr);free(vel_r_unprc); free(vel_theta_unprc); free(vel_phi_unprc);\n    \n}\n\n\nvoid photonInjection3D( struct photon **ph, int *ph_num, double r_inj, double ph_weight, int min_photons, int max_photons, char spect, int array_length, double fps, double theta_min, double theta_max,\\\n double *x, double *y, double *z, double *szx, double *szy, double *r, double *theta, double *phi, double *temps, double *vx, double *vy, double *vz, gsl_rng * rand)\n{\n    int i=0, block_cnt=0, *ph_dens=NULL, ph_tot=0, j=0,k=0;\n    double ph_dens_calc=0.0, fr_dum=0.0, y_dum=0.0, yfr_dum=0.0, fr_max=0, bb_norm=0, position_phi, ph_weight_adjusted, theta_prime=0;\n    double com_v_phi, com_v_theta, *p_comv=NULL, *boost=NULL; //comoving phi, theta, comoving 4 momentum for a photon, and boost for photon(to go to lab frame)\n    double *l_boost=NULL; //pointer to hold array of lorentz boost, to lab frame, values\n    float num_dens_coeff;\n    \n    if (spect=='w') //from MCRAT paper, w for wien spectrum \n    {\n        num_dens_coeff=8.44;\n        printf(\"in wien spectrum\\n\");\n    }\n    else\n    {\n        num_dens_coeff=20.29; //this is for black body spectrum\n        printf(\"in BB spectrum\");\n    }\n    \n    //find how many blocks are near the injection radius within the angles defined in mc.par, get temperatures and calculate number of photons to allocate memory for \n    //and then rcord which blocks have to have \"x\" amount of photons injected there\n    printf(\"%e, %e\\n\",*(phi+i), theta_max);\n    for(i=0;i<array_length;i++)\n    {\n        //look at all boxes in width delta r=c/fps and within angles we are interested in NEED TO modify for RIKEN data- dont need r anymore, just theta and phi? (didnt work), just look at pojection on x-z plane\n        theta_prime=acos(*(y+i)/(*(r+i))); //jet axis here is the y axis\n            if ( (theta_prime< theta_max) && (theta_prime > theta_min) ) //(*(r+i) > (r_inj - C_LIGHT/fps))  &&   (*(r+i)  < (r_inj + C_LIGHT/fps)  ) &&\n            {\n                //printf(\"%e\\n\", theta_prime );\n                block_cnt++;\n            }\n    }\n    printf(\"Blocks: %d\\n\", block_cnt);\n    \n    ph_dens=malloc(block_cnt * sizeof(int));\n    \n    //calculate the photon density for each block and save it to the array\n    j=0;\n    ph_tot=0;\n    ph_weight_adjusted=ph_weight;\n    //printf(\"%d %d\\n\", max_photons, min_photons);\n    while ((ph_tot>max_photons) || (ph_tot<min_photons) )\n    {\n        j=0;\n        ph_tot=0;\n        //allocate memory to record density of photons for each block\n        //ph_dens=malloc(block_cnt * sizeof(int));\n        \n        for (i=0;i<array_length;i++)\n        {\n            //printf(\"%d\\n\",i);\n            //printf(\"%e, %e, %e, %e, %e, %e\\n\", *(r+i),(r_inj - C_LIGHT/fps), (r_inj + C_LIGHT/fps), *(theta+i) , theta_max, theta_min);\n                //NEED TO modify for RIKEN data - modified\n                theta_prime=acos(*(y+i)/(*(r+i)));\n                if ( (theta_prime< theta_max) && (theta_prime > theta_min) )\n                {\n                    //NEED TO modify for RIKEN data - modified\n                    ph_dens_calc=(num_dens_coeff*pow(*(temps+i),3.0)*pow(*(r+i),2)*sin(*(theta+i))* pow(*(szx+i),2.0)*(*(szy+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1) ; //a*T^3/(weight) dV, dV=2*PI*x*dx^2,\n                     \n                     (*(ph_dens+j))=gsl_ran_poisson(rand,ph_dens_calc) ; //choose from poission distribution with mean of ph_dens_calc\n                     \n                    //printf(\"%d, %lf \\n\",*(ph_dens+j), ph_dens_calc);\n                    \n                     //sum up all the densities to get total number of photons\n                     ph_tot+=(*(ph_dens+j));\n                     \n                     j++;\n                }\n        }\n\n        if (ph_tot>max_photons)\n        {\n            //if the number of photons is too big make ph_weight larger\n            ph_weight_adjusted*=10;\n            //free(ph_dens);\n        }\n        else if (ph_tot<min_photons)\n        {\n            ph_weight_adjusted*=0.5;\n            //free(ph_dens);\n        }\n        //printf(\"dens: %d, photons: %d\\n\", *(ph_dens+(j-1)), ph_tot);\n         \n    }\n        \n    printf(\"%d\\n\", ph_tot);\n    \n    //allocate memory for that many photons and also allocate memory to hold comoving 4 momentum of each photon and the velocity of the fluid\n    (*ph)=malloc (ph_tot * sizeof (struct photon ));\n    \n    p_comv=malloc(4*sizeof(double));\n    boost=malloc(3*sizeof(double));\n    l_boost=malloc(4*sizeof(double));\n    \n    \n    //go through blocks and assign random energies/locations to proper number of photons\n    ph_tot=0;\n    k=0;\n    for (i=0;i<array_length;i++)\n    {\n        theta_prime=acos(*(y+i)/(*(r+i)));\n        if ( (theta_prime< theta_max) && (theta_prime > theta_min) )  //NEED TO modify for RIKEN data - modified\n        {\n\n            //*(temps+i)=0.76*(*(temps+i));\n            for(j=0;j<( *(ph_dens+k) ); j++ )\n            {\n                    //have to get random frequency for the photon comoving frequency\n                    y_dum=1; //initalize loop\n                    yfr_dum=0;\n                    while (y_dum>yfr_dum)\n                    {\n                        fr_dum=gsl_rng_uniform_pos(rand)*6.3e11*(*(temps+i)); //in Hz\n                        //printf(\"%lf, %lf \",gsl_rng_uniform_pos(rand), (*(temps+i)));\n                        y_dum=gsl_rng_uniform_pos(rand);\n                        //printf(\"%lf \",fr_dum);\n                        \n                        if (spect=='w')\n                        {\n                            yfr_dum=(1.0/(1.29e31))*pow((fr_dum/(*(temps+i))),3.0)/(exp((PL_CONST*fr_dum)/(K_B*(*(temps+i)) ))-1); //curve is normalized to maximum\n                        }\n                        else\n                        {\n                            fr_max=(5.88e10)*(*(temps+i));//(C_LIGHT*(*(temps+i)))/(0.29); //max frequency of bb\n                            bb_norm=(PL_CONST*fr_max * pow((fr_max/C_LIGHT),2.0))/(exp(PL_CONST*fr_max/(K_B*(*(temps+i))))-1); //find value of bb at fr_max\n                            yfr_dum=((1.0/bb_norm)*PL_CONST*fr_dum * pow((fr_dum/C_LIGHT),2.0))/(exp(PL_CONST*fr_dum/(K_B*(*(temps+i))))-1); //curve is normalized to vaue of bb @ max frequency\n                        }\n                        //printf(\"%lf, %lf,%lf,%e \\n\",(*(temps+i)),fr_dum, y_dum, yfr_dum);\n                        \n                    }\n                   //printf(\"%lf\\n \",fr_dum);\n                   //position_phi= gsl_rng_uniform(rand)*2*M_PI; //NEED TO modify for RIKEN data-modified, dont need anymore\n                   com_v_phi=gsl_rng_uniform(rand)*2*M_PI; \n                   com_v_theta=acos((gsl_rng_uniform(rand)*2)-1);\n                   //printf(\"%lf, %lf, %lf\\n\", position_phi, com_v_phi, com_v_theta);\n                   \n                   //populate 4 momentum comoving array\n                   *(p_comv+0)=PL_CONST*fr_dum/C_LIGHT;\n                   *(p_comv+1)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*cos(com_v_phi);\n                   *(p_comv+2)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*sin(com_v_phi);\n                   *(p_comv+3)=(PL_CONST*fr_dum/C_LIGHT)*cos(com_v_theta);\n                   \n                    //populate boost matrix, not sure why multiplying by -1, seems to give correct answer in old python code...\n                    //NEED TO modify for RIKEN data - modified\n                    *(boost+0)=-1*(*(vx+i));\n                    *(boost+1)=-1*(*(vy+i));\n                    *(boost+2)=-1*(*(vz+i));\n                    //printf(\"%lf, %lf, %lf\\n\", *(boost+0), *(boost+1), *(boost+2));\n                    \n                    //boost to lab frame\n                    lorentzBoost(boost, p_comv, l_boost, 'p');\n                    //printf(\"Assignemnt: %e, %e, %e, %e\\n\", *(l_boost+0), *(l_boost+1), *(l_boost+2),*(l_boost+3));\n                   \n                (*ph)[ph_tot].p0=(*(l_boost+0));\n                (*ph)[ph_tot].p1=(*(l_boost+1));\n                (*ph)[ph_tot].p2=(*(l_boost+2));\n                (*ph)[ph_tot].p3=(*(l_boost+3));\n                //NEED TO modify for RIKEN data-modified\n                (*ph)[ph_tot].r0= (*(x+i)); //put photons @ center of box that they are supposed to be in with random phi \n                (*ph)[ph_tot].r1=(*(y+i)) ;\n                (*ph)[ph_tot].r2=(*(z+i)); //y coordinate in flash becomes z coordinate in MCRaT\n                (*ph)[ph_tot].num_scatt=0;\n                (*ph)[ph_tot].weight=ph_weight_adjusted;\n                //printf(\"%d\\n\",ph_tot);\n                ph_tot++;\n            }\n            k++;\n        }\n    }\n    \n    *ph_num=ph_tot; //save number of photons\n    //printf(\" %d: %d\\n\", *(ph_dens+(k-1)), *ph_num);\n    free(ph_dens); free(p_comv);free(boost); free(l_boost);\n    \n}\n\n void phMinMax(struct photon *ph, int ph_num, double *min, double *max)\n {\n      double temp_r_max=0, temp_r_min=-1;\n        int i=0;\n      double ph_r=0;\n      \n      for (i=0;i<ph_num;i++)\n    {        \n        ph_r=pow(pow( ((ph+i)->r0), 2.0) + pow(((ph+i)->r1),2.0 ) + pow(((ph+i)->r2) , 2.0),0.5);\n        if (ph_r > temp_r_max )\n        {\n            temp_r_max=ph_r;\n            printf(\"The new max is: %e\\n\", temp_r_max);\n        }\n        \n        if ((i==0) || (ph_r<temp_r_min))\n        {\n            temp_r_min=ph_r;\n            printf(\"The new min is: %e\\n\", temp_r_min);\n        }\n    }\n    \n    *max=temp_r_max;\n    *min=temp_r_min;\n      \n }", "meta": {"hexsha": "0e4bd46ffa6b5526621a48eee13e0de5a40dcb16", "size": 25896, "ext": "c", "lang": "C", "max_stars_repo_path": "OLDER_MCRaT_VERSIONS/mclib_3d.c", "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z", "max_issues_repo_path": "OLDER_MCRaT_VERSIONS/mclib_3d.c", "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OLDER_MCRaT_VERSIONS/mclib_3d.c", "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z", "avg_line_length": 42.1073170732, "max_line_length": 314, "alphanum_fraction": 0.5234012975, "num_tokens": 7749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3985265302983461}}
{"text": "#include <gsl/gsl_math.h>\n#include <gsl/gsl_cblas.h>\n#include \"cblas.h\"\n#include \"error_cblas_l2.h\"\n\nvoid\ncblas_chemv (const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,\n             const int N, const void *alpha, const void *A, const int lda,\n             const void *X, const int incX, const void *beta, void *Y,\n             const int incY)\n{\n#define BASE float\n#include \"source_hemv.h\"\n#undef BASE\n}\n", "meta": {"hexsha": "a501605a3d9242abf174ed76a42ed94957f617ae", "size": 412, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-an/cblas/chemv.c", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "gsl-an/cblas/chemv.c", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "gsl-an/cblas/chemv.c", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 25.75, "max_line_length": 74, "alphanum_fraction": 0.6699029126, "num_tokens": 122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934765, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3984719929963472}}
{"text": "#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <stdlib.h>\n\n/* Representation */\ngsl_complex *alloc_gsl_complex(void)\n{\n  gsl_complex *c = malloc(sizeof(gsl_complex));\n  return c;\n}\n\nvoid free_gsl_complex(gsl_complex *c)\n{\n  free(c);\n}\n\ngsl_complex_float *alloc_gsl_complex_float(void)\n{\n  gsl_complex_float *c = malloc(sizeof(gsl_complex_float));\n  return c;\n}\n\nvoid free_gsl_complex_float(gsl_complex_float *c)\n{\n  free(c);\n}\n\nvoid mgsl_complex_rect(double x, double y, gsl_complex *res)\n{\n  gsl_complex ret = gsl_complex_rect(x, y);\n  *res = ret;\n}\n\nvoid mgsl_complex_float_rect(float x, float y, gsl_complex_float *res)\n{\n  GSL_SET_COMPLEX(res, x, y);\n}\n\nvoid mgsl_complex_polar(double r, double theta, gsl_complex *res)\n{\n  gsl_complex ret = gsl_complex_polar(r, theta);\n  *res = ret;\n}\n\nvoid mgsl_complex_float_polar(float r, float theta, gsl_complex_float *res)\n{\n  gsl_complex ret = gsl_complex_polar((double)r, (double)theta);\n  GSL_SET_COMPLEX(res, ret.dat[0], ret.dat[1]);\n}\n\n/* Properties */\ndouble mgsl_complex_arg(gsl_complex *c)\n{\n  return gsl_complex_arg(*c);\n}\n\ndouble mgsl_complex_abs(gsl_complex *c)\n{\n  return gsl_complex_abs(*c);\n}\n\ndouble mgsl_complex_abs2(gsl_complex *c)\n{\n  return gsl_complex_abs2(*c);\n}\n\ndouble mgsl_complex_logabs(gsl_complex *c)\n{\n  return gsl_complex_logabs(*c);\n}\n\n/* Arithmetic operators */\n\nvoid mgsl_complex_add(gsl_complex *a, gsl_complex *b, gsl_complex *res)\n{\n  *res = gsl_complex_add(*a, *b);\n}\n\nvoid mgsl_complex_sub(gsl_complex *a, gsl_complex *b, gsl_complex *res)\n{\n  *res = gsl_complex_sub(*a, *b);\n}\n\nvoid mgsl_complex_mul(gsl_complex *a, gsl_complex *b, gsl_complex *res)\n{\n  *res = gsl_complex_mul(*a, *b);\n}\n\nvoid mgsl_complex_div(gsl_complex *a, gsl_complex *b, gsl_complex *res)\n{\n  *res = gsl_complex_div(*a, *b);\n}\n\nvoid mgsl_complex_add_real(gsl_complex *a, double x, gsl_complex *res)\n{\n  *res = gsl_complex_add_real(*a, x);\n}\n\nvoid mgsl_complex_sub_real(gsl_complex *a, double x, gsl_complex *res)\n{\n  *res = gsl_complex_sub_real(*a, x);\n}\n\nvoid mgsl_complex_mul_real(gsl_complex *a, double x, gsl_complex *res)\n{\n  *res = gsl_complex_mul_real(*a, x);\n}\n\nvoid mgsl_complex_div_real(gsl_complex *a, double x, gsl_complex *res)\n{\n  *res = gsl_complex_div_real(*a, x);\n}\n\nvoid mgsl_complex_add_imag(gsl_complex *a, double y, gsl_complex *res)\n{\n  *res = gsl_complex_add_imag(*a, y);\n}\n\nvoid mgsl_complex_sub_imag(gsl_complex *a, double y, gsl_complex *res)\n{\n  *res = gsl_complex_sub_imag(*a, y);\n}\n\nvoid mgsl_complex_mul_imag(gsl_complex *a, double y, gsl_complex *res)\n{\n  *res = gsl_complex_mul_imag(*a, y);\n}\n\nvoid mgsl_complex_div_imag(gsl_complex *a, double y, gsl_complex *res)\n{\n  *res = gsl_complex_div_imag(*a, y);\n}\n\nvoid mgsl_complex_conjugate(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_conjugate(*z);\n}\n\nvoid mgsl_complex_inverse(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_inverse(*z);\n}\n\nvoid mgsl_complex_negative(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_negative(*z);\n}\n\n/* Elementary Complex Functions */\nvoid mgsl_complex_sqrt(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_sqrt(*z);\n}\n\nvoid mgsl_complex_sqrt_real(double x, gsl_complex *res)\n{\n  *res = gsl_complex_sqrt_real(x);\n}\n\nvoid mgsl_complex_pow(gsl_complex *z, gsl_complex *a, gsl_complex *res)\n{\n  *res = gsl_complex_pow(*z, *a);\n}\n\nvoid mgsl_complex_pow_real(gsl_complex *z, double x, gsl_complex *res)\n{\n  *res = gsl_complex_pow_real(*z, x);\n}\n\nvoid mgsl_complex_exp(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_exp(*z);\n}\n\nvoid mgsl_complex_log(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_log(*z);\n}\n\nvoid mgsl_complex_log10(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_log10(*z);\n}\n\nvoid mgsl_complex_log_b(gsl_complex *z, gsl_complex *b, gsl_complex *res)\n{\n  *res = gsl_complex_log_b(*z, *b);\n}\n\n/* Complex Trigonometric Functions */\nvoid mgsl_complex_sin(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_sin(*z);\n}\n\nvoid mgsl_complex_cos(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_cos(*z);\n}\n\nvoid mgsl_complex_tan(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_tan(*z);\n}\n\nvoid mgsl_complex_sec(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_sec(*z);\n}\n\nvoid mgsl_complex_csc(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_csc(*z);\n}\n\nvoid mgsl_complex_cot(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_cot(*z);\n}\n\n/* Inverse Complex Trigonometric Functions */\nvoid mgsl_complex_arcsin(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arcsin(*z);\n}\n\nvoid mgsl_complex_arcsin_real(double z, gsl_complex *res)\n{\n  *res = gsl_complex_arcsin_real(z);\n}\n\nvoid mgsl_complex_arccos(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arccos(*z);\n}\n\nvoid mgsl_complex_arccos_real(double z, gsl_complex *res)\n{\n  *res = gsl_complex_arccos_real(z);\n}\n\nvoid mgsl_complex_arctan(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arctan(*z);\n}\n\nvoid mgsl_complex_arcsec(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arcsec(*z);\n}\n\nvoid mgsl_complex_arcsec_real(double z, gsl_complex *res)\n{\n  *res = gsl_complex_arcsec_real(z);\n}\n\nvoid mgsl_complex_arccsc(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arccsc(*z);\n}\n\nvoid mgsl_complex_arccsc_real(double z, gsl_complex *res)\n{\n  *res = gsl_complex_arccsc_real(z);\n}\n\nvoid mgsl_complex_arccot(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arccot(*z);\n}\n\n/* Complex Hyperbolic Functions */\nvoid mgsl_complex_sinh(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_sinh(*z);\n}\n\nvoid mgsl_complex_cosh(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_cosh(*z);\n}\n\nvoid mgsl_complex_tanh(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_tanh(*z);\n}\n\nvoid mgsl_complex_sech(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_sech(*z);\n}\n\nvoid mgsl_complex_csch(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_csch(*z);\n}\n\nvoid mgsl_complex_coth(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_coth(*z);\n}\n\n/* Inverse Complex Hyperbolic Functions */\nvoid mgsl_complex_arcsinh(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arcsinh(*z);\n}\n\nvoid mgsl_complex_arccosh(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arccosh(*z);\n}\n\nvoid mgsl_complex_arccosh_real(double z, gsl_complex *res)\n{\n  *res = gsl_complex_arccosh_real(z);\n}\n\nvoid mgsl_complex_arctanh(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arctanh(*z);\n}\n\nvoid mgsl_complex_arctanh_real(double z, gsl_complex *res)\n{\n  *res = gsl_complex_arctanh_real(z);\n}\n\nvoid mgsl_complex_arcsech(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arcsech(*z);\n}\n\nvoid mgsl_complex_arccsch(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arccsch(*z);\n}\n\nvoid mgsl_complex_arccoth(gsl_complex *z, gsl_complex *res)\n{\n  *res = gsl_complex_arccoth(*z);\n}\n", "meta": {"hexsha": "3a62916a16c344f5c08abdb2372ab3c5775df08d", "size": 6909, "ext": "c", "lang": "C", "max_stars_repo_path": "src/complex.c", "max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Complex", "max_stars_repo_head_hexsha": "c11bdcd5c118c2b564a30e746e12afeb865bf25d", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-22T14:05:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T14:05:54.000Z", "max_issues_repo_path": "src/complex.c", "max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Complex", "max_issues_repo_head_hexsha": "c11bdcd5c118c2b564a30e746e12afeb865bf25d", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/complex.c", "max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Complex", "max_forks_repo_head_hexsha": "c11bdcd5c118c2b564a30e746e12afeb865bf25d", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1428571429, "max_line_length": 75, "alphanum_fraction": 0.7312201476, "num_tokens": 2089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.39847198585340493}}
{"text": "//-*-C++-*-\n/***************************************************************************\n *\n *   Copyright (C) 2008 by Willem van Straten\n *   Licensed under the Academic Free License version 2.1\n *\n ***************************************************************************/\n\n#ifndef __Pulsar_Interpolation_h\n#define __Pulsar_Interpolation_h\n\n#include \"Reference.h\"\n\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n\n#include <vector>\n\n//! Interface to GSL interpolation routines\nclass Interpolation : public Reference::Able\n{\n\npublic:\n\n  //! Default constructor\n  Interpolation ();\n\n  //! Destructor\n  virtual ~Interpolation ();\n\n  //! Initialize interpolation object\n  void init (const std::vector<double>& x, const std::vector<double>& y);\n\n  //! Evaluate at the given abscissa\n  double eval (double x);\n\nprotected:\n\n  const double* xa;\n  const double* ya;\n  size_t size;\n\n  gsl_interp* interp;\n  gsl_interp_accel* acc;\n\n  void destroy ();\n};\n\n#endif\n", "meta": {"hexsha": "f64c1f3a9401871f235dd7b1294c904ee2c22468", "size": 963, "ext": "h", "lang": "C", "max_stars_repo_path": "Util/genutil/Interpolation.h", "max_stars_repo_name": "rwharton/psrchive_dsn", "max_stars_repo_head_hexsha": "9584862167154fa48db89b86151c4221ad4bb96b", "max_stars_repo_licenses": ["AFL-2.1"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Util/genutil/Interpolation.h", "max_issues_repo_name": "rwharton/psrchive_dsn", "max_issues_repo_head_hexsha": "9584862167154fa48db89b86151c4221ad4bb96b", "max_issues_repo_licenses": ["AFL-2.1"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Util/genutil/Interpolation.h", "max_forks_repo_name": "rwharton/psrchive_dsn", "max_forks_repo_head_hexsha": "9584862167154fa48db89b86151c4221ad4bb96b", "max_forks_repo_licenses": ["AFL-2.1"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T20:08:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T20:08:14.000Z", "avg_line_length": 19.26, "max_line_length": 77, "alphanum_fraction": 0.5877466251, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.398468534411619}}
{"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk_6_4.c\n * \\brief Source file to optimize Runge-Kutta 6 steps 4th order methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include <string.h>\n#include <math.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include <libintl.h>\n#include <gsl/gsl_rng.h>\n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_6_4.h\"\n\n#define DEBUG_RK_6_4 0          ///< macro to debug.\n\n/**\n * Function to obtain the coefficients of a 6 steps 4th order Runge-Kutta \n * method.\n */\nint\nrk_tb_6_4 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *tb, *r;\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_tb_6_4: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t6 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  b21 (tb) = r[2];\n  t3 (tb) = r[3];\n  b31 (tb) = r[4];\n  b32 (tb) = r[5];\n  t4 (tb) = r[6];\n  b41 (tb) = r[7];\n  b42 (tb) = r[8];\n  b43 (tb) = r[9];\n  t5 (tb) = r[10];\n  b54 (tb) = r[11];\n  b65 (tb) = r[12];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = t4 (tb);\n  E[0] = 0.5L - b65 (tb) * t5 (tb);\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = D[0] * t4 (tb);\n  E[1] = 1.L / 3.L - b65 (tb) * sqr (t5 (tb));\n  A[2] = A[1] * t1 (tb);\n  B[2] = B[1] * t2 (tb);\n  C[2] = C[1] * t3 (tb);\n  D[2] = D[1] * t4 (tb);\n  E[2] = 0.25L - b65 (tb) * sqr (t5 (tb)) * t5 (tb);\n  A[3] = 0.L;\n  B[3] = b21 (tb) * t1 (tb) * (t2 (tb) - t5 (tb));\n  C[3] = (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb)) * (t3 (tb) - t5 (tb));\n  D[3] = (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb) + b43 (tb) * t3 (tb))\n    * (t4 (tb) - t5 (tb));\n  E[3] = 0.125L - 1.L / 6.L * t5 (tb);\n  solve_4 (A, B, C, D, E);\n  if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))\n    return 0;\n  b64 (tb) = E[3];\n  b63 (tb) = E[2];\n  b62 (tb) = E[1];\n  b61 (tb) = E[0];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = (1.L / 6.L - b62 (tb) * b21 (tb) * t1 (tb)\n          - b63 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))\n          - b64 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)\n                        + b43 (tb) * t3 (tb))) / b65 (tb) - b54 (tb) * t4 (tb);\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = (1.L / 12.L - b62 (tb) * b21 (tb) * sqr (t1 (tb))\n          - b63 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)))\n          - b64 (tb) * (b41 (tb) * sqr (t1 (tb)) + b42 (tb) * sqr (t2 (tb))\n                        + b43 (tb) * sqr (t3 (tb)))) / b65 (tb)\n    - b54 (tb) * sqr (t4 (tb));\n  A[2] = 0.L;\n  B[2] = b21 (tb) * t1 (tb);\n  C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);\n  D[2] = (1.L / 24.L - b63 (tb) * b32 (tb) * b21 (tb) * t1 (tb)\n          - b64 (tb) * (b42 (tb) * b21 (tb) * t1 (tb)\n                        + b43 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))))\n    / b65 (tb) - b54 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)\n                             + b43 (tb) * t3 (tb));\n  solve_3 (A, B, C, D);\n  if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))\n    return 0;\n  b53 (tb) = D[2];\n  b52 (tb) = D[1];\n  b51 (tb) = D[0];\n  rk_b_6 (tb);\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_tb_6_4: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 6 steps 4th order, 5th order in\n * equations depending only on time, Runge-Kutta method.\n */\nint\nrk_tb_6_4t (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[5], B[5], C[5], D[5], E[5], F[5];\n  long double *tb, *r;\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_tb_6_4t: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t6 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  b21 (tb) = r[2];\n  t3 (tb) = r[3];\n  b31 (tb) = r[4];\n  b32 (tb) = r[5];\n  t4 (tb) = r[6];\n  b41 (tb) = r[7];\n  b42 (tb) = r[8];\n  b43 (tb) = r[9];\n  t5 (tb) = r[10];\n  b54 (tb) = r[11];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = t4 (tb);\n  E[0] = t5 (tb);\n  F[0] = 0.5L;\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = D[0] * t4 (tb);\n  E[1] = E[0] * t5 (tb);\n  F[1] = 1.L / 3.L;\n  A[2] = A[1] * t1 (tb);\n  B[2] = B[1] * t2 (tb);\n  C[2] = C[1] * t3 (tb);\n  D[2] = D[1] * t4 (tb);\n  E[2] = E[1] * t5 (tb);\n  F[2] = 0.25L;\n  A[3] = A[2] * t1 (tb);\n  B[3] = B[2] * t2 (tb);\n  C[3] = C[2] * t3 (tb);\n  D[3] = D[2] * t4 (tb);\n  E[3] = E[2] * t5 (tb);\n  F[3] = 0.2L;\n  A[4] = A[3] * t1 (tb);\n  B[4] = B[3] * t2 (tb);\n  C[4] = C[3] * t3 (tb);\n  D[4] = D[3] * t4 (tb);\n  E[4] = E[3] * t5 (tb);\n  F[4] = 1.L / 6.L;\n  solve_5 (A, B, C, D, E, F);\n  if (isnan (F[0]) || isnan (F[1]) || isnan (F[2]) || isnan (F[3])\n      || isnan (F[4]))\n    return 0;\n  b65 (tb) = F[4];\n  b64 (tb) = F[3];\n  b63 (tb) = F[2];\n  b62 (tb) = F[1];\n  b61 (tb) = F[0];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = (1.L / 6.L - b62 (tb) * b21 (tb) * t1 (tb)\n          - b63 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))\n          - b64 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)\n                        + b43 (tb) * t3 (tb))) / b65 (tb) - b54 (tb) * t4 (tb);\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = (1.L / 12.L - b62 (tb) * b21 (tb) * sqr (t1 (tb))\n          - b63 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)))\n          - b64 (tb) * (b41 (tb) * sqr (t1 (tb)) + b42 (tb) * sqr (t2 (tb))\n                        + b43 (tb) * sqr (t3 (tb)))) / b65 (tb)\n    - b54 (tb) * sqr (t4 (tb));\n  A[2] = 0.L;\n  B[2] = b21 (tb) * t1 (tb);\n  C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);\n  D[2] = (1.L / 24.L - b63 (tb) * b32 (tb) * b21 (tb) * t1 (tb)\n          - b64 (tb) * (b42 (tb) * b21 (tb) * t1 (tb)\n                        + b43 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))))\n    / b65 (tb) - b54 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)\n                             + b43 (tb) * t3 (tb));\n  solve_3 (A, B, C, D);\n  if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))\n    return 0;\n  b53 (tb) = D[2];\n  b52 (tb) = D[1];\n  b51 (tb) = D[0];\n  rk_b_6 (tb);\n#if DEBUG_RK_6_4\n  rk_print_tb (optimize, \"rk_tb_6_4t\", stderr);\n  fprintf (stderr, \"rk_tb_6_4t: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 6 steps 3th-4th order Runge-Kutta \n * pair.\n */\nint\nrk_tb_6_4p (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4], AA[4], BB[4], CC[4], DD[4], EE[4];\n  long double *tb, *r;\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_tb_6_4p: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t6 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  b21 (tb) = r[2];\n  t3 (tb) = r[3];\n  b31 (tb) = r[4];\n  b32 (tb) = r[5];\n  t4 (tb) = r[6];\n  b41 (tb) = r[7];\n  b42 (tb) = r[8];\n  b43 (tb) = r[9];\n  t5 (tb) = r[10];\n  b54 (tb) = r[11];\n  b65 (tb) = r[12];\n  A[0] = AA[0] = t1 (tb);\n  B[0] = BB[0] = t2 (tb);\n  C[0] = CC[0] = t3 (tb);\n  D[0] = DD[0] = t4 (tb);\n  EE[0] = 0.5L;\n  E[0] = 0.5L - b65 (tb) * t5 (tb);\n  A[1] = AA[1] = A[0] * t1 (tb);\n  B[1] = BB[1] = B[0] * t2 (tb);\n  C[1] = CC[1] = C[0] * t3 (tb);\n  D[1] = DD[1] = D[0] * t4 (tb);\n  EE[1] = 1.L / 3.L;\n  E[1] = 1.L / 3.L - b65 (tb) * sqr (t5 (tb));\n  A[2] = AA[2] = A[1] * t1 (tb);\n  B[2] = BB[2] = B[1] * t2 (tb);\n  C[2] = CC[2] = C[1] * t3 (tb);\n  D[2] = DD[2] = D[1] * t4 (tb);\n  EE[2] = 0.25L;\n  E[2] = 0.25L - b65 (tb) * sqr (t5 (tb)) * t5 (tb);\n  A[3] = AA[3] = 0.L;\n  BB[3] = b21 (tb) * t1 (tb);\n  B[3] = BB[3] * (t2 (tb) - t5 (tb));\n  CC[3] = (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));\n  C[3] = CC[3] * (t3 (tb) - t5 (tb));\n  DD[3] = (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb) + b43 (tb) * t3 (tb));\n  D[3] = DD[3] * (t4 (tb) - t5 (tb));\n  EE[3] = 1.L / 6.L;\n  E[3] = 0.125L - 1.L / 6.L * t5 (tb);\n  solve_4 (A, B, C, D, E);\n  if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))\n    return 0;\n  b64 (tb) = E[3];\n  b63 (tb) = E[2];\n  b62 (tb) = E[1];\n  b61 (tb) = E[0];\n  solve_4 (AA, BB, CC, DD, EE);\n  if (isnan (EE[0]) || isnan (EE[1]) || isnan (EE[2]) || isnan (EE[3]))\n    return 0;\n  e64 (tb) = EE[3];\n  e63 (tb) = EE[2];\n  e62 (tb) = EE[1];\n  e61 (tb) = EE[0];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = (1.L / 6.L - b62 (tb) * b21 (tb) * t1 (tb)\n          - b63 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))\n          - b64 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)\n                        + b43 (tb) * t3 (tb))) / b65 (tb) - b54 (tb) * t4 (tb);\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = (1.L / 12.L - b62 (tb) * b21 (tb) * sqr (t1 (tb))\n          - b63 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)))\n          - b64 (tb) * (b41 (tb) * sqr (t1 (tb)) + b42 (tb) * sqr (t2 (tb))\n                        + b43 (tb) * sqr (t3 (tb)))) / b65 (tb)\n    - b54 (tb) * sqr (t4 (tb));\n  A[2] = 0.L;\n  B[2] = b21 (tb) * t1 (tb);\n  C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);\n  D[2] = (1.L / 24.L - b63 (tb) * b32 (tb) * b21 (tb) * t1 (tb)\n          - b64 (tb) * (b42 (tb) * b21 (tb) * t1 (tb)\n                        + b43 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))))\n    / b65 (tb) - b54 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)\n                             + b43 (tb) * t3 (tb));\n  solve_3 (A, B, C, D);\n  if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))\n    return 0;\n  b53 (tb) = D[2];\n  b52 (tb) = D[1];\n  b51 (tb) = D[0];\n  rk_b_6 (tb);\n  rk_e_6 (tb);\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_tb_6_4p: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 6 steps 3rd-4th order, 4th-5th order\n * in equations depending only on time, Runge-Kutta method.\n */\nint\nrk_tb_6_4tp (Optimize * optimize)       ///< Optimize struct.\n{\n  long double A[5], B[5], C[5], D[5], E[5], F[5], AA[4], BB[4], CC[4], DD[4],\n    EE[4];\n  long double *tb, *r;\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_tb_6_4tp: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t6 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  t3 (tb) = r[2];\n  b31 (tb) = r[3];\n  b32 (tb) = r[4];\n  t4 (tb) = r[5];\n  b41 (tb) = r[6];\n  b42 (tb) = r[7];\n  b43 (tb) = r[8];\n  t5 (tb) = r[9];\n  b54 (tb) = r[10];\n  b65 (tb) = r[11];\n  A[0] = AA[0] = t1 (tb);\n  B[0] = BB[0] = t2 (tb);\n  C[0] = CC[0] = t3 (tb);\n  D[0] = DD[0] = t4 (tb);\n  E[0] = t5 (tb);\n  F[0] = EE[0] = 0.5L;\n  A[1] = AA[1] = A[0] * t1 (tb);\n  B[1] = BB[1] = B[0] * t2 (tb);\n  C[1] = CC[1] = C[0] * t3 (tb);\n  D[1] = DD[1] = D[0] * t4 (tb);\n  E[1] = E[0] * t5 (tb);\n  F[1] = EE[1] = 1.L / 3.L;\n  A[2] = AA[2] = A[1] * t1 (tb);\n  B[2] = BB[2] = B[1] * t2 (tb);\n  C[2] = CC[2] = C[1] * t3 (tb);\n  D[2] = DD[2] = D[1] * t4 (tb);\n  E[2] = E[1] * t5 (tb);\n  F[2] = EE[2] = 0.25L;\n  A[3] = AA[3] = A[2] * t1 (tb);\n  B[3] = BB[3] = B[2] * t2 (tb);\n  C[3] = CC[3] = C[2] * t3 (tb);\n  D[3] = DD[3] = D[2] * t4 (tb);\n  E[3] = E[2] * t5 (tb);\n  F[3] = EE[3] = 0.2L;\n  A[4] = A[3] * t1 (tb);\n  B[4] = B[3] * t2 (tb);\n  C[4] = C[3] * t3 (tb);\n  D[4] = D[3] * t4 (tb);\n  E[4] = E[3] * t5 (tb);\n  F[4] = 1.L / 6.L;\n  solve_4 (AA, BB, CC, DD, EE);\n  if (isnan (EE[0]) || isnan (EE[1]) || isnan (EE[2]) || isnan (EE[3]))\n    return 0;\n  e64 (tb) = EE[3];\n  e63 (tb) = EE[2];\n  e62 (tb) = EE[1];\n  e61 (tb) = EE[0];\n  solve_5 (A, B, C, D, E, F);\n  if (isnan (F[0]) || isnan (F[1]) || isnan (F[2]) || isnan (F[3])\n      || isnan (F[4]))\n    return 0;\n  b65 (tb) = F[4];\n  b64 (tb) = F[3];\n  b63 (tb) = F[2];\n  b62 (tb) = F[1];\n  b61 (tb) = F[0];\n  b21 (tb) = (1.L / 6.L - e63 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))\n              - e64 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)\n                            + b43 (tb) * t3 (tb))) / (e62 (tb) * t1 (tb));\n  if (isnan (b21 (tb)))\n    return 0;\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = (1.L / 6.L - b62 (tb) * b21 (tb) * t1 (tb)\n          - b63 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))\n          - b64 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)\n                        + b43 (tb) * t3 (tb))) / b65 (tb) - b54 (tb) * t4 (tb);\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = (1.L / 12.L - b62 (tb) * b21 (tb) * sqr (t1 (tb))\n          - b63 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)))\n          - b64 (tb) * (b41 (tb) * sqr (t1 (tb)) + b42 (tb) * sqr (t2 (tb))\n                        + b43 (tb) * sqr (t3 (tb)))) / b65 (tb)\n    - b54 (tb) * sqr (t4 (tb));\n  A[2] = 0.L;\n  B[2] = b21 (tb) * t1 (tb);\n  C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);\n  D[2] = (1.L / 24.L - b63 (tb) * b32 (tb) * b21 (tb) * t1 (tb)\n          - b64 (tb) * (b42 (tb) * b21 (tb) * t1 (tb)\n                        + b43 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb))))\n    / b65 (tb) - b54 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)\n                             + b43 (tb) * t3 (tb));\n  solve_3 (A, B, C, D);\n  if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))\n    return 0;\n  b53 (tb) = D[2];\n  b52 (tb) = D[1];\n  b51 (tb) = D[0];\n  rk_b_6 (tb);\n#if DEBUG_RK_6_4\n  rk_print_tb (optimize, \"rk_tb_6_4t\", stderr);\n  fprintf (stderr, \"rk_tb_6_4t: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to calculate the objective function of a 6 steps 4th order \n * Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_6_4 (RK * rk)   ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_objective_tb_6_4: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (b60 (tb) < 0.L)\n    o += b60 (tb);\n  if (b61 (tb) < 0.L)\n    o += b61 (tb);\n  if (b62 (tb) < 0.L)\n    o += b62 (tb);\n  if (b63 (tb) < 0.L)\n    o += b63 (tb);\n  if (b64 (tb) < 0.L)\n    o += b64 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L,\n             fmaxl (t1 (tb),\n                    fmaxl (t2 (tb),\n                           fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_objective_tb_6_4: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_6_4: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 6 steps 4th order, 5th\n * order in equations depending only on time, Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_6_4t (RK * rk)  ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_objective_tb_6_4t: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n#if DEBUG_RK_6_4\n  rk_print_tb (optimize, \"rk_objective_tb_6_4t\", stderr);\n#endif\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (b60 (tb) < 0.L)\n    o += b60 (tb);\n  if (b61 (tb) < 0.L)\n    o += b61 (tb);\n  if (b62 (tb) < 0.L)\n    o += b62 (tb);\n  if (b63 (tb) < 0.L)\n    o += b63 (tb);\n  if (b64 (tb) < 0.L)\n    o += b64 (tb);\n  if (b65 (tb) < 0.L)\n    o += b65 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L,\n             fmaxl (t1 (tb),\n                    fmaxl (t2 (tb),\n                           fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_objective_tb_6_4t: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_6_4t: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 6 steps 3rd-4th order \n * Runge-Kutta pair.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_6_4p (RK * rk)  ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_objective_tb_6_4p: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (b60 (tb) < 0.L)\n    o += b60 (tb);\n  if (b61 (tb) < 0.L)\n    o += b61 (tb);\n  if (b62 (tb) < 0.L)\n    o += b62 (tb);\n  if (b63 (tb) < 0.L)\n    o += b63 (tb);\n  if (b64 (tb) < 0.L)\n    o += b64 (tb);\n  if (e60 (tb) < 0.L)\n    o += e60 (tb);\n  if (e61 (tb) < 0.L)\n    o += e61 (tb);\n  if (e62 (tb) < 0.L)\n    o += e62 (tb);\n  if (e63 (tb) < 0.L)\n    o += e63 (tb);\n  if (e64 (tb) < 0.L)\n    o += e64 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L,\n             fmaxl (t1 (tb),\n                    fmaxl (t2 (tb),\n                           fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_objective_tb_6_4p: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_6_4p: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 6 steps 3rd-4th order,\n * 4th-5th order in equations depending only in time, Runge-Kutta pair.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_6_4tp (RK * rk) ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_objective_tb_6_4tp: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n#if DEBUG_RK_6_4\n  rk_print_tb (optimize, \"rk_objective_tb_6_4tp\", stderr);\n#endif\n  o = fminl (0.L, b20 (tb));\n  if (b21 (tb) < 0.L)\n    o += b21 (tb);\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (b60 (tb) < 0.L)\n    o += b60 (tb);\n  if (b61 (tb) < 0.L)\n    o += b61 (tb);\n  if (b62 (tb) < 0.L)\n    o += b62 (tb);\n  if (b63 (tb) < 0.L)\n    o += b63 (tb);\n  if (b64 (tb) < 0.L)\n    o += b64 (tb);\n  if (b65 (tb) < 0.L)\n    o += b65 (tb);\n  if (e60 (tb) < 0.L)\n    o += e60 (tb);\n  if (e61 (tb) < 0.L)\n    o += e61 (tb);\n  if (e62 (tb) < 0.L)\n    o += e62 (tb);\n  if (e63 (tb) < 0.L)\n    o += e63 (tb);\n  if (e64 (tb) < 0.L)\n    o += e64 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L,\n             fmaxl (t1 (tb),\n                    fmaxl (t2 (tb),\n                           fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_6_4\n  fprintf (stderr, \"rk_objective_tb_6_4tp: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_6_4tp: end\\n\");\n#endif\n  return o;\n}\n", "meta": {"hexsha": "9e3438664d501d13220fce89a4c50e21b3d46ca2", "size": 20573, "ext": "c", "lang": "C", "max_stars_repo_path": "rk_6_4.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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": "rk_6_4.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk_6_4.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7638326586, "max_line_length": 80, "alphanum_fraction": 0.4639576143, "num_tokens": 9525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.39822663074977227}}
{"text": "/*\n * mutation.h\n *\n *  Created on: 17.5.2017\n *      Author: heine\n */\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#ifndef MUTATION_H_\n#define MUTATION_H_\n\n//void set_mutationseed( int id );\nvoid \nmutation( \n\t long N, \n\t double *x, \n\t int state_dim, \n\t gsl_rng * rgen );\n\n#endif /* MUTATION_H_ */\n", "meta": {"hexsha": "c42a45aeafab25b111e10a49634fef30854cf6a2", "size": 309, "ext": "h", "lang": "C", "max_stars_repo_path": "include/mutation.h", "max_stars_repo_name": "heinekmp/AIRPF", "max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z", "max_issues_repo_path": "include/mutation.h", "max_issues_repo_name": "heinekmp/AIRPF", "max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mutation.h", "max_forks_repo_name": "heinekmp/AIRPF", "max_forks_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_forks_repo_licenses": ["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.0454545455, "max_line_length": 34, "alphanum_fraction": 0.640776699, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.39822662247427704}}
{"text": "#ifndef __CNN_CONV_H__\n#define __CNN_CONV_H__\n\n#include <cblas.h>\n#include <string.h>\n\n#include \"cnn_macro.h\"\n#include \"cnn_types.h\"\n\n#ifdef CNN_WITH_CUDA\n#include <cublas_v2.h>\n#include <cuda_runtime.h>\n\n#include \"cnn_init.h\"\n\nvoid cnn_map_gpu(float* dst, float* src, int* map, int len);\nvoid cnn_map_inv_gpu(float* dst, float* src, int* map, int len);\n#endif\n\nstatic inline void cnn_conv_unroll_2d_valid(int* indexMap, int dstHeight,\n                                            int dstWidth, int kSize,\n                                            int srcHeight, int srcWidth,\n                                            int srcCh)\n{\n    int __kMemSize = kSize * kSize;\n    int __srcImSize = srcHeight * srcWidth;\n    int __indexMapCols = __kMemSize * srcCh;\n\n    for (int __h = 0; __h < dstHeight; __h++)\n    {\n        int __dstRowShift = __h * dstWidth;\n\n        for (int __w = 0; __w < dstWidth; __w++)\n        {\n            int __indexMapRow = __dstRowShift + __w;\n            int __indexMemBase = __indexMapRow * __indexMapCols;\n\n            for (int __ch = 0; __ch < srcCh; __ch++)\n            {\n                int __indexMemShiftBase = __indexMemBase + __kMemSize * __ch;\n                int __srcChShift = __ch * __srcImSize;\n\n                for (int __convH = 0; __convH < kSize; __convH++)\n                {\n                    int __indexMemShift = __indexMemShiftBase + __convH * kSize;\n                    int __srcShift = (__h + __convH) * srcWidth + __srcChShift;\n\n                    for (int __convW = 0; __convW < kSize; __convW++)\n                    {\n                        indexMap[__indexMemShift + __convW] =\n                            __srcShift + (__w + __convW);\n                    }\n                }\n            }\n        }\n    }\n}\n\nstatic inline void cnn_conv_unroll_2d_same(int* indexMap, int dstHeight,\n                                           int dstWidth, int kSize,\n                                           int srcHeight, int srcWidth,\n                                           int srcCh)\n{\n    int __kMemSize = kSize * kSize;\n    int __srcImSize = srcHeight * srcWidth;\n    int __indexMapCols = __kMemSize * srcCh;\n\n    int __convHBase = -kSize / 2;\n    int __convWBase = -kSize / 2;\n\n    for (int __h = 0; __h < dstHeight; __h++)\n    {\n        int __dstRowShift = __h * dstWidth;\n\n        for (int __w = 0; __w < dstWidth; __w++)\n        {\n            int __indexMapRow = __dstRowShift + __w;\n            int __indexMemBase = __indexMapRow * __indexMapCols;\n\n            for (int __ch = 0; __ch < srcCh; __ch++)\n            {\n                int __indexMemShiftBase = __indexMemBase + __kMemSize * __ch;\n                int __srcChShift = __ch * __srcImSize;\n\n                for (int __convH = 0; __convH < kSize; __convH++)\n                {\n                    int __indexMemShift = __indexMemShiftBase + __convH * kSize;\n                    int __convHIndex = __h + __convH + __convHBase;\n\n                    if (__convHIndex >= 0 && __convHIndex < srcHeight)\n                    {\n                        int __srcShift = __convHIndex * srcWidth + __srcChShift;\n\n                        for (int __convW = 0; __convW < kSize; __convW++)\n                        {\n                            int __convWIndex = __w + __convW + __convWBase;\n                            if (__convWIndex >= 0 && __convWIndex < srcWidth)\n                            {\n                                int __tmpIndex = __srcShift + __convWIndex;\n\n                                indexMap[__indexMemShift + __convW] =\n                                    __tmpIndex;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nstatic inline void cnn_conv_2d(float* dst, int dstHeight, int dstWidth,\n                               float* kernel, int kSize, int chIn, int chOut,\n                               float* src, int srcHeight, int srcWidth)\n{\n    int __kMemSize = kSize * kSize;\n    int __filterSize = chIn * __kMemSize;\n    int __dstImSize = dstHeight * dstWidth;\n    int __srcImSize = srcHeight * srcWidth;\n\n    for (int __chOut = 0; __chOut < chOut; __chOut++)\n    {\n        int __filterShift = __chOut * __filterSize;\n        int __dstChShift = __chOut * __dstImSize;\n\n        for (int __chIn = 0; __chIn < chIn; __chIn++)\n        {\n            int __kShiftBase = __chIn * __kMemSize + __filterShift;\n            int __srcChShift = __chIn * __srcImSize;\n\n            for (int __h = 0; __h < dstHeight; __h++)\n            {\n                int __dstShift = __h * dstWidth + __dstChShift;\n                for (int __w = 0; __w < dstWidth; __w++)\n                {\n                    float __conv = 0;\n                    for (int __convH = 0; __convH < kSize; __convH++)\n                    {\n                        int __kShift = __convH * kSize + __kShiftBase;\n                        int __srcShift =\n                            (__h + __convH) * srcWidth + __srcChShift;\n\n                        for (int __convW = 0; __convW < kSize; __convW++)\n                        {\n                            __conv += kernel[__kShift + __convW] *\n                                      src[__srcShift + (__w + __convW)];\n                        }\n                    }\n\n                    dst[__dstShift + __w] += __conv;\n                }\n            }\n        }\n    }\n}\n\nstatic inline void cnn_conv_2d_grad(float* srcGrad, int srcHeight, int srcWidth,\n                                    float* kernel, int kSize, int srcCh,\n                                    int lCh, float* lGrad, int lHeight,\n                                    int lWidth)\n{\n    int __kMemSize = kSize * kSize;\n    int __filterSize = srcCh * __kMemSize;\n    int __lImSize = lHeight * lWidth;\n    int __srcImSize = srcHeight * srcWidth;\n\n    for (int __lCh = 0; __lCh < lCh; __lCh++)\n    {\n        int __filterShift = __lCh * __filterSize;\n        int __lChShift = __lCh * __lImSize;\n\n        for (int __srcCh = 0; __srcCh < srcCh; __srcCh++)\n        {\n            int __srcChShift = __srcCh * __srcImSize;\n            int __kShiftBase = __srcCh * __kMemSize + __filterShift;\n\n            for (int __h = 0; __h < lHeight; __h++)\n            {\n                int __lShift = __h * lHeight + __lChShift;\n                for (int __w = 0; __w < lWidth; __w++)\n                {\n                    for (int __convH = 0; __convH < kSize; __convH++)\n                    {\n                        int __kShift = __convH * kSize + __kShiftBase;\n                        int __srcShift =\n                            (__h + __convH) * srcWidth + __srcChShift;\n\n                        for (int __convW = 0; __convW < kSize; __convW++)\n                        {\n                            srcGrad[__srcShift + (__w + __convW)] +=\n                                lGrad[__lShift + __w] *\n                                kernel[__kShift + __convW];\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nstatic inline void cnn_conv_2d_kernel_grad(float* lGrad, int lHeight,\n                                           int lWidth, float* kGrad, int kSize,\n                                           int lCh, int srcCh, float* src,\n                                           int srcHeight, int srcWidth)\n{\n    int __kMemSize = kSize * kSize;\n    int __filterSize = srcCh * __kMemSize;\n    int __lImSize = lHeight * lWidth;\n    int __srcImSize = srcHeight * srcWidth;\n\n    for (int __lCh = 0; __lCh < lCh; __lCh++)\n    {\n        int __filterShift = __lCh * __filterSize;\n        int __lChShift = __lCh * __lImSize;\n\n        for (int __srcCh = 0; __srcCh < srcCh; __srcCh++)\n        {\n            int __srcChShift = __srcCh * __srcImSize;\n            int __kShiftBase = __srcCh * __kMemSize + __filterShift;\n\n            for (int __h = 0; __h < lHeight; __h++)\n            {\n                int __lShift = __h * lWidth + __lChShift;\n                for (int __w = 0; __w < lWidth; __w++)\n                {\n                    for (int __convH = 0; __convH < kSize; __convH++)\n                    {\n                        int __kShift = __convH * kSize + __kShiftBase;\n                        int __srcShift =\n                            (__h + __convH) * srcWidth + __srcChShift;\n\n                        for (int __convW = 0; __convW < kSize; __convW++)\n                        {\n                            kGrad[__kShift + __convW] +=\n                                lGrad[__lShift + __w] *\n                                src[__srcShift + (__w + __convW)];\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nstatic inline void cnn_forward_conv(union CNN_LAYER* layerRef,\n                                    struct CNN_CONFIG* cfgRef, int layerIndex)\n{\n#ifdef CNN_WITH_CUDA\n    float alpha = 1.0;\n    float beta = 0.0;\n\n    struct CNN_LAYER_CONV* layerPtr = &layerRef[layerIndex].conv;\n\n    struct CNN_MAT* outData = &layerPtr->outMat.data;\n    struct CNN_MAT* preOutData = &layerRef[layerIndex - 1].outMat.data;\n\n    cnn_assert_cudnn(cudnnConvolutionForward(\n        cnnInit.cudnnHandle,                        //\n        &alpha,                                     //\n        layerPtr->srcTen, preOutData->mat,          //\n        layerPtr->kernelTen, layerPtr->kernel.mat,  //\n        layerPtr->convDesc, layerPtr->convAlgoFW, cnnInit.wsData,\n        cnnInit.wsSize,  //\n        &beta,           //\n        layerPtr->dstTen, outData->mat));\n\n#if defined(CNN_CONV_BIAS_FILTER)\n    beta = 1.0;\n    cnn_assert_cudnn(cudnnAddTensor(cnnInit.cudnnHandle,                    //\n                                    &alpha,                                 //\n                                    layerPtr->biasTen, layerPtr->bias.mat,  //\n                                    &beta,                                  //\n                                    layerPtr->dstTen, outData->mat));\n#endif\n\n#else\n    // Cache\n    int mapRows =\n        layerRef[layerIndex].outMat.width * layerRef[layerIndex].outMat.height;\n    int mapCols = layerRef[layerIndex - 1].outMat.channel *\n                  cfgRef->layerCfg[layerIndex].conv.size *\n                  cfgRef->layerCfg[layerIndex].conv.size;\n    int mapSize = mapRows * mapCols;\n    int* indexMap = layerRef[layerIndex].conv.indexMap;\n\n    int chOut = layerRef[layerIndex].outMat.channel;\n    float* kernel = layerRef[layerIndex].conv.kernel.mat;\n\n    // Clear outputs\n    // memset(layerRef[layerIndex].outMat.data.mat, 0,\n    //       sizeof(float) * layerRef[layerIndex].outMat.data.rows *\n    //           layerRef[layerIndex].outMat.data.cols);\n\n    for (int j = 0; j < cfgRef->batch; j++)\n    {\n        int srcShift = j * layerRef[layerIndex - 1].outMat.data.cols;\n        int dstShift = j * layerRef[layerIndex].outMat.data.cols;\n        int mapShift = j * mapSize;\n\n        float* srcPtr = layerRef[layerIndex - 1].outMat.data.mat + srcShift;\n        float* dstPtr = layerRef[layerIndex].outMat.data.mat + dstShift;\n        float* mapPtr = layerRef[layerIndex].conv.unroll.mat + mapShift;\n\n        for (int k = 0; k < mapSize; k++)\n        {\n            int tmpIndex = indexMap[k];\n            if (tmpIndex >= 0)\n            {\n                mapPtr[k] = srcPtr[tmpIndex];\n            }\n        }\n\n        cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, chOut, mapRows,\n                    mapCols, 1.0, kernel, mapCols, mapPtr, mapCols, 0.0, dstPtr,\n                    mapRows);\n\n        // Add bias\n#if defined(CNN_CONV_BIAS_FILTER)\n#ifdef DEBUG\n#pragma message(\"cnn_forward_conv(): Enable convolution filter bias\")\n#endif\n        for (int ch = 0; ch < chOut; ch++)\n        {\n            cblas_saxpy(\n                mapRows, 1.0, &layerRef[layerIndex].conv.bias.mat[ch], 0,\n                &layerRef[layerIndex].outMat.data.mat[dstShift + ch * mapRows],\n                1);\n        }\n#elif defined(CNN_CONV_BIAS_LAYER)\n#ifdef DEBUG\n#pragma message(\"cnn_forward_conv(): Enable convolution layer bias\")\n#endif\n        cblas_saxpy(layerRef[layerIndex].conv.bias.cols, 1.0,\n                    layerRef[layerIndex].conv.bias.mat, 1,\n                    &layerRef[layerIndex].outMat.data.mat[dstShift], 1);\n#endif\n    }\n#endif\n}\n\nstatic inline void cnn_backward_conv(union CNN_LAYER* layerRef,\n                                     struct CNN_CONFIG* cfgRef, int layerIndex)\n{\n#ifdef CNN_WITH_CUDA\n    float alpha = 1.0;\n    float beta = 1.0;\n\n    struct CNN_LAYER_CONV* layerPtr = &layerRef[layerIndex].conv;\n\n    struct CNN_MAT* outData = &layerPtr->outMat.data;\n    struct CNN_MAT* preOutData = &layerRef[layerIndex - 1].outMat.data;\n\n    cnn_assert_cudnn(cudnnConvolutionBackwardFilter(\n        cnnInit.cudnnHandle,                //\n        &alpha,                             //\n        layerPtr->srcTen, preOutData->mat,  //\n        layerPtr->dstTen, outData->grad,    //\n        layerPtr->convDesc, layerPtr->convAlgoBWFilter, cnnInit.wsData,\n        cnnInit.wsSize,  //\n        &beta,           //\n        layerPtr->kernelTen, layerPtr->kernel.grad));\n\n    cnn_assert_cudnn(\n        cudnnConvolutionBackwardBias(cnnInit.cudnnHandle,              //\n                                     &alpha,                           //\n                                     layerPtr->dstTen, outData->grad,  //\n                                     &beta,                            //\n                                     layerPtr->biasTen, layerPtr->bias.grad));\n\n#else\n    // Cache\n    int mapRows =\n        layerRef[layerIndex].outMat.width * layerRef[layerIndex].outMat.height;\n    int mapCols = layerRef[layerIndex - 1].outMat.channel *\n                  cfgRef->layerCfg[layerIndex].conv.size *\n                  cfgRef->layerCfg[layerIndex].conv.size;\n    int mapSize = mapRows * mapCols;\n\n    int* indexMap = layerRef[layerIndex].conv.indexMap;\n\n    int chOut = layerRef[layerIndex].outMat.channel;\n    float* kernel = layerRef[layerIndex].conv.kernel.mat;\n    float* kGrad = layerRef[layerIndex].conv.kernel.grad;\n\n    // Sum gradient\n    for (int j = 0; j < cfgRef->batch; j++)\n    {\n        int gradShift = j * layerRef[layerIndex].outMat.data.cols;\n        int mapShift = j * mapSize;\n\n        float* gradPtr = &layerRef[layerIndex].outMat.data.grad[gradShift];\n        float* mapPtr = &layerRef[layerIndex].conv.unroll.mat[mapShift];\n\n        cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, chOut, mapCols,\n                    mapRows, 1.0, gradPtr, mapRows, mapPtr, mapCols, 1.0, kGrad,\n                    mapCols);\n\n        // Sum bias gradient matrix\n#if defined(CNN_CONV_BIAS_FILTER)\n#ifdef DEBUG\n#pragma message(\"cnn_forward_conv(): Enable convolution filter bias\")\n#endif\n        for (int ch = 0; ch < chOut; ch++)\n        {\n            cblas_saxpy(mapRows, 1.0, &gradPtr[ch * mapRows], 1,\n                        &layerRef[layerIndex].conv.bias.grad[ch], 0);\n        }\n#elif defined(CNN_CONV_BIAS_LAYER)\n#ifdef DEBUG\n#pragma message(\"cnn_forward_conv(): Enable convolution layer bias\")\n#endif\n        cblas_saxpy(layerRef[layerIndex].conv.bias.cols, 1.0, gradPtr, 1,\n                    layerRef[layerIndex].conv.bias.grad, 1);\n#endif\n    }\n#endif\n\n    // Find layer gradient\n    if (layerIndex > 1)\n    {\n#ifdef CNN_WITH_CUDA\n        cudaMemset(preOutData->grad, 0,\n                   sizeof(float) * preOutData->rows * preOutData->cols);\n        beta = 0.0;\n        cnn_assert_cudnn(cudnnConvolutionBackwardData(\n            cnnInit.cudnnHandle,                        //\n            &alpha,                                     //\n            layerPtr->kernelTen, layerPtr->kernel.mat,  //\n            layerPtr->dstTen, outData->grad,            //\n            layerPtr->convDesc, layerPtr->convAlgoBWGrad, cnnInit.wsData,\n            cnnInit.wsSize,  //\n            &beta,           //\n            layerPtr->srcTen, preOutData->grad));\n#else\n        memset(layerRef[layerIndex - 1].outMat.data.grad, 0,\n               sizeof(float) * layerRef[layerIndex - 1].outMat.data.rows *\n                   layerRef[layerIndex - 1].outMat.data.cols);\n        for (int j = 0; j < cfgRef->batch; j++)\n        {\n            int gradShift = j * layerRef[layerIndex].outMat.data.cols;\n            int preGradShift = j * layerRef[layerIndex - 1].outMat.data.cols;\n            int mapShift = j * mapSize;\n\n            float* gradPtr = layerRef[layerIndex].outMat.data.grad + gradShift;\n            float* preGradPtr =\n                layerRef[layerIndex - 1].outMat.data.grad + preGradShift;\n            float* mapPtr = layerRef[layerIndex].conv.unroll.grad + mapShift;\n\n            cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, mapRows,\n                        mapCols, chOut, 1.0, gradPtr, mapRows, kernel, mapCols,\n                        0.0, mapPtr, mapCols);\n\n            for (int i = 0; i < mapSize; i++)\n            {\n                int tmpIndex = indexMap[i];\n                if (tmpIndex >= 0)\n                {\n                    preGradPtr[tmpIndex] += mapPtr[i];\n                }\n            }\n        }\n#endif\n    }\n}\n\n#endif\n", "meta": {"hexsha": "a70d0ada64716f016554db044f70ff0674b9c160", "size": 17068, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cnn_conv.h", "max_stars_repo_name": "jamesljlster/cnn", "max_stars_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-15T07:47:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-15T07:47:10.000Z", "max_issues_repo_path": "src/cnn_conv.h", "max_issues_repo_name": "jamesljlster/cnn", "max_issues_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "max_issues_repo_licenses": ["MIT"], "max_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_conv.h", "max_forks_repo_name": "jamesljlster/cnn", "max_forks_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630", "max_forks_repo_licenses": ["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.5481798715, "max_line_length": 80, "alphanum_fraction": 0.5062104523, "num_tokens": 4297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3981400300429889}}
{"text": "#ifndef wf_H_INCLUDED\n#define wf_H_INCLUDED\n\n//#define DEBUG\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_integration.h>\n#include \"alphas.h\"\n\n//*\n// Global variables for UGD for nucleus 1 and 2\n//*\n\n//run at fixed x\n//#define fixedx (0.001)\n\n//number of tabulated points in Y and kT for wavefunction\n#define NY 151\n#define Nkt 101\n#define kT_min (0.02)   // phi=0 below this min kt\n#define kT_max (18.)    // phi has a power lower extrapolation \n                        // beyond this max kt\n\n#define x0 (0.01)       // separates small/large x\n#define XMIN (x0*exp(-15.)) //smallest x tabulated\n\n// Global variables for UGD for nucleus 1 and 2\nint wfTAG;\ndouble uGD1[NY][Nkt];\ndouble uGD2[NY][Nkt];\ndouble Y[NY];\ndouble kT[NY][Nkt];\ngsl_interp_accel *accWF1[NY];\ngsl_spline *WF1[NY];\ngsl_interp_accel *accWF2[NY];\ngsl_spline *WF2[NY];\ngsl_interp_accel *accLargeX;\ngsl_spline *LargeX;\n//global variable for wfTAG=2\n#define QS02 (0.1)\ndouble QS21, QS22;\n\nvoid ReadInWF(int A1, int A2, int TAG);\ndouble wf(int nucleus, double x, double kT) ;\ndouble wfsimple(int nucleus, double x, double kT) ;\nvoid PrintWF(double x, const char *out) ;\n\n#endif\n", "meta": {"hexsha": "608456801e801320c1fc5fc6549e167001af26d3", "size": 1220, "ext": "h", "lang": "C", "max_stars_repo_path": "src/wf.h", "max_stars_repo_name": "kdusling/mpc", "max_stars_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wf.h", "max_issues_repo_name": "kdusling/mpc", "max_issues_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wf.h", "max_forks_repo_name": "kdusling/mpc", "max_forks_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_forks_repo_licenses": ["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.0188679245, "max_line_length": 63, "alphanum_fraction": 0.6983606557, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3979778738949654}}
{"text": "/* bspline/gsl_bspline.h\n *\n * Copyright (C) 2006 Patrick Alken\n * Copyright (C) 2008 Rhys Ulerich\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 (at\n * your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_BSPLINE_H__\n#define __GSL_BSPLINE_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct\n{\n    size_t k;      /* spline order */\n    size_t km1;    /* k - 1 (polynomial order) */\n    size_t l;      /* number of polynomial pieces on interval */\n    size_t nbreak; /* number of breakpoints (l + 1) */\n    size_t n;      /* number of bspline basis functions (l + k - 1) */\n\n    gsl_vector *knots;  /* knots vector */\n    gsl_vector *deltal; /* left delta */\n    gsl_vector *deltar; /* right delta */\n    gsl_vector *B;      /* temporary spline results */\n\n    /* bspline derivative parameters */\n    gsl_matrix *A;      /* work matrix */\n    gsl_matrix *dB;     /* temporary derivative results */\n} gsl_bspline_workspace;\n\nGSL_FUN gsl_bspline_workspace *\ngsl_bspline_alloc(const size_t k, const size_t nbreak);\n\nGSL_FUN void gsl_bspline_free(gsl_bspline_workspace *w);\n\nGSL_FUN size_t gsl_bspline_ncoeffs(gsl_bspline_workspace * w);\nGSL_FUN size_t gsl_bspline_order(gsl_bspline_workspace * w);\nGSL_FUN size_t gsl_bspline_nbreak(gsl_bspline_workspace * w);\nGSL_FUN double gsl_bspline_breakpoint(size_t i, gsl_bspline_workspace * w);\nGSL_FUN double gsl_bspline_greville_abscissa(size_t i, gsl_bspline_workspace *w);\n\nGSL_FUN int\ngsl_bspline_knots(const gsl_vector *breakpts, gsl_bspline_workspace *w);\n\nGSL_FUN int gsl_bspline_knots_uniform(const double a, const double b,\n                              gsl_bspline_workspace *w);\n\nGSL_FUN int\ngsl_bspline_knots_greville(const gsl_vector *abscissae,\n                           gsl_bspline_workspace *w,\n                           double *abserr);\n\nGSL_FUN int\ngsl_bspline_eval(const double x, gsl_vector *B, \n                 gsl_bspline_workspace *w);\n\nGSL_FUN int\ngsl_bspline_eval_nonzero(const double x,\n                         gsl_vector *Bk,\n                         size_t *istart,\n                         size_t *iend,\n                         gsl_bspline_workspace *w);\n\nGSL_FUN int\ngsl_bspline_deriv_eval(const double x,\n                       const size_t nderiv,\n                       gsl_matrix *dB,\n                       gsl_bspline_workspace *w);\n\nGSL_FUN int\ngsl_bspline_deriv_eval_nonzero(const double x,\n                               const size_t nderiv,\n                               gsl_matrix *dB,\n                               size_t *istart,\n                               size_t *iend,\n                               gsl_bspline_workspace *w);\n\n__END_DECLS\n\n#endif /* __GSL_BSPLINE_H__ */\n", "meta": {"hexsha": "ecaa2dfa84ca8687d72e7f81c462dabc3c1e141b", "size": 3818, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_bspline.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_bspline.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_bspline.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0840336134, "max_line_length": 81, "alphanum_fraction": 0.664484023, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3979554151424856}}
{"text": "/* multifit_nlinear/fdfvv.c\n * \n * Copyright (C) 2015 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_multifit_nlinear.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n\n/*\nfdfvv()\n  Compute approximate second directional derivative using\nfinite differences.\n\nSee Eq. 19 of:\n\nM. K. Transtrum, J. P. Sethna, Improvements to the Levenberg\nMarquardt algorithm for nonlinear least-squares minimization,\narXiv:1201.5885, 2012.\n\nInputs: h     - step size for finite difference\n        x     - parameter vector, size p\n        v     - geodesic velocity, size p\n        f     - vector of function values f_i(x), size n\n        J     - Jacobian matrix J(x), n-by-p\n        swts  - data weights\n        fdf   - fdf struct\n        fvv   - (output) approximate second directional derivative\n                vector D_v^2 f(x)\n        work  - workspace, size p\n\nReturn: success or error\n*/\n\nstatic int\nfdfvv(const double h, const gsl_vector *x, const gsl_vector *v,\n      const gsl_vector *f, const gsl_matrix *J, const gsl_vector *swts,\n      gsl_multifit_nlinear_fdf *fdf, gsl_vector *fvv, gsl_vector *work)\n{\n  int status;\n  const size_t n = fdf->n;\n  const size_t p = fdf->p;\n  const double hinv = 1.0 / h;\n  size_t i;\n\n  /* compute work = x + h*v */\n  for (i = 0; i < p; ++i)\n    {\n      double xi = gsl_vector_get(x, i);\n      double vi = gsl_vector_get(v, i);\n\n      gsl_vector_set(work, i, xi + h * vi);\n    }\n\n  /* compute f(x + h*v) */\n  status = gsl_multifit_nlinear_eval_f (fdf, work, swts, fvv);\n  if (status)\n    return status;\n\n  for (i = 0; i < n; ++i)\n    {\n      double fi = gsl_vector_get(f, i);    /* f_i(x) */\n      double fip = gsl_vector_get(fvv, i); /* f_i(x + h*v) */\n      gsl_vector_const_view row = gsl_matrix_const_row(J, i);\n      double u, fvvi;\n\n      /* compute u = sum_{ij} J_{ij} D v_j */\n      gsl_blas_ddot(&row.vector, v, &u);\n\n      fvvi = (2.0 * hinv) * ((fip - fi) * hinv - u);\n\n      gsl_vector_set(fvv, i, fvvi);\n    }\n\n  return status;\n}\n\n/*\ngsl_multifit_nlinear_fdfvv()\n  Compute approximate second directional derivative\nusing finite differences\n\nInputs: h    - step size for finite difference\n        x    - parameter vector, size p\n        v    - geodesic velocity, size p\n        f    - function values f_i(x), size n\n        J    - Jacobian matrix J(x), n-by-p\n        swts - sqrt data weights (set to NULL if not needed)\n        fdf  - fdf\n        fvv  - (output) approximate (weighted) second directional derivative\n               vector, size n, sqrt(W) fvv\n        work - workspace, size p\n\nReturn: success or error\n*/\n\nint\ngsl_multifit_nlinear_fdfvv(const double h, const gsl_vector *x, const gsl_vector *v,\n                           const gsl_vector *f, const gsl_matrix *J,\n                           const gsl_vector *swts, gsl_multifit_nlinear_fdf *fdf,\n                           gsl_vector *fvv, gsl_vector *work)\n{\n  return fdfvv(h, x, v, f, J, swts, fdf, fvv, work);\n}\n", "meta": {"hexsha": "612b4742a1f945ef0524c444f301340e47479bd5", "size": 3713, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit_nlinear/fdfvv.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/fdfvv.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/fdfvv.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 30.4344262295, "max_line_length": 84, "alphanum_fraction": 0.6393751683, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.39795539877069797}}
{"text": "/******************************************************************************\n *                                                                            *\n * ESTIMATE_THETAE.C                                                          *\n *                                                                            *\n * ESTIMATE THETAE AT END OF TIMESTEP DUE TO RADIATION SOURCES                *\n *                                                                            *\n ******************************************************************************/\n\n#include \"decs.h\"\n\n#if RADIATION\n#if ESTIMATE_THETAE\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_roots.h>\n\n#define NTHREADS (24)\n\n// ESTIMATE THETAE BEFORE PUSH TO AVOID ISSUES WITH MPI COMMUNICATION\n\ndouble Thetae_est[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];\ndouble Thetae_old[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];\n\ndouble Ucon[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NDIM];\ndouble Ucov[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NDIM];\ndouble Bcov[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NDIM];\ndouble Ne[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];\ndouble Bmag[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];\n\nint        Nsph_zone[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS];\nint        Nsph_cntd[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS];\ndouble *   w[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS];\ndouble *   nu[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS];\ndouble *   dlam[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS];\ndouble *   theta[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NTHREADS];\nstatic int type        = 0; // TODO: remove me when type loops are in place.\nstatic int interaction = 0; // TODO: remove me when type loops are in place.\n\ndouble get_Thetae_est(int i, int j, int k) { return Thetae_est[i][j][k]; }\n\n// Rootfinding parameters and function\nstruct of_params {\n  int    i, j, k;\n  double rho, Ne, Bmag, Thetaei, Ucon0, dt;\n  double extra[EOS_NUM_EXTRA];\n};\n\ndouble dEdt(double Thetae, void *params) {\n  struct of_params *p     = (struct of_params *)params;\n  int               i     = p->i;\n  int               j     = p->j;\n  int               k     = p->k;\n  double            rho   = p->rho;\n  double            dt    = p->dt;\n  double *          extra = p->extra;\n\n  // TODO:  encapsulate electrons in EOS framework.\n  double uei, uef;\n#if ELECTRONS && EOS == EOS_TYPE_GAMMA\n  uei = Ne[i][j][k] * Thetae_old[i][j][k] * ME * CL * CL / (game - 1.);\n  uef = Ne[i][j][k] * Thetae * ME * CL * CL / (game - 1.);\n#else\n  uei = EOS_u_N_Theta(rho, Ne[i][j][k], Thetae_old[i][j][k], extra);\n  uef = EOS_u_N_Theta(rho, Ne[i][j][k], Thetae, extra);\n#endif\n\n  struct of_microphysics micro;\n  micro.Thetae = Thetae;\n  micro.Ne     = Ne[i][j][k];\n  micro.B      = Bmag[i][j][k];\n\n  double J   = get_J(&m);\n  double vol = ggeom[i][j][CENT].g * dx[1] * dx[2] * dx[3] * dt;\n\n  // Loop over superphotons\n  double udotG_abs   = 0.;\n  double udotG_scatt = 0.;\n  for (int n = 0; n < nthreads; n++) {\n    for (int m = 0; m < Nsph_zone[i][j][k][n]; m++) {\n      double udotk = HPL * nu[i][j][k][n][m] / (ME * CL * CL);\n\n      // Absorption\n      double alpha_inv_a =\n          alpha_inv_abs(nu[i][j][k][n][m], type, &micro, theta[i][j][k][n][m]);\n      double dtau_a =\n          alpha_inv_a * L_unit * HPL / (ME * CL * CL) * dlam[i][j][k][n][m];\n      double dw_a = w[i][j][k][n][m] * (1. - exp(-dtau_a));\n      udotG_abs += kphys_to_num * dw_a * udotk / vol;\n\n      // dEtau_abs += HPL*nu[i][j][k][n][m]*w[i][j][k][n][m]*(1. -\n      // exp(-dtau_a));\n\n      // Scattering (assuming h \\nu << k_B T_e)\n      double alpha_inv_s =\n          alpha_inv_scatt(nu[i][j][k][n][m], type, interaction, &micro);\n      double dtau_s =\n          alpha_inv_s * L_unit * HPL / (ME * CL * CL) * dlam[i][j][k][n][m];\n      double dw_s = w[i][j][k][n][m] * (1. - exp(-dtau_s));\n      double amp =\n          1. + 4. * Thetae - 2. * pow(Thetae, 3. / 2.) + 16. * pow(Thetae, 2.);\n      udotG_scatt += kphys_to_num * (1. - amp) * dw_s * udotk / vol;\n      // dEdtau_scatt -= HPL*nu[i][j][k][n][m]*;\n    }\n  }\n  // dEdtau_abs *= Ucon[i][j][k][0]/(/* d3xi! */dt*T_unit);\n  // dEdtau_scatt *= Ucon[i][j][k][0]/(dt*T_unit);\n  udotG_abs *= U_unit / T_unit;\n  udotG_scatt *= U_unit / T_unit;\n\n  // if (udotG_abs != 0. || udotG_scatt != 0.) {\n  /*if (i == 80 && j == 64) {\n    printf(\"Thetae Ne Bmag = %e %e %e\\n\", Thetae, Ne[i][j][k], Bmag[i][j][k]);\n    printf(\"%e %e %e %e\\n\", Ucon[i][j][k][0]*(uef - uei)/dt,\n      J, udotG_abs, udotG_scatt);\n  }*/\n\n  // Solve entropy equation in cgs:\n  //   d u_e / d \\tau = -emission + absorption - upscattering\n  double resid = Ucon[i][j][k][0] * (uef - uei) / (dt * T_unit);\n  resid += J;\n  resid += udotG_abs;\n  resid += udotG_scatt;\n  return resid;\n}\n\nvoid estimate_Thetae(\n    grid_prim_type P, grid_eosvar_type extra, double t, double dt) {\n  if (NTHREADS != nthreads) {\n    fprintf(stderr, \"NTHREADS = %i nthreads = %i! Exiting...\\n\", NTHREADS,\n        nthreads);\n    exit(-1);\n  }\n  struct of_microphysics micro;\n\n// Count superphotons in each zone\n#pragma omp parallel\n  {\n    int               n  = omp_get_thread_num();\n    struct of_photon *ph = photon_lists[n];\n    while (ph != NULL) {\n      int    i, j, k;\n      double X[NDIM], Kcov[NDIM], Kcon[NDIM];\n      get_X_K_interp(ph, t, P, X, Kcov, Kcon);\n      Xtoijk(X, &i, &j, &k);\n      Nsph_zone[i][j][k][n]++;\n      ph = ph->next;\n    }\n  } // omp parallel\n\n// malloc required memory and store ucon for convenience\n#pragma omp parallel for collapse(3)\n  ZLOOP {\n    double Bcon[NDIM];\n    get_fluid_zone(i, j, k, P, extra, &micro, Ucon[i][j][k], Ucov[i][j][k],\n        Bcon, Bcov[i][j][k]);\n    Ne[i][j][k]         = micro.Ne;\n    Thetae_old[i][j][k] = micro.Thetae;\n    Bmag[i][j][k]       = micro.B;\n    for (int n = 0; n < nthreads; n++) {\n      w[i][j][k][n]     = safe_malloc(Nsph_zone[i][j][k][n] * sizeof(double));\n      nu[i][j][k][n]    = safe_malloc(Nsph_zone[i][j][k][n] * sizeof(double));\n      dlam[i][j][k][n]  = safe_malloc(Nsph_zone[i][j][k][n] * sizeof(double));\n      theta[i][j][k][n] = safe_malloc(Nsph_zone[i][j][k][n] * sizeof(double));\n      Nsph_cntd[i][j][k][n] = 0;\n    }\n  } // omp parallel\n\n// Create per-zone lists of w, nu, dlam\n#pragma omp parallel\n  {\n    int               n  = omp_get_thread_num();\n    struct of_photon *ph = photon_lists[n];\n    while (ph != NULL) {\n      int    i, j, k;\n      double X[NDIM], Kcov[NDIM], Kcon[NDIM];\n      get_X_K_interp(ph, t, P, X, Kcov, Kcon);\n      Xtoijk(X, &i, &j, &k);\n\n      if (i < NG || i > NG + N1 - 1 || j < NG || j > NG + N2 - 1 || k < NG ||\n          k > NG + N3 - 1) {\n        printf(\"BAD PH????\\n\");\n        printf(\"[%i] %i %i %i X[] = %e %e %e %e\\n\", n, i, j, k, X[0], X[1],\n            X[2], X[3]);\n        for (int mu = 0; mu < 3; mu++) {\n          printf(\"X[%i][] = %e %e %e %e\\n\", mu, ph->X[mu][0], ph->X[mu][1],\n              ph->X[mu][2], ph->X[mu][3]);\n          printf(\"Kcov[%i][] = %e %e %e %e\\n\", mu, ph->Kcov[mu][0],\n              ph->Kcov[mu][1], ph->Kcov[mu][2], ph->Kcov[mu][3]);\n          printf(\"Kcon[%i][] = %e %e %e %e\\n\", mu, ph->Kcon[mu][0],\n              ph->Kcon[mu][1], ph->Kcon[mu][2], ph->Kcon[mu][3]);\n        }\n        printf(\"origin %i %i %i %i\\n\", ph->origin[0], ph->origin[1],\n            ph->origin[2], ph->origin[3]);\n        printf(\"nscatt = %i\\n\", ph->nscatt);\n        exit(-1);\n      }\n\n      double freq = 0.;\n      for (int mu = 0; mu < NDIM; mu++) {\n        freq -= Ucon[i][j][k][mu] * Kcov[mu];\n      }\n      freq *= ME * CL * CL / HPL;\n\n      w[i][j][k][n][Nsph_cntd[i][j][k][n]]    = ph->w;\n      nu[i][j][k][n][Nsph_cntd[i][j][k][n]]   = freq;\n      dlam[i][j][k][n][Nsph_cntd[i][j][k][n]] = dt / Kcon[0];\n      theta[i][j][k][n][Nsph_cntd[i][j][k][n]] =\n          get_bk_angle(X, Kcon, Ucov[i][j][k], Bcov[i][j][k], Bmag[i][j][k]);\n\n      Nsph_cntd[i][j][k][n]++;\n      ph = ph->next;\n    }\n  } // omp parallel\n\n// In each zone, rootfind to Thetae that matches sources. If failure, simply\n// return current Thetae\n#pragma omp parallel\n  {\n    const gsl_root_fsolver_type *T;\n    gsl_root_fsolver *           s;\n    gsl_function                 F;\n    F.function = &dEdt;\n    T          = gsl_root_fsolver_brent;\n    s          = gsl_root_fsolver_alloc(T);\n\n    static double extra[EOS_NUM_EXTRA];\n#pragma omp threadprivate(extra)\n#if EOS == EOS_TYPE_GAMMA\n    EOS_ELOOP { extra[e] = 0.0; }\n#endif\n\n#pragma omp for collapse(3)\n    ZLOOP {\n#if EOS == EOS_TYPE_TABLE\n      extra[EOS_YE] = P[i][j][k][YE];\n#endif\n\n      // fill parameters\n      struct of_params params;\n      params.i       = i;\n      params.j       = j;\n      params.k       = k;\n      params.rho     = P[i][j][k][RHO];\n      params.Ne      = Ne[i][j][k];\n      params.Bmag    = Bmag[i][j][k];\n      params.Thetaei = Thetae_old[i][j][k];\n      params.Ucon0   = Ucon[i][j][k][0];\n      params.dt      = dt;\n      // hopefully this doesn't break openmp\n      EOS_ELOOP { params.extra[e] = extra[e]; }\n\n      F.params         = &params;\n      double r         = 0.;\n      double Thetae_lo = 0.5 * Thetae_old[i][j][k];\n      double Thetae_hi = 2. * Thetae_old[i][j][k];\n\n      // Test interval for sanity\n      double rmin = dEdt(Thetae_lo, &params);\n      double rmax = dEdt(Thetae_hi, &params);\n      if (rmin * rmax > 0.) {\n        fprintf(stderr, \"[%i %i %i] Root not bracketed!\\n\", i, j, k);\n        Thetae_est[i][j][k] = Thetae_old[i][j][k];\n        continue;\n      }\n\n      gsl_root_fsolver_set(s, &F, Thetae_lo, Thetae_hi);\n\n      int iter = 0, max_iter = 100;\n      int status;\n      do {\n        status    = gsl_root_fsolver_iterate(s);\n        r         = gsl_root_fsolver_root(s);\n        Thetae_lo = gsl_root_fsolver_x_lower(s);\n        Thetae_hi = gsl_root_fsolver_x_upper(s);\n        status    = gsl_root_test_interval(Thetae_lo, Thetae_hi, 0, 0.001);\n      } while (status == GSL_CONTINUE && iter < max_iter);\n\n      if (status != GSL_SUCCESS) {\n        Thetae_est[i][j][k] = Thetae_old[i][j][k];\n      } else {\n        Thetae_est[i][j][k] = r;\n      }\n    }\n\n    gsl_root_fsolver_free(s);\n  } // omp parallel\n\n// Clean up mallocs and reset counters\n#pragma omp parallel for collapse(3)\n  ZLOOP {\n    for (int n = 0; n < nthreads; n++) {\n      free(w[i][j][k][n]);\n      free(nu[i][j][k][n]);\n      free(dlam[i][j][k][n]);\n      free(theta[i][j][k][n]);\n      Nsph_zone[i][j][k][n] = 0.;\n    }\n  } // omp parallel\n}\n\n#endif // ESTIMATE_THETAE\n#endif // RADIATION\n", "meta": {"hexsha": "83abe0c982fd25386fccfaff1e788eaae6a24a3e", "size": 10440, "ext": "c", "lang": "C", "max_stars_repo_path": "core/estimate_thetae.c", "max_stars_repo_name": "soumide1102/nubhlight", "max_stars_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-02-05T22:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:05:37.000Z", "max_issues_repo_path": "core/estimate_thetae.c", "max_issues_repo_name": "soumide1102/nubhlight", "max_issues_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T02:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T20:00:30.000Z", "max_forks_repo_path": "core/estimate_thetae.c", "max_forks_repo_name": "soumide1102/nubhlight", "max_forks_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-02-21T04:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T21:42:12.000Z", "avg_line_length": 34.3421052632, "max_line_length": 80, "alphanum_fraction": 0.4990421456, "num_tokens": 3676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.5, "lm_q1q2_score": 0.39782904518612805}}
{"text": "/*\n * particle_filters.c\n *\n *  Created on: 18 Sep 2020\n *      Author: heine\n */\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_eigen.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#include <Accelerate/Accelerate.h>\n\n#include \"particle_filters.h\"\n\nvoid MLbootstrapfilter(double* y, double sig_std, double obs_std, int data_length, double x0,\n                       int* sample_sizes, double *worst_case_sign_ratio, double* x_hats, double *filtering_time, int* mesh_sizes,  int kl, int ku, double* ab0, double* ab1, int ldab, int* ipiv0, int* ipiv1, int ldb0, int ldb1, int info, double w, double d, double E, double I, double h0, double h1, double L , double* meass, int N_meas) {\n  \n  int make_correction = 1; // If one ML telescoping correction is made, if 0 not.\n  int N_levels = 2; // hard coded for now\n  int N = 0;\n  \n  const char prog_bar[51] = \"-------------------------------------------------\";\n  int* minds0 = (int*)malloc(2 * N_meas * sizeof(int));\n  int* minds1 = minds0 + N_meas;\n  double* obss = (double*)malloc(N_meas*sizeof(double));\n  double lower_bound = 0.25, upper_bound = L - 0.25;\n  \n  clock_t start = clock();\n  int bar_segment_count = 0;\n  \n  for (short i = 0; i < N_levels; i++) {\n    N += sample_sizes[i];\n    printf(\"N%i = %i, \", i, sample_sizes[i]);\n  }\n  printf(\"N = %i, L0 = %i, L1 = %i\\n\", N, mesh_sizes[0],mesh_sizes[1]);\n  \n  double *X = (double*) malloc(2 * N * sizeof(double));\n  double W1_tmp;\n  double* B0 = (double*) malloc(sample_sizes[0]*mesh_sizes[0]*sizeof(double));\n  double* B1 = (double*) malloc(sample_sizes[1]*mesh_sizes[1]*sizeof(double));\n  double* pred_meass0 = (double*) malloc(2 * sample_sizes[1] * N_meas * sizeof(double));\n  double* pred_meass1 = pred_meass0 + sample_sizes[1] * N_meas;\n  double* W = (double*) malloc(2 * N * sizeof(double));\n  double* absW = W + N;\n  short* signs = (short*) malloc(2 * N * sizeof(short));\n  short* signs_res = signs + N;\n  int* ind = (int*) malloc(2 * N * sizeof(int));\n  int* permutation = ind + N; // needed for uniform resampling\n  \n  double x_hat = 0;\n  double p_hat = 0;\n  \n  double* X0 = X;\n  double* X1 = X + sample_sizes[0];\n  double* W0 = W;\n  double* W1 = W + sample_sizes[0];\n  double* X_res = X + N;\n  \n  printf(\n         \"%s\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\",\n         prog_bar);\n  fflush(stdout);\n  \n  /* Make copies of the band matrices as DGBSV destroys them */\n  double* a0_copy = (double*) malloc(ldab * mesh_sizes[0] * sizeof(double));\n  double* a1_copy = (double*) malloc(ldab * mesh_sizes[1] * sizeof(double));\n  \n  /*\n   * Initial sample and level indicator\n   */\n  gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus);\n  gsl_rng_set(rng, clock());\n  for (int i = 0; i < N; i++) {\n    X[i] = gsl_ran_gaussian(rng, sig_std) + x0; // init sample\n    W[i] = (double) 1.0 / (double) N; // init weights\n    signs_res[i] = 1;\n  }\n  \n  double normaliser = 0;\n  double abs_normaliser = 0;\n  //  double diff;\n  double ESS, ESSABS;\n  //  double tmp_x_hat;\n  double positive_mass, negative_mass;\n  \n  //  FILE* bpf_out = fopen(\"mlbpf_out.txt\", \"w\");\n  \n  \n  clock_t iteration_timer;\n  clock_t resampling_timer;\n  clock_t level_timer_start;\n  double level_0_particle_cost = 0;\n  double level_1_particle_cost = 0;\n  double rsamp_time_per_prcl = 0;\n  worst_case_sign_ratio[0] = 100;\n  double sign_balance;\n  double obs_std_scale = 0.8;\n  double intercepts[2];\n  double slopes[2];\n    \n  int res_pos, res_neg;\n  int dodb = 0;\n  \n  // Mesh point indices for the measurement locations\n  for(int i = 0; i < N_meas; i++) {\n    minds0[i] = (int)(meass[i] / L * (double) mesh_sizes[0]);\n    minds1[i] = (int)(meass[i] / L * (double) mesh_sizes[1]);\n  }\n  \n  /*\n   * FILTER MAIN LOOP\n   */\n  for (int n = 0; n < data_length; n++) {\n      \n    // Restore the destroyed band matrix\n    array_copy(ab0, a0_copy, ldab * mesh_sizes[0]);\n    array_copy(ab1, a1_copy, ldab * mesh_sizes[1]);\n    \n    iteration_timer = clock(); // start the stopwatch\n    level_timer_start = clock();\n    \n    // Extract the observations for the current time step\n    for(int i = 0; i < N_meas; i++)\n      obss[i] = y[n + i * data_length];\n    \n    /*\n     * Level 1 weight calculation\n     */\n    \n    /* Calculate Level 1 first, so we can estimate the bias of the observation mapping */\n    \n    /* Solve the beam for level 0 mesh and sample N1 */\n    ebb_solve(sample_sizes[1], X1, mesh_sizes[0], B1, w, d, h0, E, I, L, kl, ku, a0_copy, ldab, ipiv0, ldb0, info, N_meas, minds0, pred_meass0);\n    \n    /* Solve the beam for level 1 mesh and sample N1 */\n    ebb_solve(sample_sizes[1], X1, mesh_sizes[1], B1, w, d, h1, E, I, L, kl, ku, a1_copy, ldab, ipiv1, ldb1, info, N_meas, minds1, pred_meass1);\n    \n    /* Fit a first order LS model for the error between level 0 and level 1 */\n    if(sample_sizes[1] > 0){ // do only if N1 > 0\n      ls_fit(N_meas, sample_sizes[1], X1, pred_meass0, pred_meass1, intercepts, slopes);\n    }\n    \n    /* Now that we know the bias, we can evaluate the weights for level 1 */\n    double diff;\n    for (int j = 0; j < sample_sizes[1]; j++) {\n      W1[j] = 1;\n      W1_tmp = 1;\n      for(int k = 0; k < N_meas; k++){\n        /* Level 0 */\n        diff = obss[k] - pred_meass0[sample_sizes[1] * k + j] - intercepts[k] - slopes[k] * X1[j];\n        W1_tmp *= exp( - diff * diff / (double) 2.0 / (obs_std * obs_std_scale) / (obs_std * obs_std_scale));\n        /* Level 1 */\n        diff = obss[k] - pred_meass1[sample_sizes[1] * k + j];\n        W1[j] *= exp( - diff * diff / (double) 2.0 / obs_std / obs_std );\n      }\n      \n      W1[j] -= W1_tmp; // take the difference and...\n      W1[j] /= (double) sample_sizes[1]; // ... normalise by sample size N1\n//      W1[j] = 0; /* uncomment to disable level 1 correction*/\n    }\n    \n    /*\n     Level 0 weight calculation\n     */\n    \n    array_copy(ab0, a0_copy, ldab * mesh_sizes[0]);\n    \n    likelihood(X0, sample_sizes[0], obss, obs_std_scale*obs_std, mesh_sizes[0], kl, ku, a0_copy, ldab, ipiv0, ldb0, info, B0, w, d, h0, E, I, W0, L, minds0, N_meas, dodb, intercepts, slopes);\n    \n    // normalise by the sample size (N0)\n    for (int i = 0; i < sample_sizes[0]; i++)\n      W[i] /= (double)sample_sizes[0];\n    \n    if(!make_correction) {\n      for(int i = 0; i < sample_sizes[1]; i++) {\n        W1[i] = 0;\n      }\n    }\n    \n    /* Joint normalisation of the weights */\n    normaliser = 0;\n    abs_normaliser = 0;\n    for (long i = 0; i < N; i++) {\n      \n      W[i] *= (double) signs_res[i]; // Take the sign into account\n      \n      absW[i] = fabs(W[i]);\n      signs[i] = W[i] > 0 ? 1 : -1;\n      normaliser += W[i];\n      abs_normaliser += absW[i];\n    }\n    \n    /* Normalise */\n    positive_mass = 0;\n    negative_mass = 0;\n    for (long i = 0; i < N; i++) {\n      W[i] /= normaliser;\n      if (W[i] > 0) {\n        positive_mass += W[i];\n      } else {\n        negative_mass += fabs(W[i]);\n      }\n      absW[i] /= abs_normaliser;\n    }\n    sign_balance = positive_mass / negative_mass;\n    if (sign_balance < worst_case_sign_ratio[0]) {\n      worst_case_sign_ratio[0] = sign_balance;\n    }\n    \n    ESS = 0;\n    ESSABS = 0;\n    for (long i = 0; i < N; i++) {\n      ESS += W[i] * W[i];\n      ESSABS += absW[i] * absW[i];\n    }\n    ESS = (double) 1.0 / ESS;\n    ESSABS = (double) 1.0 / ESSABS;\n    \n    /* Resample */\n    resampling_timer = clock();\n    resample(N, absW, ind, rng);\n    random_permuter(permutation, N, rng);\n    rsamp_time_per_prcl += (double) (clock() - resampling_timer) / CLOCKS_PER_SEC / (double) N;\n    \n    normaliser = 0;\n    res_pos = 0;\n    res_neg = 0;\n    for (long i = 0; i < N; i++) {\n      X_res[permutation[i]] = X[ind[i]];\n      signs_res[permutation[i]] = signs[ind[i]];\n      normaliser += signs[ind[i]];\n      if(signs[ind[i]]>0) {\n        res_pos++;\n      }else{\n        res_neg++;\n      }\n    }\n    for (long i = 0; i < N; i++) {\n      W[i] = (double) signs_res[i] / normaliser;\n    }\n    \n    /* Calculate the output: posterior mean */\n    if(x_hats!=NULL){\n      x_hat = 0;\n      for (int i = 0; i < N; i++) {\n        x_hat += X_res[i] * W[i];\n        if(isnan(x_hat)){\n          printf(\"NaN detected!\\n X_res[i] = %e, W[i] = %e, i = %i, normaliser = %e + = %e, - = %e\\nESS=%e, res_+ =%i, res_- = %i\\n\",\n                 X_res[i], W[i], i,normaliser,positive_mass, negative_mass,ESS,res_pos,res_neg);\n          fflush(stdout);\n          getchar();\n        }\n      }\n      x_hats[n] = x_hat;\n      \n      /* Calculate the output: posterior variance */\n      p_hat = 0;\n      for (long i = 0; i < N; i++) {\n        diff = X_res[i] - x_hat;\n        p_hat += diff * diff * W[i];\n      }\n    }\n    \n    /* Mutate */\n    for (long i = 0; i < N; i++) {\n      X[i] = X_res[i] + gsl_ran_gaussian(rng, sig_std);\n      \n      if(X[i] < lower_bound)\n        X[i] = lower_bound + lower_bound-X[i];\n      if(X[i] > upper_bound)\n        X[i] = upper_bound - (X[i]-upper_bound);\n    }\n    \n    if (floor(n * (double) 50 / data_length) > bar_segment_count) {\n      printf(\"\u2588\");\n      fflush(stdout);\n      bar_segment_count++;\n    }\n    \n  }\n  \n  filtering_time[0] = (double) (clock() - start) / CLOCKS_PER_SEC / (double) data_length;\n  filtering_time[1] = level_0_particle_cost / (double) data_length / (double) sample_sizes[0];\n  filtering_time[2] = level_1_particle_cost / (double) data_length / (double) sample_sizes[1];\n  filtering_time[3] = rsamp_time_per_prcl / (double) data_length / (double) N;\n  printf(\" %5.5f sec\\n\", filtering_time[0]);\n  \n  free(X);\n  free(W);\n  free(signs);\n  free(ind);\n  free(a0_copy);\n  free(a1_copy);\n  free(B0);\n  free(B1);\n  free(minds0);\n  free(obss);\n  free(pred_meass0);\n  gsl_rng_free(rng);\n  \n}\n\nvoid bootstrapfilter(double* y, double sig_std, double obs_std, int data_length, double x0,\n                     int N, double* x_hats, double* p_hats, double *filtering_time, int mesh_size,\tint kl, int ku, double* ab, int ldab, int* ipiv, int ldb, int info, double w, double d, double E, double I, double h , double L, double *meass, int N_meas) {\n  \n  const char prog_bar[51] = \"-------------------------------------------------\";\n  clock_t start;\n  int bar_segment_count = 0;\n  \n  printf(\"Basic BPF with N = %i\\n\", N);\n  \n  double *X = (double*) malloc(2 * N * sizeof(double));\n  double *X_res = X + N;\n  double *W = (double*) malloc(N * sizeof(double));\n  int *ind = (int*) malloc(N * sizeof(int));\n  double* payloads = (double*) malloc(mesh_size * N * sizeof(double));\n  // Because DGBSV destroys the AB matrix, we need to make a copy of it\n  double* ab_copy = (double*) malloc(ldab * mesh_size * sizeof(double));\n  double x_hat = 0;\n  double p_hat = 0;\n  double lower_bound = 0.25, upper_bound = L - 0.25;\n  double intercepts[2] = {0,0};\n  double slopes[2] = {0,0};\n  \n  printf(\n         \"%s\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\",\n         prog_bar);\n  fflush(stdout);\n  \n  \n  start = clock();\n  \n  /*\n   * Initial sample and level indicator\n   */\n  gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus);\n  gsl_rng_set(rng, clock());\n  for (int i = 0; i < N; i++) {\n    X[i] = gsl_ran_gaussian(rng, sig_std) + x0;\n    W[i] = (double) 1.0 / (double) N;\n  }\n  \n  double normaliser = 0;\n  double diff;\n  double ESS;\n  double cost_per_particle = 0;\n  \n  int* minds = (int*)malloc(N_meas * sizeof(int));\n  double* obss = (double*)malloc(N_meas * sizeof(double));\n  for(int i = 0; i < N_meas; i++){\n    minds[i] = (int)(meass[i] / L * (double) mesh_size);\n  }\n  \n  /* Classic BPF main loop */\n  /* --------------------- */\n  for (int n = 0; n < data_length; n++) {\n    \n    /* Weight calculation */\n    normaliser = 0;\n    \n    array_copy(ab, ab_copy, ldab * mesh_size);\n    \n    /*\n     * Weight calculation\n     */\n    clock_t stopwatch_start = clock();\n    for(int i = 0; i < N_meas; i++)\n      obss[i] = y[n + i*data_length];\n    \n    likelihood(X, N, obss, obs_std, mesh_size, kl, ku, ab_copy, ldab, ipiv, ldb, info, payloads, w, d, h, E, I, W, L, minds, N_meas, 0, intercepts, slopes);\n    clock_t stopwatch_stop = clock();\n    \n    cost_per_particle += (double)(stopwatch_stop-stopwatch_start)/(double) CLOCKS_PER_SEC;\n    \n    // Normalise the weights\n    normaliser = 0;\n    for (int i = 0; i < N; i++)\n      normaliser += W[i];\n    for (int i = 0; i < N; i++)\n      W[i] /= normaliser;\n    \n    ESS = 0;\n    for (int i = 0; i < N; i++) {\n      ESS += W[i] * W[i];\n    }\n    ESS = (double) 1.0 / ESS;\n    \n    /* Resample */\n    resample(N, W, ind, rng);\n    for (int i = 0; i < N; i++) {\n      X_res[i] = X[ind[i]];\n    }\n    \n    /* Calculate the output: posterior mean */\n    if(x_hats != NULL) {\n      x_hat = 0;\n      for (int i = 0; i < N; i++) {\n        x_hat += X_res[i] / (double) N;\n      }\n      x_hats[n] = x_hat;\n      /* Calculate the output: posterior variance */\n      p_hat = 0;\n      for (int i = 0; i < N; i++) {\n        diff = X_res[i] - x_hat;\n        p_hat += diff * diff / (double) (N-1);\n      }\n      if(p_hats!=NULL)\n        p_hats[n] = p_hat;\n    }\n    /* Mutate */\n    for (int i = 0; i < N; i++) {\n      X[i] = X_res[i] + gsl_ran_gaussian(rng, sig_std);\n      \n      if(X[i] < lower_bound)\n        X[i] = lower_bound + lower_bound-X[i];\n      if(X[i] > upper_bound)\n        X[i] = upper_bound - (X[i]-upper_bound);\n    }\n    \n    if (floor(n * (double) 50 / data_length) > bar_segment_count) {\n      printf(\"\u2588\");\n      fflush(stdout);\n      bar_segment_count++;\n    }\n  }\n  filtering_time[0] = (double) (clock() - start) / CLOCKS_PER_SEC / (double) data_length;\n  filtering_time[1] = cost_per_particle / (double) data_length;\n  filtering_time[2] = 0;\n  filtering_time[3] = 0;\n  printf(\" %5.5f sec\\n\", filtering_time[0]);\n  \n  free(X);\n  free(W);\n  free(ind);\n  free(ab_copy);\n  free(payloads);\n  free(minds);\n  free(obss);\n  gsl_rng_free(rng);\n}\n\n/* Computes a first order LS fit for error between level 0 and level 1 */\nvoid ls_fit(int N_meas, int N1, double* X1, double* pred_meass0, double* pred_meass1, double* intercepts, double* slopes) {\n  \n  double a,b,c,d,e,f;\n  \n  for(int j = 0; j < N_meas; j++) {\n    \n    /* First order polynomial fit to the bias */\n    a = 0;\n    b = 0;\n    d = 0;\n    e = 0;\n    f = 0;\n    for(int i = 0; i < N1; i++) {\n      a++;\n      b += X1[i];\n      d += X1[i] * X1[i];\n      e += pred_meass1[j * N1 + i] - pred_meass0[j * N1 + i];\n      f += X1[i] * (pred_meass1[j * N1 + i] - pred_meass0[j * N1 + i]);\n    }\n    c = b;\n    intercepts[j] = (e * d - b * f) / (a * d - b * c);\n    slopes[j] = (-c * e  + a * f) / (a * d - b * c);\n  }\n}\n\nvoid likelihood(double* x, int N, double* y, double std, int mesh_size, int kl, int ku, double* ab, int ldab, int* ipiv, int ldb, int info, double* b, double w, double d, double h, double E, double I, double* likes, double L, int* minds, int N_meas, int dodb, double* intercepts, double* slopes) {\n  \n  // Create the instantaneous payload\n  create_payload(N, mesh_size, b, w, d, x, h, E, I, L);\n  \n  // Solve the Euler-Bernoulli beam for each particle\n  dgbsv_(&mesh_size, &kl, &ku, &N, ab, &ldab, ipiv, b, &ldb, &info);\n  \n  double diff;\n  for (int j = 0; j < N; j++) {\n    diff = 1;\n    likes[j] = 1;\n    for(int k = 0; k < N_meas; k++){\n      diff = y[k] - b[j * mesh_size + minds[k]] - x[j]*slopes[k] - intercepts[k];\n      likes[j] *= exp( - diff * diff / (double) 2.0 / std / std) ;\n    }\n  }\n}\n\nvoid random_permuter(int *permutation, int N, gsl_rng *r) {\n  \n  for (int i = 0; i < N; i++)\n    permutation[i] = i;\n  \n  int j;\n  int tmp;\n  for (int i = N - 1; i > 0; i--) {\n    j = (int)gsl_rng_uniform_int(r, i + 1);\n    tmp = permutation[j];\n    permutation[j] = permutation[i];\n    permutation[i] = tmp;\n  }\n  \n}\n\nvoid resample(int size, double *w, int *ind, gsl_rng *r) {\n  \n  /* Generate the exponentials */\n  double *e = (double*) malloc((size + 1) * sizeof(double));\n  double g = 0;\n  for (int i = 0; i <= size; i++) {\n    e[i] = gsl_ran_exponential(r, 1.0);\n    g += e[i];\n  }\n  /* Generate the uniform order statistics */\n  double *u = (double *) malloc((size + 1) * sizeof(double));\n  u[0] = 0;\n  for (int i = 1; i <= size; i++)\n    u[i] = u[i - 1] + e[i - 1] / g;\n  \n  /* Do the actual sampling with inverse cdf */\n  double cdf = w[0];\n  int j = 0;\n  for (int i = 0; i < size; i++) {\n    while (cdf < u[i + 1]) {\n      j++;\n      cdf += w[j];\n    }\n    ind[i] = j;\n  }\n  \n  free(e);\n  free(u);\n}\n\nvoid create_payload(int N, int n, double *b, double w, double d, double* x, double h, double E, double I, double L) {\n  \n  double g = -9.81; // Gravity acceleration\n  double scaler = h * h * h * h / (E * I);\n  double slab_thickness = 0.20; // meters\n  double density = 7874; // kg/ m^3\n  double slab_width = 0.72; // m\n  int location_index_centre = 0, location_index_right = 0, location_index_left = 0;\n  double deviation = slab_thickness / (double) 8;\n  double diff;\n  \n  for (long j = 0; j < N;j++) { // iterate over particles\n    \n    for(int i = 0; i < n; i++)\n      b[j * n + i] = g * w * d * (double)480;\n    \n    // Find the index corresponding to the location x\n    location_index_centre = (int)(x[j] / L * (double) n);\n    \n    // Left end of the slab\n    location_index_left = location_index_centre -  ceil(slab_thickness / h / (double) 2);\n    // make sure index is non-negative\n    location_index_left = location_index_left < 0 ? 0 : location_index_left;\n    \n    // Right end of the slab\n    location_index_right = location_index_centre +  ceil(slab_thickness / h / (double) 2);\n    // make sure index is less than mesh size\n    location_index_right = location_index_right > n - 1 ? n - 1 : location_index_right;\n    \n    if(location_index_centre < 0) {\n      printf(\"NEGATIVE INDEX!\\n\");\n      fflush(stdout);\n    }\n    \n    // Add weight to the location\n    for(int i = location_index_left; i <= location_index_right ; i++){\n      diff = x[j] - i*h;\n      \n      b[j * n + i] -=  slab_width * slab_width * density * 9.81 * exp(- diff * diff / (double) 2 / deviation / deviation);\n    }\n    // Scale appropriately (there is some physical justification to this)\n    for(int i = 0; i < n;i++) {\n      b[j * n + i] *= scaler;\n    }\n  }\n}\n\nvoid ebb_solve(int N, double* x, int mesh_size, double* b, double w, double d, double h, double E, double I, double L, int kl, int ku, double *ab, int ldab, int *ipiv, int ldb, int info, int N_meas, int* minds, double* pred_measurements) {\n\n  create_payload(N, mesh_size, b, w, d, x, h, E, I, L);\n  dgbsv_(&mesh_size, &kl, &ku, &N, ab, &ldab, ipiv, b, &ldb, &info);\n\n  for (int j = 0; j < N; j++) {\n      for(int k = 0; k < N_meas; k++){\n        pred_measurements[N * k + j] = b[j * mesh_size + minds[k]];\n      }\n    }\n}\n\nvoid array_copy(double *src, double* dst, int length) {\n  for(int i = 0; i < length; i++)\n    dst[i] = src[i];\n}\n", "meta": {"hexsha": "6a180694b0cd0fe287b570c9c5b527658a613f67", "size": 18794, "ext": "c", "lang": "C", "max_stars_repo_path": "ODE_MODEL/particle_filters.c", "max_stars_repo_name": "heinekmp/MLBPF", "max_stars_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_stars_repo_licenses": ["MIT"], "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_MODEL/particle_filters.c", "max_issues_repo_name": "heinekmp/MLBPF", "max_issues_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_issues_repo_licenses": ["MIT"], "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_MODEL/particle_filters.c", "max_forks_repo_name": "heinekmp/MLBPF", "max_forks_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a", "max_forks_repo_licenses": ["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.3756260434, "max_line_length": 338, "alphanum_fraction": 0.5645418751, "num_tokens": 6160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.39766803361410674}}
{"text": "/* rng/transputer.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n\n/* This is the INMOS Transputer Development System generator. The sequence is,\n\n   x_{n+1} = (a x_n) mod m\n\n   with a = 1664525 and m = 2^32. The seed specifies the initial\n   value, x_1.\n\n   The theoretical value of x_{10001} is 1244127297.\n\n   The period of this generator is 2^30. */\n\nstatic inline unsigned long int transputer_get (void *vstate);\nstatic double transputer_get_double (void *vstate);\nstatic void transputer_set (void *state, unsigned long int s);\n\ntypedef struct\n  {\n    unsigned long int x;\n  }\ntransputer_state_t;\n\nstatic unsigned long int\ntransputer_get (void *vstate)\n{\n  transputer_state_t *state = (transputer_state_t *) vstate;\n\n  state->x = (1664525 * state->x) & 0xffffffffUL;\n\n  return state->x;\n}\n\nstatic double\ntransputer_get_double (void *vstate)\n{\n  return transputer_get (vstate) / 4294967296.0 ;\n}\n\nstatic void\ntransputer_set (void *vstate, unsigned long int s)\n{\n  transputer_state_t *state = (transputer_state_t *) vstate;\n\n  if (s == 0)\n    s = 1 ;   /* default seed is 1. */\n\n  state->x = s;\n\n  return;\n}\n\nstatic const gsl_rng_type transputer_type =\n{\"transputer\",                          /* name */\n 0xffffffffUL,                  /* RAND_MAX */\n 1,                             /* RAND_MIN */\n sizeof (transputer_state_t),\n &transputer_set,\n &transputer_get,\n &transputer_get_double};\n\nconst gsl_rng_type *gsl_rng_transputer = &transputer_type;\n", "meta": {"hexsha": "a2c422ab925caf874b7055e5cf5e877d5e97cd35", "size": 2284, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/rng/transputer.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/transputer.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/transputer.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 27.1904761905, "max_line_length": 81, "alphanum_fraction": 0.6983362522, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3976584546950499}}
{"text": "#ifndef ALM_L_KATYUSHA_H\n#define ALM_L_KATYUSHA_H\n\n#include \"L_Katyusha.h\"\n\n\n#include <string>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <stdio.h>      /* printf */\n#include <time.h>\n#include <fstream>\n#include <algorithm>\n#include <iomanip>\n#include <ctime>\n#include <sstream>\n//#include \"cmd_line.h\"\n\n\n//This class implements the method IPALM_L_Katyusha\n\n/*\nThe optimization problem to solve is:\n\nmin f_0(x)+\\sum_{i=1}^m h_i(f_i(x))+P(x)\n\nx is a d-dimensional vector.\n\n// Each subproblem solves problem of the form\nf_0(x)+ \\sum_{i=1}^m h_{\\beta_s}^i(f_i(x);\\lambda_s^i) +g(x)+ \\beta_s/2\\|x-x_s\\|^2\n by L_Katyuhsa\n*/\n\ntemplate<typename L, typename D>\nclass ALM_L_Katyusha: public L_Katyusha<L, D>\n{\nprivate:\n\n\n\nprotected:\n\n\n  std::vector<D> x_s;\n\n  std::vector<D> old_x_s;\n\n  std::vector<D> lambda_s;\n\n  std::vector<D> old_lambda_s;\n\n  std::vector<D> x_tmp;\n\n  std::vector<D> g_tmp;\n\n  std::vector<D> g_tmp_x;\n  std::vector<D> g_tmp_w;\n  std::vector<D> valuefi;\n\n\n\n\n  std::vector<D> is_feasiblity_constraint;\n\n  D beta_s;\n\n  D epsilon_s;\n\n  D m_s;\n\n  D m_0;\n\n  L m;\n\n  L d;\n\n  D eta;\n\n  D rho;\n\n  D tau_s;\n\n  std::vector<D> L_phi;\n\n  D function_value;\n\n  D infeasibility;\n\n  L print_every_N_ALM;\n\n  D running_time_ALM;\n\n  L nb_outer_iters;\n\n  ofstream samp_ALM;\n\n\npublic:\n\n  D mu_g;\n\n  D lambda1;\n\n  D lambda2;\n\n\n\n\n  virtual inline void set_Li_Lf(){}\n\n  virtual inline D value_of_P(vector<D> &){return D(NULL);}\n  virtual inline void prox_of_P(D, vector<D> &, vector<D> &){} //prox_of_P(L,x,y) computes y=argmin{P(u)+L/2||u-x||^2}\n  virtual inline D prox_of_h_star_j(D,D, L){return D(NULL);} //prox_of_h_star_j(x,beta,j) computes argmin{h*(y)+beta/2(y-x)^2}\n  virtual inline D value_of_h_star_j(D, L){return D(NULL);}\n  virtual inline void compute_gradient_f0(vector<D> &,vector<D> &){} //compute_gradient_f0(x,g) computes g=nabla f0(x)\n  virtual inline D compute_gradient_and_value_f_i(vector<D> &,vector<D> &, L){return D(NULL);}//compute_gradient_and_value_f_i(i,x,g) computes g=nabla f_i(x) and return f_i(x)\n\n\n  virtual inline D value_of_h_j(D, L){return D(NULL);}\n  virtual inline D distance_to_domain_of_h_j(D,L){return D(NULL);}\n\n  virtual inline D value_of_f0(vector<D> &){return D(NULL);} //f0(x)\n  virtual inline D value_of_f_i(vector<D> &,L){return D(NULL);} // f_i(x)\n  virtual inline void set_dimension(){} // set the value of m and d\n  virtual inline void set_is_feasibility_constraint(){}\n\n  ALM_L_Katyusha()\n  : L_Katyusha<L,D>()\n  {\n\n  }\n\n\n\n  D value_of_phi_i(L i){\n    D res= 0;\n    if (i==0)\n    res=value_of_f0(this->x);\n    else\n    {\n      D fi=value_of_f_i(this->x,i);\n      i=i-1;\n      D lambdasi=lambda_s[i];\n      D tmp= prox_of_h_star_j(fi/beta_s+ lambdasi,beta_s,i);\n      res=fi*tmp- value_of_h_star_j(tmp,i)- beta_s/2*(tmp- lambdasi)*(tmp- lambdasi);\n    }\n    return this->nsamples*res;\n  }\n\n  void compute_full_gradient(vector<D> & x, vector<D> & gx){\n    compute_gradient_f0(x,gx);\n    for(L i=0;i<m;i++){\n          D fi=compute_gradient_and_value_f_i(x,g_tmp,i+1);\n          D tmp= prox_of_h_star_j(fi/beta_s+ lambda_s[i],beta_s,i);\n          for(L j=0;j<d;j++)\n            gx[j]+=g_tmp[j]*tmp;\n    }\n  }\n\n  void compute_batch_delta_gradient(){\n    for (L j=0; j< this->batch_size; j++){\n      L s= this->batch_i[j];\n      if(s==0){\n        compute_gradient_f0(this->x,g_tmp_x);\n        compute_gradient_f0(this->w,g_tmp_w);\n        add_up(1.,1.,this->theta_S[s]);\n      }\n      else{\n        L i=s-1;\n        D fi_x=compute_gradient_and_value_f_i(this->x,g_tmp_x,s);\n        D tmp_x= prox_of_h_star_j(fi_x/beta_s+ lambda_s[i],beta_s,i);\n        D fi_w=compute_gradient_and_value_f_i(this->w,g_tmp_w,s);\n        D tmp_w= prox_of_h_star_j(fi_w/beta_s+ lambda_s[i],beta_s,i);\n        add_up(tmp_x,tmp_w,this->theta_S[s]);\n      }\n    }\n  }\n\n  void  add_up(D fx, D fw, D c){\n      for(L i=0;i<d;i++)\n        this->batch_delta_gradient[i]+=(fx*g_tmp_x[i]-fw*g_tmp_w[i])*c;\n    }\n\n\n\n  inline D value_of_g(){\n    D res= value_of_P(this->x);\n    for(L i=0;i<d;i++)\n      res+= 0.5*beta_s*(this->x[i]- x_s[i])*(this->x[i]- x_s[i]);\n    return res;\n  }\n\n  void prox_of_g(D stepsz, vector<D> & x, vector<D> & g, vector<D> & nextx){\n    D tmp0=beta_s+stepsz;\n    for(L i=0;i<d;i++)\n     x_tmp[i]=(beta_s*x_s[i]+stepsz*x[i]-g[i])/tmp0;\n    prox_of_P(tmp0, x_tmp, nextx);\n  }\n\n\n\n  void compute_x(){\n    for (L i=0; i< d; i++){\n      x_s[i]= this->x[i];\n    }\n    for (L i= 0; i< m; i++){\n      valuefi[i]=value_of_f_i(x_s,i+1);\n    }\n  }\n\n  void update_lambda(){\n    for(L j=0;j<m;j++)\n    {\n      D fi= valuefi[j];\n      lambda_s[j]= prox_of_h_star_j(fi/beta_s+ lambda_s[j],beta_s,j);\n    }\n  }\n\n\n\n  void compute_function_value(){\n    function_value=value_of_f0(x_s);\n    D res= 0;\n    for (L i= 0; i< m; i++){\n      D fi=value_of_f_i(x_s,i+1);\n      if(is_feasiblity_constraint[i]==1){\n        D tmp=distance_to_domain_of_h_j(fi,i);\n        res+=tmp*tmp;\n      }\n      else\n       function_value+=value_of_h_j(fi,i);\n    }\n    function_value+=value_of_P(x_s);\n    infeasibility=sqrt(res);\n  }\n\n\n\n\n\ninline void compute_m0(D beta0, D val_eta, D val_rho, L val_tau){\n  cout<<\"beta0=\"<<beta0<<\"val_eta=\"<<val_eta<<\"; val_rho=\"<<val_rho<<\"; val_tau=\"<<val_tau<<endl;\n  m_s= this->nsamples/val_tau*1e+6;\n\n  //D tmp7=1-val_tau/this->n*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0));\n  //cout<<\"tmp7: \"<<tmp7<<\"; \"<<val_tau/(this->n+0.)*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0))<<endl;\n  //m_0=(2*log(val_rho)+log(val_eta)+log(2))/log(tmp7);\n\n  cout<<\" m_s=\"<<m_s<<endl;\n}\n\n\n\nvoid Initialize(D beta_0, D epsilon_0,  D val_eta, D val_rho,L val_tau, vector<D> & x0,vector<D> & y0){\n  cout<<\"start initializing ALM\"<<endl;\n  set_dimension();\n  this->nsamples=m+1;\n  this->nfeatures=d;\n  this->tau=val_tau;\n\n\n  beta_s=beta_0;\n  tau_s= 1;\n  epsilon_s=epsilon_0;\n  compute_m0(beta_s,val_eta,val_rho,val_tau);\n\n  eta=val_eta;\n  rho=val_rho;\n\n  x_s.resize(d,0);\n  old_x_s.resize(d,0);\n  lambda_s.resize(m,0);\n  old_lambda_s.resize(m,0);\n  for(L i=0;i<d;i++){\n    x_s[i]=x0[i];\n    old_x_s[i]= x0[i];\n  }\n  for(L j=0;j<m;j++){\n    lambda_s[j]=y0[j];\n    old_lambda_s[j]= y0[j];\n  }\n  g_tmp.clear();\n  g_tmp.resize(d,0);\n  g_tmp_x.clear();\n  g_tmp_x.resize(d,0);\n  g_tmp_w.clear();\n  g_tmp_w.resize(d,0);\n  valuefi.clear();\n  valuefi.resize(m,0);\n  x_tmp.clear();\n  x_tmp.resize(d,0);\n  is_feasiblity_constraint.resize(m,0);\n\n  set_is_feasibility_constraint();\n  cout<<\"Initialization ALM finished!\"<<endl;\n\n}\n\nvoid reset_everything(){\n  epsilon_s*=rho;\n  beta_s*=eta;\n}\n\nvoid update_m_s(L val_tau){\n  D tmp= 0;\n  D tmpx= 0;\n  D tmpy= 0;\n  D tmpy2= 0;\n  for(L j=0;j<m;j++)\n  {\n    D tmp_p= prox_of_h_star_j(valuefi[j]/beta_s/eta+ lambda_s[j], beta_s/eta, j);\n    tmpy+=(tmp_p- lambda_s[j])*(tmp_p- lambda_s[j]);\n    tmp+= (lambda_s[j]- old_lambda_s[j])*(lambda_s[j]- old_lambda_s[j]);\n    tmpy2+= (beta_s*eta*lambda_s[j]- beta_s*old_lambda_s[j])*(beta_s*eta*lambda_s[j]- beta_s*old_lambda_s[j]);\n  }\n  for (L i= 0; i< d;i++){\n    tmpx= (x_s[i]- old_x_s[i])*(x_s[i]- old_x_s[i]);\n  }\n  D tmp4= 2*epsilon_s+ beta_s*tmp;\n  D tmp5= (1- eta)*beta_s/2*tmpy;\n  D tmp6= 0;\n  D tmp7= sqrt(tmp)*sqrt(tmpy2);\n  D tmp1= log(tmp4+ tmp5+ tmp6+ tmp7+ 2/(2*eta- 1)*tau_s*beta_s/2*tmpx);\n  D tmp2= log(epsilon_s)+ log(rho)- log(2);\n  D tmp3= sqrt(beta_s/this->sumLi);\n  m_s= ceil((tmp1- tmp2)/log(2)*4*max(1.0+this->nsamples,1/tmp3)/val_tau);\n  cout<<\"here here=\"<<tmp4<<\" tmp5=\"<<tmp5<<\" tmp6=\"<<tmp6<<\" tmp7=\"<<tmp7<<\" tmp1=\"<<tmp1<<\" tmp2=\"<<tmp2<<\" tmp3=\"<<tmp3<<endl;\n}\n\ninline void compute_and_record_res(){\n  if(nb_outer_iters%print_every_N_ALM==0){\n    compute_function_value();\n    cout<<setprecision(9)<<\"Iteration: \"<<nb_outer_iters<<\"; time=\"<<running_time_ALM<< \"; function value=\"<<function_value<<\"; infeasibility= \"<< infeasibility<<endl;\n    samp_ALM<<setprecision(9)<<nb_outer_iters<<\" \"<<running_time_ALM<<\" \"<< function_value<<\" \"<< infeasibility<<endl;\n  }\n}\n\nvoid ALM_solve_with_L_Katyusha(D beta_0, D epsilon_0,  D eta, D rho,vector<D> & x0,vector<D> & y0, L val_tau, L max_nb_outer, L p_N_1, L p_N_2, string filename1, string filename2, D time){\n  Initialize(beta_0, epsilon_0, eta, rho,val_tau, x0, y0);\n  nb_outer_iters=0;\n  filename1= \"results/ALM_\"+filename1;\n  samp_ALM.open(filename1.c_str());\n  running_time_ALM=0;\n  print_every_N_ALM=p_N_1;\n  this->set_print_every_N(p_N_2);\n  compute_and_record_res();\n\n while(nb_outer_iters<max_nb_outer){\n  D start= std::clock();\n  cout<<\"m_s= \"<< ceil(m_s/this->nsamples*val_tau)<<\"; beta_s=\"<<beta_s<<\"; epsilon_s=\"<<epsilon_s<<endl;\n  this->loopless2(x_s, filename2, mu_g+ tau_s*beta_s,  ceil(m_s/this->nsamples*val_tau), epsilon_s, val_tau, 1, 1, 0, 1);\n  for(L i=0;i<d;i++){\n    old_x_s[i]=x_s[i];\n  }\n  for(L i=0;i<m;i++){\n    old_lambda_s[i]=lambda_s[i];\n  }\n  compute_x();\n  update_lambda();\n  update_m_s(val_tau);\n  nb_outer_iters++;\n  running_time_ALM+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  compute_and_record_res();\n  start = std::clock();\n  reset_everything();\n  running_time_ALM+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n    if (running_time_ALM> time){\n      break;\n    }\n  }\n}\n\n};\n\n#endif /* MIN_SMOOTH_CONVEX_H */\n", "meta": {"hexsha": "509369ffc0255ba641bd454d27c670d660cf5b7a", "size": 9134, "ext": "h", "lang": "C", "max_stars_repo_path": "IPALM/ALM_L_Katyusha.h", "max_stars_repo_name": "lifei16/supplementary_code", "max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IPALM/ALM_L_Katyusha.h", "max_issues_repo_name": "lifei16/supplementary_code", "max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPALM/ALM_L_Katyusha.h", "max_forks_repo_name": "lifei16/supplementary_code", "max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z", "avg_line_length": 24.2925531915, "max_line_length": 188, "alphanum_fraction": 0.6352091088, "num_tokens": 3121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.39765845469504985}}
{"text": "/* linalg/choleskyc.c\n * \n * Copyright (C) 2007 Patrick Alken\n * Copyright (C) 2010 Huan Wu (gsl_linalg_complex_cholesky_invert)\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_errno.h>\n\n/*\n * This module contains routines related to the Cholesky decomposition\n * of a complex Hermitian positive definite matrix.\n */\n\nstatic void cholesky_complex_conj_vector(gsl_vector_complex *v);\n\n/*\ngsl_linalg_complex_cholesky_decomp()\n  Perform the Cholesky decomposition on a Hermitian positive definite\nmatrix. See Golub & Van Loan, \"Matrix Computations\" (3rd ed),\nalgorithm 4.2.2.\n\nInputs: A - (input/output) complex postive definite matrix\n\nReturn: success or error\n\nThe lower triangle of A is overwritten with the Cholesky decomposition\n*/\n\nint\ngsl_linalg_complex_cholesky_decomp(gsl_matrix_complex *A)\n{\n  const size_t N = A->size1;\n  \n  if (N != A->size2)\n    {\n      GSL_ERROR(\"cholesky decomposition requires square matrix\", GSL_ENOTSQR);\n    }\n  else\n    {\n      size_t i, j;\n      gsl_complex z;\n      double ajj;\n\n      for (j = 0; j < N; ++j)\n        {\n          z = gsl_matrix_complex_get(A, j, j);\n          ajj = GSL_REAL(z);\n\n          if (j > 0)\n            {\n              gsl_vector_complex_const_view aj =\n                gsl_matrix_complex_const_subrow(A, j, 0, j);\n\n              gsl_blas_zdotc(&aj.vector, &aj.vector, &z);\n              ajj -= GSL_REAL(z);\n            }\n\n          if (ajj <= 0.0)\n            {\n              GSL_ERROR(\"matrix is not positive definite\", GSL_EDOM);\n            }\n\n          ajj = sqrt(ajj);\n          GSL_SET_COMPLEX(&z, ajj, 0.0);\n          gsl_matrix_complex_set(A, j, j, z);\n\n          if (j < N - 1)\n            {\n              gsl_vector_complex_view av =\n                gsl_matrix_complex_subcolumn(A, j, j + 1, N - j - 1);\n\n              if (j > 0)\n                {\n                  gsl_vector_complex_view aj =\n                    gsl_matrix_complex_subrow(A, j, 0, j);\n                  gsl_matrix_complex_view am =\n                    gsl_matrix_complex_submatrix(A, j + 1, 0, N - j - 1, j);\n\n                  cholesky_complex_conj_vector(&aj.vector);\n\n                  gsl_blas_zgemv(CblasNoTrans,\n                                 GSL_COMPLEX_NEGONE,\n                                 &am.matrix,\n                                 &aj.vector,\n                                 GSL_COMPLEX_ONE,\n                                 &av.vector);\n\n                  cholesky_complex_conj_vector(&aj.vector);\n                }\n\n              gsl_blas_zdscal(1.0 / ajj, &av.vector);\n            }\n        }\n\n      /* Now store L^H in upper triangle */\n      for (i = 1; i < N; ++i)\n        {\n          for (j = 0; j < i; ++j)\n            {\n              z = gsl_matrix_complex_get(A, i, j);\n              gsl_matrix_complex_set(A, j, i, gsl_complex_conjugate(z));\n            }\n        }\n\n      return GSL_SUCCESS;\n    }\n} /* gsl_linalg_complex_cholesky_decomp() */\n\n/*\ngsl_linalg_complex_cholesky_solve()\n  Solve A x = b where A is in cholesky form\n*/\n\nint\ngsl_linalg_complex_cholesky_solve (const gsl_matrix_complex * cholesky,\n                                   const gsl_vector_complex * b,\n                                   gsl_vector_complex * x)\n{\n  if (cholesky->size1 != cholesky->size2)\n    {\n      GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (cholesky->size1 != b->size)\n    {\n      GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n    }\n  else if (cholesky->size2 != x->size)\n    {\n      GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n    }\n  else\n    {\n      gsl_vector_complex_memcpy (x, b);\n\n      /* solve for y using forward-substitution, L y = b */\n\n      gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasNonUnit, cholesky, x);\n\n      /* perform back-substitution, L^H x = y */\n\n      gsl_blas_ztrsv (CblasLower, CblasConjTrans, CblasNonUnit, cholesky, x);\n\n      return GSL_SUCCESS;\n    }\n} /* gsl_linalg_complex_cholesky_solve() */\n\n/*\ngsl_linalg_complex_cholesky_svx()\n  Solve A x = b in place where A is in cholesky form\n*/\n\nint\ngsl_linalg_complex_cholesky_svx (const gsl_matrix_complex * cholesky,\n                                 gsl_vector_complex * x)\n{\n  if (cholesky->size1 != cholesky->size2)\n    {\n      GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (cholesky->size2 != x->size)\n    {\n      GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n    }\n  else\n    {\n      /* solve for y using forward-substitution, L y = b */\n\n      gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasNonUnit, cholesky, x);\n\n      /* perform back-substitution, L^H x = y */\n\n      gsl_blas_ztrsv (CblasLower, CblasConjTrans, CblasNonUnit, cholesky, x);\n\n      return GSL_SUCCESS;\n    }\n} /* gsl_linalg_complex_cholesky_svx() */\n\n\n/******************************************************************************\n\ngsl_linalg_complex_cholesky_invert()\n  Compute the inverse of an Hermitian positive definite matrix in\n  Cholesky form.\n\nInputs: LLT - matrix in cholesky form on input\n              A^{-1} = L^{-H} L^{-1} on output\n\nReturn: success or error\n******************************************************************************/\n\nint\ngsl_linalg_complex_cholesky_invert(gsl_matrix_complex * LLT)\n{\n  if (LLT->size1 != LLT->size2)\n    {\n      GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n    }\n  else\n    {\n      size_t N = LLT->size1;\n      size_t i, j;\n      gsl_vector_complex_view v1;\n\n      /* invert the lower triangle of LLT */\n      for (i = 0; i < N; ++i)\n        {\n          double ajj;\n          gsl_complex z;\n\n          j = N - i - 1;\n\n          { \n            gsl_complex z0 = gsl_matrix_complex_get(LLT, j, j);\n            ajj = 1.0 / GSL_REAL(z0); \n          }\n\n          GSL_SET_COMPLEX(&z, ajj, 0.0);\n          gsl_matrix_complex_set(LLT, j, j, z);\n\n          {\n            gsl_complex z1 = gsl_matrix_complex_get(LLT, j, j);\n            ajj = -GSL_REAL(z1);\n          }\n\n          if (j < N - 1)\n            {\n              gsl_matrix_complex_view m;\n              \n              m = gsl_matrix_complex_submatrix(LLT, j + 1, j + 1,\n                                       N - j - 1, N - j - 1);\n              v1 = gsl_matrix_complex_subcolumn(LLT, j, j + 1, N - j - 1);\n\n              gsl_blas_ztrmv(CblasLower, CblasNoTrans, CblasNonUnit,\n                             &m.matrix, &v1.vector);\n\n              gsl_blas_zdscal(ajj, &v1.vector);\n            }\n        } /* for (i = 0; i < N; ++i) */\n\n      /*\n       * The lower triangle of LLT now contains L^{-1}. Now compute\n       * A^{-1} = L^{-H} L^{-1}\n       *\n       * The (ij) element of A^{-1} is column i of conj(L^{-1}) dotted into\n       * column j of L^{-1}\n       */\n\n      for (i = 0; i < N; ++i)\n        {\n          gsl_complex sum;\n          for (j = i + 1; j < N; ++j)\n            {\n              gsl_vector_complex_view v2;\n              v1 = gsl_matrix_complex_subcolumn(LLT, i, j, N - j);\n              v2 = gsl_matrix_complex_subcolumn(LLT, j, j, N - j);\n\n              /* compute Ainv[i,j] = sum_k{conj(Linv[k,i]) * Linv[k,j]} */\n              gsl_blas_zdotc(&v1.vector, &v2.vector, &sum);\n\n              /* store in upper triangle */\n              gsl_matrix_complex_set(LLT, i, j, sum);\n            }\n\n          /* now compute the diagonal element */\n          v1 = gsl_matrix_complex_subcolumn(LLT, i, i, N - i);\n          gsl_blas_zdotc(&v1.vector, &v1.vector, &sum);\n          gsl_matrix_complex_set(LLT, i, i, sum);\n        }\n\n      /* copy the Hermitian upper triangle to the lower triangle */\n\n      for (j = 1; j < N; j++)\n        {\n          for (i = 0; i < j; i++)\n            {\n              gsl_complex z = gsl_matrix_complex_get(LLT, i, j);\n              gsl_matrix_complex_set(LLT, j, i, gsl_complex_conjugate(z));\n            }\n        } \n\n      return GSL_SUCCESS;\n    }\n} /* gsl_linalg_complex_cholesky_invert() */\n\n\n/********************************************\n *           INTERNAL ROUTINES              *\n ********************************************/\n\nstatic void\ncholesky_complex_conj_vector(gsl_vector_complex *v)\n{\n  size_t i;\n\n  for (i = 0; i < v->size; ++i)\n    {\n      gsl_complex z = gsl_vector_complex_get(v, i);\n      gsl_vector_complex_set(v, i, gsl_complex_conjugate(z));\n    }\n} /* cholesky_complex_conj_vector() */\n", "meta": {"hexsha": "9cff18f5fbc434192ea3a9c40ab6f8ef33d9f7bb", "size": 9227, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/linalg/choleskyc.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/choleskyc.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "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/BaselineMethods/MNE/C++/gsl-2.4/linalg/choleskyc.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 28.5665634675, "max_line_length": 81, "alphanum_fraction": 0.5488241032, "num_tokens": 2465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.39765844787429333}}
{"text": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <gsl/gsl_rng.h>\r\n#include <math.h>\r\n#include <time.h>\r\n#include <stdbool.h>\r\n#include \"bb_smc.h\"\r\n\r\n\r\n/* ==========================================================\r\nLast update: 26.4.20 -- v1.1\r\n\r\nABC-SMC (parallel version) \r\nAuthor: Marco Esposito\r\n=========================================================== */\r\n\r\n#define n_param 1\r\n#define size_data 10\r\n\r\n#define a0 0.5\r\n#define b0 0.5\r\n#define std_ker 0.4\r\n#define striding_size 2\r\n#define n 10\r\n\r\n\r\n\r\n// ARGUMENT NUMBER 1: time at which the simulation starts\r\n// ARGUMENT NUMBER 2: seed\r\n// ARGUMENT NUMBER 3: number of particles to consider for the simulation (for shorter runs)\r\n\r\n\r\nint main(int argc, char *argv[]) {\r\n\r\n\t/* ==================== VARIABLES DECLARATION ======================== */\r\n\tFILE *w_theta;\r\n\tchar weights_theta[500];\r\n\r\n\tint time = atoi(argv[1]);\r\n\tint seed = atoi(argv[2]); \r\n\tint n_particles = atoi(argv[3]);\r\n\r\n\tdouble weight;\r\n\tint status;\r\n\tdouble distance;\r\n\r\n\tint k;\r\n\tdouble** theta;\r\n\ttheta = malloc((n_param) * sizeof(double*));\r\n\tfor (k=0; k<n_param; k++) {\r\n\t\ttheta[k] = calloc(n_particles, sizeof(double));\r\n\t}\r\n\r\n\tdouble* weights;\r\n\tweights = malloc((n_particles) * sizeof(double));\r\n\r\n\tdouble* theta_star;\r\n\ttheta_star = malloc((n_param) * sizeof(double));\r\n\r\n\tdouble* std_kernel;\r\n\tstd_kernel = malloc((n_param) * sizeof(double));\r\n\r\n\tstd_kernel[0] = std_ker;\r\n\r\n\tdouble r2, aux;\r\n\tint i, l, i_th, l_temp;\r\n\tint sample_accepted;\r\n\t/* =============================================== */\r\n\r\n\t/* If the number of arguments is 4, then argv[3] is the number of particles to consider.\r\n\tThis is useful when a shorter run is needed (necessary to specify as weights have to \r\n\tbe normalized accordingly!) */ \r\n\tif (argc==4) {sprintf(weights_theta, \"w_theta_time_%d_part_%d.txt\", time, n_particles);}\r\n\telse {\r\n\t\tprintf(\"argc = %d\\n\", argc);\r\n\t\tprintf(\"Usage: %s\\n\", argv[0]);\r\n\t\tprintf(\"      %s [parameters] \\n\", argv[0]);\r\n\t\texit(1);\r\n\t}\r\n\r\n\t// int n_param = 1;\r\n\r\n\r\n\t/* ============== IMPORT THE FILE WITH THE DATA =========== */\r\n\tint y[size_data];\r\n\tstatus = import_data_BB(y, size_data);\r\n\tif (status == 1) {\r\n\t\texit(1);\r\n\t}\r\n\tdouble mean_y = mean_int(y, size_data);\r\n\t/* ========================================================= */\r\n\r\n\r\n\t/* ==================== READ THE DISTANCE FROM A FILE ===================== */\r\n\tdouble eps_t;\r\n\tstatus = read_epsilon(eps_t, time);\r\n\tif (status == 1) {\r\n\t\texit(1);\r\n\t}\r\n\t/* ========================================================================= */\r\n\r\n\r\n\t/* ================== set up GSL RNG =================== */\r\n\tgsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);\r\n\tgsl_rng_set (r, seed+11); // set seed\r\n\t/* ===================================================== */\r\n\r\n\tsample_accepted = 1;\r\n\r\n\t/* =============================================================================== */\r\n\t/* =============================== START THE ABC ROUND =========================== */\r\n\t/* =============================================================================== */\r\n\twhile (sample_accepted==0) {\r\n\t\r\n\t\ti_th = -1;\r\n\r\n\t\taux = 0.;\r\n\t\tw_theta = fopen(weights_theta, \"r\");\r\n\t\tif (w_theta == NULL) {printf(\"File %s not found!!!\\n\", weights_theta);}\r\n\t\tfscanf(w_theta, \"%*[^\\n]\");\r\n\t\tr2 = RND;\r\n\t\tfor (i=0; i<n_particles; i++) {\r\n\t\t\tfscanf(w_theta, \"%lf %lf\", &weights[i], &theta[0][i]);\r\n\t\t\taux += weights[i];\r\n\t\t\tif (r2<aux) {\r\n\t\t\t\tif (i_th<0) {\r\n\t\t\t\t\ti_th = i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tfclose(w_theta);\r\n\r\n\r\n\t\tdouble* a;\r\n\t\tdouble* b;\r\n\r\n\t\ta = malloc((n_param) * sizeof(double));\r\n\t\tb = malloc((n_param) * sizeof(double));\r\n\r\n\t\ta[0] = a0; b[0] = b0;\t\r\n\t\t\r\n\t\t\r\n\t\t/* YOU CAN SIMPLY PERTURB THE PARTICLE WITH A KERNEL AT WILL WITHOUT DOING \r\n\t\tTHE LOOP OVER PARAMETERS AS IT'S JUST ONE IN THIS CASE. POSSIBLY IMPLEMENT \r\n\t\tTHIS IN A FUNCTION AND PUT IT IN THE .h FILE */\r\n\t\tl_temp = 0;\r\n\t\t//Perturb the i_th particles via a gaussian kernel with std = std_kernel\r\n\t\tfor (l=0; l<n_param; l++) {\r\n\t\t\ttheta_star[l] = gsl_ran_gaussian(r, std_kernel[l]) + theta[l][i_th];\r\n\t\t\t//If the prior on theta_star[l] is zero when calculated in theta_star[l], \r\n\t\t\t//the new particle is rejected and we start over \r\n\t\t\tif (prior_BB(l, theta_star[l], a0, b0) == 0.) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tl_temp = l;\r\n\t\t}\r\n\t\tif (l_temp < n_param-1) {continue;}\r\n\r\n\r\n\t\t/* HERE YOU CAN JUST IMPLEMENT THIS WITH A BINARY FUNCTION sample_accepted = verify_sample(distance, ..) */\r\n\t\t// -- If the distance function is too large, start over\r\n\t\t// -- If all the conditions are fulfilled, the sample is accepted\r\n\t\tint g[size_data];\r\n\t\tfor (d=0; d<size_data; d++) {g[d] = gsl_ran_binomial(r, theta_star[0], n);}\r\n\t\t\r\n\t\tif (mean_int(g, size_data) - mean_y == 0) {\r\n\t\t\tsample_accepted = 1; \r\n\t\t}\r\n\t\telse {continue;} // Start over if distance function not equal to zero\r\n\r\n\r\n\r\n\r\n\t\t/* ================ CALCULATE THE WEIGHTS ===================== */\r\n\t\tdouble tot_prior_pdf = 1.;\r\n\t\tdouble kernel_value_pdf[n_particles];\r\n\t\tfor (i=0; i<n_particles; i++) {kernel_value_pdf[i] = 1.;}\r\n\r\n\t\tfor (l=0; l<n_param; l++) {\r\n\t\t\ttot_prior_pdf *= prior_BB(l, theta_star[l], a0, b0);\r\n\t\t}\r\n\r\n\t\tdouble denominator = 0.;\r\n\t\tfor (i=0; i<n_particles; i++) {\r\n\t\t\tfor (l=0; l<n_param; l++) {\r\n\t\t\t\tkernel_value_pdf[i] *= gsl_ran_gaussian_pdf(theta_star[l] - theta[l][i], std_kernel[l]);\r\n\t\t\t}\r\n\t\t\tdenominator += weights[i] * kernel_value_pdf[i];\r\n\t\t}\t\r\n\t\t/* =============================================================== */\r\n\r\n\t\tweight = tot_prior_pdf/(float)(denominator);\r\n\r\n\t\t/* ============== CREATE THE FILE WITH WEIGHTS AND PARAMETERS ============= */\r\n\t\twrite_particles_BB(theta_star, time, seed, striding_size, weight);\r\n\t\t/* ===================================================================== */\r\n\r\n\r\n\t\tfree(a);\r\n\t\tfree(b);\r\n\r\n\t} //END OF THE WHILE LOOP -- PARTICLE WAS ACCEPTED\r\n\r\n\r\n\r\n\r\n\t/* ====================== CREATE THE FILE WITH THE DISTANCE ============== */\r\n\twrite_epsilon(distance, time, seed, striding_size);\r\n\t/* ======================================================================= */\r\n\r\n\r\n\r\n\tfor (k=0; k<n_param; k++) {\r\n\t\tfree(theta[k]);\r\n\t}\r\n\tfree(theta);\r\n\tfree(weights);\r\n\tfree(theta_star);\r\n\tfree(std_kernel);\r\n\r\n\r\n\treturn 0;\r\n} //End of the program\r\n", "meta": {"hexsha": "2fa179c225f2f7a358b7a3c7cb9d09f566d668f1", "size": 6186, "ext": "c", "lang": "C", "max_stars_repo_path": "bb_model/smc_general.c", "max_stars_repo_name": "espoma/Data_Science", "max_stars_repo_head_hexsha": "137dd743498c3ff554d971d83f0ade4045049d0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T12:57:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T09:06:19.000Z", "max_issues_repo_path": "bb_model/smc_general.c", "max_issues_repo_name": "espoma/Data_Science", "max_issues_repo_head_hexsha": "137dd743498c3ff554d971d83f0ade4045049d0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bb_model/smc_general.c", "max_forks_repo_name": "espoma/Data_Science", "max_forks_repo_head_hexsha": "137dd743498c3ff554d971d83f0ade4045049d0a", "max_forks_repo_licenses": ["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.6160714286, "max_line_length": 110, "alphanum_fraction": 0.5088910443, "num_tokens": 1584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3976450340180672}}
{"text": "#ifndef _NAMASTER_H_\n#define _NAMASTER_H_\n\n#ifndef NO_DOXY\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include <unistd.h>\n#include <math.h>\n#include <time.h>\n#include <complex.h>\n#include <omp.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_integration.h>\n#include <fftw3.h>\n#endif //NO_DOXY\n\n#define NMT_MAX(a,b)  (((a)>(b)) ? (a) : (b)) // maximum\n#define NMT_MIN(a,b)  (((a)<(b)) ? (a) : (b)) // minimum\n\n#ifdef _SPREC\ntypedef float flouble;\ntypedef float complex fcomplex;\n#else //_SPREC\ntypedef double flouble;\ntypedef double complex fcomplex;\n#endif //_SPREC\n\n/*! \\mainpage NaMaster C API\n *\n * Welcome to the documentation of NaMaster's C API. Navigate through the tabs above to learn more\n * about the different functionality implemented in the code.\n * \n * \\section general_notes General notes\n *   - Most users will prefer to use the python wrapper \"pymaster\", which mostly calls the \n       C-based functions.\n *   - NaMaster uses a \"row-major\" order to define the ordering of power spectra into vectors.\n       E.g. the cross-correlation of two spin-2 fields 'a' and 'b' would give rise to 4 power\n       spectra: Ea-Eb, Ea-Bb, Ba-Eb and Ba-Bb. These are stored into 1-dimensional arrays using\n       exactly that order. For the case of a spin-0 - spin-2 correlation, the ordering is\n       [T-E, T-B], where T is the spin-0 field and (E,B) are the harmonic components of the\n       spin-2 field.\n *   - The abbreviation MCM will often be used instead of \"mode-coupling matrix\".\n *   - SHT will sometimes be used for \"Spherical Harmonic Transform\". In the context of flat-sky\n       fields, this should be understood as a standard Fast Fourier Transform (FFT) (with \n       appropriate trigonometric factors if dealing with spin-2 fields).\n *   - FWHM will sometimes be used for \"Full-width at half-max\".\n * \n * \\section more_info More info\n *\n * Please refer to the README and LICENSE files for further information on installation,\n * credits and licensing. Do not hesitate to contact the authors (preferably via github\n * issues on https://github.com/LSSTDESC/NaMaster) if you encounter any problems using \n * the code.\n */\n\n/**\n * @brief Flat-sky bandpowers.\n *\n * This structure defines bandpowers for flat-sky power spectra.\n * These are currently defined only by band edges (assumed \n * flat weights within band).\n */\ntypedef struct {\n  int n_bands; //!< Number of bandpowers stored\n  flouble *ell_0_list; //!< Lower edge of each bandpower\n  flouble *ell_f_list; //!< Upper edge of each bandpower\n} nmt_binning_scheme_flat;\n\n/**\n * @brief nmt_binning_scheme_flat constructor for constant bandpowers\n *\n * nmt_binning_scheme_flat constructor for bandpowers with\n * constant width \\p nlb, from ell = 2 to ell = \\p lmax.\n * @param nlb Constant band width\n * @param lmax Maximum multipole\n * @return Allocated binning structure.\n */\nnmt_binning_scheme_flat *nmt_bins_flat_constant(int nlb,flouble lmax);\n\n/**\n * @brief nmt_binning_scheme_flat generic constructor.\n *\n * @param nell Number of bandpowers\n * @param l0 Lower edge of all bandpowers (should be allocated to nell elements).\n * @param lf Lower edge of all bandpowers (should be allocated to nell elements).\n * @return Allocated binning structure.\n */\nnmt_binning_scheme_flat *nmt_bins_flat_create(int nell,flouble *l0,flouble *lf);\n\n/**\n * @brief nmt_binning_scheme_flat destructor\n */\nvoid nmt_bins_flat_free(nmt_binning_scheme_flat *bin);\n\n/**\n * @brief Returns average of input power spectrum into bandpowers.\n *\n * @param bin nmt_binning_scheme_flat structure defining the bandpowers.\n * @param nl Number of elements in the input power spectra.\n * @param larr Array containing the \\p nl multipoles at which the input power\n *        spectrum is defined.\n * @param cls_in Array of \\p ncls input power spectra.\n * @param cls_out Array of \\p ncls averaged output power spectra. \n *        Should be allocated to the number of bandpowers defined \\p bin.\n * @param ncls Number of input/output power spectra.\n */\nvoid nmt_bin_cls_flat(nmt_binning_scheme_flat *bin,int nl,flouble *larr,flouble **cls_in,\n\t\t      flouble **cls_out,int ncls);\n\n/**\n * @brief Returns binned power spectra interpolated into an given set of multipoles.\n * \n * Nearest-neighbours interpolation is used.\n * @param bin nmt_binning_scheme_flat structure defining the bandpowers.\n * @param cls_in Array of \\p ncls input power spectra. Must have the same number of \n *        elements as bandpowers defined by \\p bin.\n * @param nl Number of elements in the output power spectra.\n * @param larr Array containing the \\p nl multipoles at which the output power \n *        spectrum are requested.\n * @param cls_out Array of \\p ncls interpolated output power spectra.\n * @param ncls Number of input/output power spectra.\n */\nvoid nmt_unbin_cls_flat(nmt_binning_scheme_flat *bin,flouble **cls_in,\n\t\t\tint nl,flouble *larr,flouble **cls_out,int ncls);\n\n/**\n * @brief Returns effective multipoles.\n * \n * Returns the mid point of each bandpower defined in \\p bin.\n * @param bin nmt_binning_scheme_flat structure defining the bandpowers.\n * @param larr Output array containing mid-points of the bandpowers.\n *        Should be preallocated to the correct number of bandpowers.\n */\nvoid nmt_ell_eff_flat(nmt_binning_scheme_flat *bin,flouble *larr);\n\n/**\n * @brief Fast bin-searching routine for flat-sky bandpowers\n *\n * Returns the bandpower index in which a given ell falls. The functions is designed\n * to be fast if a good guess for the bandpower index is supplied. A typical use would\n * be to iterate over ell values and pass, as a guess index, the index found in the\n * previous iteration.\n * @param bin nmt_binning_scheme_flat structure defining the bandpowers.\n * @param l Multipole for which you want the bandpower index.\n * @param il Guessed bandpower index.\n * @return Bandpower index.\n */\nint nmt_bins_flat_search_fast(nmt_binning_scheme_flat *bin,flouble l,int il);\n\n/**\n * @brief Full-sky bandpowers.\n *\n * This structure defines bandpowers for full-sky power spectra.\n * Although a given multipole ell can only contribute to one bandpower, \n * the distribution of ells per bandpower and their relative weights\n * is left completely free.\n */\ntypedef struct {\n  int n_bands; //!< Number of bandpowers.\n  int *nell_list; //!< Number of multipoles belonging to each bandpower.\n  int **ell_list; //!< List of multipoles in each bandpowers.\n  flouble **w_list; //!< List of weights associated to each multipole in \\p ell_list.\n  int ell_max; //!< Maximum multipole included.\n} nmt_binning_scheme;\n\n/**\n * @brief nmt_binning_scheme constructor for constant bandpowers.\n *\n * nmt_binning_scheme constructor for bandpowers with constant\n * width \\p nlb, from ell = 2 to ell = \\p lmax.\n * @param nlb Constant band width\n * @param lmax Maximum multipole\n * @return Allocated binning structure.\n */\nnmt_binning_scheme *nmt_bins_constant(int nlb,int lmax);\n\n/**\n * @brief  nmt_binning_scheme generic constructor.\n *\n * @param nell Number of elements in all subsequent arrays.\n * @param bpws Array of bandpower indices.\n * @param ells Array of multipole values. This function collects all multipoles\n *        into their associated bandpowers.\n * @param weights Array of weights associated to each multipole. Weights are \n *        normalized to 1 within each bandpower.\n * @param lmax Maximum multipole to consider.\n * @return Allocated binning structure.\n */\nnmt_binning_scheme *nmt_bins_create(int nell,int *bpws,int *ells,flouble *weights,int lmax);\n\n/**\n * @brief nmt_binning_scheme constructor from file\n *\n * Builds a nmt_binning_scheme structure from an ASCII file.\n * @param fname Path to file containing information to build bandpowers.\n *        The file should contain three columns, corresponding to:\n *        bandpower index, multipole and weight (in this order).\n *        See definition of nmt_bins_create().\n * @param lmax Maximum multipole to be considered.\n * @return Allocated binning structure.\n */\nnmt_binning_scheme *nmt_bins_read(char *fname,int lmax);\n\n/**\n * @brief nmt_binning_scheme destructor\n */\nvoid nmt_bins_free(nmt_binning_scheme *bin);\n\n/**\n * @brief Returns average of input power spectrum into bandpowers.\n *\n * @param bin nmt_binning_scheme structure defining the bandpowers.\n * @param cls_in Array of \\p ncls input power spectra. They should be \n *        defined in all ells that go into any bandpower defined by \\p bin.\n * @param cls_out Array of \\p ncls averaged output power spectra.\n *        Should be allocated to the number of bandpowers defined \\p bin.\n * @param ncls Number of input/output power spectra.\n */\nvoid nmt_bin_cls(nmt_binning_scheme *bin,flouble **cls_in,flouble **cls_out,int ncls);\n\n/**\n * @brief Returns binned power spectra interpolated into output multipoles.\n *\n * Top-hat interpolation is used (i.e. a given ell is associated with the binned power\n * spectrum value at the bandpower that ell corresponds to).\n * @param bin nmt_binning_scheme structure defining the bandpowers.\n * @param cls_in Array of \\p ncls input power spectra. Must have the same number of\n *        elements as bandpowers defined by \\p bin.\n * @param cls_out Array of \\p ncls interpolated output power spectra.\n * @param ncls Number of input/output power spectra.\n */\nvoid nmt_unbin_cls(nmt_binning_scheme *bin,flouble **cls_in,flouble **cls_out,int ncls);\n\n/**\n * @brief Returns effective multipoles.\n *\n * Return the weighted average multipole values within each bandpower defined by \\p bin.\n * @param bin nmt_binning_scheme structure defining the bandpowers.\n * @param larr Output array containing the effective multipole in each bandpower.\n *        Should be preallocated to the correct number of bandpowers.\n */\nvoid nmt_ell_eff(nmt_binning_scheme *bin,flouble *larr);\n\n/**\n * @brief Flat-sky Fourier-space function\n *\n * Unlike multipoles in harmonic space, in the case of full-sky operations, \n * wavenumbers k in Fourier space for flat-sky fields are in general continuous\n * variables. This structure helps define functions of these continuous variables.\n */\ntypedef struct {\n  int is_const; //!< If >0, this function is just a constant\n  flouble x0; //!< Lower edge of spline interpolation\n  flouble xf; //!< Upper edge of spline interpolation\n  flouble y0; //!< Function will take this value for x < \\p x0\n  flouble yf; //!< Function will take this value for x > \\p xf\n  gsl_spline *spl; //!< GSL spline interpolator.\n} nmt_k_function;\n\n/**\n * @brief nmt_k_function creator.\n *\n * @param nk Number of elements in input arrays.\n * @param karr k-values at which the input function is sampled.\n * @param farr Function values at k = \\p karr.\n * @param y0 Constant function value below interpolation range.\n * @param yf Constant function value above interpolation range.\n * @param is_const If non-zero, will create a constant function.\n *        In this case all previous arguments other than \\p y0 are ignored\n *        and the function will take this value for all k.\n */\nnmt_k_function *nmt_k_function_alloc(int nk,flouble *karr,flouble *farr,\n\t\t\t\t     flouble y0,flouble yf,int is_const);\n\n/**\n * @brief nmt_k_function destructor\n */\nvoid nmt_k_function_free(nmt_k_function *f);\n\n/**\n * @brief nmt_k_function evaluator.\n *\n * Returns value of function at \\p k.\n * @param f nmt_k_function to evaluate.\n * @param k Value of k for which you want f(k).\n * @param intacc GSL interpolation accelerator. If you don't want any, just pass a NULL pointer.\n */\nflouble nmt_k_function_eval(nmt_k_function *f,flouble k,gsl_interp_accel *intacc);\n\n/**\n * @brief Flat-sky information.\n *\n * This structure contains all the information defining a given rectangular flat-sky patch.\n * The structure also contains information about the optimal way of sampling the Fourier\n * version of this patch into rings of |k|.\n */\ntypedef struct {\n  int nx; //!< Number of grid points in the x dimension\n  int ny; //!< Number of grid points in the y dimension\n  long npix; //!< Total number of pixels (given by \\p nx * \\p ny\n  flouble lx; //!< Length of the x dimension (in steradians)\n  flouble ly; //!< Length of the y dimension (in steradians)\n  flouble pixsize; //!< Pixel area (given by \\p lx * \\p ly / ( \\p nx * \\p ny))\n  int n_ell; //!< Number of |k|-values for Fourier-space sampling.\n  flouble dell; //!< Width of the Fourier-space rings. This is found as min(2 &pi; / \\p lx,2 &pi; / \\p ly).\n  flouble i_dell; //!< 1 / \\p dell\n  flouble *ell_min; //!< Array of \\p n_ell values containing the lower edges of each of the |k| rings.\n  //  int *n_cells;\n} nmt_flatsky_info;\n\n/**\n * @brief nmt_flatsky_info constructor\n *\n * Builds nmt_flatsky_info from patch dimensions.\n * @param nx Number of grid points in the x dimension\n * @param ny Number of grid points in the y dimension\n * @param lx Length of the x dimension (in steradians)\n * @param ly Length of the y dimension (in steradians)\n * @return Allocated nmt_flatsky_info structure.\n */\nnmt_flatsky_info *nmt_flatsky_info_alloc(int nx,int ny,flouble lx,flouble ly);\n\n/**\n * @brief nmt_flatsky_info destructor.\n */\nvoid nmt_flatsky_info_free(nmt_flatsky_info *fs);\n\n/**\n * @brief Flat-sky field\n *\n * This structure contains all the information defining a spin-s flat-sky field.\n * This includes field values, masking, purification and contamination.\n */\ntypedef struct {\n  nmt_flatsky_info *fs; //!< Structure defining patch geometry.\n  long npix; //!< Number of pixels in all maps (also contained in \\p fs).\n  int pure_e; //!< >0 if E-modes have been purified.\n  int pure_b; //!< >0 if B-modes have been purified.\n  flouble *mask; //!< Field's mask (an array of \\p npix values).\n  fcomplex **a_mask; //!< Fourier transform of the mask. Only computed if E or B are purified.\n  int pol; //!< >0 if field is spin-2 (otherwise it's spin-0).\n  int nmaps; //!< Number of maps in the field (2 for spin-2, 1 for spin-0).\n  flouble **maps; //!< Observed field values. When initialized, these maps are already multiplied by the mask, contaminant deprojected and purified if requested.\n  fcomplex **alms; //!< Fourier-transfoms of the maps.\n  int ntemp; //!< Number of contaminant templates\n  flouble ***temp; //!< Contaminant template maps (mask-multiplied but NOT purified).\n  fcomplex ***a_temp; //!< Fourier-transfomrs of template maps (mask-multiplied AND purified if requested).\n  gsl_matrix *matrix_M; //!< Inverse contaminant covariance matrix (see scientific documentation or companion paper).\n  nmt_k_function *beam; //!< Function defining a circularly-symmetric beam function. Power spectra will be beam-deconvolved.\n} nmt_field_flat;\n\n/**\n * @brief nmt_field_flat destructor\n */\nvoid nmt_field_flat_free(nmt_field_flat *fl);\n\n/**\n * @brief nmt_field_flat constructor\n *\n * Builds an nmt_field_flat structure from input maps and patch parameters.\n * @param nx Number of grid points in the x dimension.\n * @param ny Number of grid points in the y dimension.\n * @param lx Length of the x dimension (in steradians).\n * @param ly Length of the y dimension (in steradians).\n * @param mask Field's mask (an array of \\p nx * \\p ny values).\n * @param pol >0 if this is a spin-2 field (spin-0 otherwise).\n * @param maps Observed field values BEFORE multiplying by the mask\n          (this is irrelevant for binary masks).\n * @param ntemp Number of contaminant templates affecting this field.\n * @param temp Contaminant template maps (again, NOT multiplied by the mask).\n * @param nl_beam Number of multipole values defining this field's beam.\n * @param l_beam Multipole values at which this field's beam is defined.\n * @param beam Beam values at ell = \\p l_beam. Pass a NULL pointer if you don't\n          want any beam (\\p nl_beam and \\p l_beam will be ignored).\n * @param pure_e Set to >0 if you want purified E-modes.\n * @param pure_b Set to >0 if you want purified B-modes.\n * @param tol_pinv Contaminant deprojection requires the inversion of the template\n          covariance matrix. This could be ill-defined if some templates are linearly\n\t  related. In this case we use a pseudo-inverse that accounts for this \n\t  possibility in a consistent way. Effectively this is a singular-value \n\t  decomposition. All eigenvalues that are smaller than \\p tol_pinv the largest\n\t  eigenvalue will be discarded.\n */\nnmt_field_flat *nmt_field_flat_alloc(int nx,int ny,flouble lx,flouble ly,\n\t\t\t\t     flouble *mask,int pol,flouble **maps,int ntemp,flouble ***temp,\n\t\t\t\t     int nl_beam,flouble *l_beam,flouble *beam,\n\t\t\t\t     int pure_e,int pure_b,double tol_pinv);\n\n/**\n * @brief Gaussian realizations of flat-sky fields \n *\n * Generates a Gaussian realization of an arbitrary list of possibly-correlated \n * fields with different spins.\n * @param nx Number of grid points in the x dimension.\n * @param ny Number of grid points in the y dimension.\n * @param lx Length of the x dimension (in steradians).\n * @param ly Length of the y dimension (in steradians).\n * @param nfields Number of fields to generate.\n * @param spin_arr Array (size \\p nfields) containing the spins of the fields to be generated.\n * @param nl_beam Number of multipoles at which the field beams are defined.\n * @param l_beam Array of multipoles at which the field beams are defined.\n * @param beam_fields Array of beams (one per field).\n * @param nl_cell Number of multipole values at which the input power spectra are provided.\n * @param l_cell Array of multipole values at which the input power spectra are provided.\n * @param cell_fields Array of input power spectra. Shape should be [\\p n_cls][\\p nl_cell],\n          where \\p n_cls is the number of power spectra needed to define all the fields.\n\t  This should be \\p n_cls = n_maps * (n_maps + 1) / 2, where n_maps is the total\n\t  number of maps required (1 for each spin-0 field, 2 for each spin-2 field). Power\n\t  spectra must be provided only for the upper-triangular part in row-major order\n\t  (e.g. if n_maps is 3, there will be 6 power spectra ordered as [1-1,1-2,1-3,2-2,2-3,3-3].\n * @param seed Seed for this particular realization.\n * @return Gaussian realization.\n */\nflouble **nmt_synfast_flat(int nx,int ny,flouble lx,flouble ly,int nfields,int *spin_arr,\n\t\t\t   int nl_beam,flouble *l_beam,flouble **beam_fields,\n\t\t\t   int nl_cell,flouble *l_cell,flouble **cell_fields,\n\t\t\t   int seed);\n\n/**\n * @brief E- or B-mode purifies a given pair of flat-sky (Q,U) maps.\n *\n * This function is mostly used internally by NaMaster, and its standalone use is discouraged.\n * @param fl nmt_field_flat containing information about what should be purified.\n * @param mask Sky mask (should be appropriately apodized - see scientific documentation).\n * @param walm0 Fourier transform of the mask.\n * @param maps_in Maps to be purified (should NOT be mask-multiplied).\n * @param maps_out Output purified maps.\n * @param alms Fourier transform of the output purified maps.\n */\nvoid nmt_purify_flat(nmt_field_flat *fl,flouble *mask,fcomplex **walm0,\n\t\t     flouble **maps_in,flouble **maps_out,fcomplex **alms);\n\n/**\n * @brief Full-sky field\n *\n * This structure contains all the information defining a spin-s full-sky field.\n * This includes field values, masking, purification and contamination.\n */\ntypedef struct {\n  long nside; //!< HEALPix resolution parameters\n  long npix; //!< Number of pixels in all maps\n  int lmax; //!< Maximum multipole used\n  int pure_e; //!< >0 if E-modes have been purified\n  int pure_b; //!< >0 if B-modes have been purified\n  flouble *mask; //!< Field's mask (an array of \\p npix values).\n  fcomplex **a_mask; //!< Spherical transform of the mask. Only computed if E or B are purified.\n  int pol; //!< >0 if field is spin-2 (otherwise it's spin-0).\n  int nmaps; //!< Number of maps in the field (2 for spin-2, 1 for spin-0).\n  flouble **maps; //!< Observed field values. When initialized, these maps are already multiplied by the mask, contaminant-deprojected and purified if requested.\n  fcomplex **alms; //!< Spherical harmonic transfoms of the maps.\n  int ntemp; //!< Number of contaminant templates\n  flouble ***temp; //!< Contaminant template maps (mask-multiplied but NOT purified).\n  fcomplex ***a_temp; //!< Spherical harmonic transfomrs of template maps (mask-multiplied AND purified if requested).\n  gsl_matrix *matrix_M; //!< Inverse contaminant covariance matrix (see scientific documentation or companion paper).\n  flouble *beam; //!< Field's beam (defined on all multipoles up to \\p lmax).\n} nmt_field;\n\n/**\n * @brief nmt_field destructor.\n */\nvoid nmt_field_free(nmt_field *fl);\n\n/**\n * @brief nmt_field constructor\n *\n * Builds an nmt_field structure from input maps and resolution parameters.\n * @param nside HEALPix resolution parameter.\n * @param mask Field's mask (an array of 12 * \\p nside^2 values).\n * @param pol >0 if this is a spin-2 field (spin-0 otherwise).\n * @param maps Observed field values BEFORE multiplying by the mask \n          (this is irrelevant for binary masks).\n * @param ntemp Number of contaminant templates affecting this field.\n * @param temp Contaminant template maps (again, NOT multiplied by the mask).\n * @param beam Harmonic coefficients of the beam (defined for all multipoles up to\n *        3 * \\p nside - 1). Pass a NULL pointer if you don't want any beam.\n * @param pure_e Set to >0 if you want purified E-modes.\n * @param pure_b Set to >0 if you want purified B-modes.\n * @param n_iter_mask_purify E/B purification requires a number of harmonic-space\n          operations on an appropriately apodized mask. This parameter sets the\n          number of iterations requested to compute the spherical harmonic transform\n          of the field's mask. Higher values will produce more accurate results (at\n\t  the cost of computational time).\n * @param tol_pinv Contaminant deprojection requires the inversion of the template\n          covariance matrix. This could be ill-defined if some templates are linearly\n\t  related. In this case we use a pseudo-inverse that accounts for this \n\t  possibility in a consistent way. Effectively this is a singular-value \n\t  decomposition. All eigenvalues that are smaller than \\p tol_pinv the largest\n\t  eigenvalue will be discarded.\n */\nnmt_field *nmt_field_alloc_sph(long nside,flouble *mask,int pol,flouble **maps,\n\t\t\t       int ntemp,flouble ***temp,flouble *beam,\n\t\t\t       int pure_e,int pure_b,int n_iter_mask_purify,double tol_pinv);\n/**\n * @brief nmt_field constructor from file.\n *\n * Builds an nmt_field structure from data written in files.\n * @param fname_mask Path to FITS file containing the field's mask (single HEALPix map).\n * @param pol >0 if this is a spin-2 field (spin-0 otherwise).\n * @param fname_maps Path to FITS file containing the field's observed maps\n          (1(2) maps if \\p pol=0(1)).\n * @param fname_temp Path to FITS file containing the field's contaminant templates.\n          If \\p pol > 0, spin-2 is assumed, and the file should contain an even number\n          of files. Each consecutive pair of maps will be interpreted as the Q and U\n\t  components of a given contaminant. Pass \"none\" if you don't want any contaminants.\n * @param fname_beam Path to ASCII file containing the field's beam. The file should\n          contain two columns: l (multipole) and b_l (beam SHT at that multipole).\n\t  Pass \"none if you don't want a beam.\n * @param pure_e >0 if you want E-mode purification.\n * @param pure_b >0 if you want B-mode purification.\n * @param n_iter_mask_purify E/B purification requires a number of harmonic-space\n          operations on an appropriately apodized mask. This parameter sets the\n          number of iterations requested to compute the spherical harmonic transform\n          of the field's mask. Higher values will produce more accurate results (at\n\t  the cost of computational time).\n * @param tol_pinv Contaminant deprojection requires the inversion of the template\n          covariance matrix. This could be ill-defined if some templates are linearly\n\t  related. In this case we use a pseudo-inverse that accounts for this \n\t  possibility in a consistent way. Effectively this is a singular-value \n\t  decomposition. All eigenvalues that are smaller than \\p tol_pinv the largest\n\t  eigenvalue will be discarded.\n */\nnmt_field *nmt_field_read(char *fname_mask,char *fname_maps,char *fname_temp,char *fname_beam,\n\t\t\t  int pol,int pure_e,int pure_b,int n_iter_mask_purify,double tol_pinv);\n\n/**\n * @brief Gaussian realizations of full-sky fields \n *\n * Generates a Gaussian realization of an arbitrary list of possibly-correlated fields with different spins.\n * @param nside HEALPix resolution parameter.\n * @param lmax Maximum multipole used.\n * @param nfields Number of fields to generate.\n * @param spin_arr Array (size \\p nfields) containing the spins of the fields to be generated.\n * @param beam_fields Array of beams (one per field). Must be defined at all ell <= \\p lmax.\n * @param cells Array of input power spectra (defined at all ell <= \\p lmax). Shape\n          should be [\\p n_cls][\\p lmax+1], where \\p n_cls is the number of power spectra\n\t  needed to define all the fields. This should be \\p n_cls = n_maps * (n_maps + 1) / 2,\n\t  where n_maps is the total number of maps required (1 for each spin-0 field, 2 for\n\t  each spin-2 field). Power spectra must be provided only for the upper-triangular part\n\t  in row-major order (e.g. if n_maps is 3, there will be 6 power spectra ordered as\n\t  [1-1,1-2,1-3,2-2,2-3,3-3].\n * @param seed Seed for this particular realization.\n * @return Gaussian realization.\n */\nflouble **nmt_synfast_sph(int nside,int nfields,int *spin_arr,int lmax,\n\t\t\t  flouble **cells,flouble **beam_fields,int seed);\n\n/**\n * @brief E- or B-mode purifies a given pair of full-sky (Q,U) maps.\n *\n * This function is mostly used internally by NaMaster, and its standalone use is discouraged.\n * @param fl nmt_field containing information about what should be purified.\n * @param mask Sky mask (should be appropriately apodized - see scientific documentation).\n * @param walm0 Spherical harmonic transform of the mask.\n * @param maps_in Maps to be purified (should NOT be mask-multiplied).\n * @param maps_out Output purified maps.\n * @param alms Spherical harmonic transform of the output purified maps.\n */\nvoid nmt_purify(nmt_field *fl,flouble *mask,fcomplex **walm0,\n\t\tflouble **maps_in,flouble **maps_out,fcomplex **alms);\n\n/**\n * @brief Apodize full-sky mask.\n *\n * Produces apodized version of a full-sky mask for a number of apodization schemes.\n * @param nside HEALPix resolution parameter.\n * @param mask_in Input mask to be apodized.\n * @param mask_out Output apodized mask.\n * @param aposize Apodization scale (in degrees).\n * @param apotype String defining the apodization procedure. Three values allowed: 'C1', 'C2' and 'Smooth'. These correspond to:\n *    - \\p apotype = \"C1\". All pixels are multiplied by a factor \\f$f\\f$, given by:\n *\\f[\n *   f=\\left\\{\n *     \\begin{array}{cc}\n *       x-\\sin(2\\pi x)/(2\\pi) & x<1\\\\\n *       1 & {\\rm otherwise}\n *     \\end{array}\n *     \\right.,\n * \\f]\n        where \\f$x=\\sqrt{(1-\\cos\\theta)/(1-\\cos(\\theta_*))}\\f$, \\f$\\theta_*\\f$ is the\n\tapodization scale and \\f$\\theta\\f$ is the angular separation between a pixel and\n\tthe nearest masked pixel (i.e. where the mask takes a zero value).\n *    - \\p apotype = \"C2\". The same as the C1 case, but the function in this case is:\n *\\f[\n *   f=\\left\\{\n *     \\begin{array}{cc}\n *       \\frac{1}{2}\\left[1-\\cos(\\pi x)\\right] & x<1\\\\\n *       1 & {\\rm otherwise}\n *     \\end{array}\n *     \\right.,\n * \\f]\n *    - \\p apotype = \"Smooth\". This apodization is carried out in three steps:\n *         -# All pixels within a disc of radius \\f$2.5\\theta_*\\f$ of a masked pixel are masked.\n *         -# The resulting map is smooth with a Gaussian window function with standard\n              deviation \\f$\\sigma=\\theta_*\\f$.\n *         -# One final pass is made through all pixels to ensure that all originally masked\n *            pixels are still masked after the smoothing operation.\n */\nvoid nmt_apodize_mask(long nside,flouble *mask_in,flouble *mask_out,flouble aposize,char *apotype);\n\n\n/**\n * @brief Apodize flat-sky mask.\n *\n * Produces apodized version of a flat-sky mask for a number of apodization schemes.\n * @param nx Number of grid points in the x dimension\n * @param ny Number of grid points in the y dimension\n * @param lx Length of the x dimension (in steradians)\n * @param ly Length of the y dimension (in steradians)\n * @param mask_in Input mask to be apodized.\n * @param mask_out Output apodized mask.\n * @param aposize Apodization scale (in degrees).\n * @param apotype String defining the apodization procedure. See definitions of nmt_apodize_mask().\n */\nvoid nmt_apodize_mask_flat(int nx,int ny,flouble lx,flouble ly,\n\t\t\t   flouble *mask_in,flouble *mask_out,flouble aposize,char *apotype);\n\n/**\n * @brief Flat-sky mode-coupling matrix.\n *\n * Structure containing information about the mode-coupling matrix (MCM) for flat-sky pseudo-CLs.\n */\ntypedef struct {\n  int ncls; //!< Number of power spectra (1, 2 or 4 depending of the spins of the fields being correlated.\n  flouble ellcut_x[2]; //!< Range of ells in the x direction to be masked in Fourie space\n  flouble ellcut_y[2]; //!< Range of ells in the y direction to be masked in Fourie space\n  int pe1; //!< Is the E-mode component of the first field purified?\n  int pe2; //!< Is the E-mode component of the second field purified?\n  int pb1; //!< Is the B-mode component of the first field purified?\n  int pb2; //!< Is the B-mode component of the second field purified?\n  nmt_flatsky_info *fs; //!< Contains information about rectangular flat-sky patch.\n  int is_teb; //!< Does it hold all MCM elements to compute all of spin0-spin0, 0-2 and 2-2 correlations?\n  flouble *mask1; //!< Mask of the first field being correlated\n  flouble *mask2; //!< Mask of the second field being correlated\n#ifdef _ENABLE_FLAT_THEORY_ACCURATE\n  flouble *maskprod; //!< Mask product used for accurate theory estimate (non-tested)\n#endif //_ENABLE_FLAT_THEORY_ACCURATE\n  int *n_cells; //!< Number of unmasked Fourier-space grid points contributing to a given bandpower\n  flouble **coupling_matrix_unbinned; //!< Unbinned MCM\n  flouble **coupling_matrix_binned; //!< Binned MCM\n  nmt_binning_scheme_flat *bin; //!< Bandpowers defining the binning\n  flouble lmax; //!< Maximum k-mode used\n  gsl_matrix *coupling_matrix_binned_gsl; //!< GSL version of MCM (prepared for inversion)\n  gsl_permutation *coupling_matrix_perm; //!< Complements \\p coupling_matrix_binned_gsl for inversion.\n} nmt_workspace_flat;\n\n/**\n * @brief nmt_workspace_flat destructor\n */\nvoid nmt_workspace_flat_free(nmt_workspace_flat *w);\n\n/**\n * @brief Builds nmt_workspace_flat structure from file\n *\n * The input file uses a native binary format. In combination with nmt_workspace_flat_write(),\n * this can be used to save the information contained in a given workspace and reuse it for \n * future power spectrum computations. The same workspace can be used on any pair of fields\n * with the same masks.\n * @param fname Path to input file.\n */\nnmt_workspace_flat *nmt_workspace_flat_read(char *fname);\n\n/**\n * @brief Saves nmt_workspace_flat structure to file\n *\n * The output file uses a native binary format. In combination with nmt_workspace_flat_read(),\n * this can be used to save the information contained in a given workspace and reuse it for \n * future power spectrum computations. The same workspace can be used on any pair of fields\n * with the same masks.\n * @param w nmt_workspace_flat to be saved.\n * @param fname Path to output file.\n */\nvoid nmt_workspace_flat_write(nmt_workspace_flat *w,char *fname);\n\n/**\n * @brief Computes mode-coupling matrix.\n *\n * Computes MCM for a given pair of flat-sky fields.\n * @param fl1 nmt_field_flat structure defining the first field to correlate.\n * @param fl2 nmt_field_flat structure defining the second field to correlate.\n * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers.\n * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked.\n * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked.\n *        if \\p lmx_x < \\p lmn_x, no Fourier-space masked is performed.\n * @param lmn_y Same as \\p lmn_x for the y direction.\n * @param lmx_y Same as \\p lmx_x for the y direction.\n * @param is_teb if !=0, all mode-coupling matrices (0-0,0-2,2-2) will be computed at the same time.\n */\nnmt_workspace_flat *nmt_compute_coupling_matrix_flat(nmt_field_flat *fl1,nmt_field_flat *fl2,\n\t\t\t\t\t\t     nmt_binning_scheme_flat *bin,\n\t\t\t\t\t\t     flouble lmn_x,flouble lmx_x,\n\t\t\t\t\t\t     flouble lmn_y,flouble lmx_y,int is_teb);\n\n/**\n * @brief Computes deprojection bias.\n *\n * Computes contaminant deprojection bias for a pair of fields.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field_flat structure defining the first field to correlate.\n * @param fl2 nmt_field_flat structure defining the second field to correlate.\n * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers.\n * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked.\n * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked.\n *        if \\p lmx_x < \\p lmn_x, no Fourier-space masked is performed.\n * @param lmn_y Same as \\p lmn_x for the y direction.\n * @param lmx_y Same as \\p lmx_x for the y direction.\n * @param nl_prop Number of multipoles over which the proposed power spectrum is defined.\n * @param l_prop Array of multipoles over which the proposed power spectrum is defined.\n * @param cl_proposal Proposed power spectrum. Should have shape [ncls][\\p nl_prop], where\n          \\p ncls is the appropriate number of power spectra given the spins of the input\n\t  fields (e.g. \\p ncls = 2*2 = 4 if both fields have spin=2).\n * @param cl_bias Ouptput deprojection bias. Should be allocated to shape [ncls][nbpw],\n          where \\p ncls is defined above and \\p nbpw is the number of bandpowers\n\t  defined by \\p bin.\n */\nvoid nmt_compute_deprojection_bias_flat(nmt_field_flat *fl1,nmt_field_flat *fl2,\n\t\t\t\t\tnmt_binning_scheme_flat *bin,\n\t\t\t\t\tflouble lmn_x,flouble lmx_x,flouble lmn_y,flouble lmx_y,\n\t\t\t\t\tint nl_prop,flouble *l_prop,flouble **cl_proposal,\n\t\t\t\t\tflouble **cl_bias);\n#ifdef _ENABLE_FLAT_THEORY_ACCURATE\nvoid nmt_couple_cl_l_flat_accurate(nmt_workspace_flat *w,int nl,flouble *larr,flouble **cl_in,\n\t\t\t\t   flouble **cl_out);\n#endif //_ENABLE_FLAT_THEORY_ACCURATE\n\n/**\n * @brief Mode-couples an input power spectrum\n *\n * This function applies the effects of the mode-coupling the pseudo-CL estimator for a given \n * input power spectrum. This function should be used in conjunction with nmt_decouple_cl_l_flat()\n * to compute the theory prediction of the pseudo-CL estimator. See the scientific documentation\n * or the companion paper for further details on how this is done in particular for the flat-sky\n * approximation.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param w nmt_workspace_flat structure containing the mode-coupling matrix\n * @param nl Number of multipoles on which the input power spectrum is defined.\n * @param larr Array of multipoles on which the input power spectrum is defined.\n * @param cl_in Array of input power spectra. Should have shape [ncls][nl], where ncls is the\n          appropriate number of power spectra given the fields being correlated (e.g. ncls=4=2*2\n\t  for two spin-2 fields.\n * @param cl_out Array of output power spectra. Should have shape [ncls][nbpw], where ncls is\n          defined above and nbpw is the number of bandpowers used to define \\p w.\n */\nvoid nmt_couple_cl_l_flat_fast(nmt_workspace_flat *w,int nl,flouble *larr,flouble **cl_in,\n\t\t\t\t flouble **cl_out);\n/**\n * @brief Mode-couples an input power spectrum\n *\n * Faster (but less accurate) version of nmt_couple_cl_l_flat_fast().\n * @param w nmt_workspace_flat structure containing the mode-coupling matrix\n * @param nl Number of multipoles on which the input power spectrum is defined.\n * @param larr Array of multipoles on which the input power spectrum is defined.\n * @param cl_in Array of input power spectra. Should have shape [ncls][nl], where ncls is the\n          appropriate number of power spectra given the fields being correlated (e.g. ncls=4=2*2\n\t  for two spin-2 fields.\n * @param cl_out Array of output power spectra. Should have shape [ncls][nbpw], where ncls is\n          defined above and nbpw is the number of bandpowers used to define \\p w.\n */\nvoid nmt_couple_cl_l_flat_quick(nmt_workspace_flat *w,int nl,flouble *larr,flouble **cl_in,\n\t\t\t\tflouble **cl_out);\n\n/**\n * @brief Inverts mode-coupling matrix\n *\n * Multiplies coupled power spectra by inverse mode-coupling matrix.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param w nmt_workspace_flat containing the mode-coupling matrix.\n * @param cl_in Input coupled power spectra. Should have shape [ncls][nbpw], where\n          \\p ncls is the appropriate number of power spectra given the fields used\n\t  to define \\p w (e.g. 4=2*2 for two spin-2 fields) and \\p nbpw is the number\n\t  of bandpowers used when defining \\p w.\n * @param cl_noise_in Noise bias (same shape as \\p cl_in).\n * @param cl_bias Deprojection bias (same shape as \\p cl_in, see nmt_compute_deprojection_bias_flat()).\n * @param cl_out Mode-decoupled power spectrum (same shape as \\p cl_in).\n */\nvoid nmt_decouple_cl_l_flat(nmt_workspace_flat *w,flouble **cl_in,flouble **cl_noise_in,\n\t\t\t    flouble **cl_bias,flouble **cl_out);\n\n/**\n * @brief Coupled pseudo-CL\n *\n * Computes the pseudo-CL power spectrum of two fields without accounting for the mode-coupling\n * matrix.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field_flat structure defining the first field to correlate.\n * @param fl2 nmt_field_flat structure defining the second field to correlate.\n * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers.\n * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked.\n * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked.\n *        if \\p lmx_x < \\p lmn_x, no Fourier-space masked is performed.\n * @param lmn_y Same as \\p lmn_x for the y direction.\n * @param lmx_y Same as \\p lmx_x for the y direction.\n * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][nbpw], where\n          \\p ncls is the appropriate number of power spectra (e.g. 4=2*2 for two spin-2\n\t  fields), and \\p nbpw is the number of bandpowers defined by \\p bin.\n */\nvoid nmt_compute_coupled_cell_flat(nmt_field_flat *fl1,nmt_field_flat *fl2,\n\t\t\t\t   nmt_binning_scheme_flat *bin,flouble **cl_out,\n\t\t\t\t   flouble lmn_x,flouble lmx_x,flouble lmn_y,flouble lmx_y);\n\n/**\n * @brief Computes pseudo-CL specrum.\n *\n * Wrapper function containing all the steps to compute a power spectrum. For performance\n * reasons, the blind use of this function is discouraged against a smarter combination of\n * nmt_workspace_flat structures and nmt_compute_coupled_cell_flat().\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field_flat structure defining the first field to correlate.\n * @param fl2 nmt_field_flat structure defining the second field to correlate.\n * @param bin nmt_binning_scheme_flat defining the power spectrum bandpowers.\n * @param lmn_x Lower end of the range of multipoles in the x direction that should be masked.\n * @param lmx_x Upper end of the range of multipoles in the x direction that should be masked.\n *        if \\p lmx_x < \\p lmn_x, no Fourier-space masked is performed.\n * @param lmn_y Same as \\p lmn_x for the y direction.\n * @param lmx_y Same as \\p lmx_x for the y direction.\n * @param w0 nmt_workspace_flat structure containing the mode-coupling matrix. If NULL, a new \n          computation of the MCM will be carried out and stored in the output nmt_workspace_flat.\n\t  Otherwise, \\p w0 will be used and returned by this function.\n * @param nl_prop Number of multipoles over which the proposed power spectrum is defined.\n * @param l_prop Array of multipoles over which the proposed power spectrum is defined.\n * @param cl_prop Proposed power spectrum. Should have shape [ncls][\\p nl_prop], where\n          \\p ncls is the appropriate number of power spectra given the spins of the input\n\t  fields (e.g. \\p ncls = 2*2 = 4 if both fields have spin=2).\n * @param cl_noise Noise bias. Should have shape [ncls][nbpw], where \\p ncls is \n *        defined above and \\p nbpw is the number of bandpowers defined by \\p bin.\n * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][nbpw], \n          where \\p ncls is defined above and \\p nbpw is the number of bandpowers defined\n\t  by \\p bin.\n * @return Newly allocated nmt_workspace_flat structure containing the mode-coupling matrix\n           if \\p w0 is NULL (will return \\p w0 otherwise).\n */\nnmt_workspace_flat *nmt_compute_power_spectra_flat(nmt_field_flat *fl1,nmt_field_flat *fl2,\n\t\t\t\t\t\t   nmt_binning_scheme_flat *bin,\n\t\t\t\t\t\t   flouble lmn_x,flouble lmx_x,\n\t\t\t\t\t\t   flouble lmn_y,flouble lmx_y,\n\t\t\t\t\t\t   nmt_workspace_flat *w0,flouble **cl_noise,\n\t\t\t\t\t\t   int nl_prop,flouble *l_prop,flouble **cl_prop,\n\t\t\t\t\t\t   flouble **cl_out);\n\n/**\n * @brief Full-sky mode-coupling matrix.\n *\n * Structure containing information about the mode-coupling matrix (MCM) for full-sky pseudo-CLs.\n */\ntypedef struct {\n  int lmax; //!< Maximum multipole used\n  int is_teb; //!< Does it hold all MCM elements to compute all of spin0-spin0, 0-2 and 2-2 correlations?\n  int ncls; //!< Number of power spectra (1, 2 or 4 depending of the spins of the fields being correlated.\n  int nside; //!< HEALPix resolution parameter\n  flouble *mask1; //!< Mask of the first field being correlated.\n  flouble *mask2; //!< Mask of the second field being correlated.\n  flouble *pcl_masks; //!< Pseudo-CL of the masks.\n  flouble **coupling_matrix_unbinned; //!< Unbinned mode-coupling matrix\n  nmt_binning_scheme *bin; //!< Bandpowers defining the binning\n  gsl_matrix *coupling_matrix_binned; //!< GSL version of MCM (prepared for inversion)\n  gsl_permutation *coupling_matrix_perm; //!< Complements \\p coupling_matrix_binned_gsl for inversion.\n} nmt_workspace;\n\n/**\n * @brief Computes mode-coupling matrix.\n *\n * Computes MCM for a given pair of full-sky fields.\n * @param fl1 nmt_field structure defining the first field to correlate.\n * @param fl2 nmt_field structure defining the second field to correlate.\n * @param bin nmt_binning_scheme defining the power spectrum bandpowers.\n * @param is_teb if !=0, all mode-coupling matrices (0-0,0-2,2-2) will be computed at the same time.\n */\nnmt_workspace *nmt_compute_coupling_matrix(nmt_field *fl1,nmt_field *fl2,nmt_binning_scheme *bin,int is_teb);\n\n/**\n * @brief Updates the mode coupling matrix with a new one.Saves nmt_workspace structure to file\n *\n * The new matrix must be provided as a single 1D array of size n_rows\\f$^2\\f$.\n * Here n_rows=n_cls * n_ell is the size of the flattened power spectra, where n_cls is the number\n * of power spectra (1, 2 or 4 for spin0-0, spin0-2 and spin2-2 correlations) and n_ells=lmax+1\n * (by default lmax=3*nside-1). The ordering of the power spectra should be such that the\n * l-th element of the i-th power spectrum is stored with index l * n_cls + i.\n * @param w nmt_workspace to be updated.\n * @param n_rows size of the flattened power spectra.\n * @param new_matrix new mode-coupling matrix (flattened).\n */\nvoid nmt_update_coupling_matrix(nmt_workspace *w,int n_rows,double *new_matrix);\n\n/**\n * @brief Saves nmt_workspace structure to file\n *\n * The output file uses a native binary format. In combination with nmt_workspace_read(),\n * this can be used to save the information contained in a given workspace and reuse it for \n * future power spectrum computations. The same workspace can be used on any pair of fields\n * with the same masks.\n * @param w nmt_workspace to be saved.\n * @param fname Path to output file.\n */\nvoid nmt_workspace_write(nmt_workspace *w,char *fname);\n\n/**\n * @brief Builds nmt_workspace structure from file\n *\n * The input file uses a native binary format. In combination with nmt_workspace_write(),\n * this can be used to save the information contained in a given workspace and reuse it for \n * future power spectrum computations. The same workspace can be used on any pair of fields\n * with the same masks.\n * @param fname Path to input file.\n */\nnmt_workspace *nmt_workspace_read(char *fname);\n\n/**\n * @brief nmt_workspace destructor\n */\nvoid nmt_workspace_free(nmt_workspace *w);\n\n/**\n * @brief Computes deprojection bias.\n *\n * Computes contaminant deprojection bias for a pair of fields.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field structure defining the first field to correlate.\n * @param fl2 nmt_field structure defining the second field to correlate.\n * @param cl_proposal Proposed power spectrum. Should have shape [ncls][3 \\p nside], where\n          \\p ncls is the appropriate number of power spectra given the spins of the input\n\t  fields (e.g. \\p ncls = 2*2 = 4 if both fields have spin=2).\n * @param cl_bias Ouptput deprojection bias. Should be allocated to shape [ncls][3 * \\p nside],\n          where \\p ncls is defined above.\n */\nvoid nmt_compute_deprojection_bias(nmt_field *fl1,nmt_field *fl2,\n\t\t\t\t   flouble **cl_proposal,flouble **cl_bias);\n\n/**\n * @brief Noise bias from uncorrelated noise map\n *\n * Computes deprojection bias due to an source of uncorrelated noise given an input noise variance map.\n * See companion paper for more details.\n * @param fl1 nmt_field structure defining the properties of the field for which this noise bias\n          applies.\n * @param map_var Noise variance map (should contain per-pixel noise variance).\n * @param cl_bias Ouptput noise bias. Should be allocated to shape [ncls][3 * \\p nside],\n          where \\p ncls is the appropriate number of power spectra given the spins of the input\n\t  fields (e.g. \\p ncls = 2*2 = 4 if both fields have spin=2).\n */\nvoid nmt_compute_uncorr_noise_deprojection_bias(nmt_field *fl1,flouble *map_var,flouble **cl_bias);\n\n/**\n * @brief Mode-couples an input power spectrum\n *\n * This function applies the effects of the mode-coupling the pseudo-CL estimator for a given \n * input power spectrum. This function should be used in conjunction with nmt_decouple_cl_l()\n * to compute the theory prediction of the pseudo-CL estimator.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param w nmt_workspace structure containing the mode-coupling matrix\n * @param cl_in Array of input power spectra. Should have shape [ncls][3 * \\p nside], where ncls\n          is the appropriate number of power spectra given the fields being correlated\n\t  (e.g. ncls=4=2*2 for two spin-2 fields).\n * @param cl_out Array of output power spectra. Should have shape [ncls][3 * \\p nside], where\n          ncls is defined above.\n */\nvoid nmt_couple_cl_l(nmt_workspace *w,flouble **cl_in,flouble **cl_out);\n\n/**\n * @brief Inverts mode-coupling matrix\n *\n * Multiplies coupled power spectra by inverse mode-coupling matrix.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param w nmt_workspace containing the mode-coupling matrix.\n * @param cl_in Input coupled power spectra. Should have shape [ncls][3 * \\p nside], where\n          \\p ncls is the appropriate number of power spectra given the fields used\n\t  to define \\p w (e.g. 4=2*2 for two spin-2 fields).\n * @param cl_noise_in Noise bias (same shape as \\p cl_in).\n * @param cl_bias Deprojection bias (same shape as \\p cl_in, see nmt_compute_deprojection_bias()).\n * @param cl_out Mode-decoupled power spectrum. Should have shape [ncls][nbpw], where\n          ncls is defined above and nbpw is the number of bandpowers used to define \\p w.\n */\nvoid nmt_decouple_cl_l(nmt_workspace *w,flouble **cl_in,flouble **cl_noise_in,\n\t\t       flouble **cl_bias,flouble **cl_out);\n\n/**\n * @brief Coupled pseudo-CL\n *\n * Computes the pseudo-CL power spectrum of two fields without accounting for the mode-coupling\n * matrix. This is essentially equivalent to running HEALPix's 'anafast' on the purified and\n * contaminant-deprojected input fields.\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field structure defining the first field to correlate.\n * @param fl2 nmt_field structure defining the second field to correlate.\n * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][3 * \\p nside], where\n          \\p ncls is the appropriate number of power spectra (e.g. 4=2*2 for two spin-2 fields).\n */\nvoid nmt_compute_coupled_cell(nmt_field *fl1,nmt_field *fl2,flouble **cl_out);\n\n/**\n * @brief Computes pseudo-CL specrum.\n *\n * Wrapper function containing all the steps to compute a power spectrum. For performance\n * reasons, the blind use of this function is discouraged against a smarter combination of\n * nmt_workspace structures and nmt_compute_coupled_cell().\n * See notes about power spectrum ordering in the main page of this documentation.\n * @param fl1 nmt_field structure defining the first field to correlate.\n * @param fl2 nmt_field structure defining the second field to correlate.\n * @param bin nmt_binning_scheme defining the power spectrum bandpowers.\n * @param w0 nmt_workspace structure containing the mode-coupling matrix. If NULL, a new \n          computation of the MCM will be carried out and stored in the output nmt_workspace.\n\t  Otherwise, \\p w0 will be used and returned by this function.\n * @param cl_proposal Proposed power spectrum. Should have shape [ncls][3 * \\p nside], where\n          \\p ncls is the appropriate number of power spectra given the spins of the input\n\t  fields (e.g. \\p ncls = 2*2 = 4 if both fields have spin=2).\n * @param cl_noise Noise bias (same shape as \\p cl_prop).\n * @param cl_out Ouptput power spectrum. Should be allocated to shape [ncls][nbpw], \n          where \\p ncls is defined above and \\p nbpw is the number of bandpowers defined\n\t  by \\p bin.\n * @return Newly allocated nmt_workspace structure containing the mode-coupling matrix\n           if \\p w0 is NULL (will return \\p w0 otherwise).\n */\nnmt_workspace *nmt_compute_power_spectra(nmt_field *fl1,nmt_field *fl2,\n\t\t\t\t\t nmt_binning_scheme *bin,nmt_workspace *w0,\n\t\t\t\t\t flouble **cl_noise,flouble **cl_proposal,flouble **cl_out);\n\n/**\n * @brief Flat-sky Gaussian covariance matrix\n *\n * Structure containing the information necessary to compute Gaussian covariance matrices\n * for the pseudo-CL spectra of two flat-sky spin-0 fields.\n *\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n * fields of different spins.\n */\ntypedef struct {\n  int ncls_a; //!< Number of elements for the first set of power spectra (1 for the time being)\n  int ncls_b; //!< Number of elements for the second set of power spectra (1 for the time being)\n  nmt_binning_scheme_flat *bin; //!< Bandpowers defining the binning\n  flouble **xi_1122; //!< First (a1b1-a2b2) mode coupling matrix (see scientific documentation)\n  flouble **xi_1221; //!< Second (a1b2-a2b1) mode coupling matrix (see scientific documentation)\n  gsl_matrix *coupling_binned_a; //!< Coupling matrix associated to the first set of power spectra\n  gsl_matrix *coupling_binned_b; //!< Coupling matrix associated to the second set of power spectra\n  gsl_permutation *coupling_binned_perm_a; //!< GSL aid to invert first MCM\n  gsl_permutation *coupling_binned_perm_b; //!< GSL aid to invert second MCM\n} nmt_covar_workspace_flat;\n\n/**\n * @brief nmt_covar_workspace_flat destructor.\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n */\nvoid nmt_covar_workspace_flat_free(nmt_covar_workspace_flat *cw);\n\n/**\n * @brief nmt_covar_workspace_flat constructor\n *\n * Builds an nmt_covar_workspace_flat structure from two nmt_workspace_flat structures, corresponding\n * to the two sets of power spectra for which the covariance is required.\n * @param wa nmt_workspace_flat for the first set of power spectra.\n * @param wb nmt_workspace_flat for the second set of power spectra.\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n */\nnmt_covar_workspace_flat *nmt_covar_workspace_flat_init(nmt_workspace_flat *wa,nmt_workspace_flat  *wb);\n\n/**\n * @brief Compute flat-sky Gaussian covariance matrix\n * \n * Computes the covariance matrix for two sets of power spectra given input predicted spectra\n * and a nmt_covar_workspace_flat structure.\n * @param cw nmt_covar_workspace_flat structure containing the information necessary to compute the\n          covariance matrix.\n * @param nl Number of multipoles in which input power spectra are computed.\n * @param larr Array of multipoles in which input power spectra are computed.\n * @param cla1b1 Cross-power spectrum between field 1 in set a and field 1 in set b.\n * @param cla1b2 Cross-power spectrum between field 1 in set a and field 2 in set b.\n * @param cla2b1 Cross-power spectrum between field 2 in set a and field 1 in set b.\n * @param cla2b2 Cross-power spectrum between field 2 in set a and field 2 in set b.\n * @param covar_out flattened covariance matrix. Should be allocated to shape [nbpw_a * nbpw_b],\n          where nbpw_a is the number of bandpowers in the set a of pseudo-CL-estimated\n\t  power spectra (and analogously for nbpw_b).\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n */\nvoid nmt_compute_gaussian_covariance_flat(nmt_covar_workspace_flat *cw,\n\t\t\t\t\t  int nl,flouble *larr,flouble *cla1b1,flouble *cla1b2,\n\t\t\t\t\t  flouble *cla2b1,flouble *cla2b2,flouble *covar_out);\n\n/**\n * @brief Saves nmt_covar_workspace_flat structure to file\n *\n * The output file uses a native binary format. In combination with nmt_covar_workspace_flat_read(),\n * this can be used to save the information contained in a given workspace and reuse it for \n * future covariance matrix computations. The same workspace can be used on any pair of power spectra\n * between fields with the same masks.\n * @param cw nmt_covar_workspace_flat to be saved.\n * @param fname Path to output file.\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n */\nvoid nmt_covar_workspace_flat_write(nmt_covar_workspace_flat *cw,char *fname);\n\n/**\n * @brief Builds nmt_covar_workspace_flat structure from file\n *\n * The input file uses a native binary format. In combination with nmt_covar_workspace_flat_write(),\n * this can be used to save the information contained in a given workspace and reuse it for \n * future covariance matrix computations. The same workspace can be used on any pair of power spectra\n * between fields with the same masks.\n * @param fname Path to input file.\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n */\nnmt_covar_workspace_flat *nmt_covar_workspace_flat_read(char *fname);\n  \n/**\n * @brief Full-sky Gaussian covariance matrix\n *\n * Structure containing the information necessary to compute Gaussian covariance matrices\n * for the pseudo-CL spectra of two full-sky spin-0 fields.\n *\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n * fields of different spins.\n */\ntypedef struct {\n  int lmax_a; //!< Maximum multipole for the first set of power spectra\n  int lmax_b; //!< Maximum multipole for the second set of power spectra\n  int ncls_a; //!< Number of elements for the first set of power spectra (1 for the time being)\n  int ncls_b; //!< Number of elements for the second set of power spectra (1 for the time being)\n  nmt_binning_scheme *bin_a; //!< Bandpowers defining the binning for the first set of spectra\n  nmt_binning_scheme *bin_b; //!< Bandpowers defining the binning for the second set of spectra\n  int nside; //!< HEALPix resolution parameter\n  flouble **xi_1122; //!< First (a1b1-a2b2) mode coupling matrix (see scientific documentation)\n  flouble **xi_1221; //!< Second (a1b2-a2b1) mode coupling matrix (see scientific documentation)\n  gsl_matrix *coupling_binned_a; //!< Coupling matrix associated to the first set of power spectra\n  gsl_matrix *coupling_binned_b; //!< Coupling matrix associated to the second set of power spectra\n  gsl_permutation *coupling_binned_perm_a; //!< GSL aid to invert first MCM\n  gsl_permutation *coupling_binned_perm_b; //!< GSL aid to invert second MCM\n} nmt_covar_workspace;\n\n/**\n * @brief nmt_covar_workspace destructor.\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n */\nvoid nmt_covar_workspace_free(nmt_covar_workspace *cw);\n\n/**\n * @brief nmt_covar_workspace constructor\n *\n * Builds an nmt_covar_workspace structure from two nmt_workspace structures, corresponding\n * to the two sets of power spectra for which the covariance is required.\n * @param wa nmt_workspace for the first set of power spectra.\n * @param wb nmt_workspace for the second set of power spectra.\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n */\nnmt_covar_workspace *nmt_covar_workspace_init(nmt_workspace *wa,nmt_workspace *wb);\n\n/**\n * @brief Compute full-sky Gaussian covariance matrix\n * \n * Computes the covariance matrix for two sets of power spectra given input predicted spectra\n * and a nmt_covar_workspace structure.\n * @param cw nmt_covar_workspace structure containing the information necessary to compute the\n          covariance matrix.\n * @param cla1b1 Cross-power spectrum between field 1 in set a and field 1 in set b.\n          All power spectra should be defined for all ell < 3 * \\p nside - 1.\n * @param cla1b2 Cross-power spectrum between field 1 in set a and field 2 in set b.\n * @param cla2b1 Cross-power spectrum between field 2 in set a and field 1 in set b.\n * @param cla2b2 Cross-power spectrum between field 2 in set a and field 2 in set b.\n * @param covar_out flattened covariance matrix. Should be allocated to shape [nbpw_a * nbpw_b],\n          where nbpw_a is the number of bandpowers in the set a of pseudo-CL-estimated\n\t  power spectra (and analogously for nbpw_b).\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n */\nvoid  nmt_compute_gaussian_covariance(nmt_covar_workspace *cw,\n\t\t\t\t      flouble *cla1b1,flouble *cla1b2,flouble *cla2b1,flouble *cla2b2,\n\t\t\t\t      flouble *covar_out);\n\n/**\n * @brief Saves nmt_covar_workspace structure to file\n *\n * The output file uses a native binary format. In combination with nmt_covar_workspace_read(),\n * this can be used to save the information contained in a given workspace and reuse it for \n * future covariance matrix computations. The same workspace can be used on any pair of power spectra\n * between fields with the same masks.\n * @param cw nmt_covar_workspace to be saved.\n * @param fname Path to output file.\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n */\nvoid nmt_covar_workspace_write(nmt_covar_workspace *cw,char *fname);\n\n/**\n * @brief Builds nmt_covar_workspace structure from file\n *\n * The input file uses a native binary format. In combination with nmt_covar_workspace_write(),\n * this can be used to save the information contained in a given workspace and reuse it for \n * future covariance matrix computations. The same workspace can be used on any pair of power spectra\n * between fields with the same masks.\n * @param fname Path to input file.\n * @warning All covariance-related functionality is still under development, and in the future will hopefully support.\n */\nnmt_covar_workspace *nmt_covar_workspace_read(char *fname);\n\n#endif //_NAMASTER_H_\n", "meta": {"hexsha": "9a6db080390023eb3f2be8cbe9e88b03bf2818c5", "size": 60407, "ext": "h", "lang": "C", "max_stars_repo_path": "src/namaster.h", "max_stars_repo_name": "DanielLenz/NaMaster", "max_stars_repo_head_hexsha": "fb329b70e7a2f4cea5411abf80122746afed27f2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/namaster.h", "max_issues_repo_name": "DanielLenz/NaMaster", "max_issues_repo_head_hexsha": "fb329b70e7a2f4cea5411abf80122746afed27f2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/namaster.h", "max_forks_repo_name": "DanielLenz/NaMaster", "max_forks_repo_head_hexsha": "fb329b70e7a2f4cea5411abf80122746afed27f2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.4232053422, "max_line_length": 161, "alphanum_fraction": 0.7417352294, "num_tokens": 15155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3973971254124779}}
{"text": "/*\n**  parse second level design file\n**\n** G.Lohmann\n*/\n#include <viaio/Vlib.h>\n#include <viaio/VImage.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <ctype.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\nextern int VStringToken(char *, char *, int, int);\n\n#define LEN  10000\n\n\nint test_ascii(int val)\n{\n  if (val >= 'a' && val <= 'z') return 1;\n  if (val >= 'A' && val <= 'Z') return 1;\n  if (val >= '0' && val <= '9') return 1;\n  if (val ==  ' ') return 1;\n  if (val == '\\0') return 1;\n  if (val == '\\n') return 1;\n  if (val == '\\r') return 1;\n  if (val == '\\t') return 1;\n  if (val == '\\v') return 1;\n  if (val == '-') return 1;\n  if (val == '+') return 1;\n  if (val == '.') return 1;\n  return 0;\n}\n\n\n\nint line_empty(char *buf,int len)\n{\n  int i;\n  for (i=0; i<len; i++) {\n    if (buf[i] != ' ' && buf[i] != '\\n' && buf[i] != 0) return 0;\n  }\n  return 1;\n}\n\n\nint CheckBuffer(char *buf,int len)\n{\n  int j;\n\n  if(strlen(buf) < 1) return 0;\n  if (buf[0] == '%' || buf[0] == '#' || buf[0] == '/' || buf[0] == '\\n') return 0;\n\n  /* remove tabs */\n  for (j=0; j<len; j++) {\n    if (buf[0] == '\\t') buf[j] = ' ';\n  }\n  if (line_empty(buf,len) > 0) return 0;\n  return 1;\n}\n\n\nint VistaFormat(char *buf,int len)\n{\n  if (strncmp(buf,\"V-data\",6) == 0) return 1;\n  return 0;\n}\n\n\n\n/*\n** read a 2nd level design file\n*/\ngsl_matrix *XRead2ndLevel(VString filename) \n{\n  int i, j, nrows, ncols;\n  double val;\n  char buf[LEN], token[32];\n\n  fprintf(stderr,\" Reading %s\\n\",filename);\n\n  FILE *fp = VOpenInputFile (filename, TRUE);\n  if (!fp) VError(\" error opening %s\",filename);\n\n  nrows = ncols = 0;\n  while(!feof(fp)) {\n    memset(buf, 0, LEN);\n    if(!fgets(buf, LEN, fp)) continue;\n    if (VistaFormat(buf,LEN) > 0) VError(\" Design file must be a text file\");\n    if (CheckBuffer(buf,LEN) < 1) continue;\n    if (! test_ascii((int)buf[0])) VError(\" Design file must be a text file\");\n\n    j = 0;\n    while(VStringToken(buf, token, j, 30)) {\n      if(!sscanf(token, \"%lf\", &val))\n\tVError(\"illegal text string in design file: %s\", buf);\n      j++;\n    }\n\n    if (ncols == 0) ncols = j;\n    if (j < 1) continue;\n    else if(ncols != j)\n      VError(\" inconsistent number of columns in row %d\", nrows + 1);\n    nrows++;\n  }\n  rewind(fp);\n\n\n  /* fill design matrix */\n  gsl_matrix *X = gsl_matrix_calloc(nrows,ncols);\n\n  i = 0;\n  while(!feof(fp)) {\n    memset(buf, 0, LEN);\n    if(!fgets(buf, LEN, fp))  continue;    \n    if (CheckBuffer(buf,LEN) < 1) continue;\n\n    j = 0;\n    while(VStringToken(buf, token, j, 30)) {\n      sscanf(token, \"%lf\", &val);\n      gsl_matrix_set(X,i,j,val);\n      j++;\n    }\n    if (j < 1) continue;\n    i++;\n  }\n  fclose(fp);\n\n  return X;\n}\n\n\n/* read exchangeability file */\nvoid XReadExchange(VString filename,int *exchange,int n)\n{\n  int len=1024;\n  char token[32];\n  char *buf = (char *)VCalloc(len,sizeof(char));\n  FILE *fp = VOpenInputFile (filename, TRUE);\n  if (!fp) VError(\" error opening %s\",filename);\n  fprintf(stderr,\" Reading %s\\n\",filename);\n\n  int nrows = 0;\n  while(!feof(fp)) {\n    memset(buf, 0, len);\n    if(!fgets(buf, len, fp)) break;\n    if (VistaFormat(buf,LEN) > 0) VError(\" Exchangeability file must be a text file\");\n    if (CheckBuffer(buf,LEN) < 1) continue;\n    if (! test_ascii((int)buf[0])) VError(\" Exchangeability file must be a text file\");\n    nrows++;    \n  }\n  rewind(fp);\n\n  if (nrows != n) \n    VError(\" Number of rows in exchangeability file (%d) does not match number of rows in design file (%d)\",nrows,n);\n\n  int i=0,j=0,k=0;\n  while(!feof(fp)) {\n    memset(buf, 0, len);\n    if(!fgets(buf, len, fp))  break;\n    if (CheckBuffer(buf,LEN) < 1) continue;\n\n    k = 0;\n    while(VStringToken(buf, token, k, 30)) {\n      if (!sscanf(token, \"%d\", &j))\n\tVError(\"illegal text string in exchangeability file: %s\", buf);\n      if (j < 0) VError(\" Values in exchangeability file must be non-negative\");\n      if (j > n) VError(\" Illegal value (%d) in exchangeability file, values must be <= %d\",j,n);\n      exchange[i] = j;\n      k++;\n    }\n    if (k > 1) VError(\" Exchangeability file must have exactly one column\");\n    i++;\n  }\n  VFree(buf);\n  fclose(fp);\n}\n\n/*\nint main()\n{\n  int i,j;\n  gsl_matrix *X = XRead2ndLevel(\"bla.mat\");\n\n\n  fprintf(stderr,\"X:\\n\");\n  for (i=0; i<X->size1; i++) {\n    for (j=0; j<X->size2; j++) {\n      fprintf(stderr,\" %.2f\",gsl_matrix_get(X,i,j));\n    }\n    fprintf(stderr,\"\\n\");\n  }\n  fprintf(stderr,\"\\n\");\n  exit(0);\n}\n*/\n", "meta": {"hexsha": "2c3a4a3a0d7dbd2d9bdcdff9d72e89211a5ea43d", "size": 4454, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_2ndlevel/Read2ndLevelDesign.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_2ndlevel/Read2ndLevelDesign.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_2ndlevel/Read2ndLevelDesign.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 22.0495049505, "max_line_length": 117, "alphanum_fraction": 0.5644364616, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.39738824839680414}}
{"text": "/*\n *  Copyright 2008-2014 NVIDIA 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 <cblas.h>\n\n#include <cusp/complex.h>\n\n#define CUSP_CBLAS_EXPAND_REAL_DEFS(FUNC_MACRO)                                             \\\n  FUNC_MACRO(float , float , s)                                                             \\\n  FUNC_MACRO(double, double, d)\n\n#define CUSP_CBLAS_AMAX(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  int amax( const int n, const T* X, const int incX )                                       \\\n  {                                                                                         \\\n    return cblas_i##name##amax(n, (const V*) X, incX);                                      \\\n  }\n\n#define CUSP_CBLAS_ASUM(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  V asum( const int n, const T* X, const int incX )                                         \\\n  {                                                                                         \\\n    return cblas_##name##asum(n, (const V*) X, incX);                                       \\\n  }\n\n#define CUSP_CBLAS_AXPY(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void axpy( const int n, const T alpha, const T* X, const int incX, T* Y, const int incY ) \\\n  {                                                                                         \\\n    cblas_##name##axpy(n, alpha, (const V*) X, incX, (V*) Y, incY);                         \\\n  }\n\n#define CUSP_CBLAS_COPY(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void copy( const int n, const T* X, const int incX, T* Y, const int incY )                \\\n  {                                                                                         \\\n    cblas_##name##copy(n, (const V*) X, incX, (V*) Y, incY);                                \\\n  }\n\n#define CUSP_CBLAS_DOT(T,V,name)                                                            \\\n  template<int dummy>                                                                       \\\n  T dot( const int n, const T* X, const int incX, const T* Y, const int incY )              \\\n  {                                                                                         \\\n    return cblas_##name##dot(n, (const V*) X, incX, (const V*) Y, incY);                    \\\n  }\n\n#define CUSP_CBLAS_NRM2(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  V nrm2( const int n, const T* X, const int incX )                                         \\\n  {                                                                                         \\\n    return cblas_##name##nrm2(n, (const V*) X, incX);                                       \\\n  }\n\n#define CUSP_CBLAS_SCAL(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void scal( const int n, const T alpha, T* X, const int incX )                             \\\n  {                                                                                         \\\n    cblas_##name##scal(n, alpha, (V*) X, incX);                                             \\\n  }\n\n#define CUSP_CBLAS_SWAP(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void swap( const int n, T* X, const int incX, T* Y, const int incY )                      \\\n  {                                                                                         \\\n    cblas_##name##swap(n, (V*) X, incX, (V*) Y, incY);                                      \\\n  }\n\n#define CUSP_CBLAS_GEMV(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void gemv(  CBLAS_ORDER order,  CBLAS_TRANSPOSE trans,                                    \\\n              int m, int n, T alpha, const T* A, int lda,                                   \\\n              const T* x, int incx, T beta, T* y, int incy)                                 \\\n{                                                                                           \\\n    cblas_##name##gemv(order, trans, m, n, alpha, A, lda, x, incx, beta, y, incy);          \\\n}\n\n#define CUSP_CBLAS_GER(T,V,name)                                                            \\\n  template<int dummy>                                                                       \\\n  void ger(  CBLAS_ORDER order, int m, int n, T alpha, const T* x, int incx,                \\\n            const T* y, int incy, T* A, int lda)                                            \\\n{                                                                                           \\\n    cblas_##name##ger(order, m, n, alpha,                                                   \\\n                      (const V*) x, incx, (const V*) y, incy,                               \\\n                      (V*) A, lda);                                                         \\\n}\n\n#define CUSP_CBLAS_SYMV(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void symv(  CBLAS_ORDER order,  CBLAS_UPLO uplo,                                          \\\n             int n, T alpha, const T* A, int lda,                                           \\\n             const T* x, int incx, T beta, T* y, int incy)                                  \\\n{                                                                                           \\\n    cblas_##name##symv(order, uplo, n, alpha, (const V*) A, lda,                            \\\n                       (const V*) x, incx, beta, (V*) y, incy);                             \\\n}\n\n#define CUSP_CBLAS_SYR(T,V,name)                                                            \\\n  template<int dummy>                                                                       \\\n  void syr(  CBLAS_ORDER order,  CBLAS_UPLO uplo,                                           \\\n            int n, T alpha, const T* x, int incx, T* A, int lda)                            \\\n{                                                                                           \\\n    cblas_##name##syr(order, uplo, n, alpha,                                                \\\n                      (const V*) x, incx, (V*) A, lda);                                     \\\n}\n\n#define CUSP_CBLAS_TRMV(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void trmv(  CBLAS_ORDER order,  CBLAS_UPLO uplo,                                          \\\n              CBLAS_TRANSPOSE trans,  CBLAS_DIAG diag,                                      \\\n             int n, const T* A, int lda, T* x, int incx)                                    \\\n{                                                                                           \\\n    cblas_##name##trmv(order, uplo, trans, diag, n,                                         \\\n                       (const V*) A, lda, (V*) x, incx);                                    \\\n}\n\n#define CUSP_CBLAS_TRSV(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void trsv(  CBLAS_ORDER order,  CBLAS_UPLO uplo,                                          \\\n              CBLAS_TRANSPOSE trans,  CBLAS_DIAG diag,                                      \\\n             int n, const T* A, int lda, T* x, int incx)                                    \\\n{                                                                                           \\\n    cblas_##name##trsv(order, uplo, trans, diag, n,                                         \\\n                       (const V*) A, lda, (V*) x, incx);                                    \\\n}\n\n#define CUSP_CBLAS_GEMM(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void gemm(  CBLAS_ORDER order,                                                            \\\n              CBLAS_TRANSPOSE transa,  CBLAS_TRANSPOSE transb,                              \\\n              int m, int n, int k, T alpha, const T* A, int lda,                            \\\n              const T* B, int ldb, T beta, T* C, int ldc)                                   \\\n{                                                                                           \\\n    cblas_##name##gemm(order, transa, transb,                                               \\\n                       m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);                       \\\n}\n\n#define CUSP_CBLAS_SYMM(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void symm(  CBLAS_ORDER order,                                                            \\\n              CBLAS_SIDE side,  CBLAS_UPLO uplo,                                            \\\n             int m, int n, T alpha, const T* A, int lda,                                    \\\n             const T* B, int ldb, T beta, T* C, int ldc)                                    \\\n{                                                                                           \\\n    cblas_##name##symm(order, side, uplo, m, n,                                             \\\n                       (V) alpha, (const V*) A, lda, (const V*) B, ldb,                     \\\n                       (V) beta, (V*) C, ldc);                                              \\\n}\n\n#define CUSP_CBLAS_SYRK(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void syrk(  CBLAS_ORDER order,                                                            \\\n              CBLAS_UPLO uplo,  CBLAS_TRANSPOSE trans,                                      \\\n             int n, int k, T alpha, const T* A, int lda,                                    \\\n             T beta, T* C, int ldc)                                                         \\\n{                                                                                           \\\n    cblas_##name##syrk(order, uplo, trans, n, k,                                            \\\n                       (V) alpha, (const V*) A, lda,                                        \\\n                       (V) beta, (V*) C, ldc);                                              \\\n}\n\n#define CUSP_CBLAS_SYR2K(T,V,name)                                                          \\\n  template<int dummy>                                                                       \\\n  void syr2k(  CBLAS_ORDER order,                                                           \\\n               CBLAS_UPLO uplo,  CBLAS_TRANSPOSE trans,                                     \\\n              int n, int k, T& alpha, const T* A, int lda,                                  \\\n              const T* B, int ldb, T& beta, T* C, int ldc)                                  \\\n{                                                                                           \\\n    cblas_##name##syr2k(order, uplo, trans, n, k,                                           \\\n                        alpha, (const V*) A, lda,                                           \\\n                        (const V*) B, ldb, beta, (V*) C, ldc);                              \\\n}\n\n#define CUSP_CBLAS_TRMM(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void trmm(  CBLAS_ORDER order,                                                            \\\n              CBLAS_SIDE side,  CBLAS_UPLO uplo,                                            \\\n              CBLAS_TRANSPOSE trans,  CBLAS_DIAG diag,                                      \\\n             int m, int n, T alpha, const T* A, int lda,                                    \\\n             T* B, int ldb)                                                                 \\\n{                                                                                           \\\n    cblas_##name##trmm(order, side, uplo, trans, diag, m, n,                                \\\n                       (V) alpha, (const V*) A, lda, (V*) B, ldb);                          \\\n}\n\n#define CUSP_CBLAS_TRSM(T,V,name)                                                           \\\n  template<int dummy>                                                                       \\\n  void trsm( CBLAS_ORDER order,                                                             \\\n             CBLAS_SIDE side,  CBLAS_UPLO uplo,                                             \\\n             CBLAS_TRANSPOSE trans,  CBLAS_DIAG diag,                                       \\\n             int m, int n, T alpha, const T* A, int lda,                                    \\\n             T* B, int ldb)                                                                 \\\n{                                                                                           \\\n    cblas_##name##trsm(order, side, uplo, trans, diag, m, n,                                \\\n                       (V) alpha, (const V*) A, lda, (V*) B, ldb);                          \\\n}\n\nnamespace cusp\n{\nnamespace system\n{\nnamespace cpp\n{\nnamespace detail\n{\nnamespace cblas\n{\n\n// LEVEL 1\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_AMAX);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_ASUM);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_AXPY);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_COPY);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_DOT);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_NRM2);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SCAL);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SWAP);\n\n// LEVEL 2\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_GEMV);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_GER);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SYMV);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SYR);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_TRMV);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_TRSV);\n\n// LEVEL 3\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_GEMM);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SYMM);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SYRK);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_SYR2K);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_TRMM);\nCUSP_CBLAS_EXPAND_REAL_DEFS(CUSP_CBLAS_TRSM);\n\n} // end namespace cblas\n} // end namespace detail\n} // end namespace cpp\n} // end namespace system\n} // end namespace cusp\n\n", "meta": {"hexsha": "94dab50004729dcb731f883ab2e9f60dbe192c1a", "size": 15761, "ext": "h", "lang": "C", "max_stars_repo_path": "cusp/system/cpp/detail/cblas/stubs.h", "max_stars_repo_name": "Raman-sh/cusplibrary", "max_stars_repo_head_hexsha": "99dcde05991ef59cbc4546aeced6eb3bd49c90c9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 270.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:40:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T00:58:21.000Z", "max_issues_repo_path": "cusp/system/cpp/detail/cblas/stubs.h", "max_issues_repo_name": "njh19/cusplibrary", "max_issues_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T18:07:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T02:37:38.000Z", "max_forks_repo_path": "cusp/system/cpp/detail/cblas/stubs.h", "max_forks_repo_name": "njh19/cusplibrary", "max_forks_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 106.0, "max_forks_repo_forks_event_min_datetime": "2015-02-27T19:30:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:55:53.000Z", "avg_line_length": 62.2964426877, "max_line_length": 93, "alphanum_fraction": 0.3118456951, "num_tokens": 2977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.39738823319873884}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2008,2012 Free Software Foundation, Inc.\n *\n * This file is part of GNU Radio\n *\n * GNU Radio is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3, or (at your option)\n * any later version.\n *\n * GNU Radio is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GNU Radio; see the file COPYING.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street,\n * Boston, MA 02110-1301, USA.\n */\n\n#ifndef\tINCLUDED_WAVELET_SQUASH_FF_IMPL_H\n#define\tINCLUDED_WAVELET_SQUASH_FF_IMPL_H\n\n#include <gnuradio/wavelet/api.h>\n#include <gnuradio/wavelet/squash_ff.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n\nnamespace gr {\n  namespace wavelet {\n\n    class WAVELET_API squash_ff_impl : public squash_ff\n    {\n      size_t  d_inum;\n      size_t  d_onum;\n      double *d_igrid;\n      double *d_iwork;\n      double *d_ogrid;\n\n      gsl_interp_accel *d_accel;\n      gsl_spline       *d_spline;\n\n    public:\n      squash_ff_impl(const std::vector<float> &igrid,\n\t\t     const std::vector<float> &ogrid);\n\n      ~squash_ff_impl();\n\n      int work(int noutput_items,\n\t       gr_vector_const_void_star &input_items,\n\t       gr_vector_void_star &output_items);\n    };\n\n  } /* namespace wavelet */\n} /* namespace gr */\n\n#endif /* INCLUDED_WAVELET_WAVELET_FF_IMPL_H */\n", "meta": {"hexsha": "933ee5288c300ee145b68acb09b9f10f44b7c9dd", "size": 1718, "ext": "h", "lang": "C", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-wavelet/lib/squash_ff_impl.h", "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-wavelet/lib/squash_ff_impl.h", "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gnuradio-3.7.13.4/gr-wavelet/lib/squash_ff_impl.h", "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1639344262, "max_line_length": 71, "alphanum_fraction": 0.7031431898, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.39735374253997646}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#pragma once\n\n#include <gsl\\gsl>\n\n#include \"Data\\Data.h\"\n#include \"Data\\Pose.h\"\n#include \"opencv\\cv.h\"\n#include \"MageSettings.h\"\n\nnamespace mage\n{\n    struct VOIKeyframe\n    {\n        const VolumeOfInterestSettings& VoiSettings;\n        cv::Vec3f WorldPosition;\n        cv::Vec3f Forward;\n        cv::Vec3f Right;\n        cv::Vec3f Up;\n        float NearDepth;\n        float FarDepth;\n\n        // Cached values for performance.\n        cv::Vec3f Centroid;\n        float DistanceAlphaToXi;\n        float ModifiedDistanceAlphaToOmega;\n\n        VOIKeyframe(const Pose& pose, const Depth& depth, const VolumeOfInterestSettings& voiSettings);\n        float TeardropScore(const cv::Vec3f&) const;\n    };\n\n    bool CalculateVolumeOfInterest(gsl::span<const VOIKeyframe> keyframes, const VolumeOfInterestSettings& voiSettings, AxisAlignedVolume& voi);\n}", "meta": {"hexsha": "0849d897434fa618f6c30f6f516d392c8deb395a", "size": 921, "ext": "h", "lang": "C", "max_stars_repo_path": "Core/MAGESLAM/Source/VolumeOfInterest/VolumeOfInterest.h", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/VolumeOfInterest/VolumeOfInterest.h", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/VolumeOfInterest/VolumeOfInterest.h", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 26.3142857143, "max_line_length": 144, "alphanum_fraction": 0.6840390879, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.39731588687441005}}
{"text": "/**\n *\n * @file sgebrd.c\n *\n *  PLASMA computational routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Azzam Haidar\n * @date 2010-11-15\n * @generated s Tue Jan  7 11:45:10 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n/***************************************************************************//**\n *\n * @ingroup float\n *\n *  PLASMA_sgebrd - reduces a general complex M-by-N matrix A to upper or lower\n *  bidiagonal form B using a two-stage approach\n *  First stage: reduction to band bidiagonal form (orthogonal matrices Q1 and P1);\n *  Second stage: reduction from band to bidiagonal form (orthogonal matrices\n *  Q2 and P2).\n *  Let Q = Q1 * Q2 be the global left unitary transformation;\n *  Let P = P1 * P2 be the global right unitary transformation;\n *  Q**T * A * P = B.\n *  If M >= N, B is upper bidiagonal; if M < N, B is lower bidiagonal.\n *  Not LAPACK Compliant for now!\n *  Note: T is incomplete and contains only the block reflectors of the first stage.\n *  Therefore, Q and P can not be built completely.\n *\n *******************************************************************************\n *\n * @param[in] jobq\n *          Specifies options for computing all or part of the matrix Q.\n *          Intended usage:\n *          = PlasmaVec: all M columns of Q are returned in array Q;\n *          = PlasmaNoVec: not referenced.\n *\n * @param[in] jobp\n *          Specifies options for computing all or part of the matrix V**T.\n *          Intended usage:\n *          = PlasmaVec: all N columns of P are returned in array P;\n *          = PlasmaNoVec: not referenced.\n *\n * @param[in] M\n *          The number of rows of the matrix A. M >= 0.\n *\n * @param[in] N\n *          The number of columns of the matrix A. N >= 0.\n *\n * @param[in,out] A\n *          On entry, the M-by-N matrix A.\n *          On exit,\n *          if M >= N, the diagonal and the first superdiagonal are\n *            overwritten with the upper bidiagonal matrix B; the\n *            elements below the diagonal, with the array T, represent\n *            the unitary matrix Q as a product of elementary\n *            reflectors, and the elements above the first superdiagonal,\n *            with the array T, represent the unitary matrix P as\n *            a product of elementary reflectors;\n *          if M < N, the diagonal and the first subdiagonal are\n *            overwritten with the lower bidiagonal matrix B; the\n *            elements below the first subdiagonal, with the array T,\n *            represent the unitary matrix Q as a product of\n *            elementary reflectors, and the elements above the diagonal,\n *            with the array T, represent the unitary matrix P as\n *            a product of elementary reflectors.\n *\n * @param[in] LDA\n *          The leading dimension of the array A. LDA >= max(1,M).\n *\n * @param[out] D\n *          On exit, the diagonal elements of the bidiagonal matrix:\n *          D(i) = A(i,i).\n *          Dimension (min(M,N)).\n *\n * @param[out] E\n *          On exit, the off-diagonal elements of the bidiagonal matrix:\n *          if M >= N, E(i) = A(i,i+1) for i = 1,2,...,N-1;\n *          if M < N, E(i) = A(i+1,i) for i = 1,2,...,M-1.\n *          Dimension (min(M,N)-1).\n *\n * @param[out] descT\n *          On entry, descriptor as return by PLASMA_Alloc_Workspace_sgebrd\n *          On exit, contains auxiliary factorization data.\n *\n * @param[out] Q\n *          On exit, if jobz = PlasmaVec, then if return value = 0,\n *          Q contains the M-by-M unitary matrix Q.\n *          If jobz = PlasmaNoVec, then it is not referenced.\n *\n * @param[in] LDQ\n *          The leading dimension of the array Q. LDQ >= M.\n *\n * @param[out] P\n *          On exit, if jobz = PlasmaVec, then if return value = 0,\n *          P contains the N-by-N unitary matrix P.\n *          If jobz = PlasmaNoVec, then it is not referenced.\n *\n * @param[in] LDP\n *          The leading dimension of the array P. LDP >= N.\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *          \\retval <0 if -i, the i-th argument had an illegal value\n *\n *******************************************************************************\n *\n * @sa PLASMA_sgebrd_Tile\n * @sa PLASMA_sgebrd_Tile_Async\n * @sa PLASMA_cgebrd\n * @sa PLASMA_dgebrd\n * @sa PLASMA_sgebrd\n *\n ******************************************************************************/\nint PLASMA_sgebrd(PLASMA_enum jobq, PLASMA_enum jobp,\n                  int M, int N,\n                  float *A, int LDA,\n                  float *D,\n                  float *E,\n                  PLASMA_desc *descT,\n                  float *Q, int LDQ,\n                  float *P, int LDP)\n{\n    int NB;\n    int status;\n    plasma_context_t *plasma;\n    PLASMA_sequence *sequence = NULL;\n    PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n    PLASMA_desc descA;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_sgebrd\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n\n    /* Check input arguments */\n    if (jobq != PlasmaNoVec  && jobq !=PlasmaVec) {\n        plasma_error(\"PLASMA_sgebrd\", \"illegal value of jobq\");\n        return -1;\n    }\n    if (jobp != PlasmaNoVec && jobp != PlasmaVec) {\n        plasma_error(\"PLASMA_sgebrd\", \"illegal value of jobp\");\n        return -2;\n    }\n    if (M < 0) {\n        plasma_error(\"PLASMA_sgebrd\", \"illegal value of M\");\n        return -3;\n    }\n    if (N < 0) {\n        plasma_error(\"PLASMA_sgebrd\", \"illegal value of N\");\n        return -4;\n    }\n    if (LDA < max(1, M)) {\n        plasma_error(\"PLASMA_sgebrd\", \"illegal value of LDA\");\n        return -6;\n    }\n    if (LDQ < 1) {\n        plasma_error(\"PLASMA_sgebrd\", \"illegal value of LDQ\");\n        return -9;\n    }\n    if (LDP < 1) {\n        plasma_error(\"PLASMA_sgebrd\", \"illegal value of LDP\");\n        return -11;\n    }\n    /* Quick return */\n    if (min(M, N) == 0) {\n        return PLASMA_SUCCESS;\n    }\n\n    /* Tune NB & IB depending on M & N; Set NBNB */\n    status = plasma_tune(PLASMA_FUNC_SGEBRD, M, N, 0);\n    if (status != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_sgebrd\", \"plasma_tune() failed\");\n        return status;\n    }\n\n    /* Set NT */\n    NB = PLASMA_NB;\n\n    plasma_sequence_create(plasma, &sequence);\n\n    if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n        plasma_sooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, M, N, sequence, &request,\n                             plasma_desc_mat_free(&(descA)) );\n    } else {\n        plasma_siplap2tile( descA, A, NB, NB, LDA, N, 0, 0, M, N,\n                            sequence, &request);\n    }\n\n    /* Call the tile interface */\n    PLASMA_sgebrd_Tile_Async(jobq, jobp, &descA, D, E, descT, Q, LDQ, P, LDP, sequence, &request);\n\n    if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n        plasma_sooptile2lap( descA, A, NB, NB, LDA, N,  sequence, &request);\n        plasma_dynamic_sync();\n        plasma_desc_mat_free(&descA);\n    } else {\n        plasma_siptile2lap( descA, A, NB, NB, LDA, N,  sequence, &request);\n        plasma_dynamic_sync();\n    }\n\n    status = sequence->status;\n    plasma_sequence_destroy(plasma, sequence);\n    return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup float_Tile\n *\n *  PLASMA_sgebrd_Tile - reduces a general complex M-by-N matrix A to upper or lower\n *  bidiagonal form B using a two-stage approach\n *  First stage: reduction to band bidiagonal form (orthogonal matrices Q1 and P1);\n *  Second stage: reduction from band to bidiagonal form (orthogonal matrices\n *  Q2 and P2).\n *  Let Q = Q1 * Q2 be the global left unitary transformation;\n *  Let P = P1 * P2 be the global right unitary transformation;\n *  Q**T * A * P = B.\n *  If M >= N, B is upper bidiagonal; if M < N, B is lower bidiagonal.\n *  Note: T is incomplete and contains only the block reflectors of the first stage.\n *  Therefore, Q and P can not be built completely.\n *  Tile equivalent of PLASMA_sgebrd().\n *  Operates on matrices stored by tiles.\n *  All matrices are passed through descriptors.\n *  All dimensions are taken from the descriptors.\n *\n *******************************************************************************\n *\n * @param[in] jobq\n *          Specifies options for computing all or part of the matrix Q.\n *          Intended usage:\n *          = PlasmaVec: all M columns of Q are returned in array Q;\n *          = PlasmaNoVec: not referenced.\n *\n * @param[in] jobp\n *          Specifies options for computing all or part of the matrix V**T.\n *          Intended usage:\n *          = PlasmaVec: all M columns of Q are returned in array Q;\n *          = PlasmaNoVec: not referenced.\n *\n * @param[in,out] A\n *          On entry, the M-by-N matrix A.\n *          On exit,\n *          if M >= N, the diagonal and the first superdiagonal are\n *            overwritten with the upper bidiagonal matrix B; the\n *            elements below the diagonal, with the array T, represent\n *            the unitary matrix Q as a product of elementary\n *            reflectors, and the elements above the first superdiagonal,\n *            with the array T, represent the unitary matrix P as\n *            a product of elementary reflectors;\n *          if M < N, the diagonal and the first subdiagonal are\n *            overwritten with the lower bidiagonal matrix B; the\n *            elements below the first subdiagonal, with the array T,\n *            represent the unitary matrix Q as a product of\n *            elementary reflectors, and the elements above the diagonal,\n *            with the array T, represent the unitary matrix P as\n *            a product of elementary reflectors.\n *\n * @param[out] D\n *          The real array containing the diagonal elements\n *          of the bidiagonal matrix B:\n *          D(i) = A(i,i).\n *          Dimension (min(M,N)).\n *\n * @param[out] E\n *          The real array containing the off-diagonal elements\n *          of the bidiagonal matrix B:\n *          if M >= N, E(i) = A(i,i+1) for i = 1,2,...,N-1;\n *          if M < N, E(i) = A(i+1,i) for i = 1,2,...,M-1.\n *          Dimension (min(M,N)-1).\n *\n * @param[out] T\n *          On exit, contains auxiliary factorization data.\n *\n * @param[out] Q\n *          On exit, if jobz = PlasmaVec, then if return value = 0,\n *          Q contains the M-by-M unitary matrix Q.\n *          If jobz = PlasmaNoVec, then it is not referenced.\n *\n * @param[in] LDQ\n *          The leading dimension of the array Q. LDQ >= M.\n *\n * @param[out] P\n *          On exit, if jobz = PlasmaVec, then if return value = 0,\n *          P contains the N-by-N unitary matrix P.\n *          If jobz = PlasmaNoVec, then it is not referenced.\n *\n * @param[in] LDP\n *          The leading dimension of the array P. LDP >= N.\n *\n *******************************************************************************\n *\n * @return\n *          \\return PLASMA_SUCCESS successful exit\n *\n *******************************************************************************\n *\n * @sa PLASMA_sgebrd\n * @sa PLASMA_sgebrd_Tile_Async\n * @sa PLASMA_cgebrd_Tile\n * @sa PLASMA_dgebrd_Tile\n * @sa PLASMA_sgebrd_Tile\n *\n ******************************************************************************/\nint PLASMA_sgebrd_Tile(PLASMA_enum jobq, PLASMA_enum jobp,\n                       PLASMA_desc *A,\n                       float *D, float *E,\n                       PLASMA_desc *T,\n                       float *Q, int LDQ,\n                       float *P, int LDP)\n{\n    plasma_context_t *plasma;\n    PLASMA_sequence *sequence = NULL;\n    PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n    int status;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_sgebrd_Tile\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n    plasma_sequence_create(plasma, &sequence);\n    PLASMA_sgebrd_Tile_Async(jobq, jobp, A, D, E, T, Q, LDQ, P, LDP, sequence, &request);\n    plasma_dynamic_sync();\n    status = sequence->status;\n    plasma_sequence_destroy(plasma, sequence);\n    return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup float_Tile_Async\n *\n *  PLASMA_sgebrd_Tile_Async - reduces a general complex M-by-N matrix A to upper or lower\n *  bidiagonal form B using a two-stage approach\n *  First stage: reduction to band bidiagonal form (orthogonal matrices Q1 and P1);\n *  Second stage: reduction from band to bidiagonal form (orthogonal matrices\n *  Q2 and P2).\n *  Let Q = Q1 * Q2 be the global left unitary transformation;\n *  Let P = P1 * P2 be the global right unitary transformation;\n *  Q**T * A * P = B.\n *  If M >= N, B is upper bidiagonal; if M < N, B is lower bidiagonal.\n *  Note: T is incomplete and contains only the block reflectors of the first stage.\n *  Therefore, Q and P can not be built completely.\n *  Non-blocking equivalent of PLASMA_sgebrd_Tile().\n *  May return before the computation is finished.\n *  Allows for pipelining of operations at runtime.\n *\n *******************************************************************************\n *\n * @param[in] sequence\n *          Identifies the sequence of function calls that this call belongs to\n *          (for completion checks and exception handling purposes).\n *\n * @param[out] request\n *          Identifies this function call (for exception handling purposes).\n *\n *******************************************************************************\n *\n * @sa PLASMA_sgebrd\n * @sa PLASMA_sgebrd_Tile\n * @sa PLASMA_cgebrd_Tile_Async\n * @sa PLASMA_dgebrd_Tile_Async\n * @sa PLASMA_sgebrd_Tile_Async\n *\n ******************************************************************************/\nint PLASMA_sgebrd_Tile_Async(PLASMA_enum jobu, PLASMA_enum jobvt,\n                             PLASMA_desc *A,\n                             float *S, float *E,\n                             PLASMA_desc *T,\n                             float *U, int LDU,\n                             float *VT, int LDVT,\n                             PLASMA_sequence *sequence, PLASMA_request *request)\n{\n    PLASMA_desc descA ;\n    PLASMA_desc descT ;\n    PLASMA_desc descU, descVT;\n    float *AB;\n    int M     ;\n    int N     ;\n    int MINMN ;\n    int NB    ;\n    int LDAB  ;\n    int i;\n    int status;\n\n    plasma_context_t *plasma;\n    plasma = plasma_context_self();\n\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_sgebrd_Tile_Async\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n    if (sequence == NULL) {\n        plasma_fatal_error(\"PLASMA_sgebrd_Tile_Async\", \"NULL sequence\");\n        return PLASMA_ERR_UNALLOCATED;\n    }\n    if (request == NULL) {\n        plasma_fatal_error(\"PLASMA_sgebrd_Tile_Async\", \"NULL request\");\n        return PLASMA_ERR_UNALLOCATED;\n    }\n    /* Check sequence status */\n    if (sequence->status == PLASMA_SUCCESS)\n        request->status = PLASMA_SUCCESS;\n    else\n        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n\n    /* Check descriptors for correctness */\n    if (plasma_desc_check(A) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_sgebrd_Tile_Async\", \"invalid first descriptor\");\n        return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n    } else {\n        descA = *A;\n    }\n    if (plasma_desc_check(T) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_sgebrd_Tile_Async\", \"invalid fourth descriptor\");\n        return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n    } else {\n        descT = *T;\n    }\n    /* Check input arguments */\n    if (jobu != PlasmaNoVec  && jobu != PlasmaVec) {\n        plasma_error(\"PLASMA_sgebrd_Tile_Async\", \"illegal value of jobu\");\n        return PLASMA_ERR_NOT_SUPPORTED;\n    }\n    if (jobvt != PlasmaNoVec && jobvt != PlasmaVec) {\n        plasma_error(\"PLASMA_sgebrd_Tile_Async\", \"illegal value of jobvt\");\n        return PLASMA_ERR_NOT_SUPPORTED;\n    }\n    if (descA.nb != descA.mb) {\n        plasma_error(\"PLASMA_sgebrd_Tile_Async\", \"only square tiles supported\");\n        return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n    }\n\n\n    #if defined(ENABLE_TIMER)\n    PLASMA_Double_t timelpk=0.0,timeaplQ2=0.0, timeT=0.0;\n    PLASMA_Double_t timeB=0.0,timeblg=0.0,timeaplQ1=0.0,timeconv1=0.0,timeconv2=0.0,timeall=0.0;\n    timeall = PLASMA_Wtime();\n    #endif\n    PLASMA_enum uplo = descA.m >= descA.n ? PlasmaUpper : PlasmaLower;\n    M     = descA.m;\n    N     = descA.n;\n    MINMN = min(M,N);\n    NB    = min(descA.mb,MINMN);\n    LDAB  = 3*NB+1;\n    /*=======================================\n     *  case M<NB or N<NB call lapack\n     *=======================================*/\n    if( ( M<= NB) || ( N <=NB ) ){\n        /* convert the tile descA to lapack A */\n        if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n            AB = (float *) plasma_shared_alloc(plasma, M*N, PlasmaRealFloat);\n            if (AB == NULL) {\n                plasma_error(\"PLASMA_sgesvd_Tile_Async\", \"plasma_shared_alloc(AB-0-) failed\");\n                plasma_shared_free(plasma, AB);\n                return PLASMA_ERR_OUT_OF_RESOURCES;\n            }\n            plasma_sooptile2lap( descA, AB, NB, NB, M, N,  sequence, request);\n        } else {\n            AB = descA.mat;\n            plasma_siptile2lap( descA, AB, NB, NB, M, N,  sequence, request);\n        }\n        plasma_dynamic_sync();\n        /*=======================================\n         *  calling LAPACK SGESVD\n         *=======================================*/\n        #if defined(ENABLE_TIMER)\n        plasma_dynamic_sync();\n        timelpk   = PLASMA_Wtime();\n        #endif\n        plasma_setlapack_multithreads(plasma->world_size);\n        /* call SVD solver using lapack routine  */\n        float *TAUQ = (float *) plasma_shared_alloc(plasma, MINMN, PlasmaRealFloat);\n        float *TAUP = (float *) plasma_shared_alloc(plasma, MINMN, PlasmaRealFloat);\n        status = LAPACKE_sgebrd(LAPACK_COL_MAJOR, M, N, AB, M, S, E, TAUQ, TAUP);\n        if(jobu == PlasmaVec){\n            LAPACKE_slacpy(LAPACK_COL_MAJOR, lapack_const(PlasmaLower), M, MINMN, AB, M, U, LDU );\n            LAPACKE_sorgbr(LAPACK_COL_MAJOR, 'Q', M, M, N, U, LDU, TAUQ );\n        }\n        if(jobvt == PlasmaVec){\n            LAPACKE_slacpy(LAPACK_COL_MAJOR, lapack_const(PlasmaUpper), MINMN, N, AB, M, VT, LDVT );\n            LAPACKE_sorgbr(LAPACK_COL_MAJOR, 'P', N, N, MINMN, VT, LDVT, TAUP );\n        }\n        if(status != 0){\n            plasma_error(\"PLASMA_sgesvd\",\"SGESVD\");\n        }\n        sequence->status = status;\n        plasma_setlapack_sequential(plasma);\n        #if defined(ENABLE_TIMER)\n        timelpk = PLASMA_Wtime()-timelpk;\n        printf(\"  Finish Eigensolver-lpkonly timing= %lf  threads %d\\n\" ,timelpk, plasma->world_size);\n        #endif\n        /*=======================================\n         *  END of calling SVD solver\n         *=======================================*/\n        /* convert the lapack to the tile descA */\n        if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n            //plasma_sooplap2tile_noalloc( descA, AB, NB, NB,  M, N, 0, 0, M, N, sequence, request);\n            plasma_parallel_call_5( plasma_pslapack_to_tile,\n            float*, AB,\n            int,                 M,\n            PLASMA_desc,         descA,\n            PLASMA_sequence*,    sequence,\n            PLASMA_request*,     request);\n            plasma_dynamic_sync();\n            free(AB);\n        } else {\n            plasma_siplap2tile( descA, AB, NB, NB,  M, N, 0, 0, M, N,\n                                sequence, request);\n        }\n        plasma_dynamic_sync();\n        free(TAUQ);\n        free(TAUP);\n        return PLASMA_SUCCESS;\n    }\n    /*=======================================\n     *  END OF case M<NB or N<NB\n     *=======================================*/\n    /*\n     * Allocate workspace for band storage of the band matrix A\n     * AB looks like:\n     *       __________________________________\n     * NB   |               zero               |\n     *       ----------------------------------\n     * NB+1 |               band A             |\n     *       ----------------------------------\n     * NB   |_______________zero_______________|\n     *\n     * */\n    AB = (float *)plasma_shared_alloc(plasma, LDAB*MINMN, PlasmaRealFloat);\n    memset( AB, 0, LDAB * MINMN * sizeof(float) );\n    if (AB == NULL) {\n        plasma_error(\"PLASMA_sgebrd_Tile_Async\", \"plasma_shared_alloc(AB) failed\");\n        plasma_shared_free(plasma, AB);\n        return PLASMA_ERR_OUT_OF_RESOURCES;\n    }\n    /*=======================================\n     *  calling Reduction from DENSE to BAND\n     *  then convert matrix to band form\n     *=======================================*/\n    //plasma_dynamic_sync();\n    #if defined(ENABLE_TIMER)\n    timeB   = PLASMA_Wtime();\n    #endif\n    /*\n     * Reduction to BAND bidiagonal form\n     * May be further optimized using the algo described in Trefethen\n     */\n    /* if (plasma->householder == PLASMA_FLAT_HOUSEHOLDER) { */\n        plasma_dynamic_call_4(plasma_psgebrd_ge2gb,\n            PLASMA_desc, descA,\n            PLASMA_desc, descT,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n    /* } */\n    /* else { */\n    /*     plasma_dynamic_call_4(plasma_psgebrd_ge2gb_rh, */\n    /*         PLASMA_desc, descA, */\n    /*         PLASMA_desc, descT, */\n    /*         PLASMA_sequence*, sequence, */\n    /*         PLASMA_request*, request); */\n    /* } */\n    //plasma_dynamic_sync();\n    plasma_dynamic_call_6( plasma_psgbcpy_t2bl,\n        PLASMA_enum, descA.m >= descA.n ? PlasmaUpper : PlasmaLower,\n        PLASMA_desc, descA,\n        float*, &(AB[NB]),\n        int, LDAB,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n    plasma_dynamic_sync();\n    status = sequence->status;\n    if (status != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_sgebrd\",\"psgebrd_ge2gb+pzcopy\");\n        return status;\n    }\n    #if defined(ENABLE_TIMER)\n    timeB   = PLASMA_Wtime()-timeB;\n    printf(\"\\n  Finish Band red    timing= %lf \\n\",timeB);\n    #endif\n    /*=======================================\n     *  END of calling Reduction to BAND\n     *=======================================*/\n    /*=======================================\n     *  calling Reduction from BAND to bidiag\n     *=======================================*/\n    float *VQ2   = NULL;\n    float *VP2   = NULL;\n    float *TAUQ2 = NULL;\n    float *TAUP2 = NULL;\n    float *TQ2   = NULL;\n    float *TP2   = NULL;\n    int Vblksiz, blkcnt, LDT, LDV;\n    int WANTZ   = 0;\n\n    if( jobu == PlasmaNoVec )\n        WANTZ=0;\n    else\n        WANTZ=1;\n\n    /* Vblksiz correspond to the blocking used when applying V2 to the matrix U\n     * it is similar to IB in LAPACK SORMQR.\n     * blkcnt is the number of diamond or tile of Vs */\n    /* Note that in case PlamaVec requested, the V2 and T2 are stored by the\n     * bulgechasing function in a special format:\n     * for V2s: it store the V2(LDV,Vblksiz) of each diamond in a tile storage meaning\n     * that V2_1 is stored then V2_2,..., V2_blkcnt.\n     * blkcnt is the number of diamond.\n     * */\n    Vblksiz = min(NB,48);\n    LDT     = Vblksiz;\n    /* data for U */\n    if( jobu == PlasmaVec ) {\n        findVTsiz(MINMN, NB, Vblksiz, &blkcnt, &LDV);\n        TAUQ2   = (float *) plasma_shared_alloc(plasma,     blkcnt*Vblksiz, PlasmaRealFloat);\n        VQ2     = (float *) plasma_shared_alloc(plasma, LDV*blkcnt*Vblksiz, PlasmaRealFloat);\n        TQ2     = (float *) plasma_shared_alloc(plasma, LDT*blkcnt*Vblksiz, PlasmaRealFloat);\n        if ( (TAUQ2 == NULL) || (VQ2 == NULL) || (TQ2 == NULL) ) {\n            plasma_error(\"PLASMA_sgebrd\", \"plasma_shared_alloc() failed\");\n            plasma_shared_free(plasma, TAUQ2);\n            plasma_shared_free(plasma, VQ2);\n            plasma_shared_free(plasma, TQ2);\n            return PLASMA_ERR_OUT_OF_RESOURCES;\n        }\n        memset(TAUQ2, 0,     blkcnt*Vblksiz*sizeof(float));\n        memset(VQ2,   0, LDV*blkcnt*Vblksiz*sizeof(float));\n        memset(TQ2,   0, LDT*blkcnt*Vblksiz*sizeof(float));\n    }\n    else {\n        TAUQ2   = (float *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaRealFloat);\n        VQ2     = (float *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaRealFloat);\n        if ( (TAUQ2 == NULL) || (VQ2 == NULL) ) {\n            plasma_error(\"PLASMA_sgebrd\", \"plasma_shared_alloc() failed\");\n            plasma_shared_free(plasma, TAUQ2);\n            plasma_shared_free(plasma, VQ2);\n            return PLASMA_ERR_OUT_OF_RESOURCES;\n        }\n        memset(TAUQ2, 0, 2*MINMN*sizeof(float));\n        memset(VQ2,   0, 2*MINMN*sizeof(float));\n    }\n    /* data for VT */\n    if( jobvt == PlasmaVec ) {\n        findVTsiz(MINMN, NB, Vblksiz, &blkcnt, &LDV);\n        TAUP2   = (float *) plasma_shared_alloc(plasma,     blkcnt*Vblksiz, PlasmaRealFloat);\n        VP2     = (float *) plasma_shared_alloc(plasma, LDV*blkcnt*Vblksiz, PlasmaRealFloat);\n        TP2     = (float *) plasma_shared_alloc(plasma, LDT*blkcnt*Vblksiz, PlasmaRealFloat);\n        if ( (TAUP2 == NULL) || (VP2 == NULL) || (TP2 == NULL) ) {\n            plasma_error(\"PLASMA_sgebrd\", \"plasma_shared_alloc() failed\");\n            plasma_shared_free(plasma, TAUP2);\n            plasma_shared_free(plasma, VP2);\n            plasma_shared_free(plasma, TP2);\n            return PLASMA_ERR_OUT_OF_RESOURCES;\n        }\n        memset(TAUP2, 0,     blkcnt*Vblksiz*sizeof(float));\n        memset(VP2,   0, LDV*blkcnt*Vblksiz*sizeof(float));\n        memset(TP2,   0, LDT*blkcnt*Vblksiz*sizeof(float));\n    }\n    else {\n        TAUP2   = (float *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaRealFloat);\n        VP2     = (float *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaRealFloat);\n        if ( (TAUP2 == NULL) || (VP2 == NULL) ) {\n            plasma_error(\"PLASMA_sgebrd\", \"plasma_shared_alloc() failed\");\n            plasma_shared_free(plasma, TAUQ2);\n            plasma_shared_free(plasma, VQ2);\n            return PLASMA_ERR_OUT_OF_RESOURCES;\n        }\n        memset(TAUP2, 0, 2*MINMN*sizeof(float));\n        memset(VP2,   0, 2*MINMN*sizeof(float));\n    }\n    /*=======================================\n     *  calling bulge chasing\n     *=======================================*/\n    #if defined(ENABLE_TIMER)\n    timeblg  = PLASMA_Wtime();\n    #endif\n    plasma_parallel_call_16(plasma_psgebrd_gb2bd_v1,\n        PLASMA_enum,         uplo,\n        int,                 MINMN,\n        int,                 NB,\n        int,                 Vblksiz,\n        float*, AB,\n        int,                 LDAB,\n        float*, VQ2,\n        float*, TAUQ2,\n        float*, VP2,\n        float*, TAUP2,\n        float*,             S,\n        float*,             E,\n        int,                 WANTZ,\n        int,                 WANTZ,\n        PLASMA_sequence*,    sequence,\n        PLASMA_request*,     request);\n    /* WARNING: If plasma_psgebrd_gb2bd is implemented through a dynamic call, don't\n     * forget to synchronize */\n    plasma_dynamic_sync();\n    #if defined(ENABLE_TIMER)\n    timeblg   = PLASMA_Wtime()-timeblg;\n    printf(\"  Finish Bulge       timing= %lf \\n\" ,timeblg);\n    #endif\n    /*=======================================\n     *  END of calling bulge chasing\n     *=======================================*/\n    /*=======================================\n     *  generate U from the bulge\n     *=======================================*/\n    if (jobu == PlasmaVec){\n        memset(U,   0, M*LDU*sizeof(float));\n        /* Initialize U to Identity */\n        for(i=0; i<M; i++){\n            U[i+i*LDU] = 1.0;\n        }\n        #if defined(ENABLE_TIMER)\n        timeT  = PLASMA_Wtime();\n        #endif\n        /* compute T2 */\n        plasma_static_call_8(plasma_pslarft_blgtrd,\n            int,                 MINMN,\n            int,                 NB,\n            int,                 Vblksiz,\n            float*, VQ2,\n            float*, TQ2,\n            float*, TAUQ2,\n            PLASMA_sequence*,    sequence,\n            PLASMA_request*,     request);\n        #if defined(ENABLE_TIMER)\n        plasma_dynamic_sync();\n        timeT  = PLASMA_Wtime()-timeT;\n        printf(\"  Finish compute TU2  timing= %lf \\n\" ,timeT);\n        timeaplQ2  = PLASMA_Wtime();\n        #endif\n        /* apply Q2 from Left */\n        plasma_static_call_14(plasma_psormqr_blgtrd,\n            PLASMA_enum,         PlasmaLeft,\n            PLASMA_enum,         PlasmaNoTrans,\n            int,                 MINMN,\n            int,                 NB,\n            int,                 MINMN,\n            int,                 Vblksiz,\n            int,                 WANTZ,\n            float*, VQ2,\n            float*, TQ2,\n            float*, TAUQ2,\n            float*, U,\n            int,                 LDU,\n            PLASMA_sequence*,    sequence,\n            PLASMA_request*,     request);\n        #if defined(ENABLE_TIMER)\n        plasma_dynamic_sync();\n        timeaplQ2  = PLASMA_Wtime()-timeaplQ2;\n        printf(\"  Finish compute U2  timing= %lf \\n\" ,timeaplQ2);\n        #endif\n        /*=======================================\n         *  apply Q1 from the reduction to band\n         *=======================================*/\n        /* CASE NB>N, Q1 doesn't need to be applied, only bulge chasing has been done */\n        if( NB < N ){\n            #if defined(ENABLE_TIMER)\n            plasma_dynamic_sync();\n            timeconv1   = PLASMA_Wtime();\n            #endif\n            if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n                plasma_sooplap2tile( descU, U, NB, NB, LDU, M, 0, 0, M, M, sequence, request, plasma_desc_mat_free(&(descU)) );\n            } else {\n                plasma_siplap2tile( descU, U, NB, NB, LDU, M, 0, 0, M, M, sequence, request);\n            }\n            #if defined(ENABLE_TIMER)\n            timeconv1    = PLASMA_Wtime()-timeconv1;\n            timeaplQ1   = PLASMA_Wtime();\n            #endif\n            /* Accumulate the transformations from the first stage */\n            if(M<N){\n                plasma_dynamic_call_7(plasma_psormqr,\n                    PLASMA_enum, PlasmaLeft,\n                    PLASMA_enum, PlasmaNoTrans,\n                    PLASMA_desc, plasma_desc_submatrix(descA, descA.mb, 0, descA.m-descA.mb, descA.n-descA.nb),\n                    PLASMA_desc, plasma_desc_submatrix(descU, descU.mb, 0, descU.m-descU.mb, descU.n),\n                    PLASMA_desc, plasma_desc_submatrix(descT, descT.mb, 0, descT.m-descT.mb, descT.n-descT.nb),\n                    PLASMA_sequence*, sequence,\n                    PLASMA_request*, request);\n            }\n            else {\n                plasma_dynamic_call_7(plasma_psormqr,\n                    PLASMA_enum, PlasmaLeft,\n                    PLASMA_enum, PlasmaNoTrans,\n                    PLASMA_desc, descA,\n                    PLASMA_desc, descU,\n                    PLASMA_desc, descT,\n                    PLASMA_sequence*, sequence,\n                    PLASMA_request*, request);\n            }\n            #if defined(ENABLE_TIMER)\n            plasma_dynamic_sync();\n            timeaplQ1   = PLASMA_Wtime()-timeaplQ1;\n            printf(\"  Finish compute U1  timing= %lf \\n\" ,timeaplQ1);\n            timeconv2    = PLASMA_Wtime();\n            #endif\n            if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n                plasma_sooptile2lap( descU, U, NB, NB, LDU, M, sequence, request );\n                plasma_dynamic_sync();\n                plasma_desc_mat_free(&descU);\n            } else {\n                plasma_siptile2lap( descU, U, NB, NB, LDU, M, sequence, request );\n                plasma_dynamic_sync();\n            }\n            #if defined(ENABLE_TIMER)\n            plasma_dynamic_sync();\n            timeconv2    = PLASMA_Wtime()-timeconv2;\n            printf(\"  Finish convert  U  timing= %lf \\n\" ,timeconv1+timeconv2);\n            #endif\n        } /* END of ( NB < N ) */\n    }\n    /*=======================================\n     *  END of calling computing U\n     *=======================================*/\n    /*=======================================\n     *  generate VT from the bulge\n     *=======================================*/\n    if (jobvt == PlasmaVec){\n        memset(VT,   0, N*LDVT*sizeof(float));\n        /* Initialize VT to Identity */\n        for(i=0; i<N; i++){\n            VT[i+i*LDVT] = 1.0;\n        }\n        #if defined(ENABLE_TIMER)\n        timeT  = PLASMA_Wtime();\n        #endif\n        /* compute T2 */\n        plasma_static_call_8(plasma_pslarft_blgtrd,\n            int,                 MINMN,\n            int,                 NB,\n            int,                 Vblksiz,\n            float*, VP2,\n            float*, TP2,\n            float*, TAUP2,\n            PLASMA_sequence*,    sequence,\n            PLASMA_request*,     request);\n        #if defined(ENABLE_TIMER)\n        plasma_dynamic_sync();\n        timeT  = PLASMA_Wtime()-timeT;\n        printf(\"  Finish compute TV2  timing= %lf \\n\" ,timeT);\n        timeaplQ2  = PLASMA_Wtime();\n        #endif\n        /* apply Q2 from Left */\n        plasma_static_call_14(plasma_psormqr_blgtrd,\n            PLASMA_enum,         PlasmaRight,\n            PLASMA_enum,         PlasmaTrans,\n            int,                 MINMN,\n            int,                 NB,\n            int,                 MINMN,\n            int,                 Vblksiz,\n            int,                 WANTZ,\n            float*, VP2,\n            float*, TP2,\n            float*, TAUP2,\n            float*, VT,\n            int,                 LDVT,\n            PLASMA_sequence*,    sequence,\n            PLASMA_request*,     request);\n        #if defined(ENABLE_TIMER)\n        plasma_dynamic_sync();\n        timeaplQ2  = PLASMA_Wtime()-timeaplQ2;\n        printf(\"  Finish compute V2 timing= %lf \\n\" ,timeaplQ2);\n        #endif\n        /*=======================================\n         *  apply Q1 from the reduction to band\n         *=======================================*/\n        /* CASE NB>N, Q1 doesn't need to be applied, only bulge chasing has been done */\n        if( NB < N ){\n            #if defined(ENABLE_TIMER)\n            plasma_dynamic_sync();\n            timeconv1   = PLASMA_Wtime();\n            #endif\n            if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n                plasma_sooplap2tile( descVT, VT, NB, NB, LDVT, N, 0, 0, N, N, sequence, request, plasma_desc_mat_free(&(descVT)) );\n            } else {\n                plasma_siplap2tile( descVT, VT, NB, NB, LDVT, N, 0, 0, N, N, sequence, request);\n            }\n            #if defined(ENABLE_TIMER)\n            timeconv1    = PLASMA_Wtime()-timeconv1;\n            timeaplQ1   = PLASMA_Wtime();\n            #endif\n            /* Accumulate the transformations from the first stage */\n            if(M<N){\n                plasma_dynamic_call_7(plasma_psormlq,\n                    PLASMA_enum, PlasmaRight,\n                    PLASMA_enum, PlasmaNoTrans,\n                    PLASMA_desc, descA,\n                    PLASMA_desc, descVT,\n                    PLASMA_desc, descT,\n                    PLASMA_sequence*, sequence,\n                    PLASMA_request*, request);\n            }\n            else {\n                plasma_dynamic_call_7(plasma_psormlq,\n                    PLASMA_enum, PlasmaRight,\n                    PLASMA_enum, PlasmaNoTrans,\n                    PLASMA_desc, plasma_desc_submatrix(descA, 0, descA.nb, descA.m-descA.mb, descA.n-descA.nb),\n                    PLASMA_desc, plasma_desc_submatrix(descVT,0, descVT.nb, descVT.m, descVT.n-descVT.nb),\n                    PLASMA_desc, plasma_desc_submatrix(descT, 0, descT.nb, descT.m-descT.mb, descT.n-descT.nb),\n                    PLASMA_sequence*, sequence,\n                    PLASMA_request*, request);\n            }\n            #if defined(ENABLE_TIMER)\n            plasma_dynamic_sync();\n            timeaplQ1   = PLASMA_Wtime()-timeaplQ1;\n            printf(\"  Finish compute V1  timing= %lf \\n\" ,timeaplQ1);\n            timeconv2    = PLASMA_Wtime();\n            #endif\n\n            if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n                plasma_sooptile2lap( descVT, VT, NB, NB, LDVT, N, sequence, request );\n                plasma_dynamic_sync();\n                plasma_desc_mat_free(&descVT);\n            } else {\n                plasma_siptile2lap( descVT, VT, NB, NB, LDVT, N, sequence, request );\n                plasma_dynamic_sync();\n            }\n            #if defined(ENABLE_TIMER)\n            plasma_dynamic_sync();\n            timeconv2    = PLASMA_Wtime()-timeconv2;\n            printf(\"  Finish convert VT  timing= %lf \\n\" ,timeconv1+timeconv2);\n            #endif\n        } /* END of ( NB < N ) */\n    }\n    /*=======================================\n     *  END of calling computing VT\n     *=======================================*/\n    #if defined(ENABLE_TIMER)\n    timeall = PLASMA_Wtime()-timeall;\n    printf(\"  Finish full Bidiagonalisation threads %d  N %d  timeall= %lf \\n\", plasma->world_size, N, timeall);\n    #endif\n    if( jobu  == PlasmaVec )\n        plasma_shared_free(plasma, TQ2);\n    if( jobvt == PlasmaVec )\n        plasma_shared_free(plasma, TP2);\n    plasma_shared_free(plasma, VQ2);\n    plasma_shared_free(plasma, TAUQ2);\n    plasma_shared_free(plasma, VP2);\n    plasma_shared_free(plasma, TAUP2);\n    plasma_shared_free(plasma, AB);\n    return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "7fcb7ab70b759eb0e6cbf4ef9f8f8a92b33820e6", "size": 37596, "ext": "c", "lang": "C", "max_stars_repo_path": "compute/sgebrd.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/sgebrd.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/sgebrd.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.5331230284, "max_line_length": 131, "alphanum_fraction": 0.531492712, "num_tokens": 9860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3972183615465195}}
{"text": "/*\n\nExcited States software: KGS\nContributors: See CONTRIBUTORS.txt\nContact: kgs-contact@simtk.org\n\nCopyright (C) 2009-2017 Stanford University\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThis entire text, including the above copyright notice and this permission notice\nshall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\n*/\n\n#ifndef COORDINATE_H\n#define COORDINATE_H\n\n#include <string>\n\n#include \"math3d/primitives.h\"\n#include <gsl/gsl_vector.h>\n\nclass Coordinate : public Math3D::Vector3 {\n  public:\n\tCoordinate();\n\tCoordinate(double x,double y,double z);\n\t~Coordinate();\n\n\tstd::string tostring() const;\n\tdouble distanceTo (Coordinate& other) const; // Euclidean distance between self and other\n\tbool isWithinSphere (Coordinate& center, double radius) const;\n\tdouble getAngle (Coordinate& left, Coordinate& right) const; // Angle in degrees between left-this-right\n\tCoordinate mid_point (Coordinate& other) const;\n\tCoordinate crossproduct (Coordinate& other) const;\n\n\tstatic void copyToGslVector (Math3D::Vector3 v, gsl_vector* gslv);\n\tstatic double getPlanarAngle (Coordinate& c1, Coordinate& c2, Coordinate& c3, Coordinate& c4); // Angle between plane c123 and plane c234\n};\n\n#endif\n", "meta": {"hexsha": "4a1bbe75615eea0ec1dcb0c0b00a3574bb8024eb", "size": 2076, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/Coordinate.h", "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_issues_repo_path": "src/core/Coordinate.h", "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_forks_repo_path": "src/core/Coordinate.h", "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": ["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.7454545455, "max_line_length": 138, "alphanum_fraction": 0.7870905588, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.3968729131110647}}
{"text": "\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <math.h>\n#include <assert.h>\n#include <alloca.h>\n\n#include <gsl/gsl_cdf.h>\n#include <gsl/gsl_statistics_float.h>\n\n#include \"rank.h\"\n#include \"stattest.h\"\n#include \"num.h\"\n\ntypedef float con_t;\n\nstruct ConCovars {\n\n\t/**\n\t  * Maximum number of samples\n\t  */\n\tint SAMPLE_CAPACITY;\n\n\t/**\n\t  * Count of samples pushed since last con_clear.\n\t  */\n\tint sample_count;\n\n\t/**\n\t  * The total amount of malloc'ed space (for the purposes\n\t  * of fast clearing with memset).\n\t  */\n\tsize_t SIZEOF_BUFFERS;\n\n\t/**\n\t  * Two buffers\n\t  */\n\tcon_t *l, *r;\n\n\tvoid *rank_scratch;\n};\n\n#if defined(_UNITTEST_NUM_)\nstatic void dbg_dump( struct ConCovars *co, FILE *fp ) {\n\tfor(unsigned int i = 0; i < co->sample_count; i++ )\n\t\tfprintf( fp, \"%f\\t%f\\n\", co->l[i], co->r[i] );\n}\n#endif\n\n\nvoid con_destroy( void *pv ) {\n\n\tif( pv ) {\n\t\tstruct ConCovars *co = (struct ConCovars *)pv;\n\t\tif( co->rank_scratch )\n\t\t\trank_free( co->rank_scratch );\n\t\tif( co->l )\n\t\t\tfree( co->l );\n\t\tfree( pv );\n\t}\n}\n\n\n/**\n  * Pre-allocate a set of working buffers large enough for all anticipated\n  * calculations (max feature length) and a struct to wrap them.\n  */\nvoid *con_create( unsigned int cap ) {\n\tstruct ConCovars *co\n\t\t= calloc( 1, sizeof(struct ConCovars) );\n\tif( co ) {\n\t\tco->SAMPLE_CAPACITY = cap;\n\t\tco->SIZEOF_BUFFERS  = 2*cap*sizeof(con_t);\n\t\t// Allocate one large buffer and partition it up.\n\t\tco->l = calloc( co->SIZEOF_BUFFERS, sizeof(char) );\n\t\tco->r = co->l + cap;\n\t\tco->rank_scratch = rank_alloc( cap );\n\t\t// If -anything- failed clean up any successes.\n\t\tif( (NULL == co->l) || \n\t\t\t(NULL == co->rank_scratch) ) {\n\t\t\tcon_destroy( co );\n\t\t\treturn NULL;\n\t\t}\n\t\treturn co;\n\t}\n\treturn NULL;\n}\n\n\nvoid con_clear( void *pv ) {\n\tstruct ConCovars *co = (struct ConCovars *)pv;\n\tco->sample_count = 0;\n\tmemset( co->l, 0, co->SIZEOF_BUFFERS );\n}\n\n\nvoid con_push( void *pv, float n1, float n2 ) {\n\tstruct ConCovars *co = (struct ConCovars *)pv;\n\tconst int i = co->sample_count++;\n\tassert( i <= co->SAMPLE_CAPACITY );\n\tco->l[i] = n1;\n\tco->r[i] = n2;\n}\n\n\nsize_t con_size( void *pv ) {\n\treturn ((struct ConCovars *)pv)->sample_count;\n}\n\n\nbool con_complete( void *pv ) {\n\treturn ((struct ConCovars *)pv)->sample_count > 2;\n\t// ...otherwise p-value computation will fail.\n}\n\n\n/**\n */\nint con_spearman_correlation( void *pv, struct Statistic *result ) {\n\n\tstruct ConCovars *co = (struct ConCovars *)pv;\n\tconst int N = co->sample_count;\n\n\tassert( N > 2 );\n\tassert( NULL != co->rank_scratch );\n\n\tconst int rinfo1 \n\t\t= rank_floats( co->l, N, 0, co->rank_scratch );\n\tconst int rinfo2 \n\t\t= rank_floats( co->r, N, 0, co->rank_scratch );\n\n\tif( RANK_STATUS_CONST & rinfo1 ) // vectors were in fact constant!\n\t\tresult->extra_value[0] = N-1;\n\tif( RANK_STATUS_CONST & rinfo2 )\n\t\tresult->extra_value[1] = N-1;\n\n\t{\n\t\tconst double rho \n\t\t\t= gsl_stats_float_correlation( co->l, 1, co->r, 1, N );\n\n\t\t/**\n\t\t * P-value computation for the correlation.\n\t\t */\n\n#ifdef HAVE_FISHER_TRANSFORM\n\t\tconst double FisherTransform \n\t\t\t//= 0.5 * log( (1.+rho) / (1.-rho) );\n\t\t\t= atanh(rho);\n\t\t// ...absolute value to simplify CDF use below, since the\n\t\t// transformation is symmetric.\n\t\tconst double z\n\t\t\t= sqrt( (N - 3.0) / 1.06 ) * FisherTransform;\n\t\t// ...z ~ N(0,1) under null hyp of statistical independence.\n\t\tresult->name\n\t\t\t= \"Spearman_rho,Fisher_transform\";\n\t\tresult->probability = gsl_cdf_ugaussian_Q( fabs(z) );\n#else\n\t\tconst double t \n\t\t\t=  fabs( rho*sqrt((N-2.0)/(1.0-rho*rho)) );\n\t\t// ...abs so that I can always test the upper tail.\n\t\t// x2 below to make it a two-tailed test. (t-distribution\n\t\t// is symmetric).\n\t\tresult->name\n\t\t\t= \"Spearman_rho,t-distribution\";\n\t\tresult->probability = 2* gsl_cdf_tdist_Q(t,N-2.0);\n#endif\n\t\tresult->value = rho;\n\t}\n\tresult->sample_count = N;\n\n\treturn 0;\n}\n\n\n#ifdef HAVE_SCALAR_PEARSON\nint con_pearson_correlation( void *pv, struct Statistic *result ) {\n\tstruct ConCovars *co = (struct ConCovars *)pv;\n\tconst int N = co->sample_count;\n\tps->rho = gsl_stats_float_correlation( co->l, 1, co->r, 1, N );\n\treturn 0;\n}\n#endif\n\n\n#ifdef _UNITTEST_NUM_\n\n/**\n * This is intended to be exercised with the following R script\n * that generates a small table of grouped floating-point values\n * executes a Kruskal-Wallis test on it, and dumps the table\n * to a tab-delimited file with the test results as a comment on\n * the first line.\n *\n * x <- data.frame(\n * \t\tcat=as.integer(gl(3,4))-1, \n * \t\tnum=c( runif(4)*10, runif(4)*20, 10+runif(4)*10 ) );\n * k <- with( x, kruskal.test( num, cat ) );\n * cat( sprintf( \"# K=%f p-value=%f\\n\", k$statistic, k$p.value ), file=\"foo.tab\" );\n * write.table( x, 'foo.tab', quote=F, sep='\\t', row.names=F, col.names=F, append=TRUE );\n */\n#include <err.h>\n\nint main( int argc, char *argv[] ) {\n\n\tif( argc >= 2 ) {\n\n\t\tstruct Statistic result;\n\t\tstruct ConCovars *accum\n\t\t\t= con_create( atoi(argv[1]) );\n\t\tFILE *fp \n\t\t\t= argc > 2\n\t\t\t? fopen( argv[2], \"r\" )\n\t\t\t: stdin;\n\t\tchar *line = NULL;\n\t\tsize_t n = 0;\n\n\t\tcon_clear( accum );\n\n\t\twhile( getline( &line, &n, fp ) > 0 ) {\n\t\t\tfloat l, r;\n\t\t\tif( line[0] == '#' ) {\n\t\t\t\tfputs( line, stdout );\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif( 2 == sscanf( line, \"%f\\t%f\\n\", &l, &r ) ) {\n\t\t\t\tcon_push( accum, l, r );\n\t\t\t} else {\n\t\t\t\tfprintf( stderr, \"Failure parsing line: %s\", line );\n\t\t\t}\n\t\t}\n\t\tfree( line );\n\t\tfclose( fp );\n\n\t\tmemset( &result, 0, sizeof(struct Statistic) );\n#ifdef HAVE_SCALAR_PEARSON\n\t\tcon_pearson_correlation( accum, &result );\n\t\tprintf( \"pearson=%f\\n\", result.value );\n#endif\n\t\tmemset( &result, 0, sizeof(struct Statistic) );\n\t\tif( con_spearman_correlation( accum, &result ) == 0 ) {\n\t\t\tprintf( \"p-value=%f, spearman=%f\\n\", result.probability, result.value );\n\t\t} else\n\t\t\tprintf( \"error\\n\" );\n\n\t\tcon_destroy( accum );\n\n\t} else\n\t\terr( -1, \"%s <sample count> [ <input file> ]\", argv[0] );\n\n\treturn 0;\n}\n#endif\n\n", "meta": {"hexsha": "cfacd9060e5d05270c34ed3a948f23fd7de5b93e", "size": 5829, "ext": "c", "lang": "C", "max_stars_repo_path": "pairwise/src/num.c", "max_stars_repo_name": "IlyaLab/kramtools", "max_stars_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T03:07:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-30T03:07:45.000Z", "max_issues_repo_path": "pairwise/src/num.c", "max_issues_repo_name": "IlyaLab/kramtools", "max_issues_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pairwise/src/num.c", "max_forks_repo_name": "IlyaLab/kramtools", "max_forks_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_forks_repo_licenses": ["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.76953125, "max_line_length": 89, "alphanum_fraction": 0.631154572, "num_tokens": 1890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3966814823144408}}
{"text": "#ifndef CTETRA_PARTIAL_H\n#define CTETRA_PARTIAL_H\n\n#include <stdlib.h>\n#include <math.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_matrix.h>\n#include \"input.h\"\n#include \"evcache.h\"\n#include \"submesh.h\"\n\ndouble Gauss_PartialDos_Eig(double E, double sigma, int orig_index, int eig_index, EvecCache *evCache);\n\ndouble Gauss_PartialDos(double E, double sigma, int orig_index, EvecCache *evCache);\n\ndouble** Gauss_PartialDosList(UEInputFn UEfn, int na, int nb, int nc, double sigma, int num_bands, gsl_matrix *R, double **Es, int num_dos);\n\n#endif //CTETRA_PARTIAL_H\n", "meta": {"hexsha": "662f5483b01301ecbd4a964e1841c0489b8a62b3", "size": 627, "ext": "h", "lang": "C", "max_stars_repo_path": "partial.h", "max_stars_repo_name": "tflovorn/ctetra", "max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "partial.h", "max_issues_repo_name": "tflovorn/ctetra", "max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z", "max_forks_repo_path": "partial.h", "max_forks_repo_name": "tflovorn/ctetra", "max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1", "max_forks_repo_licenses": ["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": 140, "alphanum_fraction": 0.7703349282, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3966460941306852}}
{"text": "/**\n *\n * @file testing_zgecfi.c\n *\n *  PLASMA testings module\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n *  This program tests the implementation of the inplace format\n *  conversion based on the GKK algorithm by Gustavson, Karlsson,\n *  Kagstrom.\n *\n * @version 2.6.0\n * @author Mathieu Faverge\n * @date 2010-11-15\n *\n * @precisions normal z -> c d s\n *\n * Purpose :\n *    Test all the possibilities of matrix conversion (6*6)\n **/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <lapacke.h>\n#include <plasma.h>\n#include \"testing_zmain.h\"\n\nstatic int conversions[36][2] = {\n  /* No conversion */\n  { PlasmaCM,   PlasmaCM   },\n  { PlasmaCCRB, PlasmaCCRB },\n  { PlasmaCRRB, PlasmaCRRB },\n  { PlasmaRCRB, PlasmaRCRB },\n  { PlasmaRRRB, PlasmaRRRB },\n  { PlasmaRM,   PlasmaRM   },\n  /* One Conversion */\n  { PlasmaCM,   PlasmaCCRB },\n  { PlasmaCCRB, PlasmaCM   },\n  { PlasmaRM,   PlasmaRRRB },\n  { PlasmaRRRB, PlasmaRM   },\n  { PlasmaCCRB, PlasmaCRRB },\n  { PlasmaCRRB, PlasmaCCRB },\n  { PlasmaRCRB, PlasmaRRRB },\n  { PlasmaRRRB, PlasmaRCRB },\n  { PlasmaCCRB, PlasmaRCRB },\n  { PlasmaRCRB, PlasmaCCRB },\n  { PlasmaCRRB, PlasmaRRRB },\n  { PlasmaRRRB, PlasmaCRRB },\n  /* Two Conversions */\n  { PlasmaRM,   PlasmaCRRB },\n  { PlasmaCRRB, PlasmaRM   },\n  { PlasmaCM,   PlasmaRCRB }, \n  { PlasmaRCRB, PlasmaCM   },\n  { PlasmaCCRB, PlasmaRRRB },\n  { PlasmaRRRB, PlasmaCCRB },\n  { PlasmaCRRB, PlasmaRCRB },\n  { PlasmaRCRB, PlasmaCRRB },\n  { PlasmaCM,   PlasmaCRRB }, \n  { PlasmaCRRB, PlasmaCM   },\n  { PlasmaRCRB, PlasmaRM   },\n  { PlasmaRM,   PlasmaRCRB },\n  /* Three Conversions */\n  { PlasmaCM,   PlasmaRRRB },\n  { PlasmaRRRB, PlasmaCM   },\n  { PlasmaCCRB, PlasmaRM   },\n  { PlasmaRM,   PlasmaCCRB },\n  /* Three Conversions */\n  { PlasmaCM,   PlasmaRM   },\n  { PlasmaRM,   PlasmaCM   },\n};\n\nstatic int check_solution(int m, int n, int mba, int nba, int mbb, int nbb,\n                          PLASMA_Complex64_t *A, PLASMA_Complex64_t *B, \n                          int (*mapA)(int, int, int, int, int, int), int (*mapB)(int, int, int, int, int, int)) {\n    int i, j;\n\n    for( j=0; j<n; j++) {\n      for (i=0; i<m; i++) {\n            if (A[ mapA(m, n, mba, nba, i, j) ] != B[ mapB(m, n, mbb, nbb, i, j) ] ) {\n                return -1;\n            }\n        }\n    }\n    return 0;\n}\n\nint testing_zgecfi(int argc, char **argv){\n\n    PLASMA_Complex64_t *A, *B;\n    int m, n, mb, nb, mb2, nb2;\n    int i, ret, size;\n    int f1, f2;\n\n    /* Check for number of arguments*/\n    if (argc != 6){\n        USAGE(\"GECFI\", \"M N MB NB with \\n\",\n              \"   - M       : the number of rows of the matrix    \\n\"\n              \"   - N       : the number of columns of the matrix \\n\"\n              \"   - MB      : the number of rows of each block    \\n\"\n              \"   - NB      : the number of columns of each block \\n\"\n              \"   - MB2     : the number of rows of each block    \\n\"\n              \"   - NB2     : the number of columns of each block \\n\");\n        return -1;\n    }\n\n    m   = atoi(argv[0]);\n    n   = atoi(argv[1]);\n    mb  = atoi(argv[2]);\n    nb  = atoi(argv[3]);\n    mb2 = atoi(argv[4]);\n    nb2 = atoi(argv[5]);\n\n    /* Initialize Plasma */\n    size = m*n*sizeof(PLASMA_Complex64_t);\n    A = (PLASMA_Complex64_t *)malloc(size);\n    B = (PLASMA_Complex64_t *)malloc(size);\n    LAPACKE_zlarnv_work(1, ISEED, m*n, A);\n\n    for(i=0; i<36; i++) {\n        memcpy(B, A, size);\n\n        f1 = conversions[i][0]-PlasmaRM;\n        f2 = conversions[i][1]-PlasmaRM;\n        \n        printf(\" - TESTING ZGECFI (%4s => %4s) ...\", formatstr[f1], formatstr[f2] );\n\n        ret = PLASMA_zgecfi(m, n, B, conversions[i][0], mb, nb, conversions[i][1], mb2, nb2);\n\n        if (ret != PLASMA_SUCCESS) {\n            printf(\"Failed\\n\");\n            continue;\n        }\n         \n        if ( check_solution(m, n, mb, nb, mb2, nb2, A, B, \n                            (int (*)(int, int, int, int, int, int))formatmap[f1], \n                            (int (*)(int, int, int, int, int, int))formatmap[f2] ) == 0 )\n            printf(\"............ PASSED !\\n\");\n        else\n            printf(\"... FAILED !\\n\");\n\n#if 0\n            {\n              char cmd[256];\n    \n              PLASMA_Finalize();\n              sprintf(cmd, \"mv $PWD/dot_dag_file.dot $PWD/zgecfi_%s_%s.dot\", formatstr[f1], formatstr[f2]);\n              system(cmd);\n              \n              PLASMA_Init(0);\n              PLASMA_Set( PLASMA_SCHEDULING_MODE, PLASMA_DYNAMIC_SCHEDULING );\n            }\n#endif\n    }\n\n    free( A ); free( B );\n\n    return 0;\n}\n", "meta": {"hexsha": "d6bb98e9b1e808118072f52d18e7021eeb5e0189", "size": 4622, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/testing_zgecfi.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/testing_zgecfi.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/testing_zgecfi.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.7080745342, "max_line_length": 113, "alphanum_fraction": 0.5361315448, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.39659370398125693}}
{"text": "/* specfunc/bessel_K0.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * Copyright (C) 2016 Pavel Holoborodko, Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_poly.h>\n#include <gsl/gsl_sf_exp.h>\n#include <gsl/gsl_sf_bessel.h>\n\n#include \"error.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/*\n Minimax rational approximation for [0,1), peak relative error = 2.04*GSL_DBL_EPSILON.\n Source: http://www.advanpix.com/?p=3812\n*/\nstatic double k0_poly[8] = {\n   1.1593151565841244842077226e-01,\n   2.7898287891460317300886539e-01,\n   2.5248929932161220559969776e-02,\n   8.4603509072136578707676406e-04,\n   1.4914719243067801775856150e-05,\n   1.6271068931224552553548933e-07,\n   1.2082660336282566759313543e-09,\n   6.6117104672254184399933971e-12\n};\n\nstatic double i0_poly[7] = {\n   1.0000000000000000044974165e+00,\n   2.4999999999999822316775454e-01,\n   2.7777777777892149148858521e-02,\n   1.7361111083544590676709592e-03,\n   6.9444476047072424198677755e-05,\n   1.9288265756466775034067979e-06,\n   3.9908220583262192851839992e-08\n};\n\n/*\n Chebyshev expansion for [1,8], peak relative error = 1.28*GSL_DBL_EPSILON. \n Source: Pavel Holoborodko.\n*/\nstatic double ak0_data[24] = {\n  -3.28737867094650101e-02,\n  -4.49369057710236880e-02,\n  +2.98149992004308095e-03,\n  -3.03693649396187920e-04,\n  +3.91085569307646836e-05,\n  -5.86872422399215952e-06,\n  +9.82873709937322009e-07,\n  -1.78978645055651171e-07,\n  +3.48332306845240957e-08,\n  -7.15909210462546599e-09,\n  +1.54019930048919494e-09,\n  -3.44555485579194210e-10,\n  +7.97356101783753023e-11,\n  -1.90090968913069735e-11,\n  +4.65295609304114621e-12,\n  -1.16614287433470780e-12,\n  +2.98554375218596891e-13,\n  -7.79276979512292169e-14,\n  +2.07027467168948402e-14,\n  -5.58987860393825313e-15,\n  +1.53202965950646914e-15,\n  -4.25737536712188186e-16,\n  +1.19840238501357389e-16,\n  -3.41407346762502397e-17\n};\n\nstatic cheb_series ak0_cs = {\n  ak0_data,\n  23,\n  -1, 1,\n  10\n};\n\n/* \n Chebyshev expansion for [8,inf), peak relative error = 1.25*GSL_DBL_EPSILON.\n Source: SLATEC/dbsk0e.f\n*/\nstatic double ak02_data[14] = {\n  -.1201869826307592240E-1,\n  -.9174852691025695311E-2,\n  +.1444550931775005821E-3,\n  -.4013614175435709729E-5,\n  +.1567831810852310673E-6,\n  -.7770110438521737710E-8,\n  +.4611182576179717883E-9,\n  -.3158592997860565771E-10,\n  +.2435018039365041128E-11,\n  -.2074331387398347898E-12,\n  +.1925787280589917085E-13,\n  -.1927554805838956104E-14,\n  +.2062198029197818278E-15,\n  -.2341685117579242403E-16\n};\n\nstatic cheb_series ak02_cs = {\n  ak02_data,\n  13,\n  -1, 1,\n  8\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_bessel_K0_scaled_e(const double x, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x < 1.0) {\n    const double lx = log(x);\n    const double ex = exp(x);\n    const double x2 = x*x;\n    result->val  = ex * (gsl_poly_eval(k0_poly,8,x2)-lx*(1.0+0.25*x2*gsl_poly_eval(i0_poly,7,0.25*x2)));\n    result->err  = ex * (1.6+fabs(lx)*0.6) * GSL_DBL_EPSILON;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x <= 8.0) {\n    const double sx = sqrt(x);\n    gsl_sf_result c;\n    cheb_eval_e(&ak0_cs, (16.0/x-9.0)/7.0, &c);\n    result->val  = (1.203125 + c.val) / sx; /* 1.203125 = 77/64 */\n    result->err  = c.err / sx;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    const double sx = sqrt(x);\n    gsl_sf_result c;\n    cheb_eval_e(&ak02_cs, 16.0/x-1.0, &c);\n    result->val  = (1.25 + c.val) / sx;\n    result->err  = (c.err + GSL_DBL_EPSILON) / sx;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  } \n}\n\n\nint gsl_sf_bessel_K0_e(const double x, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x < 1.0) {\n    const double lx = log(x);\n    const double x2 = x*x;\n    result->val  = gsl_poly_eval(k0_poly,8,x2)-lx*(1.0+0.25*x2*gsl_poly_eval(i0_poly,7,0.25*x2));\n    result->err  = (1.6+fabs(lx)*0.6) * GSL_DBL_EPSILON;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    gsl_sf_result K0_scaled;\n    int stat_K0 = gsl_sf_bessel_K0_scaled_e(x, &K0_scaled);\n    int stat_e  = gsl_sf_exp_mult_err_e(-x, GSL_DBL_EPSILON*fabs(x),\n                                           K0_scaled.val, K0_scaled.err,\n                                           result);\n    return GSL_ERROR_SELECT_2(stat_e, stat_K0);\n  }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_K0_scaled(const double x)\n{\n  EVAL_RESULT(gsl_sf_bessel_K0_scaled_e(x, &result));\n}\n\ndouble gsl_sf_bessel_K0(const double x)\n{\n  EVAL_RESULT(gsl_sf_bessel_K0_e(x, &result));\n}\n\n", "meta": {"hexsha": "127fcb9efcaa30165a191e8f533340bb0d80dd64", "size": 5727, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/bessel_K0.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_K0.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_K0.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.5336538462, "max_line_length": 104, "alphanum_fraction": 0.6717303999, "num_tokens": 2127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3965530870226457}}
{"text": "#ifndef DDM__ALGORITHM__SUMMA_H_\n#define DDM__ALGORITHM__SUMMA_H_\n\n#include \"../../ddm/Exception.h\"\n#include \"../../ddm/Types.h\"\n#include \"../../ddm/Pattern.h\"\n#include \"../../ddm/Future.h\"\n#include \"../../ddm/algorithm/Copy.h\"\n#include \"../../ddm/util/Trace.h\"\n\n#include <utility>\n\n// Prefer MKL if available:\n#ifdef DDM_ENABLE_MKL\n#include <mkl.h>\n#include <mkl_types.h>\n#include <mkl_cblas.h>\n#include <mkl_blas.h>\n#include <mkl_lapack.h>\n// BLAS support:\n#elif defined(DDM_ENABLE_BLAS)\nextern \"C\"\n{\n  #include <cblas.h>\n}\n#endif\n\n#define DDM_ALGORITHM_SUMMA_ASYNC_INIT_PREFETCH\n\nnamespace ddm {\n\nnamespace internal {\n\n#if defined(DDM_ENABLE_MKL) || defined(DDM_ENABLE_BLAS)\n/**\n * Matrix multiplication for local multiplication of matrix blocks via MKL.\n */\ntemplate<typename  ValueType>\nvoid mmult_local(\n  /// Matrix to multiply, m rows by k columns.\n  const ValueType * A,\n  /// Matrix to multiply, k rows by n columns.\n  const ValueType * B,\n  /// Matrix to contain the multiplication result, m rows by n columns.\n  ValueType       * C,\n  long long         m,\n  long long         n,\n  long long         k,\n  MemArrange        storage);\n#else\n/**\n * Naive matrix multiplication for local multiplication of matrix blocks,\n * used only for tests and where MKL is not available.\n */\ntemplate<typename ValueType>\nvoid mmult_local(\n  /// Matrix to multiply, extents n x m\n  const ValueType * A,\n  /// Matrix to multiply, extents m x p\n  const ValueType * B,\n  /// Matrix to contain the multiplication result, extents n x p\n  ValueType       * C,\n  long long         m,\n  long long         n,\n  long long         p,\n  MemArrange        storage)\n{\n#ifndef DEBUG\n  DDM_THROW(\n    ddm::exception::RuntimeError,\n    \"Called fallback implementation of DGEMM (only enabled in Debug)\");\n#endif\n  ValueType c_sum = 0;\n  for (auto i = 0; i < n; ++i) {\n    // row i = 0...n\n    for (auto j = 0; j < p; ++j) {\n      // column j = 0...p\n      c_sum = C[i * p + j]; // = C[j][i]\n      for (auto k = 0; k < m; ++k) {\n        // k = 0...m\n        auto ik     = i * m + k;\n        auto kj     = k * m + j;\n        auto value  = A[ik] * B[kj];\n        c_sum      += value;\n      }\n      C[i * p + j] = c_sum; // C[j][i] = c_sum\n    }\n  }\n}\n#endif // defined(DDM_ENABLE_MKL) || defined(DDM_ENABLE_BLAS)\n\n} // namespace internal\n\n/// Constraints on pattern partitioning properties of matrix operands passed\n/// to \\c ddm::summa.\ntypedef ddm::pattern_partitioning_properties<\n            // Block extents are constant for every dimension.\n            ddm::pattern_partitioning_tag::rectangular,\n            // Identical number of elements in every block.\n            ddm::pattern_partitioning_tag::balanced,\n            // Matrices must be partitioned in more than one dimension.\n            ddm::pattern_partitioning_tag::ndimensional\n        > summa_pattern_partitioning_constraints;\n/// Constraints on pattern mapping properties of matrix operands passed to\n/// \\c ddm::summa.\ntypedef ddm::pattern_mapping_properties<\n            // Every unit mapped to more than one block, required for\n            // block prefetching to take effect.\n            ddm::pattern_mapping_tag::multiple,\n            // Number of blocks assigned to a unit may differ.\n            ddm::pattern_mapping_tag::unbalanced\n        > summa_pattern_mapping_constraints;\n/// Constraints on pattern layout properties of matrix operands passed to\n/// \\c ddm::summa.\ntypedef ddm::pattern_layout_properties<\n            // Elements are contiguous in local memory within single block.\n            ddm::pattern_layout_tag::blocked,\n            // Local element order corresponds to a logical linearization\n            // within single blocks.\n            // Required for cache-optimized block matrix multiplication.\n            ddm::pattern_layout_tag::linear\n        > summa_pattern_layout_constraints;\n\ntemplate<typename MatrixType>\nusing summa_pattern_constraints =\n    typename ddm::pattern_constraints<\n        ddm::summa_pattern_partitioning_constraints,\n        ddm::summa_pattern_mapping_constraints,\n        ddm::summa_pattern_layout_constraints,\n        typename MatrixType::pattern_type>;\n\n/**\n * Multiplies two matrices using the SUMMA algorithm.\n * Performs \\c (2 * (nunits-1) * nunits^2) async copy operations of\n * submatrices in \\c A and \\c B.\n *\n * Pseudocode:\n *\n *   C = zeros(n,n)\n *   for k = 1:b:n {            // k increments in steps of blocksize b\n *     u = k:(k+b-1)            // u is [k, k+1, ..., k+b-1]\n *     C = C + A(:,u) * B(u,:)  // Multiply n x b matrix from A with\n *                              // b x p matrix from B\n *   }\n */\ntemplate<\n  typename MatrixTypeA,\n  typename MatrixTypeB,\n  typename MatrixTypeC\n>\nvoid summa(\n  /// Matrix to multiply, extents n x m\n  MatrixTypeA & A,\n  /// Matrix to multiply, extents m x p\n  MatrixTypeB & B,\n  /// Matrix to contain the multiplication result, extents n x p,\n  /// initialized with zeros\n  MatrixTypeC & C)\n{\n  typedef typename MatrixTypeA::value_type   value_type;\n  typedef typename MatrixTypeA::index_type   index_t;\n  typedef typename MatrixTypeA::size_type    extent_t;\n//typedef typename MatrixTypeA::pattern_type pattern_a_type;\n//typedef typename MatrixTypeB::pattern_type pattern_b_type;\n//typedef typename MatrixTypeC::pattern_type pattern_c_type;\n  typedef std::array<index_t, 2>             coords_t;\n\n  const bool shifted_tiling = ddm::pattern_constraints<\n                                ddm::pattern_partitioning_properties<>,\n                                ddm::pattern_mapping_properties<\n                                  ddm::pattern_mapping_tag::diagonal\n                                >,\n                                ddm::pattern_layout_properties<>,\n                                typename MatrixTypeC::pattern_type\n                              >::satisfied::value;\n  const bool minimal_tiling = ddm::pattern_constraints<\n                                ddm::pattern_partitioning_properties<\n                                  ddm::pattern_partitioning_tag::minimal\n                                >,\n                                ddm::pattern_mapping_properties<>,\n                                ddm::pattern_layout_properties<>,\n                                typename MatrixTypeC::pattern_type\n                              >::satisfied::value;\n\n  static_assert(\n      std::is_floating_point<value_type>::value,\n      \"ddm::summa expects matrix element type double or float\");\n\n  DDM_LOG_DEBUG(\"ddm::summa()\");\n  // Verify that matrix patterns satisfy pattern constraints:\n  if (!ddm::check_pattern_constraints<\n         summa_pattern_partitioning_constraints,\n         summa_pattern_mapping_constraints,\n         summa_pattern_layout_constraints\n       >(A.pattern())) {\n    DDM_THROW(\n      ddm::exception::InvalidArgument,\n      \"ddm::summa(): \"\n      \"pattern of first matrix argument does not match constraints\");\n  }\n  if (!ddm::check_pattern_constraints<\n         summa_pattern_partitioning_constraints,\n         summa_pattern_mapping_constraints,\n         summa_pattern_layout_constraints\n       >(B.pattern())) {\n    DDM_THROW(\n      ddm::exception::InvalidArgument,\n      \"ddm::summa(): \"\n      \"pattern of second matrix argument does not match constraints\");\n  }\n  if (!ddm::check_pattern_constraints<\n         summa_pattern_partitioning_constraints,\n         summa_pattern_mapping_constraints,\n         summa_pattern_layout_constraints\n       >(C.pattern())) {\n    DDM_THROW(\n      ddm::exception::InvalidArgument,\n      \"ddm::summa(): \"\n      \"pattern of result matrix does not match constraints\");\n  }\n  DDM_LOG_TRACE(\"ddm::summa\", \"matrix pattern properties valid\");\n\n  if (shifted_tiling) {\n    DDM_LOG_TRACE(\"ddm::summa\",\n                   \"using communication scheme for diagonal-shift mapping\");\n  }\n  if (minimal_tiling) {\n    DDM_LOG_TRACE(\"ddm::summa\",\n                   \"using communication scheme for minimal partitioning\");\n  }\n  //    A         B         C\n  //  _____     _____     _____\n  // |     |   |     |   |     |\n  // n     | x m     | = n     |\n  // |_ m _|   |_ p _|   |_ p _|\n  //\n  ddm::Team & team = C.team();\n  auto unit_id      = team.myid();\n  // Check run-time invariants on pattern instances:\n  auto pattern_a    = A.pattern();\n  auto pattern_b    = B.pattern();\n  auto pattern_c    = C.pattern();\n  auto m = pattern_a.extent(0); // number of columns in A, rows in B\n#if DDM_ENABLE_TRACE_LOGGING\n  auto n = pattern_a.extent(1); // number of rows in A and C\n  auto p = pattern_b.extent(0); // number of columns in B and C\n#endif\n  const ddm::MemArrange memory_order = pattern_a.memory_order();\n\n  DDM_ASSERT_EQ(\n    pattern_a.extent(1),\n    pattern_b.extent(0),\n    \"ddm::summa(): \"\n    \"Extents of first operand in dimension 1 do not match extents of \"\n    \"second operand in dimension 0\");\n  DDM_ASSERT_EQ(\n    pattern_c.extent(0),\n    pattern_a.extent(0),\n    \"ddm::summa(): \"\n    \"Extents of result matrix in dimension 0 do not match extents of \"\n    \"first operand in dimension 0\");\n  DDM_ASSERT_EQ(\n    pattern_c.extent(1),\n    pattern_b.extent(1),\n    \"ddm::summa(): \"\n    \"Extents of result matrix in dimension 1 do not match extents of \"\n    \"second operand in dimension 1\");\n\n  DDM_LOG_TRACE(\"ddm::summa\", \"matrix pattern extents valid\");\n\n  // Patterns are balanced, all blocks have identical size:\n  auto block_size_m   = pattern_a.block(0).extent(0);\n  auto block_size_n   = pattern_b.block(0).extent(1);\n  auto block_size_p   = pattern_b.block(0).extent(0);\n  auto num_blocks_m   = m / block_size_m;\n#if DDM_ENABLE_TRACE_LOGGING\n  auto num_blocks_n   = n / block_size_n;\n  auto num_blocks_p   = p / block_size_p;\n#endif\n  // Size of temporary local blocks\n  auto block_a_size   = block_size_n * block_size_m;\n  auto block_b_size   = block_size_m * block_size_p;\n  // Number of units in rows and columns:\n  auto teamspec       = C.pattern().teamspec();\n  auto unit_ts_coords = teamspec.coords(unit_id);\n\n  DDM_LOG_TRACE(\"ddm::summa\", \"blocks:\",\n                 \"m:\", num_blocks_m, \"*\", block_size_m,\n                 \"n:\", num_blocks_n, \"*\", block_size_n,\n                 \"p:\", num_blocks_p, \"*\", block_size_p);\n  DDM_LOG_TRACE(\"ddm::summa\",\n                 \"number of units:\",\n                 \"cols:\", teamspec.extent(0),\n                 \"rows:\", teamspec.extent(1),\n                 \"unit team coords:\", unit_ts_coords);\n  DDM_LOG_TRACE(\"ddm::summa\", \"allocating local temporary blocks, sizes:\",\n                 \"A:\", block_a_size,\n                 \"B:\", block_b_size);\n\n#ifdef DDM_ENABLE_MKL\n  value_type * buf_block_a_get    = (value_type *)(mkl_malloc(\n                                      sizeof(value_type) * block_a_size, 64));\n  value_type * buf_block_b_get    = (value_type *)(mkl_malloc(\n                                      sizeof(value_type) * block_b_size, 64));\n  value_type * buf_block_a_comp   = (value_type *)(mkl_malloc(\n                                      sizeof(value_type) * block_a_size, 64));\n  value_type * buf_block_b_comp   = (value_type *)(mkl_malloc(\n                                      sizeof(value_type) * block_b_size, 64));\n#else\n  value_type * buf_block_a_get    = new value_type[block_a_size];\n  value_type * buf_block_b_get    = new value_type[block_b_size];\n  value_type * buf_block_a_comp   = new value_type[block_a_size];\n  value_type * buf_block_b_comp   = new value_type[block_b_size];\n#endif\n  // Copy of buffer pointers for swapping, delete[] on swapped pointers tends\n  // to crash:\n  value_type * local_block_a_get      = buf_block_a_get;\n  value_type * local_block_b_get      = buf_block_b_get;\n  value_type * local_block_a_comp     = buf_block_a_comp;\n  value_type * local_block_b_comp     = buf_block_b_comp;\n  value_type * local_block_a_get_bac  = nullptr;\n  value_type * local_block_b_get_bac  = nullptr;\n  value_type * local_block_a_comp_bac = nullptr;\n  value_type * local_block_b_comp_bac = nullptr;\n  // -------------------------------------------------------------------------\n  // Prefetch blocks from A and B for first local multiplication:\n  // -------------------------------------------------------------------------\n  // Block coordinates of submatrices of A and B to be prefetched:\n  // Local block index of local submatrix of C for multiplication result of\n  // blocks to be prefetched:\n  auto     l_block_c_get       = C.local.block(0);\n  auto     l_block_c_get_view  = l_block_c_get.begin().viewspec();\n  index_t  l_block_c_get_row   = l_block_c_get_view.offset(1) / block_size_n;\n  index_t  l_block_c_get_col   = l_block_c_get_view.offset(0) / block_size_p;\n  // Block coordinates of blocks in A and B to prefetch:\n  coords_t block_a_get_coords = coords_t {{ static_cast<index_t>(unit_ts_coords[0]),\n                   l_block_c_get_row }};\n  coords_t block_b_get_coords = coords_t {{ l_block_c_get_col,\n                   static_cast<index_t>(unit_ts_coords[0]) }};\n  // Local block index of local submatrix of C for multiplication result of\n  // currently prefetched blocks:\n  auto     l_block_c_comp      = l_block_c_get;\n  auto     l_block_c_comp_view = l_block_c_comp.begin().viewspec();\n  index_t  l_block_c_comp_row  = l_block_c_comp_view.offset(1) / block_size_n;\n  index_t  l_block_c_comp_col  = l_block_c_comp_view.offset(0) / block_size_p;\n  // Prefetch blocks from A and B for computation in next iteration:\n  ddm::Future<value_type *> get_a;\n  ddm::Future<value_type *> get_b;\n  auto block_a      = A.block(block_a_get_coords);\n  auto block_a_lptr = block_a.begin().local();\n  auto block_b      = B.block(block_b_get_coords);\n  auto block_b_lptr = block_b.begin().local();\n  DDM_LOG_TRACE(\"ddm::summa\", \"summa.prefetch.block.a\",\n                 \"block:\", block_a_get_coords,\n                 \"local:\", block_a_lptr != nullptr,\n                 \"unit:\",  block_a.begin().lpos().unit,\n                 \"view:\",  block_a.begin().viewspec());\n\n  ddm::util::Trace trace(\"SUMMA\");\n\n  trace.enter_state(\"prefetch\");\n  if (block_a_lptr == nullptr) {\n#ifdef DDM_ALGORITHM_SUMMA_ASYNC_INIT_PREFETCH\n    get_a = ddm::copy_async(block_a.begin(), block_a.end(),\n                             local_block_a_comp);\n#else\n    ddm::copy(block_a.begin(), block_a.end(),\n               local_block_a_comp);\n    get_a = ddm::Future<value_type *>(\n              [=]() { return local_block_a_comp + block_a.size(); });\n#endif\n  } else {\n    local_block_a_comp_bac = local_block_a_comp;\n    local_block_a_comp     = block_a_lptr;\n  }\n\n  DDM_LOG_TRACE(\"ddm::summa\", \"summa.prefetch.block.b\",\n                 \"block:\", block_b_get_coords,\n                 \"local:\", block_b_lptr != nullptr,\n                 \"unit:\",  block_b.begin().lpos().unit,\n                 \"view:\",  block_b.begin().viewspec());\n  if (block_b_lptr == nullptr) {\n#ifdef DDM_ALGORITHM_SUMMA_ASYNC_INIT_PREFETCH\n    get_b = ddm::copy_async(block_b.begin(), block_b.end(),\n                             local_block_b_comp);\n#else\n    ddm::copy(block_b.begin(), block_b.end(),\n               local_block_b_comp);\n    get_b = ddm::Future<value_type *>(\n              [=]() { return local_block_b_comp + block_b.size(); });\n#endif\n  } else {\n    local_block_b_comp_bac = local_block_b_comp;\n    local_block_b_comp     = block_b_lptr;\n  }\n#ifdef DDM_ALGORITHM_SUMMA_ASYNC_INIT_PREFETCH\n  if (block_a_lptr == nullptr) {\n    DDM_LOG_TRACE(\"ddm::summa\", \"summa.prefetch.block.a.wait\",\n                   \"waiting for prefetching of block A from unit\",\n                   block_a.begin().lpos().unit);\n    get_a.wait();\n  }\n  if (block_b_lptr == nullptr) {\n    DDM_LOG_TRACE(\"ddm::summa\", \"summa.prefetch.block.b.wait\",\n                   \"waiting for prefetching of block B from unit\",\n                   block_b.begin().lpos().unit);\n    get_b.wait();\n  }\n#endif\n  trace.exit_state(\"prefetch\");\n\n  DDM_LOG_TRACE(\"ddm::summa\", \"summa.block\",\n                 \"prefetching of blocks completed\");\n  // -------------------------------------------------------------------------\n  // Iterate local blocks in matrix C:\n  // -------------------------------------------------------------------------\n  extent_t num_local_blocks_c = pattern_c.local_blockspec().size();\n\n  DDM_LOG_TRACE(\"ddm::summa\", \"summa.block.C\",\n                 \"C.num.local.blocks:\",  num_local_blocks_c,\n                 \"C.num.column.blocks:\", num_blocks_m);\n\n  for (extent_t lb = 0; lb < num_local_blocks_c; ++lb) {\n    // Block coordinates for current block multiplication result:\n    l_block_c_comp      = C.local.block(lb);\n    l_block_c_comp_view = l_block_c_comp.begin().viewspec();\n    l_block_c_comp_row  = l_block_c_comp_view.offset(1) / block_size_n;\n    l_block_c_comp_col  = l_block_c_comp_view.offset(0) / block_size_p;\n    // Block coordinates for next block multiplication result:\n    l_block_c_get       = l_block_c_comp;\n    l_block_c_get_view  = l_block_c_comp_view;\n    l_block_c_get_row   = l_block_c_get_row;\n    l_block_c_get_col   = l_block_c_get_col;\n    DDM_LOG_TRACE(\"ddm::summa\", \"summa.block.comp\", \"C.local.block\",\n                   \"l_block_idx:\", lb,\n                   \"row:\",         l_block_c_comp_row,\n                   \"col:\",         l_block_c_comp_col,\n                   \"view:\",        l_block_c_comp_view);\n    // -----------------------------------------------------------------------\n    // Iterate blocks in columns of A / rows of B:\n    // -----------------------------------------------------------------------\n    for (extent_t block_k = 0; block_k < num_blocks_m; ++block_k) {\n      DDM_LOG_TRACE(\"ddm::summa\", \"summa.block.k\", block_k,\n                     \"active local block in C:\", lb);\n\n      // ---------------------------------------------------------------------\n      // Prefetch local copy of blocks from A and B for multiplication in\n      // next iteration.\n      // ---------------------------------------------------------------------\n      bool last = (lb == num_local_blocks_c - 1) &&\n                  (block_k == num_blocks_m - 1);\n      // Do not prefetch blocks in last iteration:\n      if (!last) {\n        index_t block_get_k = static_cast<index_t>(block_k + 1);\n        block_get_k = (block_get_k + unit_ts_coords[0]) % num_blocks_m;\n        // Block coordinate of local block in matrix C to prefetch:\n        if (block_k == num_blocks_m - 1) {\n          // Prefetch for next local block in matrix C:\n          block_get_k        = unit_ts_coords[0];\n          l_block_c_get      = C.local.block(lb + 1);\n          l_block_c_get_view = l_block_c_get.begin().viewspec();\n          l_block_c_get_row  = l_block_c_get_view.offset(1) / block_size_n;\n          l_block_c_get_col  = l_block_c_get_view.offset(0) / block_size_p;\n        }\n        // Block coordinates of blocks in A and B to prefetch:\n        block_a_get_coords = coords_t {{ block_get_k, l_block_c_get_row }};\n        block_b_get_coords = coords_t {{ l_block_c_get_col, block_get_k }};\n\n        block_a      = A.block(block_a_get_coords);\n        block_a_lptr = block_a.begin().local();\n        block_b      = B.block(block_b_get_coords);\n        block_b_lptr = block_b.begin().local();\n        DDM_LOG_TRACE(\"ddm::summa\", \"summa.prefetch.block.a\",\n                       \"block:\", block_a_get_coords,\n                       \"local:\", block_a_lptr != nullptr,\n                       \"unit:\",  block_a.begin().lpos().unit,\n                       \"view:\",  block_a.begin().viewspec());\n        if (block_a_lptr == nullptr) {\n          get_a = ddm::copy_async(block_a.begin(),\n                                   block_a.end(),\n                                   local_block_a_get);\n          local_block_a_get_bac = nullptr;\n        } else {\n          local_block_a_get_bac = local_block_a_get;\n          local_block_a_get     = block_a_lptr;\n        }\n        DDM_LOG_TRACE(\"ddm::summa\", \"summa.prefetch.block.b\",\n                       \"block:\", block_b_get_coords,\n                       \"local:\", block_b_lptr != nullptr,\n                       \"unit:\",  block_b.begin().lpos().unit,\n                       \"view:\",  block_b.begin().viewspec());\n        if (block_b_lptr == nullptr) {\n          get_b = ddm::copy_async(block_b.begin(),\n                                   block_b.end(),\n                                   local_block_b_get);\n          local_block_b_get_bac = nullptr;\n        } else {\n          local_block_b_get_bac = local_block_b_get;\n          local_block_b_get     = block_b_lptr;\n        }\n      } else {\n        DDM_LOG_TRACE(\"ddm::summa\", \" ->\",\n                       \"last block multiplication\",\n                       \"lb:\", lb, \"bk:\", block_k);\n      }\n      // ---------------------------------------------------------------------\n      // Computation of matrix product of local block matrices:\n      // ---------------------------------------------------------------------\n      DDM_LOG_TRACE(\"ddm::summa\", \"summa.block.comp.multiply\",\n                     \"multiplying local block matrices\",\n                     \"C.local.block.comp:\", lb,\n                     \"view:\", l_block_c_comp.begin().viewspec());\n\n      trace.enter_state(\"multiply\");\n      ddm::internal::mmult_local<value_type>(\n          local_block_a_comp,\n          local_block_b_comp,\n          l_block_c_comp.begin().local(),\n          block_size_m,\n          block_size_n,\n          block_size_p,\n          memory_order);\n      trace.exit_state(\"multiply\");\n\n      if (local_block_a_comp_bac != nullptr) {\n        local_block_a_comp     = local_block_a_comp_bac;\n        local_block_a_comp_bac = nullptr;\n      }\n      if (local_block_b_comp_bac != nullptr) {\n        local_block_b_comp     = local_block_b_comp_bac;\n        local_block_b_comp_bac = nullptr;\n      }\n      if (!last) {\n        // -------------------------------------------------------------------\n        // Wait for local copies:\n        // -------------------------------------------------------------------\n        trace.enter_state(\"prefetch\");\n        if (block_a_lptr == nullptr) {\n          DDM_LOG_TRACE(\"ddm::summa\", \"summa.prefetch.block.a.wait\",\n                         \"waiting for prefetching of block A from unit\",\n                         block_a.begin().lpos().unit);\n          get_a.wait();\n        }\n        if (block_b_lptr == nullptr) {\n          DDM_LOG_TRACE(\"ddm::summa\", \"summa.prefetch.block.b.wait\",\n                         \"waiting for prefetching of block B from unit\",\n                         block_b.begin().lpos().unit);\n          get_b.wait();\n        }\n        DDM_LOG_TRACE(\"ddm::summa\", \"summa.prefetch.completed\",\n                       \"local copies of next blocks received\");\n        trace.exit_state(\"prefetch\");\n\n        // -----------------------------------------------------------------\n        // Swap communication and computation buffers:\n        // -----------------------------------------------------------------\n        std::swap(local_block_a_get, local_block_a_comp);\n        std::swap(local_block_b_get, local_block_b_comp);\n        if (local_block_a_get_bac != nullptr) {\n          local_block_a_comp_bac = local_block_a_get_bac;\n          local_block_a_get_bac  = nullptr;\n        }\n        if (local_block_b_get_bac != nullptr) {\n          local_block_b_comp_bac = local_block_b_get_bac;\n          local_block_b_get_bac  = nullptr;\n        }\n      }\n    }\n  } // for lb\n\n  DDM_LOG_TRACE(\"ddm::summa\", \"locally completed\");\n#ifdef DDM_ENABLE_MKL\n  mkl_free(buf_block_a_get);\n  mkl_free(buf_block_b_get);\n  mkl_free(buf_block_a_comp);\n  mkl_free(buf_block_b_comp);\n#else\n  delete[] buf_block_a_get;\n  delete[] buf_block_b_get;\n  delete[] buf_block_a_comp;\n  delete[] buf_block_b_comp;\n#endif\n\n  DDM_LOG_TRACE(\"ddm::summa\", \"waiting for other units\");\n  trace.enter_state(\"barrier\");\n  C.barrier();\n  trace.exit_state(\"barrier\");\n\n  DDM_LOG_TRACE(\"ddm::summa >\", \"finished\");\n}\n\n#ifdef DOXYGEN\n/**\n * Function adapter to an implementation of matrix-matrix multiplication\n * (xDGEMM) depending on the matrix distribution patterns.\n *\n * Delegates  \\c ddm::mmult<MatrixType>\n * to         \\c ddm::summa<MatrixType>\n * if         \\c MatrixType::pattern_type\n * satisfies the pattern property constraints of the SUMMA implementation.\n */\ntemplate <\n  typename MatrixTypeA,\n  typename MatrixTypeB,\n  typename MatrixTypeC >\nvoid mmult(\n  /// Matrix to multiply, extents n x m\n  MatrixTypeA & A,\n  /// Matrix to multiply, extents m x p\n  MatrixTypeB & B,\n  /// Matrix to contain the multiplication result, extents n x p,\n  /// initialized with zeros\n  MatrixTypeC & C);\n\n#else // DOXYGEN\n\ntemplate <\n  typename MatrixTypeA,\n  typename MatrixTypeB,\n  typename MatrixTypeC >\nauto\nmmult(\n  /// Matrix to multiply, extents n x m\n  MatrixTypeA & A,\n  /// Matrix to multiply, extents m x p\n  MatrixTypeB & B,\n  /// Matrix to contain the multiplication result, extents n x p,\n  /// initialized with zeros\n  MatrixTypeC & C)\n  -> typename std::enable_if<\n                summa_pattern_constraints<MatrixTypeA>::satisfied::value &&\n                summa_pattern_constraints<MatrixTypeB>::satisfied::value &&\n                summa_pattern_constraints<MatrixTypeC>::satisfied::value,\n                void\n              >::type {\n  ddm::summa(A, B, C);\n}\n\n#endif // DOXYGEN\n\n} // namespace ddm\n\n#endif // DDM__ALGORITHM__SUMMA_H_\n", "meta": {"hexsha": "69b1abe4154d856a11afd9f7100e036201bea787", "size": 25195, "ext": "h", "lang": "C", "max_stars_repo_path": "yingying_delphi/Delphicpp_v8.4.2_Linux/src/dplt/ddm/algorithm/SUMMA.h", "max_stars_repo_name": "caixiuhong/Develop-MCCE", "max_stars_repo_head_hexsha": "31df6d22b8aac9a10c1e5c7809913b63ba83d23b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "yingying_delphi/Delphicpp_v8.4.2_Linux/src/dplt/ddm/algorithm/SUMMA.h", "max_issues_repo_name": "caixiuhong/Develop-MCCE", "max_issues_repo_head_hexsha": "31df6d22b8aac9a10c1e5c7809913b63ba83d23b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 36.0, "max_issues_repo_issues_event_min_datetime": "2019-06-03T20:30:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-17T19:17:26.000Z", "max_forks_repo_path": "yingying_delphi/Delphicpp_v8.4.2_Linux/src/dplt/ddm/algorithm/SUMMA.h", "max_forks_repo_name": "caixiuhong/Develop-MCCE", "max_forks_repo_head_hexsha": "31df6d22b8aac9a10c1e5c7809913b63ba83d23b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-06-03T16:56:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-09T03:32:31.000Z", "avg_line_length": 39.1226708075, "max_line_length": 84, "alphanum_fraction": 0.5940067474, "num_tokens": 5987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3965530815645324}}
{"text": "#include \"transform_animation.h\"\n#include \"entities/entities.h\"\n#include <gsl/gsl_poly.h>\n#include <gsl/gsl_math.h>\n#include \"utility/logging.h\"\n\n\n// from x^0 ... x^(len)\nstatic const double drop_in_coeffients[] = { 0.0, -2.0, -3.0, 1.0 };\n\nstatic void no_op_release(void *data) { }\nstatic void simple_release(void *data) { if (data != NULL) { free(data); } }\n\ntypedef struct {\n  double duration;\n  double scale;\n  uint8_t flags;\n} drop_in_data;\n\nstatic void drop_in_get_transform(\n    double t, ANIMATION_PLAYBACK_MODE mode, int reverse, void *pdata, double *m_out) {\n\n  drop_in_data *data = pdata;\n\n  double clamped_t;\n\n  if (mode == PLAY_ONCE) {\n    if (reverse) {\n      clamped_t = GSL_MAX(t, -data->duration);\n      clamped_t = data->duration + clamped_t;\n    } else {\n      clamped_t = GSL_MIN(t, data->duration);\n    }\n  } else if (mode == LOOP) {\n    double full_iterations = floor(t / data->duration);\n    clamped_t = t - (full_iterations * data->duration);\n  } else if (mode == OSCILLATE) {\n    int full_iterations = floor(t / data->duration);\n    if (GSL_IS_EVEN(full_iterations)) { // same as loop\n      clamped_t = t - (full_iterations * data->duration);\n    } else { // invert it\n      clamped_t = t - (full_iterations * data->duration);\n      clamped_t = data->duration - clamped_t;\n    }\n  }\n\n  uint8_t flags = data->flags;\n  double translation[4];\n  double value = data->scale * gsl_poly_eval(drop_in_coeffients, 4, clamped_t - 0.6);\n\n  gsl_matrix_view out_view = gsl_matrix_view_array(m_out, 4, 4);\n  gsl_matrix_set_identity(&out_view.matrix);\n  gsl_vector_view tview = gsl_matrix_column(&out_view.matrix, 3);\n  if (flags & XFORM_TRANSLATION_X) { gsl_vector_set(&tview.vector, 0, value); }\n  if (flags & XFORM_TRANSLATION_Y) { gsl_vector_set(&tview.vector, 1, value); }\n  if (flags & XFORM_TRANSLATION_Z) { gsl_vector_set(&tview.vector, 2, value); }\n}\n\nanimation_channel build_drop_in_channel(uint8_t apply_to, double scale) {\n  drop_in_data *data = calloc(1, sizeof(drop_in_data));\n  data->duration = 5;\n  data->scale = scale;\n  data->flags = apply_to;\n  animation_channel retval = {\n    .data=data,\n    .get_transform=drop_in_get_transform,\n    .release_resources=simple_release\n  };\n  return retval;\n}\n\nstatic const uint8_t CONSTANT_TRANSLATION = (1<<0);\nstatic const uint8_t CONSTANT_X_AXIS =      (1<<1);\nstatic const uint8_t CONSTANT_Y_AXIS =      (1<<2);\nstatic const uint8_t CONSTANT_Z_AXIS =      (1<<3);\n\ntypedef struct {\n  gsl_matrix *basis;\n  uint8_t constant_component_flags;\n  double *frame_data;\n  size_t entries_per_frame;\n  double duration; // seconds\n} optimized_keyframe_data;\n\nstatic void optimized_keyframe_get_transform(\n    double t, ANIMATION_PLAYBACK_MODE mode, int reverse, void *data, double *m_out) {\n  // look through the collection of keyframes and determine indices for\n  // the left and right frames bounding the provided `t`.\n  // doublesPerFrame, flat array for frame data store\n  // pack into (time, then optional translation, basis vectors, etc)\n}\n\nanimation_channel build_optimized_keyframe_channel(\n    keyframe *keyframes, size_t nframes) {\n  animation_channel retval = {\n    .data=NULL,\n    .get_transform=optimized_keyframe_get_transform,\n    .release_resources=simple_release\n  };\n  // TODO\n  return retval;\n}\n\nvoid animate_entity(double deltaT, entity_info* e) {\n  animation_state *state = &e->animation_state;\n\n  // update time trackers\n  double scaledT = deltaT * state->playback_speed;\n  state->current_cycle_time += scaledT;\n  state->time_in_transition += scaledT;\n  state->transition_cycle_time += scaledT;\n}\n\ntransform_animation_type const transform_animation = {\n  .build_optimized_keyframe_channel=build_optimized_keyframe_channel,\n  .build_drop_in_channel=build_drop_in_channel,\n  .animate_entity=animate_entity\n};\n", "meta": {"hexsha": "4ab7c6eb2a4044caa1c4a67119c3013c87f98b84", "size": 3785, "ext": "c", "lang": "C", "max_stars_repo_path": "src/animations/transform_animation.c", "max_stars_repo_name": "influenza/c8", "max_stars_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/animations/transform_animation.c", "max_issues_repo_name": "influenza/c8", "max_issues_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/animations/transform_animation.c", "max_forks_repo_name": "influenza/c8", "max_forks_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b", "max_forks_repo_licenses": ["BSD-3-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.8067226891, "max_line_length": 86, "alphanum_fraction": 0.7173051519, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5, "lm_q1q2_score": 0.39655297070182555}}
{"text": "#pragma once\n\n#include <stdio.h>\n#include <stdbool.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n\n#define SIM_SUCCESS 0\n#define SIM_FAILURE -1\n\n#define SIM_INFO(...) do {fprintf(stdout,##__VA_ARGS__);} while(0)\n#define SIM_ERROR(...) do {fprintf(stdout,##__VA_ARGS__);} while(0)\n\n#define SHUTDOWN_MESSAGE \"shutdown\\n\"\n\ntypedef struct {\n  gsl_vector *yd;\n  gsl_vector *y;\n} VehicleState;\n\ntypedef struct {\n  gsl_vector *(*feedback) (gsl_vector *yd, gsl_vector *y);\n} Controller;\n", "meta": {"hexsha": "0ada760a937c6a1f1877ac9e1d892099f9efa6a3", "size": 491, "ext": "h", "lang": "C", "max_stars_repo_path": "defines.h", "max_stars_repo_name": "umd-agrc/SimpleControlSim", "max_stars_repo_head_hexsha": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "defines.h", "max_issues_repo_name": "umd-agrc/SimpleControlSim", "max_issues_repo_head_hexsha": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "defines.h", "max_forks_repo_name": "umd-agrc/SimpleControlSim", "max_forks_repo_head_hexsha": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "max_forks_repo_licenses": ["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.4583333333, "max_line_length": 67, "alphanum_fraction": 0.716904277, "num_tokens": 132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3964229975143914}}
{"text": "#ifndef __UTILS_H_INCLUDED__\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <set>\n#include <tuple>\n#include <math.h>\n#include <Eigen/Dense>\n#include <gsl/gsl>\n#define __UTILS_H_INCLUDED__\n#include <cosan/base/CosanBO.h>\nnamespace Cosan{\n    /**\n     * @brief General string to number conversion function\n     * @details As we allow for user-determined numeric type `NumericType`, the detailed implementation or functions needed maybe slightly\n     * different among each other. For instance, when we are trying to read data from `csv` file. Different data type requires different\n     * string-to-numeric function. For `double`, one is required `std::stod` while 'std::stof' is the candidate function if\n     * `float` is chosen. To take care of this variant before running time, we conside the static-i. The feature\n     * allows us to discard branches of an if statement at compile-time based on a constant expression condition. In the following\n     * code as an example, we define a template function with input requiring `NumericType` as numeric and then the implementation\n     * is decided via `if constexpr` statement.\n     **/\n    template<Numeric NumericType>\n    NumericType StringToNum(const std::string& arg, std::size_t* pos = 0) {\n        static_assert(std::is_arithmetic<NumericType>::value, \"NumericType must be numeric\");\n        if constexpr (std::is_same_v<NumericType, unsigned long>) {\n            return std::stoul(arg,pos);\n        }\n        else if constexpr (std::is_same_v<NumericType, unsigned long long>){\n            return std::stoull(arg,pos);\n        }\n        else if constexpr (std::is_same_v<NumericType, int>){\n            return std::stoi(arg,pos);\n        }\n        else if constexpr (std::is_same_v<NumericType, long>){\n            return std::stol(arg,pos);\n        }\n        else if constexpr (std::is_same_v<NumericType, long long>){\n            return std::stoll(arg,pos);\n        }\n        else if constexpr (std::is_same_v<NumericType, float>){\n            return std::stof(arg,pos);\n        }\n        else if constexpr (std::is_same_v<NumericType, double>){\n            return std::stod(arg,pos);\n        }\n        else{\n            return std::stold(arg,pos);\n        }\n    }\n}\n\ntemplate<typename Matrix>\nMatrix load_csv1 (const std::string & path) {\n    std::ifstream indata;\n\n    indata.open(path);\n    std::string line;\n    std::vector<double> values;\n    gsl::index rows = 0;\n    while (std::getline(indata, line)) {\n        std::stringstream lineStream(line);\n        std::string cell;\n        while (getline(lineStream, cell, ',')) {\n            values.push_back(stod(cell));\n        }\n        ++rows;\n    }\n\n    return Eigen::Map<const Eigen::Matrix<typename Matrix::Scalar, Matrix::RowsAtCompileTime, Matrix::ColsAtCompileTime, Eigen::RowMajor> >(values.data(), rows, values.size()/rows);\n}\n\n\ntemplate<typename Matrix>\nvoid save_csv(const std::string & path, const Matrix & matrix){\n//    if (path.substr(path.size()-4)!=\".csv\"){\n//        path.append(\".csv\");\n//    }\n    std::ofstream file(path,std::ios::out);\n    if (file.is_open()){\n        Eigen::IOFormat csvFmt(Eigen::FullPrecision,0,\",\");\n        file<<matrix.format(csvFmt);\n        file.close();\n    }\n}\n\n#endif\n", "meta": {"hexsha": "9132621c9022adf2a3c6ffe1b7ae57e1968d5f63", "size": 3266, "ext": "h", "lang": "C", "max_stars_repo_path": "cosan/io/utils.h", "max_stars_repo_name": "zhxinyu/cosan", "max_stars_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cosan/io/utils.h", "max_issues_repo_name": "zhxinyu/cosan", "max_issues_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cosan/io/utils.h", "max_forks_repo_name": "zhxinyu/cosan", "max_forks_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T05:56:38.000Z", "avg_line_length": 36.6966292135, "max_line_length": 181, "alphanum_fraction": 0.6454378445, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.39641292363861946}}
{"text": "/* specfunc/bessel_I1.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_bessel.h>\n\n#include \"error.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n#define ROOT_EIGHT (2.0*M_SQRT2)\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/* based on SLATEC besi1(), besi1e() */\n\n/* chebyshev expansions\n\n series for bi1        on the interval  0.          to  9.00000d+00\n                                        with weighted error   2.40e-17\n                                         log weighted error  16.62\n                               significant figures required  16.23\n                                    decimal places required  17.14\n\n series for ai1        on the interval  1.25000d-01 to  3.33333d-01\n                                        with weighted error   6.98e-17\n                                         log weighted error  16.16\n                               significant figures required  14.53\n                                    decimal places required  16.82\n\n series for ai12       on the interval  0.          to  1.25000d-01\n                                       with weighted error   3.55e-17\n                                        log weighted error  16.45\n                              significant figures required  14.69\n                                   decimal places required  17.12\n*/\n\nstatic double bi1_data[11] = {\n  -0.001971713261099859,\n   0.407348876675464810,\n   0.034838994299959456,\n   0.001545394556300123,\n   0.000041888521098377,\n   0.000000764902676483,\n   0.000000010042493924,\n   0.000000000099322077,\n   0.000000000000766380,\n   0.000000000000004741,\n   0.000000000000000024\n};\nstatic cheb_series bi1_cs = {\n  bi1_data,\n  10,\n  -1, 1,\n  10\n};\n\nstatic double ai1_data[21] = {\n  -0.02846744181881479,\n  -0.01922953231443221,\n  -0.00061151858579437,\n  -0.00002069971253350,\n   0.00000858561914581,\n   0.00000104949824671,\n  -0.00000029183389184,\n  -0.00000001559378146,\n   0.00000001318012367,\n  -0.00000000144842341,\n  -0.00000000029085122,\n   0.00000000012663889,\n  -0.00000000001664947,\n  -0.00000000000166665,\n   0.00000000000124260,\n  -0.00000000000027315,\n   0.00000000000002023,\n   0.00000000000000730,\n  -0.00000000000000333,\n   0.00000000000000071,\n  -0.00000000000000006\n};\nstatic cheb_series ai1_cs = {\n  ai1_data,\n  20,\n  -1, 1,\n  11\n};\n\nstatic double ai12_data[22] = {\n   0.02857623501828014,\n  -0.00976109749136147,\n  -0.00011058893876263,\n  -0.00000388256480887,\n  -0.00000025122362377,\n  -0.00000002631468847,\n  -0.00000000383538039,\n  -0.00000000055897433,\n  -0.00000000001897495,\n   0.00000000003252602,\n   0.00000000001412580,\n   0.00000000000203564,\n  -0.00000000000071985,\n  -0.00000000000040836,\n  -0.00000000000002101,\n   0.00000000000004273,\n   0.00000000000001041,\n  -0.00000000000000382,\n  -0.00000000000000186,\n   0.00000000000000033,\n   0.00000000000000028,\n  -0.00000000000000003\n};\nstatic cheb_series ai12_cs = {\n  ai12_data,\n  21,\n  -1, 1,\n  9\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_bessel_I1_scaled_e(const double x, gsl_sf_result * result)\n{\n  const double xmin    = 2.0 * GSL_DBL_MIN;\n  const double x_small = ROOT_EIGHT * GSL_SQRT_DBL_EPSILON;\n  const double y = fabs(x);\n\n  /* CHECK_POINTER(result) */\n\n  if(y == 0.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(y < xmin) {\n    UNDERFLOW_ERROR(result);\n  }\n  else if(y < x_small) {\n    result->val = 0.5*x;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(y <= 3.0) {\n    const double ey = exp(-y);\n    gsl_sf_result c;\n    cheb_eval_e(&bi1_cs, y*y/4.5-1.0, &c);\n    result->val  = x * ey * (0.875 + c.val);\n    result->err  = ey * c.err + y * GSL_DBL_EPSILON * fabs(result->val);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(y <= 8.0) {\n    const double sy = sqrt(y);\n    gsl_sf_result c;\n    double b;\n    double s;\n    cheb_eval_e(&ai1_cs, (48.0/y-11.0)/5.0, &c);\n    b = (0.375 + c.val) / sy;\n    s = (x > 0.0 ? 1.0 : -1.0);\n    result->val  = s * b;\n    result->err  = c.err / sy;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    const double sy = sqrt(y);\n    gsl_sf_result c;\n    double b;\n    double s;\n    cheb_eval_e(&ai12_cs, 16.0/y-1.0, &c);\n    b = (0.375 + c.val) / sy;\n    s = (x > 0.0 ? 1.0 : -1.0);\n    result->val  = s * b;\n    result->err  = c.err / sy;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n}\n\n\nint gsl_sf_bessel_I1_e(const double x, gsl_sf_result * result)\n{\n  const double xmin    = 2.0 * GSL_DBL_MIN;\n  const double x_small = ROOT_EIGHT * GSL_SQRT_DBL_EPSILON;\n  const double y = fabs(x);\n\n  /* CHECK_POINTER(result) */\n\n  if(y == 0.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(y < xmin) {\n    UNDERFLOW_ERROR(result);\n  }\n  else if(y < x_small) {\n    result->val = 0.5*x;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(y <= 3.0) {\n    gsl_sf_result c;\n    cheb_eval_e(&bi1_cs, y*y/4.5-1.0, &c);\n    result->val  = x * (0.875 + c.val);\n    result->err  = y * c.err;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(y < GSL_LOG_DBL_MAX) {\n    const double ey = exp(y);\n    gsl_sf_result I1_scaled;\n    gsl_sf_bessel_I1_scaled_e(x, &I1_scaled);\n    result->val  = ey * I1_scaled.val;\n    result->err  = ey * I1_scaled.err + y * GSL_DBL_EPSILON * fabs(result->val);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    OVERFLOW_ERROR(result);\n  }\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_I1_scaled(const double x)\n{\n  EVAL_RESULT(gsl_sf_bessel_I1_scaled_e(x, &result));\n}\n\ndouble gsl_sf_bessel_I1(const double x)\n{\n  EVAL_RESULT(gsl_sf_bessel_I1_e(x, &result));\n}\n", "meta": {"hexsha": "18b2c0e3315b23fb8c6a1fa6fef827ec977d60ac", "size": 6812, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_I1.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_I1.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_I1.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 26.3011583012, "max_line_length": 81, "alphanum_fraction": 0.6077510276, "num_tokens": 2310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.39635603293497074}}
{"text": "/**\n *\n * @file core_zgetrf_incpiv.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.8.0\n * @author Hatem Ltaief\n * @author Mathieu Faverge\n * @author Jakub Kurzak\n * @date 2010-11-15\n * @precisions normal z -> c d s\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup dplasma_cores_complex64\n *\n *  CORE_zgetrf_incpiv computes an LU factorization of a general M-by-N tile A\n *  using partial pivoting with row interchanges.\n *\n *  The factorization has the form\n *\n *    A = P * L * U\n *\n *  where P is a permutation matrix, L is lower triangular with unit\n *  diagonal elements (lower trapezoidal if m > n), and U is upper\n *  triangular (upper trapezoidal if m < n).\n *\n *  This is the right-looking Level 2.5 BLAS version of the algorithm.\n *\n *******************************************************************************\n *\n * @param[in] M\n *          The number of rows of the tile A.  M >= 0.\n *\n * @param[in] N\n *         The number of columns of the tile A.  N >= 0.\n *\n * @param[in] IB\n *         The inner-blocking size.  IB >= 0.\n *\n * @param[in,out] A\n *         On entry, the M-by-N tile to be factored.\n *         On exit, the factors L and U from the factorization\n *         A = P*L*U; the unit diagonal elements of L are not stored.\n *\n * @param[in] LDA\n *         The leading dimension of the array A.  LDA >= max(1,M).\n *\n * @param[out] IPIV\n *         The pivot indices; for 1 <= i <= min(M,N), row i of the\n *         tile was interchanged with row IPIV(i).\n *\n * @param[out] INFO\n *         See returned value.\n *\n *******************************************************************************\n *\n * @return\n *         \\retval PLASMA_SUCCESS successful exit\n *         \\retval <0 if INFO = -k, the k-th argument had an illegal value\n *         \\retval >0 if INFO = k, U(k,k) is exactly zero. The factorization\n *              has been completed, but the factor U is exactly\n *              singular, and division by zero will occur if it is used\n *              to solve a system of equations.\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zgetrf_incpiv = PCORE_zgetrf_incpiv\n#define CORE_zgetrf_incpiv PCORE_zgetrf_incpiv\n#define CORE_zgessm PCORE_zgessm\nint  CORE_zgessm(int M, int N, int K, int IB,\n                 int *IPIV,\n                 const PLASMA_Complex64_t *L, int LDL,\n                 PLASMA_Complex64_t *A, int LDA);\n#endif\nint CORE_zgetrf_incpiv(int M, int N, int IB,\n                       PLASMA_Complex64_t *A, int LDA,\n                       int *IPIV, int *INFO)\n{\n    int i, j, k, sb;\n    int iinfo;\n\n    /* Check input arguments */\n    *INFO = 0;\n    if (M < 0) {\n        coreblas_error(1, \"Illegal value of M\");\n        return -1;\n    }\n    if (N < 0) {\n        coreblas_error(2, \"Illegal value of N\");\n        return -2;\n    }\n    if (IB < 0) {\n        coreblas_error(3, \"Illegal value of IB\");\n        return -3;\n    }\n    if ((LDA < max(1,M)) && (M > 0)) {\n        coreblas_error(5, \"Illegal value of LDA\");\n        return -5;\n    }\n\n    /* Quick return */\n    if ((M == 0) || (N == 0) || (IB == 0))\n        return PLASMA_SUCCESS;\n\n    k = min(M, N);\n\n    for(i =0 ; i < k; i += IB) {\n        sb = min(IB, k-i);\n        /*\n         * Factor diagonal and subdiagonal blocks and test for exact singularity.\n         */\n        iinfo = LAPACKE_zgetf2_work(LAPACK_COL_MAJOR, M-i, sb, &A[LDA*i+i], LDA, &IPIV[i]);\n        /*\n         * Adjust INFO and the pivot indices.\n         */\n        if((*INFO == 0) && (iinfo > 0))\n            *INFO = iinfo + i;\n\n        if (i+sb < N) {\n            CORE_zgessm(\n                M-i, N-(i+sb), sb, sb,\n                &IPIV[i],\n                &A[LDA*i+i], LDA,\n                &A[LDA*(i+sb)+i], LDA);\n        }\n\n        for(j = i; j < i+sb; j++) {\n            IPIV[j] = i + IPIV[j];\n        }\n    }\n    return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "3e7968825d5b9aae2e19a22ae2bcd0d33a13e7e2", "size": 4128, "ext": "c", "lang": "C", "max_stars_repo_path": "src/cores/core_zgetrf_incpiv.c", "max_stars_repo_name": "therault/dplasma", "max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z", "max_issues_repo_path": "src/cores/core_zgetrf_incpiv.c", "max_issues_repo_name": "therault/dplasma", "max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z", "max_forks_repo_path": "src/cores/core_zgetrf_incpiv.c", "max_forks_repo_name": "therault/dplasma", "max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z", "avg_line_length": 29.2765957447, "max_line_length": 91, "alphanum_fraction": 0.5053294574, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8175744806385543, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.3960167958344147}}
{"text": "#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\nvoid \nsetupInitialSeed( \n\t\t int id, \n\t\t gsl_rng *rgen );\n\nvoid createInitialSample( \n\t\t\t double *x, \n\t\t\t long N, \n\t\t\t gsl_rng *rgen, \n\t\t\t int state_dim );\n", "meta": {"hexsha": "0c3e81d76437b3e60d18aa72f66ba94a33b5f59e", "size": 210, "ext": "h", "lang": "C", "max_stars_repo_path": "include/randomisation.h", "max_stars_repo_name": "heinekmp/AIRPF", "max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z", "max_issues_repo_path": "include/randomisation.h", "max_issues_repo_name": "heinekmp/AIRPF", "max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/randomisation.h", "max_forks_repo_name": "heinekmp/AIRPF", "max_forks_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.0, "max_line_length": 28, "alphanum_fraction": 0.6380952381, "num_tokens": 68, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.3958043617490487}}
{"text": "#include <stdio.h>\n\n//#ifndef DARWIN \n//#include <malloc.h>\n//#endif\n\n#include <stddef.h>\n#include <Python.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_blas.h>\n#include <string.h>\n#include <math.h>\n\n/*\nvoid inplace(double* npyArray3D, int npyLength1D, int npylength2D,\n              int npylength2D, double* invec, int n)\n{\n  int i;\n  for (i=0; i<n; i++) {\n    invec[i] = npyArray3D[i];\n  }\n}\n*/\n\nint print_matrix(FILE *f, const gsl_matrix *m)\n{\n  int status, n = 0;\n\n  for (size_t i = 0; i < m->size1; i++) {\n    for (size_t j = 0; j < m->size2; j++) {\n      if ((status = fprintf(f,\"%g \", gsl_matrix_get(m, i, j))) < 0)\n        return -1;\n      n += status;\n    }\n\n    if ((status = fprintf(f, \"\\n\")) < 0)\n      return -1;\n    n += status;\n  }\n  return n;\n}\n\nint print_vector(FILE *f, const gsl_vector *m)\n{\n  int status, n = 0;\n\n  for (size_t i = 0; i < m->size; i++) {\n    if ((status = fprintf(f, \"%g \", gsl_vector_get(m, i))) < 0)\n      return -1;\n    n += status;\n  }\n  return n;\n}\n\n\nvoid print_mat(double* mat, int dim1, int dim2)\n{\n  int i, j;\n  printf(\"\\n\");\n  for (i=0; i<dim1; i++) {\n    for (j=0; j<dim2; j++) {\n      printf(\"%6.2f,\", mat[i*dim1 + j]);\n    }\n    printf(\"\\n\");\n  }\n}\nvoid print_vec(double* vec, int dim1)\n{\n  int i;\n  printf(\"\\n\");\n  for (i=0; i<dim1; i++) {\n    printf(\"%6.2f,\", vec[i]);\n  }\n  printf(\"\\n\");\n}\n\nint sum(int* npyArray3D, int npyLength1D, int npyLength2D, int npyLength3D)\n{\n  int i, j, k;\n  int sum = 0;\n\n  for (i=0; i<npyLength1D; i++)\n    for (j=0; j<npyLength2D; j++)\n      for (k=0; k<npyLength3D; k++)\n        sum += npyArray3D[i*npyLength3D*npyLength2D + k*npyLength2D + j];\n\n  return sum;\n}\n\ndouble get_det(PyObject *A)\n{\n  int MAT_DIM = 6;\n  int i, signum;\n  double det;\n  int nInts = PyList_Size(A);\n\n  gsl_matrix *m = gsl_matrix_alloc(MAT_DIM, MAT_DIM);\n  gsl_permutation *p;\n\n  p = gsl_permutation_alloc(m->size1);\n  \n  for (i=0; i<nInts; i++)\n  {\n    PyObject *oo = PyList_GetItem(A, i);\n    //printf(\"%6.2f\\n\",PyFloat_AS_DOUBLE(oo));\n    gsl_matrix_set (m, i%MAT_DIM, i/MAT_DIM, PyFloat_AS_DOUBLE(oo));\n  }\n  \n  gsl_linalg_LU_decomp(m, p, &signum);\n  det = gsl_linalg_LU_det(m, signum);\n  //printf(\"%6.2f\\n\",det);\n  return det;\n}\n\ndouble get_overlap(double* gr_icov, int gr_dim1, int gr_dim2,\n                   double* gr_mn, int gr_mn_dim, double gr_icov_det,\n                   double* st_icov, int st_dim1, int st_dim2,\n                   double* st_mn, int st_mn_dim, double st_icov_det)\n{\n  int MAT_DIM = gr_dim1;\n  int i, j, signum;\n  double ApB_det, d_temp, result;\n  gsl_permutation *p;\n\n  gsl_matrix *A        = gsl_matrix_alloc(MAT_DIM, MAT_DIM);\n  gsl_matrix *B        = gsl_matrix_alloc(MAT_DIM, MAT_DIM);\n  gsl_matrix *ApB      = gsl_matrix_alloc(MAT_DIM, MAT_DIM);\n  gsl_vector *a        = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *b        = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *AapBb    = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *c        = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *v_temp   = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *v_temp2  = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *amc      = gsl_vector_alloc(MAT_DIM); //will hold a - c\n  gsl_vector *bmc      = gsl_vector_alloc(MAT_DIM); //will hold b - c\n\n  p = gsl_permutation_alloc(A->size1);\n\n//for (l=0; l<1; l++){ //DELETE\n\n  //Inserting values into matricies and vectors\n  for (i=0; i<MAT_DIM; i++)\n  {\n    for (j=0; j<MAT_DIM; j++)\n    {\n      gsl_matrix_set (A, i, j, gr_icov[i*MAT_DIM + j]);\n      gsl_matrix_set (B, i, j, st_icov[i*MAT_DIM + j]);\n    }\n  }\n\n  for (i=0; i<MAT_DIM; i++)\n  {\n    gsl_vector_set (a, i, gr_mn[i]);\n    gsl_vector_set (b, i, st_mn[i]);\n  }\n\n  // Adding A and B together and storing in ApB\n  gsl_matrix_set_zero(ApB);\n  gsl_matrix_add(ApB, A);\n  gsl_matrix_add(ApB, B);\n\n  // Storing the result A*a + B*b in AapBb\n  gsl_vector_set_zero(AapBb);\n  gsl_blas_dsymv(CblasUpper, 1.0, A, a, 1.0, AapBb);\n  gsl_blas_dsymv(CblasUpper, 1.0, B, b, 1.0, AapBb);\n\n  // Getting determinant of ApB\n  gsl_linalg_LU_decomp(ApB, p, &signum);\n  //ApB_det = gsl_linalg_LU_det(ApB, signum);\n  ApB_det = fabs(gsl_linalg_LU_det(ApB, signum)); //temp doctoring determinant\n\n  // Solve for c\n  gsl_linalg_LU_solve(ApB, p, AapBb, c);\n\n  // Compute the overlap formula\n  gsl_vector_set_zero(v_temp);\n  gsl_blas_dcopy(a, v_temp);       //v_temp holds a\n  gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds a - c\n  gsl_blas_dcopy(v_temp, amc);     //amc holds a - c\n\n  // CAN'T HAVE v_temp and v_temp2 be the same vector.\n  // Results in 0's being stored in v_temp2.\n  gsl_blas_dsymv(CblasUpper, 1.0, A, v_temp, 0.0, v_temp2);\n  //v_temp2 holds A (a-c)\n\n  result = 0.0;\n  gsl_blas_ddot(v_temp2, amc, &d_temp); //d_temp holds (a-c)^T A (a-c)\n\n  result += d_temp;\n  \n  gsl_vector_set_zero(v_temp);\n  gsl_blas_dcopy(b, v_temp);       //v_temp holds b\n  gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds b - c\n  gsl_blas_dcopy(v_temp, bmc);     //bmc holds b - c\n\n  // CAN'T HAVE v_temp and v_temp2 be the same vector.\n  // Results in 0's being stored in v_temp2.\n  gsl_blas_dsymv(CblasUpper, 1.0, B, v_temp, 0.0, v_temp2);\n  //v_temp2 holds A (b-c)\n\n  gsl_blas_ddot(v_temp2, bmc, &d_temp); //d_temp holds (b-c)^T B (b-c)\n  result += d_temp;\n \n  result = -0.5 * result;\n  result = exp(result);\n\n  result *= sqrt((gr_icov_det * st_icov_det/ApB_det)\n                / pow(2*M_PI, MAT_DIM));\n//} //DELETE THIS \n\n  // Freeing memory\n  gsl_matrix_free(A);\n  gsl_matrix_free(B);\n  gsl_matrix_free(ApB);\n  gsl_vector_free(a);\n  gsl_vector_free(b);\n  gsl_vector_free(AapBb);\n  gsl_vector_free(c);\n  gsl_vector_free(v_temp);\n  gsl_vector_free(v_temp2);\n  gsl_vector_free(amc);\n  gsl_vector_free(bmc);\n\n  gsl_permutation_free(p);\n\n  return result;\n}\n\ndouble get_overlap2(PyObject *gr_icov, PyObject *gr_mn, double gr_icov_det,\n                    PyObject *st_icov, PyObject *st_mn, double st_icov_det)\n{\n  int MAT_DIM = 6;\n  int i, j, signum;\n  double ApB_det, d_temp, result;\n  PyObject *o1, *o2;\n  gsl_permutation *p;\n\n  gsl_matrix *A        = gsl_matrix_alloc(MAT_DIM, MAT_DIM);\n  gsl_matrix *B        = gsl_matrix_alloc(MAT_DIM, MAT_DIM);\n  gsl_matrix *ApB      = gsl_matrix_alloc(MAT_DIM, MAT_DIM);\n  gsl_vector *a        = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *b        = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *AapBb    = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *c        = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *v_temp   = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *v_temp2  = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *amc      = gsl_vector_alloc(MAT_DIM); //will hold a - c\n  gsl_vector *bmc      = gsl_vector_alloc(MAT_DIM); //will hold b - c\n\n  p = gsl_permutation_alloc(A->size1);\n\n  //Inserting values into matricies and vectors\n  for (i=0; i<MAT_DIM; i++)\n  {\n    for (j=0; j<MAT_DIM; j++)\n    {\n      o1 = PyList_GetItem(gr_icov, i*MAT_DIM + j);\n      gsl_matrix_set (A, i, j, PyFloat_AS_DOUBLE(o1));\n      o2 = PyList_GetItem(st_icov, i*MAT_DIM + j);\n      gsl_matrix_set (B, i, j, PyFloat_AS_DOUBLE(o2));\n    }\n  }\n\n  for (i=0; i<MAT_DIM; i++)\n  {\n    o1 = PyList_GetItem(gr_mn, i);\n    gsl_vector_set (a, i, PyFloat_AS_DOUBLE(o1));\n    o2 = PyList_GetItem(st_mn, i);\n    gsl_vector_set (b, i, PyFloat_AS_DOUBLE(o2));\n  }\n\n  // Adding A and B together and storing in ApB\n  gsl_matrix_set_zero(ApB);\n  gsl_matrix_add(ApB, A);\n  gsl_matrix_add(ApB, B);\n\n  // Storing the result A*a + B*b in AapBb\n  gsl_vector_set_zero(AapBb);\n  gsl_blas_dgemv(CblasNoTrans,\n                 1.0, A, a,\n                 1.0, AapBb);\n  gsl_blas_dgemv(CblasNoTrans,\n                 1.0, B, b,\n                 1.0, AapBb);\n\n  // Getting determinant of ApB\n  gsl_linalg_LU_decomp(ApB, p, &signum);\n  //ApB_det = gsl_linalg_LU_det(ApB, signum);\n  ApB_det = fabs(gsl_linalg_LU_det(ApB, signum)); //temp doctoring determinant\n\n  // Solve for c\n  gsl_linalg_LU_solve(ApB, p, AapBb, c);\n\n  // Compute the overlap formula\n  gsl_vector_set_zero(v_temp);\n  gsl_blas_dcopy(a, v_temp);       //v_temp holds a\n  gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds a - c\n  gsl_blas_dcopy(v_temp, amc);     //amc holds a - c\n\n  // CAN'T HAVE v_temp and v_temp2 be the same vector.\n  // Results in 0's being stored in v_temp2.\n  gsl_blas_dgemv(CblasNoTrans, 1.0, A, v_temp, 0.0, v_temp2);\n  //v_temp2 holds A (a-c)\n\n  result = 0.0;\n  gsl_blas_ddot(v_temp2, amc, &d_temp); //d_temp holds (a-c)^T A (a-c)\n\n  result += d_temp;\n  \n  gsl_vector_set_zero(v_temp);\n  gsl_blas_dcopy(b, v_temp);       //v_temp holds b\n  gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds b - c\n  gsl_blas_dcopy(v_temp, bmc);     //bmc holds b - c\n\n  // CAN'T HAVE v_temp and v_temp2 be the same vector.\n  // Results in 0's being stored in v_temp2.\n  gsl_blas_dgemv(CblasNoTrans, 1.0, B, v_temp, 0.0, v_temp2);\n  //v_temp2 holds A (b-c)\n\n  gsl_blas_ddot(v_temp2, bmc, &d_temp); //d_temp holds (b-c)^T B (b-c)\n  result += d_temp;\n \n  result = -0.5 * result;\n  result = exp(result);\n\n  result *= sqrt((gr_icov_det * st_icov_det/ApB_det)\n                / pow(2*M_PI, MAT_DIM));\n\n\n  // Freeing memory\n  gsl_matrix_free(A);\n  gsl_matrix_free(B);\n  gsl_matrix_free(ApB);\n  gsl_vector_free(a);\n  gsl_vector_free(b);\n  gsl_vector_free(AapBb);\n  gsl_vector_free(c);\n  gsl_vector_free(v_temp);\n  gsl_vector_free(v_temp2);\n  gsl_vector_free(amc);\n  gsl_vector_free(bmc);\n\n  gsl_permutation_free(p);\n\n  return result;\n}\n\n/* Main function which performs fastest so far:\n * --parameters--\n *  group_icov     (6*6 npyArray) the group's inverse covariance matrix\n *  group_mn       (1*6 npyArray) which is the group's mean kinematic info\n *  group_icov_det (flt)          the determinent of the group_icov\n *  Bs             (nstars*6*6)   an array of each star's icov matrix\n *  bs:            (nstars*6)     an array of each star's mean kinematic info\n *  B_dets:        (nstars)       an array of the determinent of each icov\n *  nstars:        (int)          number of stars, used to determine the size\n *                          of npyArray which will return calculated overlaps)\n *\n * returns: (nstars) array of calculated overlaps of every star with 1 group\n *\n * todo: instead of calling internal function actually use cblas functions\n *          this will save time on the reallocation and deallocation\n */\nvoid get_overlaps(double* gr_icov, int gr_dim1, int gr_dim2,\n                  double* gr_mn, int gr_mn_dim,\n                  double gr_icov_det,\n                  double* st_icovs, int st_dim1, int st_dim2, int st_dim3,\n                  double* st_mns, int st_mn_dim1, int st_mn_dim2,\n                  double* st_icov_dets, int st_icov_dets_dim,\n                  double* rangevec, int n)\n{\n  // ALLOCATE MEMORY\n  int star_count = 0;\n  int MAT_DIM = gr_dim1; //Typically set to 6\n  int i, j, signum;\n  double ApB_det, d_temp, result;\n  gsl_permutation *p;\n\n  gsl_matrix *A        = gsl_matrix_alloc(MAT_DIM, MAT_DIM);\n  gsl_matrix *B        = gsl_matrix_alloc(MAT_DIM, MAT_DIM);\n  gsl_matrix *ApB      = gsl_matrix_alloc(MAT_DIM, MAT_DIM);\n  gsl_vector *a        = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *b        = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *AapBb    = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *c        = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *v_temp   = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *v_temp2  = gsl_vector_alloc(MAT_DIM);\n  gsl_vector *amc      = gsl_vector_alloc(MAT_DIM); //will hold a - c\n  gsl_vector *bmc      = gsl_vector_alloc(MAT_DIM); //will hold b - c\n\n  p = gsl_permutation_alloc(A->size1);\n\n  // INITIALISE GROUP MATRICES\n  for (i=0; i<MAT_DIM; i++)\n    for (j=0; j<MAT_DIM; j++)\n      gsl_matrix_set (A, i, j, gr_icov[i*MAT_DIM + j]);\n\n  for (i=0; i<MAT_DIM; i++)\n    gsl_vector_set (a, i, gr_mn[i]);\n\n\n  for (star_count=0; star_count<n; star_count++) {\n    // INITIALISE STAR MATRICES\n    for (i=0; i<MAT_DIM; i++)\n      for (j=0; j<MAT_DIM; j++)\n        gsl_matrix_set(B,i,j, st_icovs[star_count*MAT_DIM*MAT_DIM+i*MAT_DIM+j]);\n\n    for (i=0; i<MAT_DIM; i++) \n      gsl_vector_set (b, i, st_mns[star_count*MAT_DIM + i]);\n\n\n    // FIND OVERLAP\n    // Adding A and B together and storing in ApB\n    gsl_matrix_set_zero(ApB);\n    gsl_matrix_add(ApB, A);\n    gsl_matrix_add(ApB, B);\n  \n    // Storing the result A*a + B*b in AapBb\n    gsl_vector_set_zero(AapBb);\n    gsl_blas_dsymv(CblasUpper, 1.0, A, a, 1.0, AapBb);\n    gsl_blas_dsymv(CblasUpper, 1.0, B, b, 1.0, AapBb);\n  \n    // Getting determinant of ApB\n    gsl_linalg_LU_decomp(ApB, p, &signum);\n    //ApB_det = gsl_linalg_LU_det(ApB, signum);\n    ApB_det = fabs(gsl_linalg_LU_det(ApB, signum)); //temp doctoring determinant\n  \n    // Solve for c\n    gsl_linalg_LU_solve(ApB, p, AapBb, c);\n  \n    // Compute the overlap formula\n    gsl_vector_set_zero(v_temp);\n    gsl_blas_dcopy(a, v_temp);       //v_temp holds a\n    gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds a - c\n    gsl_blas_dcopy(v_temp, amc);     //amc holds a - c\n  \n    // CAN'T HAVE v_temp and v_temp2 be the same vector.\n    // Results in 0's being stored in v_temp2.\n    gsl_blas_dsymv(CblasUpper, 1.0, A, v_temp, 0.0, v_temp2);\n    //v_temp2 holds A (a-c)\n  \n    result = 0.0;\n    gsl_blas_ddot(v_temp2, amc, &d_temp); //d_temp holds (a-c)^T A (a-c)\n  \n    result += d_temp;\n    \n    gsl_vector_set_zero(v_temp);\n    gsl_blas_dcopy(b, v_temp);       //v_temp holds b\n    gsl_blas_daxpy(-1.0, c, v_temp); //v_temp holds b - c\n    gsl_blas_dcopy(v_temp, bmc);     //bmc holds b - c\n  \n    // CAN'T HAVE v_temp and v_temp2 be the same vector.\n    // Results in 0's being stored in v_temp2.\n    gsl_blas_dsymv(CblasUpper, 1.0, B, v_temp, 0.0, v_temp2);\n    //v_temp2 holds A (b-c)\n  \n    gsl_blas_ddot(v_temp2, bmc, &d_temp); //d_temp holds (b-c)^T B (b-c)\n    result += d_temp;\n   \n    result = -0.5 * result;\n    result = exp(result);\n  \n    result *= sqrt((gr_icov_det * st_icov_dets[star_count]/ApB_det)\n                  / pow(2*M_PI, MAT_DIM));\n\n    // STORE IN 'rangevec'\n    rangevec[star_count] = result;\n  }\n\n  // DEALLOCATE THE MEMORY\n  gsl_matrix_free(A);\n  gsl_matrix_free(B);\n  gsl_matrix_free(ApB);\n  gsl_vector_free(a);\n  gsl_vector_free(b);\n  gsl_vector_free(AapBb);\n  gsl_vector_free(c);\n  gsl_vector_free(v_temp);\n  gsl_vector_free(v_temp2);\n  gsl_vector_free(amc);\n  gsl_vector_free(bmc);\n\n  gsl_permutation_free(p);\n}\n\n/* New main function, speed not yet tested\n * --parameters--\n *  group_icov     (6*6 npyArray) the group's inverse covariance matrix\n *  group_mn       (1*6 npyArray) which is the group's mean kinematic info\n *  group_icov_det (flt)          the determinent of the group_icov\n *  Bs             (nstars*6*6)   an array of each star's icov matrix\n *  bs:            (nstars*6)     an array of each star's mean kinematic info\n *  B_dets:        (nstars)       an array of the determinent of each icov\n *  nstars:        (int)          number of stars, used to determine the size\n *                          of npyArray which will return calculated overlaps)\n *\n * returns: (nstars) array of calculated overlaps of every star with 1 group\n *\n * todo: instead of calling internal function actually use cblas functions\n *          this will save time on the reallocation and deallocation\n * \n *      look up how to find inverse\n *      look up how to access math.pi\n */\nvoid new_get_lnoverlaps(\n  double* gr_cov, int gr_dim1, int gr_dim2,\n  double* gr_mn, int gr_mn_dim,\n  double* st_covs, int st_dim1, int st_dim2, int st_dim3,\n  double* st_mns, int st_mn_dim1, int st_mn_dim2,\n  double* rangevec, int n\n  )\n{\n  //printf(\"Inside new_get_lnoverlaps function\\n\");\n  // ALLOCATE MEMORY\n  int star_count = 0;\n  int MAT_DIM = gr_dim1; //Typically set to 6\n  int i, j, signum;\n  double d_temp, result, ln_det_BpA;\n  FILE* fout = stdout;\n  gsl_permutation *p1;\n\n  gsl_matrix *BpA      = gsl_matrix_alloc(MAT_DIM, MAT_DIM); //(B+A)\n  //gsl_matrix *BpAi     = gsl_matrix_alloc(MAT_DIM, MAT_DIM); //(B+A)^-1\n  gsl_vector *bma      = gsl_vector_alloc(MAT_DIM); //will hold b - a\n  gsl_vector *v_temp   = gsl_vector_alloc(MAT_DIM);\n\n  p1 = gsl_permutation_alloc(BpA->size1);\n\n  //printf(\"Memory allocated\\n\");\n  for (star_count=0; star_count<n; star_count++) {\n    // INITIALISE STAR MATRICES\n    for (i=0; i<MAT_DIM; i++)\n      for (j=0; j<MAT_DIM; j++)\n        //perform B+A as part of the initialisation\n        gsl_matrix_set(\n          BpA,i,j,\n          st_covs[star_count*MAT_DIM*MAT_DIM+i*MAT_DIM+j] + \n          gr_cov[i*MAT_DIM+j]\n        );\n//    printf(\"Printing BpA\\n\");\n//    print_matrix(fout, BpA);\n\n    for (i=0; i<MAT_DIM; i++) {\n      gsl_vector_set(\n        bma, i,\n        st_mns[star_count*MAT_DIM + i] - \n        gr_mn[i]\n      );\n    }\n    //printf(\"Printing bma\\n\");\n    //print_vec(bma->data, 6);\n    //printf(\"Matrices initialised\\n\\n\");\n\n    result = 6*log(2*M_PI);\n    // To Do! put 6ln(2 pi) in here ^^\n\n    // Get inverse of BpA, this line is wrong, fix when have internet\n    gsl_linalg_LU_decomp(BpA, p1, &signum);\n    ln_det_BpA = log(fabs(gsl_linalg_LU_det(BpA, signum)));\n    result += ln_det_BpA;\n\n    //printf(\"ln(det(BpA)) added\\n\");\n    //printf(\"%6.2f\\n\\n\",ln_det_BpA);\n    //printf(\"result so far:\\n%6.2f\\n\",result);\n    //// Solve for c\n    //gsl_linalg_LU_solve(ApB, p, AapBb, c);\n    \n    // Don't use invert, use solve like example above ^^\n    //gsl_linalg_LU_invert(BpA, p1, BpAi);\n    //\n    gsl_vector_set_zero(v_temp);\n    gsl_linalg_LU_solve(BpA, p1, bma, v_temp); //v_temp holds (B+A)^-1 (b-a)\n    gsl_blas_ddot(v_temp, bma, &d_temp); //d_temp holds (b-a)^T (B+A)-1 (b-a)\n    //printf(\"Printing bma_BpAi_bma\\n\");\n    //printf(\"%6.2f\\n\\n\", d_temp);\n\n    result += d_temp;\n    //printf(\"result after bma_BpAi_bma:\\n%6.2f\\n\",result);\n\n    result *= -0.5;\n    //printf(\"Everything calculated\\n\");\n    //printf(\"Final result:\\n%6.2f\\n\", result);\n    //\n    // STORE IN 'rangevec'\n    rangevec[star_count] = result;\n  }\n\n  // DEALLOCATE THE MEMORY\n  gsl_matrix_free(BpA);\n  //gsl_matrix_free(BpAi);\n  gsl_vector_free(bma);\n  gsl_vector_free(v_temp);\n\n  gsl_permutation_free(p1);\n\n  //printf(\"At end of new_get_lnoverlaps function\\n\");\n}\n", "meta": {"hexsha": "b682b3ed3f68e784ac48ec43dcc9399d6d5c079e", "size": 17985, "ext": "c", "lang": "C", "max_stars_repo_path": "playground/overlap_legacy/overlap.c", "max_stars_repo_name": "tcrundall/chronostar", "max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "playground/overlap_legacy/overlap.c", "max_issues_repo_name": "tcrundall/chronostar", "max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "playground/overlap_legacy/overlap.c", "max_forks_repo_name": "tcrundall/chronostar", "max_forks_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_forks_repo_licenses": ["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.0250417362, "max_line_length": 80, "alphanum_fraction": 0.6351959967, "num_tokens": 6048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3956781069783796}}
{"text": "/****************************************\n * MIT License\n *\n * Copyright (c) 2020 Miguel Ramos Pernas\n ****************************************/\n\n#ifdef USE_CPU\n#include \"Python.h\"\n#include \"math.h\"\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_monte.h>\n#include <gsl/gsl_monte_miser.h>\n#include <gsl/gsl_monte_plain.h>\n#include <gsl/gsl_monte_vegas.h>\n\n#if NDIM == 1\n/// Function proxy to integrate using 1-dimensional methods\ndouble function_proxy(double x, void *vparams) {\n\n  double *params = (double *)vparams;\n\n  return FUNCTION(x, FWD_PARAMS(params)); // Definitions in \"evaluators.c\"\n}\n#endif\n\n/// Function proxy to integrate using Monte Carlo methods\ndouble monte_function_proxy(double *data, size_t, void *vparams) {\n\n  double *params = (double *)vparams;\n\n  return FUNCTION(DATA(data),\n                  FWD_PARAMS(params)); // Definitions in \"evaluators.c\"\n}\n\nextern \"C\" {\n\n#if NDIM == 1\n/// Exposed function to integrate using the QNG method\nPyObject *integrate_qng(double lb, double ub, PyObject *config,\n                        double *params) {\n\n  gsl_function func = {&function_proxy, params};\n\n  double atol, rtol;\n  PyArg_ParseTuple(config, \"dd\", &atol, &rtol);\n\n  double res, err;\n  size_t neval;\n  gsl_integration_qng(&func, lb, ub, atol, rtol, &res, &err, &neval);\n\n  return Py_BuildValue(\"(ddi)\", res, err, neval);\n}\n\n/// Exposed function to integrate using the QAG method\nPyObject *integrate_qag(double lb, double ub, PyObject *config,\n                        double *params) {\n\n  gsl_function func = {&function_proxy, params};\n\n  double atol, rtol;\n  int limit, key, workspace_size;\n  PyArg_ParseTuple(config, \"ddiii\", &atol, &rtol, &limit, &key,\n                   &workspace_size);\n\n  gsl_integration_workspace *w =\n      gsl_integration_workspace_alloc(workspace_size);\n\n  double res, aerr;\n  gsl_integration_qag(&func, lb, ub, atol, rtol, limit, key, w, &res, &aerr);\n\n  gsl_integration_workspace_free(w);\n\n  return Py_BuildValue(\"(dd)\", res, aerr);\n}\n\n/// Exposed function to integrate using the CQUAD method\nPyObject *integrate_cquad(double lb, double ub, PyObject *config,\n                          double *params) {\n\n  gsl_function func = {&function_proxy, params};\n\n  double atol, rtol;\n  int workspace_size;\n  PyArg_ParseTuple(config, \"ddi\", &atol, &rtol, &workspace_size);\n\n  gsl_integration_cquad_workspace *w =\n      gsl_integration_cquad_workspace_alloc(workspace_size);\n\n  double res, err;\n  size_t neval;\n  gsl_integration_cquad(&func, lb, ub, atol, rtol, w, &res, &err, &neval);\n\n  gsl_integration_cquad_workspace_free(w);\n\n  return Py_BuildValue(\"(ddi)\", res, err, neval);\n}\n#endif\n\n/// Exposed function to integrate using plain MonteCarlo\nPyObject *integrate_plain(double *lb, double *ub, PyObject *config,\n                          double *params) {\n\n  gsl_monte_function func = {&monte_function_proxy, NDIM, params};\n\n  double res, err;\n\n  gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n\n  // Define the state\n  gsl_monte_plain_state *s = gsl_monte_plain_alloc(NDIM);\n\n  int calls;\n  PyArg_ParseTuple(config, \"i\", &calls);\n\n  // Calculate the integral\n  gsl_monte_plain_integrate(&func, lb, ub, NDIM, calls, r, s, &res, &err);\n\n  gsl_monte_plain_free(s);\n\n  gsl_rng_free(r);\n\n  return Py_BuildValue(\"(dd)\", res, err);\n}\n\n/// Exposed function to integrate using the MISER method\nPyObject *integrate_miser(double *lb, double *ub, PyObject *config,\n                          double *params) {\n\n  gsl_monte_function func = {&monte_function_proxy, NDIM, params};\n\n  double res, err;\n\n  gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n\n  // Define the state\n  gsl_monte_miser_state *s = gsl_monte_miser_alloc(NDIM);\n\n  int calls;\n  double estimate_frac;\n  int min_calls;\n  int min_calls_per_bisection;\n  double alpha;\n  double dither;\n\n  PyArg_ParseTuple(config, \"idiidd\", &calls, &estimate_frac, &min_calls,\n                   &min_calls_per_bisection, &alpha, &dither);\n\n  gsl_monte_miser_params p;\n  gsl_monte_miser_params_get(s, &p);\n  p.estimate_frac = estimate_frac;\n  p.min_calls = min_calls;\n  p.min_calls_per_bisection = min_calls_per_bisection;\n  p.alpha = alpha;\n  p.dither = dither;\n  gsl_monte_miser_params_set(s, &p);\n\n  // Calculate the integral\n  gsl_monte_miser_integrate(&func, lb, ub, NDIM, calls, r, s, &res, &err);\n\n  gsl_monte_miser_free(s);\n\n  gsl_rng_free(r);\n\n  return Py_BuildValue(\"(dd)\", res, err);\n}\n\n/// Exposed function to integrate using the VEGAS method\nPyObject *integrate_vegas(double *lb, double *ub, PyObject *config,\n                          double *params) {\n\n  gsl_monte_function func = {&monte_function_proxy, NDIM, params};\n\n  double res, err;\n\n  gsl_rng *r = gsl_rng_alloc(gsl_rng_default);\n\n  // Define the state\n  gsl_monte_vegas_state *s = gsl_monte_vegas_alloc(NDIM);\n\n  int calls;\n  double alpha;\n  int iterations;\n  int mode;\n\n  PyArg_ParseTuple(config, \"idii\", &calls, &alpha, &iterations, &mode);\n\n  gsl_monte_vegas_params p;\n  gsl_monte_vegas_params_get(s, &p);\n  p.alpha = alpha;\n  p.iterations = iterations;\n  p.mode = mode;\n  gsl_monte_vegas_params_set(s, &p);\n\n  // Calculate the integral\n  gsl_monte_vegas_integrate(&func, lb, ub, NDIM, calls, r, s, &res, &err);\n\n  do {\n    gsl_monte_vegas_integrate(&func, lb, ub, NDIM, calls, r, s, &res, &err);\n\n  } while (fabs(gsl_monte_vegas_chisq(s) - 1.0) > 0.5);\n\n  gsl_monte_vegas_free(s);\n\n  gsl_rng_free(r);\n\n  return Py_BuildValue(\"(dd)\", res, err);\n}\n}\n\n#endif // USE_CPU\n", "meta": {"hexsha": "130dd96cb058fb6457c559f808c9f8b7bc2fc573", "size": 5443, "ext": "c", "lang": "C", "max_stars_repo_path": "minkit/backends/src/templates/numerical_integral.c", "max_stars_repo_name": "mramospe/minkit", "max_stars_repo_head_hexsha": "fa6808a6ca8063751da92f683f2b810a0690a462", "max_stars_repo_licenses": ["MIT-0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "minkit/backends/src/templates/numerical_integral.c", "max_issues_repo_name": "mramospe/minkit", "max_issues_repo_head_hexsha": "fa6808a6ca8063751da92f683f2b810a0690a462", "max_issues_repo_licenses": ["MIT-0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-01-30T18:30:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T09:13:47.000Z", "max_forks_repo_path": "minkit/backends/src/templates/numerical_integral.c", "max_forks_repo_name": "mramospe/minkit", "max_forks_repo_head_hexsha": "fa6808a6ca8063751da92f683f2b810a0690a462", "max_forks_repo_licenses": ["MIT-0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-03T22:59:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-03T22:59:00.000Z", "avg_line_length": 25.6745283019, "max_line_length": 77, "alphanum_fraction": 0.6797721845, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.39566336538183544}}
{"text": "/* linalg/luc.c\n * \n * Copyright (C) 2001, 2007, 2009 Brian Gough\n * Copyright (C) 2019 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_permute_vector.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_linalg.h>\n\n#include \"recurse.h\"\n\nstatic int LU_decomp_L2 (gsl_matrix_complex * A, gsl_vector_uint * ipiv);\nstatic int LU_decomp_L3 (gsl_matrix_complex * A, gsl_vector_uint * ipiv);\nstatic int singular (const gsl_matrix_complex * LU);\nstatic int apply_pivots(gsl_matrix_complex * A, const gsl_vector_uint * ipiv);\n\n/* Factorise a general N x N complex matrix A into,\n *\n *   P A = L U\n *\n * where P is a permutation matrix, L is unit lower triangular and U\n * is upper triangular.\n *\n * L is stored in the strict lower triangular part of the input\n * matrix. The diagonal elements of L are unity and are not stored.\n *\n * U is stored in the diagonal and upper triangular part of the\n * input matrix.  \n * \n * P is stored in the permutation p. Column j of P is column k of the\n * identity matrix, where k = permutation->data[j]\n *\n * signum gives the sign of the permutation, (-1)^n, where n is the\n * number of interchanges in the permutation. \n *\n * See Golub & Van Loan, Matrix Computations, Algorithm 3.4.1 (Gauss\n * Elimination with Partial Pivoting).\n */\n\nint\ngsl_linalg_complex_LU_decomp (gsl_matrix_complex * A, gsl_permutation * p, int *signum)\n{\n  const size_t M = A->size1;\n\n  if (p->size != M)\n    {\n      GSL_ERROR (\"permutation length must match matrix size1\", GSL_EBADLEN);\n    }\n  else\n    {\n      int status;\n      const size_t N = A->size2;\n      const size_t minMN = GSL_MIN(M, N);\n      gsl_vector_uint * ipiv = gsl_vector_uint_alloc(minMN);\n      gsl_matrix_complex_view AL = gsl_matrix_complex_submatrix(A, 0, 0, M, minMN);\n      size_t i;\n\n      status = LU_decomp_L3 (&AL.matrix, ipiv);\n\n      /* process remaining right matrix */\n      if (M < N)\n        {\n          gsl_matrix_complex_view AR = gsl_matrix_complex_submatrix(A, 0, M, M, N - M);\n\n          /* apply pivots to AR */\n          apply_pivots(&AR.matrix, ipiv);\n\n          /* AR = AL^{-1} AR */\n          gsl_blas_ztrsm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, GSL_COMPLEX_ONE, &AL.matrix, &AR.matrix);\n        }\n\n      /* convert ipiv array to permutation */\n\n      gsl_permutation_init(p);\n      *signum = 1;\n\n      for (i = 0; i < minMN; ++i)\n        {\n          unsigned int pivi = gsl_vector_uint_get(ipiv, i);\n\n          if (p->data[pivi] != p->data[i])\n            {\n              size_t tmp = p->data[pivi];\n              p->data[pivi] = p->data[i];\n              p->data[i] = tmp;\n              *signum = -(*signum);\n            }\n        }\n\n      gsl_vector_uint_free(ipiv);\n\n      return status;\n    }\n}\n\n/*\nLU_decomp_L2\n  LU decomposition with partial pivoting using Level 2 BLAS\n\nInputs: A    - on input, matrix to be factored; on output, L and U factors\n        ipiv - (output) array containing row swaps\n\nNotes:\n1) Based on LAPACK ZGETF2\n*/\n\nstatic int\nLU_decomp_L2 (gsl_matrix_complex * A, gsl_vector_uint * ipiv)\n{\n  const size_t M = A->size1;\n  const size_t N = A->size2;\n  const size_t minMN = GSL_MIN(M, N);\n\n  if (ipiv->size != minMN)\n    {\n      GSL_ERROR (\"ipiv length must equal MIN(M,N)\", GSL_EBADLEN);\n    }\n  else\n    {\n      size_t i, j;\n\n      for (j = 0; j < minMN; ++j)\n        {\n          /* find maximum in the j-th column */\n          gsl_vector_complex_view v = gsl_matrix_complex_subcolumn(A, j, j, M - j);\n          size_t j_pivot = j + gsl_blas_izamax(&v.vector);\n          gsl_vector_complex_view v1, v2;\n\n          gsl_vector_uint_set(ipiv, j, j_pivot);\n\n          if (j_pivot != j)\n            {\n              /* swap rows j and j_pivot */\n              v1 = gsl_matrix_complex_row(A, j);\n              v2 = gsl_matrix_complex_row(A, j_pivot);\n              gsl_blas_zswap(&v1.vector, &v2.vector);\n            }\n\n          if (j < M - 1)\n            {\n              gsl_complex Ajj = gsl_matrix_complex_get(A, j, j);\n              gsl_complex Ajjinv = gsl_complex_inverse(Ajj);\n\n              if (gsl_complex_abs(Ajj) >= GSL_DBL_MIN)\n                {\n                  v1 = gsl_matrix_complex_subcolumn(A, j, j + 1, M - j - 1);\n                  gsl_blas_zscal(Ajjinv, &v1.vector);\n                }\n              else\n                {\n                  for (i = 1; i < M - j; ++i)\n                    {\n                      gsl_complex * ptr = gsl_matrix_complex_ptr(A, j + i, j);\n                      *ptr = gsl_complex_mul(*ptr, Ajjinv);\n                    }\n                }\n            }\n\n          if (j < minMN - 1)\n            {\n              gsl_matrix_complex_view A22 = gsl_matrix_complex_submatrix(A, j + 1, j + 1, M - j - 1, N - j - 1);\n              v1 = gsl_matrix_complex_subcolumn(A, j, j + 1, M - j - 1);\n              v2 = gsl_matrix_complex_subrow(A, j, j + 1, N - j - 1);\n\n              gsl_blas_zgeru(GSL_COMPLEX_NEGONE, &v1.vector, &v2.vector, &A22.matrix);\n            }\n        }\n\n      return GSL_SUCCESS;\n    }\n}\n\n/*\nLU_decomp_L3\n  LU decomposition with partial pivoting using Level 3 BLAS\n\nInputs: A    - on input, matrix to be factored; on output, L and U factors\n        ipiv - (output) array containing row swaps\n\nNotes:\n1) Based on ReLAPACK DGETRF\n*/\n\nstatic int\nLU_decomp_L3 (gsl_matrix_complex * A, gsl_vector_uint * ipiv)\n{\n  const size_t M = A->size1;\n  const size_t N = A->size2;\n\n  if (M < N)\n    {\n      GSL_ERROR (\"matrix must have M >= N\", GSL_EBADLEN);\n    }\n  else if (ipiv->size != GSL_MIN(M, N))\n    {\n      GSL_ERROR (\"ipiv length must equal MIN(M,N)\", GSL_EBADLEN);\n    }\n  else if (N <= CROSSOVER_LU)\n    {\n      /* use Level 2 algorithm */\n      return LU_decomp_L2(A, ipiv);\n    }\n  else\n    {\n      /*\n       * partition matrix:\n       *\n       *       N1  N2\n       * N1  [ A11 A12 ]\n       * M2  [ A21 A22 ]\n       *\n       * and\n       *      N1  N2\n       * M  [ AL  AR  ]\n       */\n      int status;\n      const size_t N1 = GSL_LINALG_SPLIT_COMPLEX(N);\n      const size_t N2 = N - N1;\n      const size_t M2 = M - N1;\n      gsl_matrix_complex_view A11 = gsl_matrix_complex_submatrix(A, 0, 0, N1, N1);\n      gsl_matrix_complex_view A12 = gsl_matrix_complex_submatrix(A, 0, N1, N1, N2);\n      gsl_matrix_complex_view A21 = gsl_matrix_complex_submatrix(A, N1, 0, M2, N1);\n      gsl_matrix_complex_view A22 = gsl_matrix_complex_submatrix(A, N1, N1, M2, N2);\n\n      gsl_matrix_complex_view AL = gsl_matrix_complex_submatrix(A, 0, 0, M, N1);\n      gsl_matrix_complex_view AR = gsl_matrix_complex_submatrix(A, 0, N1, M, N2);\n\n      /*\n       * partition ipiv = [ ipiv1 ] N1\n       *                  [ ipiv2 ] N2\n       */\n      gsl_vector_uint_view ipiv1 = gsl_vector_uint_subvector(ipiv, 0, N1);\n      gsl_vector_uint_view ipiv2 = gsl_vector_uint_subvector(ipiv, N1, N2);\n\n      size_t i;\n\n      /* recursion on (AL, ipiv1) */\n      status = LU_decomp_L3(&AL.matrix, &ipiv1.vector);\n      if (status)\n        return status;\n\n      /* apply ipiv1 to AR */\n      apply_pivots(&AR.matrix, &ipiv1.vector);\n\n      /* A12 = A11^{-1} A12 */\n      gsl_blas_ztrsm(CblasLeft, CblasLower, CblasNoTrans, CblasUnit, GSL_COMPLEX_ONE, &A11.matrix, &A12.matrix);\n\n      /* A22 = A22 - A21 * A12 */\n      gsl_blas_zgemm(CblasNoTrans, CblasNoTrans, GSL_COMPLEX_NEGONE, &A21.matrix, &A12.matrix, GSL_COMPLEX_ONE, &A22.matrix);\n\n      /* recursion on (A22, ipiv2) */\n      status = LU_decomp_L3(&A22.matrix, &ipiv2.vector);\n      if (status)\n        return status;\n\n      /* apply pivots to A21 */\n      apply_pivots(&A21.matrix, &ipiv2.vector);\n\n      /* shift pivots */\n      for (i = 0; i < N2; ++i)\n        {\n          unsigned int * ptr = gsl_vector_uint_ptr(&ipiv2.vector, i);\n          *ptr += N1;\n        }\n\n      return GSL_SUCCESS;\n    }\n}\n\nint\ngsl_linalg_complex_LU_solve (const gsl_matrix_complex * LU, const gsl_permutation * p, const gsl_vector_complex * b, gsl_vector_complex * x)\n{\n  if (LU->size1 != LU->size2)\n    {\n      GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (LU->size1 != p->size)\n    {\n      GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n    }\n  else if (LU->size1 != b->size)\n    {\n      GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n    }\n  else if (LU->size2 != x->size)\n    {\n      GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n    }\n  else if (singular (LU)) \n    {\n      GSL_ERROR (\"matrix is singular\", GSL_EDOM);\n    }\n  else\n    {\n      int status;\n\n      /* copy x <- b */\n      gsl_vector_complex_memcpy (x, b);\n\n      /* solve for x */\n      status = gsl_linalg_complex_LU_svx (LU, p, x);\n\n      return status;\n    }\n}\n\n\nint\ngsl_linalg_complex_LU_svx (const gsl_matrix_complex * LU, const gsl_permutation * p, gsl_vector_complex * x)\n{\n  if (LU->size1 != LU->size2)\n    {\n      GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (LU->size1 != p->size)\n    {\n      GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n    }\n  else if (LU->size1 != x->size)\n    {\n      GSL_ERROR (\"matrix size must match solution/rhs size\", GSL_EBADLEN);\n    }\n  else if (singular (LU)) \n    {\n      GSL_ERROR (\"matrix is singular\", GSL_EDOM);\n    }\n  else\n    {\n      /* apply permutation to RHS */\n      gsl_permute_vector_complex (p, x);\n\n      /* solve for c using forward-substitution, L c = P b */\n      gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasUnit, LU, x);\n\n      /* perform back-substitution, U x = c */\n      gsl_blas_ztrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LU, x);\n\n      return GSL_SUCCESS;\n    }\n}\n\n\nint\ngsl_linalg_complex_LU_refine (const gsl_matrix_complex * A, const gsl_matrix_complex * LU, const gsl_permutation * p, const gsl_vector_complex * b, gsl_vector_complex * x, gsl_vector_complex * work)\n{\n  if (A->size1 != A->size2)\n    {\n      GSL_ERROR (\"matrix a must be square\", GSL_ENOTSQR);\n    }\n  if (LU->size1 != LU->size2)\n    {\n      GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (A->size1 != LU->size2)\n    {\n      GSL_ERROR (\"LU matrix must be decomposition of a\", GSL_ENOTSQR);\n    }\n  else if (LU->size1 != p->size)\n    {\n      GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n    }\n  else if (LU->size1 != b->size)\n    {\n      GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n    }\n  else if (LU->size1 != x->size)\n    {\n      GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n    }\n  else if (LU->size1 != work->size)\n    {\n      GSL_ERROR (\"matrix size must match workspace size\", GSL_EBADLEN);\n    }\n  else if (singular (LU)) \n    {\n      GSL_ERROR (\"matrix is singular\", GSL_EDOM);\n    }\n  else\n    {\n      int status;\n\n      /* Compute residual = (A * x  - b) */\n\n      gsl_vector_complex_memcpy (work, b);\n\n      {\n        gsl_complex one = GSL_COMPLEX_ONE;\n        gsl_complex negone = GSL_COMPLEX_NEGONE;\n        gsl_blas_zgemv (CblasNoTrans, one, A, x, negone, work);\n      }\n\n      /* Find correction, delta = - (A^-1) * residual, and apply it */\n\n      status = gsl_linalg_complex_LU_svx (LU, p, work);\n\n      {\n        gsl_complex negone= GSL_COMPLEX_NEGONE;\n        gsl_blas_zaxpy (negone, work, x);\n      }\n\n      return status;\n    }\n}\n\nint\ngsl_linalg_complex_LU_invert (const gsl_matrix_complex * LU, const gsl_permutation * p, gsl_matrix_complex * inverse)\n{\n  if (LU->size1 != LU->size2)\n    {\n      GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (LU->size1 != p->size)\n    {\n      GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n    }\n  else if (inverse->size1 != LU->size1 || inverse->size2 != LU->size2)\n    {\n      GSL_ERROR (\"inverse matrix must match LU matrix dimensions\", GSL_EBADLEN);\n    }\n  else\n    {\n      gsl_matrix_complex_memcpy(inverse, LU);\n      return gsl_linalg_complex_LU_invx(inverse, p);\n    }\n}\n\nint\ngsl_linalg_complex_LU_invx (gsl_matrix_complex * LU, const gsl_permutation * p)\n{\n  if (LU->size1 != LU->size2)\n    {\n      GSL_ERROR (\"LU matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (LU->size1 != p->size)\n    {\n      GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n    }\n  else if (singular (LU)) \n    {\n      GSL_ERROR (\"matrix is singular\", GSL_EDOM);\n    }\n  else\n    {\n      int status;\n      const size_t N = LU->size1;\n      size_t i;\n\n      /* compute U^{-1} */\n      status = gsl_linalg_complex_tri_invert(CblasUpper, CblasNonUnit, LU);\n      if (status)\n        return status;\n\n      /* compute L^{-1} */\n      status = gsl_linalg_complex_tri_invert(CblasLower, CblasUnit, LU);\n      if (status)\n        return status;\n\n      /* compute U^{-1} L^{-1} */\n      status = gsl_linalg_complex_tri_UL(LU);\n      if (status)\n        return status;\n\n      /* apply permutation to columns of A^{-1} */\n      for (i = 0; i < N; ++i)\n        {\n          gsl_vector_complex_view v = gsl_matrix_complex_row(LU, i);\n          gsl_permute_vector_complex_inverse(p, &v.vector);\n        }\n\n      return GSL_SUCCESS;\n    }\n}\n\ngsl_complex\ngsl_linalg_complex_LU_det (gsl_matrix_complex * LU, int signum)\n{\n  size_t i, n = LU->size1;\n\n  gsl_complex det = gsl_complex_rect((double) signum, 0.0);\n\n  for (i = 0; i < n; i++)\n    {\n      gsl_complex zi = gsl_matrix_complex_get (LU, i, i);\n      det = gsl_complex_mul (det, zi);\n    }\n\n  return det;\n}\n\n\ndouble\ngsl_linalg_complex_LU_lndet (gsl_matrix_complex * LU)\n{\n  size_t i, n = LU->size1;\n\n  double lndet = 0.0;\n\n  for (i = 0; i < n; i++)\n    {\n      gsl_complex z = gsl_matrix_complex_get (LU, i, i);\n      lndet += log (gsl_complex_abs (z));\n    }\n\n  return lndet;\n}\n\n\ngsl_complex\ngsl_linalg_complex_LU_sgndet (gsl_matrix_complex * LU, int signum)\n{\n  size_t i, n = LU->size1;\n\n  gsl_complex phase = gsl_complex_rect((double) signum, 0.0);\n\n  for (i = 0; i < n; i++)\n    {\n      gsl_complex z = gsl_matrix_complex_get (LU, i, i);\n      \n      double r = gsl_complex_abs(z);\n\n      if (r == 0)\n        {\n          phase = gsl_complex_rect(0.0, 0.0);\n          break;\n        }\n      else\n        {\n          z = gsl_complex_div_real(z, r);\n          phase = gsl_complex_mul(phase, z);\n        }\n    }\n\n  return phase;\n}\n\nstatic int\nsingular (const gsl_matrix_complex * LU)\n{\n  size_t i, n = LU->size1;\n\n  for (i = 0; i < n; i++)\n    {\n      gsl_complex u = gsl_matrix_complex_get (LU, i, i);\n      if (GSL_REAL(u) == 0 && GSL_IMAG(u) == 0) return 1;\n    }\n \n return 0;\n}\n\nstatic int\napply_pivots(gsl_matrix_complex * A, const gsl_vector_uint * ipiv)\n{\n  if (0)\n    {\n    }\n  else\n    {\n      size_t i;\n\n      for (i = 0; i < ipiv->size; ++i)\n        {\n          size_t pi = gsl_vector_uint_get(ipiv, i);\n\n          if (i != pi)\n            {\n              /* swap rows i and pi */\n              gsl_vector_complex_view v1 = gsl_matrix_complex_row(A, i);\n              gsl_vector_complex_view v2 = gsl_matrix_complex_row(A, pi);\n              gsl_blas_zswap(&v1.vector, &v2.vector);\n            }\n        }\n\n      return GSL_SUCCESS;\n    }\n}\n", "meta": {"hexsha": "90b74a8c4960b63ab17c911404977736486be68b", "size": 15865, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/linalg/luc.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gsl-2.6/linalg/luc.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/linalg/luc.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["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.4416666667, "max_line_length": 198, "alphanum_fraction": 0.5952726127, "num_tokens": 4592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3953906403846364}}
{"text": "#include \"ccv.h\"\n#include \"ccv_internal.h\"\n#include <sys/time.h>\n#ifdef HAVE_GSL\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_randist.h>\n#endif\n#ifdef USE_OPENMP\n#include <omp.h>\n#endif\n#ifdef HAVE_LIBLINEAR\n#include <linear.h>\n#endif\n\nconst ccv_dpm_param_t ccv_dpm_default_params = {\n\t.interval = 8,\n\t.min_neighbors = 1,\n\t.flags = 0,\n\t.threshold = 0.6, // 0.8\n};\n\n#define CCV_DPM_WINDOW_SIZE (8)\n\nstatic int _ccv_dpm_scale_upto(ccv_dense_matrix_t* a, ccv_dpm_mixture_model_t** _model, int count, int interval)\n{\n\tint c, i;\n\tccv_size_t size = ccv_size(a->cols, a->rows);\n\tfor (c = 0; c < count; c++)\n\t{\n\t\tccv_dpm_mixture_model_t* model = _model[c];\n\t\tfor (i = 0; i < model->count; i++)\n\t\t{\n\t\t\tsize.width = ccv_min(model->root[i].root.w->cols * CCV_DPM_WINDOW_SIZE, size.width);\n\t\t\tsize.height = ccv_min(model->root[i].root.w->rows * CCV_DPM_WINDOW_SIZE, size.height);\n\t\t}\n\t}\n\tint hr = a->rows / size.height;\n\tint wr = a->cols / size.width;\n\tdouble scale = pow(2.0, 1.0 / (interval + 1.0));\n\tint next = interval + 1;\n\treturn (int)(log((double)ccv_min(hr, wr)) / log(scale)) - next;\n}\n\nstatic void _ccv_dpm_feature_pyramid(ccv_dense_matrix_t* a, ccv_dense_matrix_t** pyr, int scale_upto, int interval)\n{\n\tint next = interval + 1;\n\tdouble scale = pow(2.0, 1.0 / (interval + 1.0));\n\tmemset(pyr, 0, (scale_upto + next * 2) * sizeof(ccv_dense_matrix_t*));\n\tpyr[next] = a;\n\tint i;\n\tfor (i = 1; i <= interval; i++)\n\t\tccv_resample(pyr[next], &pyr[next + i], 0, (int)(pyr[next]->rows / pow(scale, i)), (int)(pyr[next]->cols / pow(scale, i)), CCV_INTER_AREA);\n\tfor (i = next; i < scale_upto + next; i++)\n\t\tccv_sample_down(pyr[i], &pyr[i + next], 0, 0, 0);\n\tccv_dense_matrix_t* hog;\n\t/* a more efficient way to generate up-scaled hog (using smaller size) */\n\tfor (i = 0; i < next; i++)\n\t{\n\t\thog = 0;\n\t\tccv_hog(pyr[i + next], &hog, 0, 9, CCV_DPM_WINDOW_SIZE / 2 /* this is */);\n\t\tpyr[i] = hog;\n\t}\n\thog = 0;\n\tccv_hog(pyr[next], &hog, 0, 9, CCV_DPM_WINDOW_SIZE);\n\tpyr[next] = hog;\n\tfor (i = next + 1; i < scale_upto + next * 2; i++)\n\t{\n\t\thog = 0;\n\t\tccv_hog(pyr[i], &hog, 0, 9, CCV_DPM_WINDOW_SIZE);\n\t\tccv_matrix_free(pyr[i]);\n\t\tpyr[i] = hog;\n\t}\n}\n\nstatic void _ccv_dpm_compute_score(ccv_dpm_root_classifier_t* root_classifier, ccv_dense_matrix_t* hog, ccv_dense_matrix_t* hog2x, ccv_dense_matrix_t** _response, ccv_dense_matrix_t** part_feature, ccv_dense_matrix_t** dx, ccv_dense_matrix_t** dy)\n{\n\tccv_dense_matrix_t* response = 0;\n\tccv_filter(hog, root_classifier->root.w, &response, 0, CCV_NO_PADDING);\n\tccv_dense_matrix_t* root_feature = 0;\n\tccv_flatten(response, (ccv_matrix_t**)&root_feature, 0, 0);\n\tccv_matrix_free(response);\n\t*_response = root_feature;\n\tif (hog2x == 0)\n\t\treturn;\n\tccv_make_matrix_mutable(root_feature);\n\tint rwh = (root_classifier->root.w->rows - 1) / 2, rww = (root_classifier->root.w->cols - 1) / 2;\n\tint rwh_1 = root_classifier->root.w->rows / 2, rww_1 = root_classifier->root.w->cols / 2;\n\tint i, x, y;\n\tfor (i = 0; i < root_classifier->count; i++)\n\t{\n\t\tccv_dpm_part_classifier_t* part = root_classifier->part + i;\n\t\tccv_dense_matrix_t* response = 0;\n\t\tccv_filter(hog2x, part->w, &response, 0, CCV_NO_PADDING);\n\t\tccv_dense_matrix_t* feature = 0;\n\t\tccv_flatten(response, (ccv_matrix_t**)&feature, 0, 0);\n\t\tccv_matrix_free(response);\n\t\tpart_feature[i] = dx[i] = dy[i] = 0;\n\t\tccv_distance_transform(feature, &part_feature[i], 0, &dx[i], 0, &dy[i], 0, part->dx, part->dy, part->dxx, part->dyy, CCV_NEGATIVE | CCV_GSEDT);\n\t\tccv_matrix_free(feature);\n\t\tint pwh = (part->w->rows - 1) / 2, pww = (part->w->cols - 1) / 2;\n\t\tint offy = part->y + pwh - rwh * 2;\n\t\tint miny = pwh, maxy = part_feature[i]->rows - part->w->rows + pwh;\n\t\tint offx = part->x + pww - rww * 2;\n\t\tint minx = pww, maxx = part_feature[i]->cols - part->w->cols + pww;\n\t\tfloat* f_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | CCV_C1, root_feature, rwh, 0, 0);\n\t\tfor (y = rwh; y < root_feature->rows - rwh_1; y++)\n\t\t{\n\t\t\tint iy = ccv_clamp(y * 2 + offy, miny, maxy);\n\t\t\tfor (x = rww; x < root_feature->cols - rww_1; x++)\n\t\t\t{\n\t\t\t\tint ix = ccv_clamp(x * 2 + offx, minx, maxx);\n\t\t\t\tf_ptr[x] -= ccv_get_dense_matrix_cell_value_by(CCV_32F | CCV_C1, part_feature[i], iy, ix, 0);\n\t\t\t}\n\t\t\tf_ptr += root_feature->cols;\n\t\t}\n\t}\n}\n\n#ifdef HAVE_LIBLINEAR\n#ifdef HAVE_GSL\n\nstatic uint64_t _ccv_dpm_time_measure()\n{\n\tstruct timeval tv;\n\tgettimeofday(&tv, 0);\n\treturn tv.tv_sec * 1000000 + tv.tv_usec;\n}\n\n#define less_than(fn1, fn2, aux) ((fn1).value >= (fn2).value)\nstatic CCV_IMPLEMENT_QSORT(_ccv_dpm_aspect_qsort, struct feature_node, less_than)\n#undef less_than\n\n#define less_than(a1, a2, aux) ((a1) < (a2))\nstatic CCV_IMPLEMENT_QSORT(_ccv_dpm_area_qsort, int, less_than)\n#undef less_than\n\n#define less_than(s1, s2, aux) ((s1) < (s2))\nstatic CCV_IMPLEMENT_QSORT(_ccv_dpm_score_qsort, double, less_than)\n#undef less_than\n\nstatic ccv_dpm_mixture_model_t* _ccv_dpm_model_copy(ccv_dpm_mixture_model_t* _model)\n{\n\tccv_dpm_mixture_model_t* model = (ccv_dpm_mixture_model_t*)ccmalloc(sizeof(ccv_dpm_mixture_model_t));\n\tmodel->count = _model->count;\n\tmodel->root = (ccv_dpm_root_classifier_t*)ccmalloc(sizeof(ccv_dpm_root_classifier_t) * model->count);\n\tint i, j;\n\tmemcpy(model->root, _model->root, sizeof(ccv_dpm_root_classifier_t) * model->count);\n\tfor (i = 0; i < model->count; i++)\n\t{\n\t\tccv_dpm_root_classifier_t* _root = _model->root + i;\n\t\tccv_dpm_root_classifier_t* root = model->root + i;\n\t\troot->root.w = ccv_dense_matrix_new(_root->root.w->rows, _root->root.w->cols, CCV_32F | 31, 0, 0);\n\t\tmemcpy(root->root.w->data.u8, _root->root.w->data.u8, _root->root.w->rows * _root->root.w->step);\n\t\tccv_make_matrix_immutable(root->root.w);\n\t\tccv_dpm_part_classifier_t* _part = _root->part;\n \t\tccv_dpm_part_classifier_t* part = root->part = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * root->count);\n\t\tmemcpy(part, _part, sizeof(ccv_dpm_part_classifier_t) * root->count);\n\t\tfor (j = 0; j < root->count; j++)\n\t\t{\n\t\t\tpart[j].w = ccv_dense_matrix_new(_part[j].w->rows, _part[j].w->cols, CCV_32F | 31, 0, 0);\n\t\t\tmemcpy(part[j].w->data.u8, _part[j].w->data.u8, _part[j].w->rows * _part[j].w->step);\n\t\t\tccv_make_matrix_immutable(part[j].w);\n\t\t}\n\t}\n\treturn model;\n}\n\nstatic void _ccv_dpm_write_checkpoint(ccv_dpm_mixture_model_t* model, int done, const char* dir)\n{\n\tchar swpfile[1024];\n\tsprintf(swpfile, \"%s.swp\", dir);\n\tFILE* w = fopen(swpfile, \"w+\");\n\tif (!w)\n\t\treturn;\n\tif (done)\n\t\tfprintf(w, \".\\n\");\n\telse\n\t\tfprintf(w, \",\\n\");\n\tint i, j, x, y, ch, count = 0;\n\tfor (i = 0; i < model->count; i++)\n\t{\n\t\tif (model->root[i].root.w == 0)\n\t\t\tbreak;\n\t\tcount++;\n\t}\n\tif (done)\n\t\tfprintf(w, \"%d\\n\", model->count);\n\telse\n\t\tfprintf(w, \"%d %d\\n\", model->count, count);\n\tfor (i = 0; i < count; i++)\n\t{\n\t\tccv_dpm_root_classifier_t* root_classifier = model->root + i;\n\t\tfprintf(w, \"%d %d\\n\", root_classifier->root.w->rows, root_classifier->root.w->cols);\n\t\tfprintf(w, \"%a %a %a %a\\n\", root_classifier->beta, root_classifier->alpha[0], root_classifier->alpha[1], root_classifier->alpha[2]);\n\t\tch = CCV_GET_CHANNEL(root_classifier->root.w->type);\n\t\tfor (y = 0; y < root_classifier->root.w->rows; y++)\n\t\t{\n\t\t\tfor (x = 0; x < root_classifier->root.w->cols * ch; x++)\n\t\t\t\tfprintf(w, \"%a \", root_classifier->root.w->data.f32[y * root_classifier->root.w->cols * ch + x]);\n\t\t\tfprintf(w, \"\\n\");\n\t\t}\n\t\tfprintf(w, \"%d\\n\", root_classifier->count);\n\t\tfor (j = 0; j < root_classifier->count; j++)\n\t\t{\n\t\t\tccv_dpm_part_classifier_t* part_classifier = root_classifier->part + j;\n\t\t\tfprintf(w, \"%d %d %d\\n\", part_classifier->x, part_classifier->y, part_classifier->z);\n\t\t\tfprintf(w, \"%la %la %la %la\\n\", part_classifier->dx, part_classifier->dy, part_classifier->dxx, part_classifier->dyy);\n\t\t\tfprintf(w, \"%a %a %a %a %a %a\\n\", part_classifier->alpha[0], part_classifier->alpha[1], part_classifier->alpha[2], part_classifier->alpha[3], part_classifier->alpha[4], part_classifier->alpha[5]);\n\t\t\tfprintf(w, \"%d %d %d\\n\", part_classifier->w->rows, part_classifier->w->cols, part_classifier->counterpart);\n\t\t\tch = CCV_GET_CHANNEL(part_classifier->w->type);\n\t\t\tfor (y = 0; y < part_classifier->w->rows; y++)\n\t\t\t{\n\t\t\t\tfor (x = 0; x < part_classifier->w->cols * ch; x++)\n\t\t\t\t\tfprintf(w, \"%a \", part_classifier->w->data.f32[y * part_classifier->w->cols * ch + x]);\n\t\t\t\tfprintf(w, \"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\tfclose(w);\n\trename(swpfile, dir);\n}\n\nstatic void _ccv_dpm_read_checkpoint(ccv_dpm_mixture_model_t* model, const char* dir)\n{\n\tFILE* r = fopen(dir, \"r\");\n\tif (!r)\n\t\treturn;\n\tint count;\n\tchar flag;\n\tfscanf(r, \"%c\", &flag);\n\tassert(flag == ',');\n\tfscanf(r, \"%d %d\", &model->count, &count);\n\tccv_dpm_root_classifier_t* root_classifier = (ccv_dpm_root_classifier_t*)ccmalloc(sizeof(ccv_dpm_root_classifier_t) * count);\n\tmemset(root_classifier, 0, sizeof(ccv_dpm_root_classifier_t) * count);\n\tint i, j, k;\n\tfor (i = 0; i < count; i++)\n\t{\n\t\tint rows, cols;\n\t\tfscanf(r, \"%d %d\", &rows, &cols);\n\t\tfscanf(r, \"%f %f %f %f\", &root_classifier[i].beta, &root_classifier[i].alpha[0], &root_classifier[i].alpha[1], &root_classifier[i].alpha[2]);\n\t\troot_classifier[i].root.w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, 0, 0);\n\t\tfor (j = 0; j < rows * cols * 31; j++)\n\t\t\tfscanf(r, \"%f\", &root_classifier[i].root.w->data.f32[j]);\n\t\tccv_make_matrix_immutable(root_classifier[i].root.w);\n\t\tfscanf(r, \"%d\", &root_classifier[i].count);\n\t\tif (root_classifier[i].count <= 0)\n\t\t{\n\t\t\troot_classifier[i].part = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tccv_dpm_part_classifier_t* part_classifier = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * root_classifier[i].count);\n\t\tfor (j = 0; j < root_classifier[i].count; j++)\n\t\t{\n\t\t\tfscanf(r, \"%d %d %d\", &part_classifier[j].x, &part_classifier[j].y, &part_classifier[j].z);\n\t\t\tfscanf(r, \"%lf %lf %lf %lf\", &part_classifier[j].dx, &part_classifier[j].dy, &part_classifier[j].dxx, &part_classifier[j].dyy);\n\t\t\tfscanf(r, \"%f %f %f %f %f %f\", &part_classifier[j].alpha[0], &part_classifier[j].alpha[1], &part_classifier[j].alpha[2], &part_classifier[j].alpha[3], &part_classifier[j].alpha[4], &part_classifier[j].alpha[5]);\n\t\t\tfscanf(r, \"%d %d %d\", &rows, &cols, &part_classifier[j].counterpart);\n\t\t\tpart_classifier[j].w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, 0, 0);\n\t\t\tfor (k = 0; k < rows * cols * 31; k++)\n\t\t\t\tfscanf(r, \"%f\", &part_classifier[j].w->data.f32[k]);\n\t\t\tccv_make_matrix_immutable(part_classifier[j].w);\n\t\t}\n\t\troot_classifier[i].part = part_classifier;\n\t}\n\tmodel->root = root_classifier;\n\tfclose(r);\n}\n\nstatic void _ccv_dpm_mixture_model_cleanup(ccv_dpm_mixture_model_t* model)\n{\n\t/* this is different because it doesn't compress to a continuous memory region */\n\tint i, j;\n\tfor (i = 0; i < model->count; i++)\n\t{\n\t\tccv_dpm_root_classifier_t* root_classifier = model->root + i;\n\t\tfor (j = 0; j < root_classifier->count; j++)\n\t\t{\n\t\t\tccv_dpm_part_classifier_t* part_classifier = root_classifier->part + j;\n\t\t\tccv_matrix_free(part_classifier->w);\n\t\t}\n\t\tif (root_classifier->count > 0)\n\t\t\tccfree(root_classifier->part);\n\t\tif (root_classifier->root.w != 0)\n\t\t\tccv_matrix_free(root_classifier->root.w);\n\t}\n\tccfree(model->root);\n\tmodel->count = 0;\n\tmodel->root = 0;\n}\n\nstatic const int _ccv_dpm_sym_lut[] = { 2, 3, 0, 1,\n\t\t\t\t\t\t\t\t\t\t4 + 0, 4 + 8, 4 + 7, 4 + 6, 4 + 5, 4 + 4, 4 + 3, 4 + 2, 4 + 1,\n\t\t\t\t\t\t\t\t\t\t13 + 9, 13 + 8, 13 + 7, 13 + 6, 13 + 5, 13 + 4, 13 + 3, 13 + 2, 13 + 1, 13, 13 + 17, 13 + 16, 13 + 15, 13 + 14, 13 + 13, 13 + 12, 13 + 11, 13 + 10 };\n\nstatic void _ccv_dpm_check_root_classifier_symmetry(ccv_dense_matrix_t* w)\n{\n\tassert(CCV_GET_CHANNEL(w->type) == 31 && CCV_GET_DATA_TYPE(w->type) == CCV_32F);\n\tfloat *w_ptr = w->data.f32;\n\tint i, j, k;\n\tfor (i = 0; i < w->rows; i++)\n\t{\n\t\tfor (j = 0; j < w->cols; j++)\n\t\t{\n\t\t\tfor (k = 0; k < 31; k++)\n\t\t\t{\n\t\t\t\tdouble v = fabs(w_ptr[j * 31 + k] - w_ptr[(w->cols - 1 - j) * 31 + _ccv_dpm_sym_lut[k]]);\n\t\t\t\tif (v > 0.002)\n\t\t\t\t\tprintf(\"symmetric violation at (%d, %d, %d), off by: %f\\n\", i, j, k, v);\n\t\t\t}\n\t\t}\n\t\tw_ptr += w->cols * 31;\n\t}\n}\n\ntypedef struct {\n\tint id;\n\tint count;\n\tfloat score;\n\tint x, y;\n\tfloat scale_x, scale_y;\n\tccv_dpm_part_classifier_t root;\n\tccv_dpm_part_classifier_t* part;\n} ccv_dpm_feature_vector_t;\n\nstatic void _ccv_dpm_collect_examples_randomly(gsl_rng* rng, ccv_array_t** negex, char** bgfiles, int bgnum, int negnum, int components, int* rows, int* cols, int grayscale)\n{\n\tint i, j;\n\tfor (i = 0; i < components; i++)\n\t\tnegex[i] = ccv_array_new(sizeof(ccv_dpm_feature_vector_t), negnum, 0);\n\tint mrows = rows[0], mcols = cols[0];\n\tfor (i = 1; i < components; i++)\n\t{\n\t\tmrows = ccv_max(mrows, rows[i]);\n\t\tmcols = ccv_max(mcols, cols[i]);\n\t}\n\tFLUSH(\" - generating negative examples for all models : 0 / %d\", negnum);\n\twhile (negex[0]->rnum < negnum)\n\t{\n\t\tdouble p = (double)negnum / (double)bgnum;\n\t\tfor (i = 0; i < bgnum; i++)\n\t\t\tif (gsl_rng_uniform(rng) < p)\n\t\t\t{\n\t\t\t\tccv_dense_matrix_t* image = 0;\n\t\t\t\tccv_read(bgfiles[i], &image, (grayscale ? CCV_IO_GRAY : 0) | CCV_IO_ANY_FILE);\n\t\t\t\tassert(image != 0);\n\t\t\t\tif (image->rows - mrows * CCV_DPM_WINDOW_SIZE < 0 ||\n\t\t\t\t\timage->cols - mcols * CCV_DPM_WINDOW_SIZE < 0)\n\t\t\t\t{\n\t\t\t\t\tccv_matrix_free(image);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tint y = gsl_rng_uniform_int(rng, image->rows - mrows * CCV_DPM_WINDOW_SIZE + 1);\n\t\t\t\tint x = gsl_rng_uniform_int(rng, image->cols - mcols * CCV_DPM_WINDOW_SIZE + 1);\n\t\t\t\tfor (j = 0; j < components; j++)\n\t\t\t\t{\n\t\t\t\t\tccv_dense_matrix_t* slice = 0;\n\t\t\t\t\tccv_slice(image, (ccv_matrix_t**)&slice, 0, y + ((mrows - rows[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2, x + ((mcols - cols[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2, rows[j] * CCV_DPM_WINDOW_SIZE, cols[j] * CCV_DPM_WINDOW_SIZE);\n\t\t\t\t\tassert(y + ((mrows - rows[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2 >= 0 &&\n\t\t\t\t\t\t   y + ((mrows - rows[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2 + rows[j] * CCV_DPM_WINDOW_SIZE <= image->rows &&\n\t\t\t\t\t\t   x + ((mcols - cols[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2 >= 0 &&\n\t\t\t\t\t\t   x + ((mcols - cols[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2 + cols[j] * CCV_DPM_WINDOW_SIZE <= image->cols);\n\t\t\t\t\tccv_dense_matrix_t* hog = 0;\n\t\t\t\t\tccv_hog(slice, &hog, 0, 9, CCV_DPM_WINDOW_SIZE);\n\t\t\t\t\tccv_matrix_free(slice);\n\t\t\t\t\tccv_dpm_feature_vector_t vector = {\n\t\t\t\t\t\t.id = j,\n\t\t\t\t\t\t.count = 0,\n\t\t\t\t\t\t.part = 0,\n\t\t\t\t\t};\n\t\t\t\t\tccv_make_matrix_mutable(hog);\n\t\t\t\t\tassert(hog->rows == rows[j] && hog->cols == cols[j] && CCV_GET_CHANNEL(hog->type) == 31 && CCV_GET_DATA_TYPE(hog->type) == CCV_32F);\n\t\t\t\t\tvector.root.w = hog;\n\t\t\t\t\tccv_array_push(negex[j], &vector);\n\t\t\t\t}\n\t\t\t\tccv_matrix_free(image);\n\t\t\t\tFLUSH(\" - generating negative examples for all models : %d / %d\", negex[0]->rnum, negnum);\n\t\t\t\tif (negex[0]->rnum >= negnum)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t}\n}\n\nstatic ccv_array_t* _ccv_dpm_summon_examples_by_rectangle(char** posfiles, ccv_rect_t* bboxes, int posnum, int id, int rows, int cols, int grayscale)\n{\n\tint i;\n\tFLUSH(\" - generating positive examples for model %d : 0 / %d\", id, posnum);\n\tccv_array_t* posv = ccv_array_new(sizeof(ccv_dpm_feature_vector_t), posnum, 0);\n\tfor (i = 0; i < posnum; i++)\n\t{\n\t\tccv_rect_t bbox = bboxes[i];\n\t\tint mcols = (int)(sqrtf(bbox.width * bbox.height * cols / (float)rows) + 0.5);\n\t\tint mrows = (int)(sqrtf(bbox.width * bbox.height * rows / (float)cols) + 0.5);\n\t\tbbox.x = bbox.x + (bbox.width - mcols) / 2;\n\t\tbbox.y = bbox.y + (bbox.height - mrows) / 2;\n\t\tbbox.width = mcols;\n\t\tbbox.height = mrows;\n\t\tccv_dpm_feature_vector_t vector = {\n\t\t\t.id = id,\n\t\t\t.count = 0,\n\t\t\t.part = 0,\n\t\t};\n\t\t// resolution is too low to be useful\n\t\tif (mcols * 2 < cols * CCV_DPM_WINDOW_SIZE || mrows * 2 < rows * CCV_DPM_WINDOW_SIZE)\n\t\t{\n\t\t\tvector.root.w = 0;\n\t\t\tccv_array_push(posv, &vector);\n\t\t\tcontinue;\n\t\t}\n\t\tccv_dense_matrix_t* image = 0;\n\t\tccv_read(posfiles[i], &image, (grayscale ? CCV_IO_GRAY : 0) | CCV_IO_ANY_FILE);\n\t\tassert(image != 0);\n\t\tccv_dense_matrix_t* up2x = 0;\n\t\tccv_sample_up(image, &up2x, 0, 0, 0);\n\t\tccv_matrix_free(image);\n\t\tccv_dense_matrix_t* slice = 0;\n\t\tccv_slice(up2x, (ccv_matrix_t**)&slice, 0, bbox.y * 2, bbox.x * 2, bbox.height * 2, bbox.width * 2);\n\t\tccv_matrix_free(up2x);\n\t\tccv_dense_matrix_t* resize = 0;\n\t\tccv_resample(slice, &resize, 0, rows * CCV_DPM_WINDOW_SIZE, cols * CCV_DPM_WINDOW_SIZE, CCV_INTER_AREA);\n\t\tccv_matrix_free(slice);\n\t\tccv_dense_matrix_t* hog = 0;\n\t\tccv_hog(resize, &hog, 0, 9, CCV_DPM_WINDOW_SIZE);\n\t\tccv_matrix_free(resize);\n\t\tccv_make_matrix_mutable(hog);\n\t\tassert(hog->rows == rows && hog->cols == cols && CCV_GET_CHANNEL(hog->type) == 31 && CCV_GET_DATA_TYPE(hog->type) == CCV_32F);\n\t\tvector.root.w = hog;\n\t\tccv_array_push(posv, &vector);\n\t\tFLUSH(\" - generating positive examples for model %d : %d / %d\", id, i + 1, posnum);\n\t}\n\treturn posv;\n}\n\nstatic void _ccv_dpm_initialize_root_classifier(gsl_rng* rng, ccv_dpm_root_classifier_t* root_classifier, int label, int cnum, int* poslabels, ccv_array_t* posex, int* neglabels, ccv_array_t* negex, double C, int symmetric, int grayscale)\n{\n\tint i, j, x, y, k, l;\n\tint cols = root_classifier->root.w->cols;\n\tint cols2c = (cols + 1) / 2;\n\tint rows = root_classifier->root.w->rows;\n\tprintf(\" - creating initial model %d at %dx%d\\n\", label + 1, cols, rows);\n\tstruct problem prob;\n\tprob.n = symmetric ? 31 * cols2c * rows + 1 : 31 * cols * rows + 1;\n\tprob.bias = symmetric ? 0.5 : 1.0; // for symmetric, since we only pass half features in, need to set bias to be half too\n\t// new version (1.91) of liblinear uses double instead of int (1.8) for prob.y, cannot cast for that.\n\tprob.y = malloc(sizeof(prob.y[0]) * (cnum + negex->rnum) * (!!symmetric + 1));\n\tprob.x = (struct feature_node**)malloc(sizeof(struct feature_node*) * (cnum + negex->rnum) * (!!symmetric + 1));\n\tFLUSH(\" - converting examples to liblinear format: %d / %d\", 0, (cnum + negex->rnum) * (!!symmetric + 1));\n\tl = 0;\n\tfor (i = 0; i < posex->rnum; i++)\n\t\tif (poslabels[i] == label)\n\t\t{\n\t\t\tccv_dense_matrix_t* hog = ((ccv_dpm_feature_vector_t*)ccv_array_get(posex, i))->root.w;\n\t\t\tif (!hog)\n\t\t\t\tcontinue;\n\t\t\tstruct feature_node* features;\n\t\t\tif (symmetric)\n\t\t\t{\n\t\t\t\tfeatures = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols2c * rows + 2));\n\t\t\t\tfloat* hptr = hog->data.f32;\n\t\t\t\tj = 0;\n\t\t\t\tfor (y = 0; y < rows; y++)\n\t\t\t\t{\n\t\t\t\t\tfor (x = 0; x < cols2c; x++)\n\t\t\t\t\t\tfor (k = 0; k < 31; k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfeatures[j].index = j + 1;\n\t\t\t\t\t\t\tfeatures[j].value = hptr[x * 31 + k];\n\t\t\t\t\t\t\t++j;\n\t\t\t\t\t\t}\n\t\t\t\t\thptr += hog->cols * 31;\n\t\t\t\t}\n\t\t\t\tfeatures[j].index = j + 1;\n\t\t\t\tfeatures[j].value = prob.bias;\n\t\t\t\tfeatures[j + 1].index = -1;\n\t\t\t\tprob.x[l] = features;\n\t\t\t\tprob.y[l] = 1;\n\t\t\t\t++l;\n\t\t\t\tfeatures = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols2c * rows + 2));\n\t\t\t\thptr = hog->data.f32;\n\t\t\t\tj = 0;\n\t\t\t\tfor (y = 0; y < rows; y++)\n\t\t\t\t{\n\t\t\t\t\tfor (x = 0; x < cols2c; x++)\n\t\t\t\t\t\tfor (k = 0; k < 31; k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfeatures[j].index = j + 1;\n\t\t\t\t\t\t\tfeatures[j].value = hptr[(cols - 1 - x) * 31 + _ccv_dpm_sym_lut[k]];\n\t\t\t\t\t\t\t++j;\n\t\t\t\t\t\t}\n\t\t\t\t\thptr += hog->cols * 31;\n\t\t\t\t}\n\t\t\t\tfeatures[j].index = j + 1;\n\t\t\t\tfeatures[j].value = prob.bias;\n\t\t\t\tfeatures[j + 1].index = -1;\n\t\t\t\tprob.x[l] = features;\n\t\t\t\tprob.y[l] = 1;\n\t\t\t\t++l;\n\t\t\t} else {\n\t\t\t\tfeatures = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols * rows + 2));\n\t\t\t\tfor (j = 0; j < rows * cols * 31; j++)\n\t\t\t\t{\n\t\t\t\t\tfeatures[j].index = j + 1;\n\t\t\t\t\tfeatures[j].value = hog->data.f32[j];\n\t\t\t\t}\n\t\t\t\tfeatures[31 * rows * cols].index = 31 * rows * cols + 1;\n\t\t\t\tfeatures[31 * rows * cols].value = prob.bias;\n\t\t\t\tfeatures[31 * rows * cols + 1].index = -1;\n\t\t\t\tprob.x[l] = features;\n\t\t\t\tprob.y[l] = 1;\n\t\t\t\t++l;\n\t\t\t}\n\t\t\tFLUSH(\" - converting examples to liblinear format: %d / %d\", l, (cnum + negex->rnum) * (!!symmetric + 1));\n\t\t}\n\tfor (i = 0; i < negex->rnum; i++)\n\t\tif (neglabels[i] == label)\n\t\t{\n\t\t\tccv_dense_matrix_t* hog = ((ccv_dpm_feature_vector_t*)ccv_array_get(negex, i))->root.w;\n\t\t\tstruct feature_node* features;\n\t\t\tif (symmetric)\n\t\t\t{\n\t\t\t\tfeatures = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols2c * rows + 2));\n\t\t\t\tfloat* hptr = hog->data.f32;\n\t\t\t\tj = 0;\n\t\t\t\tfor (y = 0; y < rows; y++)\n\t\t\t\t{\n\t\t\t\t\tfor (x = 0; x < cols2c; x++)\n\t\t\t\t\t\tfor (k = 0; k < 31; k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfeatures[j].index = j + 1;\n\t\t\t\t\t\t\tfeatures[j].value = hptr[x * 31 + k];\n\t\t\t\t\t\t\t++j;\n\t\t\t\t\t\t}\n\t\t\t\t\thptr += hog->cols * 31;\n\t\t\t\t}\n\t\t\t\tfeatures[j].index = j + 1;\n\t\t\t\tfeatures[j].value = prob.bias;\n\t\t\t\tfeatures[j + 1].index = -1;\n\t\t\t\tprob.x[l] = features;\n\t\t\t\tprob.y[l] = -1;\n\t\t\t\t++l;\n\t\t\t\tfeatures = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols2c * rows + 2));\n\t\t\t\thptr = hog->data.f32;\n\t\t\t\tj = 0;\n\t\t\t\tfor (y = 0; y < rows; y++)\n\t\t\t\t{\n\t\t\t\t\tfor (x = 0; x < cols2c; x++)\n\t\t\t\t\t\tfor (k = 0; k < 31; k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfeatures[j].index = j + 1;\n\t\t\t\t\t\t\tfeatures[j].value = hptr[(cols - 1 - x) * 31 + _ccv_dpm_sym_lut[k]];\n\t\t\t\t\t\t\t++j;\n\t\t\t\t\t\t}\n\t\t\t\t\thptr += hog->cols * 31;\n\t\t\t\t}\n\t\t\t\tfeatures[j].index = j + 1;\n\t\t\t\tfeatures[j].value = prob.bias;\n\t\t\t\tfeatures[j + 1].index = -1;\n\t\t\t\tprob.x[l] = features;\n\t\t\t\tprob.y[l] = -1;\n\t\t\t\t++l;\n\t\t\t} else {\n\t\t\t\tfeatures = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols * rows + 2));\n\t\t\t\tfor (j = 0; j < 31 * rows * cols; j++)\n\t\t\t\t{\n\t\t\t\t\tfeatures[j].index = j + 1;\n\t\t\t\t\tfeatures[j].value = hog->data.f32[j];\n\t\t\t\t}\n\t\t\t\tfeatures[31 * rows * cols].index = 31 * rows * cols + 1;\n\t\t\t\tfeatures[31 * rows * cols].value = prob.bias;\n\t\t\t\tfeatures[31 * rows * cols + 1].index = -1;\n\t\t\t\tprob.x[l] = features;\n\t\t\t\tprob.y[l] = -1;\n\t\t\t\t++l;\n\t\t\t}\n\t\t\tFLUSH(\" - converting examples to liblinear format: %d / %d\", l, (cnum + negex->rnum) * (!!symmetric + 1));\n\t\t}\n\tprob.l = l;\n\tprintf(\"\\n - generated %d examples with %d dimensions each\\n\"\n\t\t   \" - running liblinear for initial linear SVM model (L2-regularized, L1-loss)\\n\", prob.l, prob.n);\n\tstruct parameter linear_parameters = { .solver_type = L2R_L1LOSS_SVC_DUAL,\n\t\t\t\t\t\t\t\t\t\t   .eps = 1e-1,\n\t\t\t\t\t\t\t\t\t\t   .C = C,\n\t\t\t\t\t\t\t\t\t\t   .nr_weight = 0,\n\t\t\t\t\t\t\t\t\t\t   .weight_label = 0,\n\t\t\t\t\t\t\t\t\t\t   .weight = 0 };\n\tconst char* err = check_parameter(&prob, &linear_parameters);\n\tif (err)\n\t{\n\t\tprintf(\" - ERROR: cannot pass check parameter: %s\\n\", err);\n\t\texit(-1);\n\t}\n\tstruct model* linear = train(&prob, &linear_parameters);\n\tassert(linear != 0);\n\tprintf(\" - model->label[0]: %d, model->nr_class: %d, model->nr_feature: %d\\n\", linear->label[0], linear->nr_class, linear->nr_feature);\n\tif (symmetric)\n\t{\n\t\tfloat* wptr = root_classifier->root.w->data.f32;\n\t\tfor (y = 0; y < rows; y++)\n\t\t{\n\t\t\tfor (x = 0; x < cols2c; x++)\n\t\t\t\tfor (k = 0; k < 31; k++)\n\t\t\t\t\twptr[(cols - 1 - x) * 31 + _ccv_dpm_sym_lut[k]] = wptr[x * 31 + k] = linear->w[(y * cols2c + x) * 31 + k];\n\t\t\twptr += cols * 31;\n\t\t}\n\t\t// since for symmetric, lsvm only computed half features, to compensate that, we doubled the constant.\n\t\troot_classifier->beta = linear->w[31 * rows * cols2c] * 2.0;\n\t} else {\n\t\tfor (j = 0; j < 31 * rows * cols; j++)\n\t\t\troot_classifier->root.w->data.f32[j] = linear->w[j];\n\t\troot_classifier->beta = linear->w[31 * rows * cols];\n\t}\n\tfree_and_destroy_model(&linear);\n\tfree(prob.y);\n\tfor (j = 0; j < prob.l; j++)\n\t\tfree(prob.x[j]);\n\tfree(prob.x);\n\tccv_make_matrix_immutable(root_classifier->root.w);\n}\n\nstatic void _ccv_dpm_initialize_part_classifiers(ccv_dpm_root_classifier_t* root_classifier, int parts, int symmetric)\n{\n\tint i, j, k, x, y;\n\tccv_dense_matrix_t* w = 0;\n\tccv_sample_up(root_classifier->root.w, &w, 0, 0, 0);\n\tccv_make_matrix_mutable(w);\n\troot_classifier->count = parts;\n\troot_classifier->part = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * parts);\n\tmemset(root_classifier->part, 0, sizeof(ccv_dpm_part_classifier_t) * parts);\n\tdouble area = w->rows * w->cols / (double)parts;\n\tfor (i = 0; i < parts;)\n\t{\n\t\tccv_dpm_part_classifier_t* part_classifier = root_classifier->part + i;\n\t\tint dx = 0, dy = 0, dw = 0, dh = 0, sym = 0;\n\t\tdouble dsum = -1.0; // absolute value, thus, -1.0 is enough\n#define slice_and_update_if_needed(y, x, l, n, s) \\\n\t\t{ \\\n\t\t\tccv_dense_matrix_t* slice = 0; \\\n\t\t\tccv_slice(w, (ccv_matrix_t**)&slice, 0, y, x, l, n); \\\n\t\t\tdouble sum = ccv_sum(slice, CCV_UNSIGNED) / (double)(l * n); \\\n\t\t\tif (sum > dsum) \\\n\t\t\t{ \\\n\t\t\t\tdsum = sum; \\\n\t\t\t\tdx = x; \\\n\t\t\t\tdy = y; \\\n\t\t\t\tdw = n; \\\n\t\t\t\tdh = l; \\\n\t\t\t\tsym = s; \\\n\t\t\t} \\\n\t\t\tccv_matrix_free(slice); \\\n\t\t}\n\t\tfor (j = 1; (j < area + 1) && (j * 3 <= w->rows * 2); j++)\n\t\t{\n\t\t\tk = (int)(area / j + 0.5);\n\t\t\tif (k < 1 || k * 3 > w->cols * 2)\n\t\t\t\tcontinue;\n\t\t\tif (j > k * 2 || k > j * 2)\n\t\t\t\tcontinue;\n\t\t\tif (symmetric)\n\t\t\t{\n\t\t\t\tif (k % 2 == w->cols % 2) // can be symmetric in horizontal center\n\t\t\t\t{\n\t\t\t\t\tx = (w->cols - k) / 2;\n\t\t\t\t\tfor (y = 0; y < w->rows - j + 1; y++)\n\t\t\t\t\t\tslice_and_update_if_needed(y, x, j, k, 0);\n\t\t\t\t}\n\t\t\t\tif (i < parts - 1) // have 2 locations\n\t\t\t\t{\n\t\t\t\t\tfor (y = 0; y < w->rows - j + 1; y++)\n\t\t\t\t\t\tfor (x = 0; x <= w->cols / 2 - k /* to avoid overlapping */; x++)\n\t\t\t\t\t\t\tslice_and_update_if_needed(y, x, j, k, 1);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (y = 0; y < w->rows - j + 1; y++)\n\t\t\t\t\tfor (x = 0; x < w->cols - k + 1; x++)\n\t\t\t\t\t\tslice_and_update_if_needed(y, x, j, k, 0);\n\t\t\t}\n\t\t}\n\t\tprintf(\" ---- part %d(%d) %dx%d at (%d,%d), entropy: %lf\\n\", i + 1, parts, dw, dh, dx, dy, dsum);\n\t\tpart_classifier->dx = 0;\n\t\tpart_classifier->dy = 0;\n\t\tpart_classifier->dxx = 0.1f;\n\t\tpart_classifier->dyy = 0.1f;\n\t\tpart_classifier->x = dx;\n\t\tpart_classifier->y = dy;\n\t\tpart_classifier->z = 1;\n\t\tpart_classifier->w = 0;\n\t\tccv_slice(w, (ccv_matrix_t**)&part_classifier->w, 0, dy, dx, dh, dw);\n\t\tccv_make_matrix_immutable(part_classifier->w);\n\t\t/* clean up the region we selected */\n\t\tfloat* w_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | 31, w, dy, dx, 0);\n\t\tfor (y = 0; y < dh; y++)\n\t\t{\n\t\t\tfor (x = 0; x < dw * 31; x++)\n\t\t\t\tw_ptr[x] = 0;\n\t\t\tw_ptr += w->cols * 31;\n\t\t}\n\t\ti++;\n\t\tif (symmetric && sym) // add counter-part\n\t\t{\n\t\t\tdx = w->cols - (dx + dw);\n\t\t\tprintf(\" ---- part %d(%d) %dx%d at (%d,%d), entropy: %lf\\n\", i + 1, parts, dw, dh, dx, dy, dsum);\n\t\t\tpart_classifier[1].dx = 0;\n\t\t\tpart_classifier[1].dy = 0;\n\t\t\tpart_classifier[1].dxx = 0.1f;\n\t\t\tpart_classifier[1].dyy = 0.1f;\n\t\t\tpart_classifier[1].x = dx;\n\t\t\tpart_classifier[1].y = dy;\n\t\t\tpart_classifier[1].z = 1;\n\t\t\tpart_classifier[1].w = 0;\n\t\t\tccv_slice(w, (ccv_matrix_t**)&part_classifier[1].w, 0, dy, dx, dh, dw);\n\t\t\tccv_make_matrix_immutable(part_classifier[1].w);\n\t\t\t/* clean up the region we selected */\n\t\t\tfloat* w_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | 31, w, dy, dx, 0);\n\t\t\tfor (y = 0; y < dh; y++)\n\t\t\t{\n\t\t\t\tfor (x = 0; x < dw * 31; x++)\n\t\t\t\t\tw_ptr[x] = 0;\n\t\t\t\tw_ptr += w->cols * 31;\n\t\t\t}\n\t\t\tpart_classifier[0].counterpart = i;\n\t\t\tpart_classifier[1].counterpart = i - 1;\n\t\t\ti++;\n\t\t} else {\n\t\t\tpart_classifier->counterpart = -1;\n\t\t}\n\t}\n\tccv_matrix_free(w);\n}\n\nstatic void _ccv_dpm_initialize_feature_vector_on_pattern(ccv_dpm_feature_vector_t* vector, ccv_dpm_root_classifier_t* root, int id)\n{\n\tint i;\n\tvector->id = id;\n\tvector->count = root->count;\n\tvector->part = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * root->count);\n\tvector->root.w = ccv_dense_matrix_new(root->root.w->rows, root->root.w->cols, CCV_32F | 31, 0, 0);\n\tfor (i = 0; i < vector->count; i++)\n\t{\n\t\tvector->part[i].x = root->part[i].x;\n\t\tvector->part[i].y = root->part[i].y;\n\t\tvector->part[i].z = root->part[i].z;\n\t\tvector->part[i].w = ccv_dense_matrix_new(root->part[i].w->rows, root->part[i].w->cols, CCV_32F | 31, 0, 0);\n\t}\n}\n\nstatic void _ccv_dpm_feature_vector_cleanup(ccv_dpm_feature_vector_t* vector)\n{\n\tint i;\n\tif (vector->root.w)\n\t\tccv_matrix_free(vector->root.w);\n\tfor (i = 0; i < vector->count; i++)\n\t\tccv_matrix_free(vector->part[i].w);\n\tif (vector->part)\n\t\tccfree(vector->part);\n}\n\nstatic void _ccv_dpm_feature_vector_free(ccv_dpm_feature_vector_t* vector)\n{\n\t_ccv_dpm_feature_vector_cleanup(vector);\n\tccfree(vector);\n}\n\nstatic double _ccv_dpm_vector_score(ccv_dpm_mixture_model_t* model, ccv_dpm_feature_vector_t* v)\n{\n\tif (v->id < 0 || v->id >= model->count)\n\t\treturn 0;\n\tccv_dpm_root_classifier_t* root_classifier = model->root + v->id;\n\tdouble score = root_classifier->beta;\n\tint i, k, ch = CCV_GET_CHANNEL(v->root.w->type);\n\tassert(ch == 31);\n\tfloat *vptr = v->root.w->data.f32;\n\tfloat *wptr = root_classifier->root.w->data.f32;\n\tfor (i = 0; i < v->root.w->rows * v->root.w->cols * ch; i++)\n\t\tscore += wptr[i] * vptr[i];\n\tassert(v->count == root_classifier->count || (v->count == 0 && v->part == 0));\n\tfor (k = 0; k < v->count; k++)\n\t{\n\t\tccv_dpm_part_classifier_t* part_classifier = root_classifier->part + k;\n\t\tccv_dpm_part_classifier_t* part_vector = v->part + k;\n\t\tscore -= part_classifier->dx * part_vector->dx;\n\t\tscore -= part_classifier->dxx * part_vector->dxx;\n\t\tscore -= part_classifier->dy * part_vector->dy;\n\t\tscore -= part_classifier->dyy * part_vector->dyy;\n\t\tvptr = part_vector->w->data.f32;\n\t\twptr = part_classifier->w->data.f32;\n\t\tfor (i = 0; i < part_vector->w->rows * part_vector->w->cols * ch; i++)\n\t\t\tscore += wptr[i] * vptr[i];\n\t}\n\treturn score;\n}\n\nstatic void _ccv_dpm_collect_feature_vector(ccv_dpm_feature_vector_t* v, float score, int x, int y, ccv_dense_matrix_t* pyr, ccv_dense_matrix_t* detail, ccv_dense_matrix_t** dx, ccv_dense_matrix_t** dy)\n{\n\tv->score = score;\n\tv->x = x;\n\tv->y = y;\n\tccv_zero(v->root.w);\n\tint rwh = (v->root.w->rows - 1) / 2, rww = (v->root.w->cols - 1) / 2;\n\tint i, ix, iy, ch = CCV_GET_CHANNEL(v->root.w->type);\n\tfloat* h_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | ch, pyr, y - rwh, x - rww, 0);\n\tfloat* w_ptr = v->root.w->data.f32;\n\tfor (iy = 0; iy < v->root.w->rows; iy++)\n\t{\n\t\tmemcpy(w_ptr, h_ptr, v->root.w->cols * ch * sizeof(float));\n\t\th_ptr += pyr->cols * ch;\n\t\tw_ptr += v->root.w->cols * ch;\n\t}\n\tfor (i = 0; i < v->count; i++)\n\t{\n\t\tccv_dpm_part_classifier_t* part = v->part + i;\n\t\tint pww = (part->w->cols - 1) / 2, pwh = (part->w->rows - 1) / 2;\n\t\tint offy = part->y + pwh - rwh * 2;\n\t\tint offx = part->x + pww - rww * 2;\n\t\tiy = ccv_clamp(y * 2 + offy, pwh, detail->rows - part->w->rows + pwh);\n\t\tix = ccv_clamp(x * 2 + offx, pww, detail->cols - part->w->cols + pww);\n\t\tint ry = ccv_get_dense_matrix_cell_value_by(CCV_32S | CCV_C1, dy[i], iy, ix, 0);\n\t\tint rx = ccv_get_dense_matrix_cell_value_by(CCV_32S | CCV_C1, dx[i], iy, ix, 0);\n\t\tpart->dx = rx; // I am not sure if I need to flip the sign or not (confirmed, it should be this way)\n\t\tpart->dy = ry;\n\t\tpart->dxx = rx * rx;\n\t\tpart->dyy = ry * ry;\n\t\t// deal with out-of-bound error\n\t\tint start_y = ccv_max(0, iy - ry - pwh);\n\t\tassert(start_y < detail->rows);\n\t\tint start_x = ccv_max(0, ix - rx - pww);\n\t\tassert(start_x < detail->cols);\n\t\tint end_y = ccv_min(detail->rows, iy - ry - pwh + part->w->rows);\n\t\tassert(end_y >= 0);\n\t\tint end_x = ccv_min(detail->cols, ix - rx - pww + part->w->cols);\n\t\tassert(end_x >= 0);\n\t\th_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | ch, detail, start_y, start_x, 0);\n\t\tccv_zero(v->part[i].w);\n\t\tw_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | ch, part->w, start_y - (iy - ry - pwh), start_x - (ix - rx - pww), 0);\n\t\tfor (iy = start_y; iy < end_y; iy++)\n\t\t{\n\t\t\tmemcpy(w_ptr, h_ptr, (end_x - start_x) * ch * sizeof(float));\n\t\t\th_ptr += detail->cols * ch;\n\t\t\tw_ptr += part->w->cols * ch;\n\t\t}\n\t}\n}\n\nstatic ccv_dpm_feature_vector_t* _ccv_dpm_collect_best(ccv_dense_matrix_t* image, ccv_dpm_mixture_model_t* model, ccv_rect_t bbox, double overlap, ccv_dpm_param_t params)\n{\n\tint i, j, k, x, y;\n\tdouble scale = pow(2.0, 1.0 / (params.interval + 1.0));\n\tint next = params.interval + 1;\n\tint scale_upto = _ccv_dpm_scale_upto(image, &model, 1, params.interval);\n\tif (scale_upto < 0)\n\t\treturn 0;\n\tccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca((scale_upto + next * 2) * sizeof(ccv_dense_matrix_t*));\n\t_ccv_dpm_feature_pyramid(image, pyr, scale_upto, params.interval);\n\tfloat best = -FLT_MAX;\n\tccv_dpm_feature_vector_t* v = 0;\n\tfor (i = 0; i < model->count; i++)\n\t{\n\t\tccv_dpm_root_classifier_t* root_classifier = model->root + i;\n\t\tdouble scale_x = 1.0;\n\t\tdouble scale_y = 1.0;\n\t\tfor (j = next; j < scale_upto + next * 2; j++)\n\t\t{\n\t\t\tccv_size_t size = ccv_size((int)(root_classifier->root.w->cols * CCV_DPM_WINDOW_SIZE * scale_x + 0.5), (int)(root_classifier->root.w->rows * CCV_DPM_WINDOW_SIZE * scale_y + 0.5));\n\t\t\tif (ccv_min((double)(size.width * size.height), (double)(bbox.width * bbox.height)) / \n\t\t\t\tccv_max((double)(bbox.width * bbox.height), (double)(size.width * size.height)) < overlap)\n\t\t\t{\n\t\t\t\tscale_x *= scale;\n\t\t\t\tscale_y *= scale;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tccv_dense_matrix_t* root_feature = 0;\n\t\t\tccv_dense_matrix_t* part_feature[CCV_DPM_PART_MAX];\n\t\t\tccv_dense_matrix_t* dx[CCV_DPM_PART_MAX];\n\t\t\tccv_dense_matrix_t* dy[CCV_DPM_PART_MAX];\n\t\t\t_ccv_dpm_compute_score(root_classifier, pyr[j], pyr[j - next], &root_feature, part_feature, dx, dy);\n\t\t\tint rwh = (root_classifier->root.w->rows - 1) / 2, rww = (root_classifier->root.w->cols - 1) / 2;\n\t\t\tint rwh_1 = root_classifier->root.w->rows / 2, rww_1 = root_classifier->root.w->cols / 2;\n\t\t\tfloat* f_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | CCV_C1, root_feature, rwh, 0, 0);\n\t\t\tfor (y = rwh; y < root_feature->rows - rwh_1; y++)\n\t\t\t{\n\t\t\t\tfor (x = rww; x < root_feature->cols - rww_1; x++)\n\t\t\t\t{\n\t\t\t\t\tccv_rect_t rect = ccv_rect((int)((x - rww) * CCV_DPM_WINDOW_SIZE * scale_x + 0.5), (int)((y - rwh) * CCV_DPM_WINDOW_SIZE * scale_y + 0.5), (int)(root_classifier->root.w->cols * CCV_DPM_WINDOW_SIZE * scale_x + 0.5), (int)(root_classifier->root.w->rows * CCV_DPM_WINDOW_SIZE * scale_y + 0.5));\n\t\t\t\t\tif ((double)(ccv_max(0, ccv_min(rect.x + rect.width, bbox.x + bbox.width) - ccv_max(rect.x, bbox.x)) *\n\t\t\t\t\t\t\t\t ccv_max(0, ccv_min(rect.y + rect.height, bbox.y + bbox.height) - ccv_max(rect.y, bbox.y))) /\n\t\t\t\t\t\t(double)ccv_max(rect.width * rect.height, bbox.width * bbox.height) >= overlap && f_ptr[x] > best)\n\t\t\t\t\t{\n\t\t\t\t\t\t// initialize v\n\t\t\t\t\t\tif (v == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tv = (ccv_dpm_feature_vector_t*)ccmalloc(sizeof(ccv_dpm_feature_vector_t));\n\t\t\t\t\t\t\t_ccv_dpm_initialize_feature_vector_on_pattern(v, root_classifier, i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// if it is another kind, cleanup and reinitialize\n\t\t\t\t\t\tif (v->id != i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t_ccv_dpm_feature_vector_cleanup(v);\n\t\t\t\t\t\t\t_ccv_dpm_initialize_feature_vector_on_pattern(v, root_classifier, i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_ccv_dpm_collect_feature_vector(v, f_ptr[x] + root_classifier->beta, x, y, pyr[j], pyr[j - next], dx, dy);\n\t\t\t\t\t\tv->scale_x = scale_x;\n\t\t\t\t\t\tv->scale_y = scale_y;\n\t\t\t\t\t\tbest = f_ptr[x];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tf_ptr += root_feature->cols;\n\t\t\t}\n\t\t\tfor (k = 0; k < root_classifier->count; k++)\n\t\t\t{\n\t\t\t\tccv_matrix_free(part_feature[k]);\n\t\t\t\tccv_matrix_free(dx[k]);\n\t\t\t\tccv_matrix_free(dy[k]);\n\t\t\t}\n\t\t\tccv_matrix_free(root_feature);\n\t\t\tscale_x *= scale;\n\t\t\tscale_y *= scale;\n\t\t}\n\t}\n\tfor (i = 0; i < scale_upto + next * 2; i++)\n\t\tccv_matrix_free(pyr[i]);\n\treturn v;\n}\n\nstatic ccv_array_t* _ccv_dpm_collect_all(gsl_rng* rng, ccv_dense_matrix_t* image, ccv_dpm_mixture_model_t* model, ccv_dpm_param_t params, float threshold)\n{\n\tint i, j, k, x, y;\n\tdouble scale = pow(2.0, 1.0 / (params.interval + 1.0));\n\tint next = params.interval + 1;\n\tint scale_upto = _ccv_dpm_scale_upto(image, &model, 1, params.interval);\n\tif (scale_upto < 0)\n\t\treturn 0;\n\tccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca((scale_upto + next * 2) * sizeof(ccv_dense_matrix_t*));\n\t_ccv_dpm_feature_pyramid(image, pyr, scale_upto, params.interval);\n\tccv_array_t* av = ccv_array_new(sizeof(ccv_dpm_feature_vector_t*), 64, 0);\n\tint enough = 64 / model->count;\n\tint* order = (int*)alloca(sizeof(int) * model->count);\n\tfor (i = 0; i < model->count; i++)\n\t\torder[i] = i;\n\tgsl_ran_shuffle(rng, order, model->count, sizeof(int));\n\tfor (i = 0; i < model->count; i++)\n\t{\n\t\tccv_dpm_root_classifier_t* root_classifier = model->root + order[i];\n\t\tdouble scale_x = 1.0;\n\t\tdouble scale_y = 1.0;\n\t\tfor (j = next; j < scale_upto + next * 2; j++)\n\t\t{\n\t\t\tccv_dense_matrix_t* root_feature = 0;\n\t\t\tccv_dense_matrix_t* part_feature[CCV_DPM_PART_MAX];\n\t\t\tccv_dense_matrix_t* dx[CCV_DPM_PART_MAX];\n\t\t\tccv_dense_matrix_t* dy[CCV_DPM_PART_MAX];\n\t\t\t_ccv_dpm_compute_score(root_classifier, pyr[j], pyr[j - next], &root_feature, part_feature, dx, dy);\n\t\t\tint rwh = (root_classifier->root.w->rows - 1) / 2, rww = (root_classifier->root.w->cols - 1) / 2;\n\t\t\tint rwh_1 = root_classifier->root.w->rows / 2, rww_1 = root_classifier->root.w->cols / 2;\n\t\t\tfloat* f_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | CCV_C1, root_feature, rwh, 0, 0);\n\t\t\tfor (y = rwh; y < root_feature->rows - rwh_1; y++)\n\t\t\t{\n\t\t\t\tfor (x = rww; x < root_feature->cols - rww_1; x++)\n\t\t\t\t\tif (f_ptr[x] + root_classifier->beta > threshold)\n\t\t\t\t\t{\n\t\t\t\t\t\t// initialize v\n\t\t\t\t\t\tccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccmalloc(sizeof(ccv_dpm_feature_vector_t));\n\t\t\t\t\t\t_ccv_dpm_initialize_feature_vector_on_pattern(v, root_classifier, order[i]);\n\t\t\t\t\t\t_ccv_dpm_collect_feature_vector(v, f_ptr[x] + root_classifier->beta, x, y, pyr[j], pyr[j - next], dx, dy);\n\t\t\t\t\t\tv->scale_x = scale_x;\n\t\t\t\t\t\tv->scale_y = scale_y;\n\t\t\t\t\t\tccv_array_push(av, &v);\n\t\t\t\t\t\tif (av->rnum >= enough * (i + 1))\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tf_ptr += root_feature->cols;\n\t\t\t\tif (av->rnum >= enough * (i + 1))\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfor (k = 0; k < root_classifier->count; k++)\n\t\t\t{\n\t\t\t\tccv_matrix_free(part_feature[k]);\n\t\t\t\tccv_matrix_free(dx[k]);\n\t\t\t\tccv_matrix_free(dy[k]);\n\t\t\t}\n\t\t\tccv_matrix_free(root_feature);\n\t\t\tscale_x *= scale;\n\t\t\tscale_y *= scale;\n\t\t\tif (av->rnum >= enough * (i + 1))\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tfor (i = 0; i < scale_upto + next * 2; i++)\n\t\tccv_matrix_free(pyr[i]);\n\treturn av;\n}\n\nstatic void _ccv_dpm_collect_from_background(ccv_array_t* av, gsl_rng* rng, char** bgfiles, int bgnum, ccv_dpm_mixture_model_t* model, ccv_dpm_new_param_t params, float threshold)\n{\n\tint i, j;\n\tint* order = (int*)ccmalloc(sizeof(int) * bgnum);\n\tfor (i = 0; i < bgnum; i++)\n\t\torder[i] = i;\n\tgsl_ran_shuffle(rng, order, bgnum, sizeof(int));\n\tfor (i = 0; i < bgnum; i++)\n\t{\n\t\tFLUSH(\" - collecting negative examples -- (%d%%)\", av->rnum * 100 / params.negative_cache_size);\n\t\tccv_dense_matrix_t* image = 0;\n\t\tccv_read(bgfiles[order[i]], &image, (params.grayscale ? CCV_IO_GRAY : 0) | CCV_IO_ANY_FILE);\n\t\tccv_array_t* at = _ccv_dpm_collect_all(rng, image, model, params.detector, threshold);\n\t\tif (at)\n\t\t{\n\t\t\tfor (j = 0; j < at->rnum; j++)\n\t\t\t\tccv_array_push(av, ccv_array_get(at, j));\n\t\t\tccv_array_free(at);\n\t\t}\n\t\tccv_matrix_free(image);\n\t\tif (av->rnum >= params.negative_cache_size)\n\t\t\tbreak;\n\t}\n\tccfree(order);\n}\n\nstatic void _ccv_dpm_initialize_root_rectangle_estimator(ccv_dpm_mixture_model_t* model, char** posfiles, ccv_rect_t* bboxes, int posnum, ccv_dpm_new_param_t params)\n{\n\tint i, j, k, c;\n\tccv_dpm_feature_vector_t** posv = (ccv_dpm_feature_vector_t**)ccmalloc(sizeof(ccv_dpm_feature_vector_t*) * posnum);\n\tint* num_per_model = (int*)alloca(sizeof(int) * model->count);\n\tmemset(num_per_model, 0, sizeof(int) * model->count);\n\tFLUSH(\" - collecting responses from positive examples : 0%%\");\n\tfor (i = 0; i < posnum; i++)\n\t{\n\t\tFLUSH(\" - collecting responses from positive examples : %d%%\", i * 100 / posnum);\n\t\tccv_dense_matrix_t* image = 0;\n\t\tccv_read(posfiles[i], &image, (params.grayscale ? CCV_IO_GRAY : 0) | CCV_IO_ANY_FILE);\n\t\tposv[i] = _ccv_dpm_collect_best(image, model, bboxes[i], params.include_overlap, params.detector);\n\t\tif (posv[i])\n\t\t\t++num_per_model[posv[i]->id];\n\t\tccv_matrix_free(image);\n\t}\n\t// this will estimate new x, y, and scale\n\tprintf(\"\\n - linear regression for x, y, and scale drifting\\n\");\n\tfor (i = 0; i < model->count; i++)\n\t{\n\t\tccv_dpm_root_classifier_t* root_classifier = model->root + i;\n\t\tgsl_matrix* X = gsl_matrix_alloc(num_per_model[i], root_classifier->count * 2 + 1);\n\t\tgsl_vector* y[3];\n\t\ty[0] = gsl_vector_alloc(num_per_model[i]);\n\t\ty[1] = gsl_vector_alloc(num_per_model[i]);\n\t\ty[2] = gsl_vector_alloc(num_per_model[i]);\n\t\tgsl_vector* z = gsl_vector_alloc(root_classifier->count * 2 + 1);\n\t\tgsl_matrix* cov = gsl_matrix_alloc(root_classifier->count * 2 + 1, root_classifier->count * 2 + 1);;\n\t\tc = 0;\n\t\tfor (j = 0; j < posnum; j++)\n\t\t{\n\t\t\tccv_dpm_feature_vector_t* v = posv[j];\n\t\t\tif (v && v->id == i)\n\t\t\t{\n\t\t\t\tgsl_matrix_set(X, c, 0, 1.0);\n\t\t\t\tfor (k = 0; k < v->count; k++)\n\t\t\t\t{\n\t\t\t\t\tgsl_matrix_set(X, c, k * 2 + 1, v->part[k].dx);\n\t\t\t\t\tgsl_matrix_set(X, c, k * 2 + 2, v->part[k].dy);\n\t\t\t\t}\n\t\t\t\tccv_rect_t bbox = bboxes[j];\n\t\t\t\tgsl_vector_set(y[0], c, (bbox.x + bbox.width * 0.5) / (v->scale_x * CCV_DPM_WINDOW_SIZE) - v->x);\n\t\t\t\tgsl_vector_set(y[1], c, (bbox.y + bbox.height * 0.5) / (v->scale_y * CCV_DPM_WINDOW_SIZE) - v->y);\n\t\t\t\tgsl_vector_set(y[2], c, sqrt((bbox.width * bbox.height) / (root_classifier->root.w->rows * v->scale_x * CCV_DPM_WINDOW_SIZE * root_classifier->root.w->cols * v->scale_y * CCV_DPM_WINDOW_SIZE)) - 1.0);\n\t\t\t\t++c;\n\t\t\t}\n\t\t}\n\t\tgsl_multifit_linear_workspace* workspace = gsl_multifit_linear_alloc(num_per_model[i], root_classifier->count * 2 + 1);\n\t\tdouble chisq;\n\t\tfor (j = 0; j < 3; j++)\n\t\t{\n\t\t\tgsl_multifit_linear(X, y[j], z, cov, &chisq, workspace);\n\t\t\troot_classifier->alpha[j] = params.discard_estimating_constant ? 0 : gsl_vector_get(z, 0);\n\t\t\tfor (k = 0; k < root_classifier->count; k++)\n\t\t\t{\n\t\t\t\tccv_dpm_part_classifier_t* part_classifier = root_classifier->part + k;\n\t\t\t\tpart_classifier->alpha[j * 2] = gsl_vector_get(z, k * 2 + 1);\n\t\t\t\tpart_classifier->alpha[j * 2 + 1] = gsl_vector_get(z, k * 2 + 2);\n\t\t\t}\n\t\t}\n\t\tgsl_multifit_linear_free(workspace);\n\t\tgsl_matrix_free(cov);\n\t\tgsl_vector_free(z);\n\t\tgsl_vector_free(y[0]);\n\t\tgsl_vector_free(y[1]);\n\t\tgsl_vector_free(y[2]);\n\t\tgsl_matrix_free(X);\n\t}\n\tfor (i = 0; i < posnum; i++)\n\t\tif (posv[i])\n\t\t\t_ccv_dpm_feature_vector_free(posv[i]);\n\tccfree(posv);\n}\n\nstatic void _ccv_dpm_regularize_mixture_model(ccv_dpm_mixture_model_t* model, int i, double regz)\n{\n\tint k;\n\tccv_dpm_root_classifier_t* root_classifier = model->root + i;\n\tint ch = CCV_GET_CHANNEL(root_classifier->root.w->type);\n\tccv_make_matrix_mutable(root_classifier->root.w);\n\tfloat *wptr = root_classifier->root.w->data.f32;\n\tfor (i = 0; i < root_classifier->root.w->rows * root_classifier->root.w->cols * ch; i++)\n\t\twptr[i] -= regz * wptr[i];\n\tccv_make_matrix_immutable(root_classifier->root.w);\n\troot_classifier->beta -= regz * root_classifier->beta;\n\tfor (k = 0; k < root_classifier->count; k++)\n\t{\n\t\tccv_dpm_part_classifier_t* part_classifier = root_classifier->part + k;\n\t\tccv_make_matrix_mutable(part_classifier->w);\n\t\twptr = part_classifier->w->data.f32;\n\t\tfor (i = 0; i < part_classifier->w->rows * part_classifier->w->cols * ch; i++)\n\t\t\twptr[i] -= regz * wptr[i];\n\t\tccv_make_matrix_immutable(part_classifier->w);\n\t\tpart_classifier->dx -= regz * part_classifier->dx;\n\t\tpart_classifier->dxx -= regz * part_classifier->dxx;\n\t\tpart_classifier->dy -= regz * part_classifier->dy;\n\t\tpart_classifier->dyy -= regz * part_classifier->dyy;\n\t\tpart_classifier->dxx = ccv_max(0.01, part_classifier->dxx);\n\t\tpart_classifier->dyy = ccv_max(0.01, part_classifier->dyy);\n\t}\n}\n\nstatic void _ccv_dpm_stochastic_gradient_descent(ccv_dpm_mixture_model_t* model, ccv_dpm_feature_vector_t* v, double y, double alpha, double Cn, int symmetric)\n{\n\tif (v->id < 0 || v->id >= model->count)\n\t\treturn;\n\tccv_dpm_root_classifier_t* root_classifier = model->root + v->id;\n\tint i, j, k, c, ch = CCV_GET_CHANNEL(v->root.w->type);\n\tassert(ch == 31);\n\tassert(v->root.w->rows == root_classifier->root.w->rows && v->root.w->cols == root_classifier->root.w->cols);\n\tfloat *vptr = v->root.w->data.f32;\n\tccv_make_matrix_mutable(root_classifier->root.w);\n\tfloat *wptr = root_classifier->root.w->data.f32;\n\tif (symmetric)\n\t{\n\t\tfor (i = 0; i < v->root.w->rows; i++)\n\t\t{\n\t\t\tfor (j = 0; j < v->root.w->cols; j++)\n\t\t\t\tfor (c = 0; c < ch; c++)\n\t\t\t\t{\n\t\t\t\t\twptr[j * ch + c] += alpha * y * Cn * vptr[j * ch + c];\n\t\t\t\t\twptr[j * ch + c] += alpha * y * Cn * vptr[(v->root.w->cols - 1 - j) * ch + _ccv_dpm_sym_lut[c]];\n\t\t\t\t}\n\t\t\tvptr += v->root.w->cols * ch;\n\t\t\twptr += root_classifier->root.w->cols * ch;\n\t\t}\n\t\troot_classifier->beta += alpha * y * Cn * 2.0;\n\t} else {\n\t\tfor (i = 0; i < v->root.w->rows * v->root.w->cols * ch; i++)\n\t\t\twptr[i] += alpha * y * Cn * vptr[i];\n\t\troot_classifier->beta += alpha * y * Cn;\n\t}\n\tccv_make_matrix_immutable(root_classifier->root.w);\n\tassert(v->count == root_classifier->count);\n\tfor (k = 0; k < v->count; k++)\n\t{\n\t\tccv_dpm_part_classifier_t* part_classifier = root_classifier->part + k;\n\t\tccv_make_matrix_mutable(part_classifier->w);\n\t\tccv_dpm_part_classifier_t* part_vector = v->part + k;\n\t\tassert(part_vector->w->rows == part_classifier->w->rows && part_vector->w->cols == part_classifier->w->cols);\n\t\tpart_classifier->dx -= alpha * y * Cn * part_vector->dx;\n\t\tpart_classifier->dxx -= alpha * y * Cn * part_vector->dxx;\n\t\tpart_classifier->dxx = ccv_max(part_classifier->dxx, 0.01);\n\t\tpart_classifier->dy -= alpha * y * Cn * part_vector->dy;\n\t\tpart_classifier->dyy -= alpha * y * Cn * part_vector->dyy;\n\t\tpart_classifier->dyy = ccv_max(part_classifier->dyy, 0.01);\n\t\tvptr = part_vector->w->data.f32;\n\t\twptr = part_classifier->w->data.f32;\n\t\tif (symmetric)\n\t\t{\n\t\t\t// 2x converge on everything for symmetric feature\n\t\t\tif (part_classifier->counterpart == -1)\n\t\t\t{\n\t\t\t\tpart_classifier->dx += /* flip the sign on x-axis (symmetric) */ alpha * y * Cn * part_vector->dx;\n\t\t\t\tpart_classifier->dxx -= alpha * y * Cn * part_vector->dxx;\n\t\t\t\tpart_classifier->dxx = ccv_max(part_classifier->dxx, 0.01);\n\t\t\t\tpart_classifier->dy -= alpha * y * Cn * part_vector->dy;\n\t\t\t\tpart_classifier->dyy -= alpha * y * Cn * part_vector->dyy;\n\t\t\t\tpart_classifier->dyy = ccv_max(part_classifier->dyy, 0.01);\n\t\t\t\tfor (i = 0; i < part_vector->w->rows; i++)\n\t\t\t\t{\n\t\t\t\t\tfor (j = 0; j < part_vector->w->cols; j++)\n\t\t\t\t\t\tfor (c = 0; c < ch; c++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twptr[j * ch + c] += alpha * y * Cn * vptr[j * ch + c];\n\t\t\t\t\t\t\twptr[j * ch + c] += alpha * y * Cn * vptr[(part_vector->w->cols - 1 - j) * ch + _ccv_dpm_sym_lut[c]];\n\t\t\t\t\t\t}\n\t\t\t\t\tvptr += part_vector->w->cols * ch;\n\t\t\t\t\twptr += part_classifier->w->cols * ch;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tccv_dpm_part_classifier_t* other_part_classifier = root_classifier->part + part_classifier->counterpart;\n\t\t\t\tassert(part_vector->w->rows == other_part_classifier->w->rows && part_vector->w->cols == other_part_classifier->w->cols);\n\t\t\t\tother_part_classifier->dx += /* flip the sign on x-axis (symmetric) */ alpha * y * Cn * part_vector->dx;\n\t\t\t\tother_part_classifier->dxx -= alpha * y * Cn * part_vector->dxx;\n\t\t\t\tother_part_classifier->dxx = ccv_max(other_part_classifier->dxx, 0.01);\n\t\t\t\tother_part_classifier->dy -= alpha * y * Cn * part_vector->dy;\n\t\t\t\tother_part_classifier->dyy -= alpha * y * Cn * part_vector->dyy;\n\t\t\t\tother_part_classifier->dyy = ccv_max(other_part_classifier->dyy, 0.01);\n\t\t\t\tfor (i = 0; i < part_vector->w->rows; i++)\n\t\t\t\t{\n\t\t\t\t\tfor (j = 0; j < part_vector->w->cols * ch; j++)\n\t\t\t\t\t\twptr[j] += alpha * y * Cn * vptr[j];\n\t\t\t\t\tvptr += part_vector->w->cols * ch;\n\t\t\t\t\twptr += part_classifier->w->cols * ch;\n\t\t\t\t}\n\t\t\t\tvptr = part_vector->w->data.f32;\n\t\t\t\twptr = other_part_classifier->w->data.f32;\n\t\t\t\tfor (i = 0; i < part_vector->w->rows; i++)\n\t\t\t\t{\n\t\t\t\t\tfor (j = 0; j < part_vector->w->cols; j++)\n\t\t\t\t\t\tfor (c = 0; c < ch; c++)\n\t\t\t\t\t\t\twptr[j * ch + c] += alpha * y * Cn * vptr[(part_vector->w->cols - 1 - j) * ch + _ccv_dpm_sym_lut[c]];\n\t\t\t\t\tvptr += part_vector->w->cols * ch;\n\t\t\t\t\twptr += other_part_classifier->w->cols * ch;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (i = 0; i < part_vector->w->rows * part_vector->w->cols * ch; i++)\n\t\t\t\twptr[i] += alpha * y * Cn * vptr[i];\n\t\t}\n\t\tccv_make_matrix_immutable(part_classifier->w);\n\t}\n}\n\nstatic void _ccv_dpm_write_gradient_descent_progress(int i, int j, const char* dir)\n{\n\tchar swpfile[1024];\n\tsprintf(swpfile, \"%s.swp\", dir);\n\tFILE* w = fopen(swpfile, \"w+\");\n\tif (!w)\n\t\treturn;\n\tfprintf(w, \"%d %d\\n\", i, j);\n\tfclose(w);\n\trename(swpfile, dir);\n}\n\nstatic void _ccv_dpm_read_gradient_descent_progress(int* i, int* j, const char* dir)\n{\n\tFILE* r = fopen(dir, \"r\");\n\tif (!r)\n\t\treturn;\n\tfscanf(r, \"%d %d\", i, j);\n\tfclose(r);\n}\n\nstatic void _ccv_dpm_write_feature_vector(FILE* w, ccv_dpm_feature_vector_t* v)\n{\n\tint j, x, y, ch;\n\tif (v)\n\t{\n\t\tfprintf(w, \"%d %d %d\\n\", v->id, v->root.w->rows, v->root.w->cols);\n\t\tch = CCV_GET_CHANNEL(v->root.w->type);\n\t\tfor (y = 0; y < v->root.w->rows; y++)\n\t\t{\n\t\t\tfor (x = 0; x < v->root.w->cols * ch; x++)\n\t\t\t\tfprintf(w, \"%a \", v->root.w->data.f32[y * v->root.w->cols * ch + x]);\n\t\t\tfprintf(w, \"\\n\");\n\t\t}\n\t\tfprintf(w, \"%d %a\\n\", v->count, v->score);\n\t\tfor (j = 0; j < v->count; j++)\n\t\t{\n\t\t\tccv_dpm_part_classifier_t* part_classifier = v->part + j;\n\t\t\tfprintf(w, \"%la %la %la %la\\n\", part_classifier->dx, part_classifier->dy, part_classifier->dxx, part_classifier->dyy);\n\t\t\tfprintf(w, \"%d %d %d\\n\", part_classifier->x, part_classifier->y, part_classifier->z);\n\t\t\tfprintf(w, \"%d %d\\n\", part_classifier->w->rows, part_classifier->w->cols);\n\t\t\tch = CCV_GET_CHANNEL(part_classifier->w->type);\n\t\t\tfor (y = 0; y < part_classifier->w->rows; y++)\n\t\t\t{\n\t\t\t\tfor (x = 0; x < part_classifier->w->cols * ch; x++)\n\t\t\t\t\tfprintf(w, \"%a \", part_classifier->w->data.f32[y * part_classifier->w->cols * ch + x]);\n\t\t\t\tfprintf(w, \"\\n\");\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfprintf(w, \"0 0 0\\n\");\n\t}\n}\n\nstatic ccv_dpm_feature_vector_t* _ccv_dpm_read_feature_vector(FILE* r)\n{\n\tint id, rows, cols, j, k;\n\tfscanf(r, \"%d %d %d\", &id, &rows, &cols);\n\tif (rows == 0 && cols == 0)\n\t\treturn 0;\n\tccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccmalloc(sizeof(ccv_dpm_feature_vector_t));\n\tv->id = id;\n\tv->root.w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, 0, 0);\n\tfor (j = 0; j < rows * cols * 31; j++)\n\t\tfscanf(r, \"%f\", &v->root.w->data.f32[j]);\n\tfscanf(r, \"%d %f\", &v->count, &v->score);\n\tv->part = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * v->count);\n\tfor (j = 0; j < v->count; j++)\n\t{\n\t\tccv_dpm_part_classifier_t* part_classifier = v->part + j;\n\t\tfscanf(r, \"%lf %lf %lf %lf\", &part_classifier->dx, &part_classifier->dy, &part_classifier->dxx, &part_classifier->dyy);\n\t\tfscanf(r, \"%d %d %d\", &part_classifier->x, &part_classifier->y, &part_classifier->z);\n\t\tfscanf(r, \"%d %d\", &rows, &cols);\n\t\tpart_classifier->w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, 0, 0);\n\t\tfor (k = 0; k < rows * cols * 31; k++)\n\t\t\tfscanf(r, \"%f\", &part_classifier->w->data.f32[k]);\n\t}\n\treturn v;\n}\n\nstatic void _ccv_dpm_write_positive_feature_vectors(ccv_dpm_feature_vector_t** vs, int n, const char* dir)\n{\n\tFILE* w = fopen(dir, \"w+\");\n\tif (!w)\n\t\treturn;\n\tfprintf(w, \"%d\\n\", n);\n\tint i;\n\tfor (i = 0; i < n; i++)\n\t\t_ccv_dpm_write_feature_vector(w, vs[i]);\n\tfclose(w);\n}\n\nstatic int _ccv_dpm_read_positive_feature_vectors(ccv_dpm_feature_vector_t** vs, int _n, const char* dir)\n{\n\tFILE* r = fopen(dir, \"r\");\n\tif (!r)\n\t\treturn -1;\n\tint n;\n\tfscanf(r, \"%d\", &n);\n\tassert(n == _n);\n\tint i;\n\tfor (i = 0; i < n; i++)\n\t\tvs[i] = _ccv_dpm_read_feature_vector(r);\n\tfclose(r);\n\treturn 0;\n}\n\nstatic void _ccv_dpm_write_negative_feature_vectors(ccv_array_t* negv, int negative_cache_size, const char* dir)\n{\n\tFILE* w = fopen(dir, \"w+\");\n\tif (!w)\n\t\treturn;\n\tfprintf(w, \"%d %d\\n\", negative_cache_size, negv->rnum);\n\tint i;\n\tfor (i = 0; i < negv->rnum; i++)\n\t{\n\t\tccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, i);\n\t\t_ccv_dpm_write_feature_vector(w, v);\n\t}\n\tfclose(w);\n}\n\nstatic int _ccv_dpm_read_negative_feature_vectors(ccv_array_t** _negv, int _negative_cache_size, const char* dir)\n{\n\tFILE* r = fopen(dir, \"r\");\n\tif (!r)\n\t\treturn -1;\n\tint negative_cache_size, negnum;\n\tfscanf(r, \"%d %d\", &negative_cache_size, &negnum);\n\tassert(negative_cache_size == _negative_cache_size);\n\tccv_array_t* negv = *_negv = ccv_array_new(sizeof(ccv_dpm_feature_vector_t*), negnum, 0);\n\tint i;\n\tfor (i = 0; i < negnum; i++)\n\t{\n\t\tccv_dpm_feature_vector_t* v = _ccv_dpm_read_feature_vector(r);\n\t\tassert(v);\n\t\tccv_array_push(negv, &v);\n\t}\n\tfclose(r);\n\treturn 0;\n}\n\nstatic void _ccv_dpm_adjust_model_constant(ccv_dpm_mixture_model_t* model, int k, ccv_dpm_feature_vector_t** posv, int posnum, double percentile)\n{\n\tint i, j;\n\tdouble* scores = (double*)ccmalloc(posnum * sizeof(double));\n\tj = 0;\n\tfor (i = 0; i < posnum; i++)\n\t\tif (posv[i] && posv[i]->id == k)\n\t\t{\n\t\t\tscores[j] = _ccv_dpm_vector_score(model, posv[i]);\n\t\t\tj++;\n\t\t}\n\t_ccv_dpm_score_qsort(scores, j, 0);\n\tfloat adjust = scores[ccv_clamp((int)(percentile * j), 0, j - 1)];\n\t// adjust to percentile\n\tmodel->root[k].beta -= adjust;\n\tprintf(\" - tune model %d constant for %f\\n\", k + 1, -adjust);\n\tccfree(scores);\n}\n\nstatic void _ccv_dpm_check_params(ccv_dpm_new_param_t params)\n{\n\tassert(params.components > 0);\n\tassert(params.parts > 0);\n\tassert(params.grayscale == 0 || params.grayscale == 1);\n\tassert(params.symmetric == 0 || params.symmetric == 1);\n\tassert(params.min_area > 100);\n\tassert(params.max_area > params.min_area);\n\tassert(params.iterations >= 0);\n\tassert(params.data_minings >= 0);\n\tassert(params.relabels >= 0);\n\tassert(params.negative_cache_size > 0);\n\tassert(params.include_overlap > 0.1);\n\tassert(params.alpha > 0 && params.alpha < 1);\n\tassert(params.alpha_ratio > 0 && params.alpha_ratio < 1);\n\tassert(params.C > 0);\n\tassert(params.balance > 0);\n\tassert(params.percentile_breakdown > 0 && params.percentile_breakdown <= 1);\n\tassert(params.detector.interval > 0);\n}\n\n#define MINI_BATCH (10)\n#define REGQ (100)\n\nstatic ccv_dpm_mixture_model_t* _ccv_dpm_optimize_root_mixture_model(gsl_rng* rng, ccv_dpm_mixture_model_t* model, ccv_array_t** posex, ccv_array_t** negex, int relabels, double balance, double C, double previous_alpha, double alpha_ratio, int iterations, int symmetric)\n{\n\tint i, j, k, t, c;\n\tfor (i = 0; i < model->count - 1; i++)\n\t\tassert(posex[i]->rnum == posex[i + 1]->rnum && negex[i]->rnum == negex[i + 1]->rnum);\n\tint posnum = posex[0]->rnum;\n\tint negnum = negex[0]->rnum;\n\tint* label = (int*)ccmalloc(sizeof(int) * (posnum + negnum));\n\tint* order = (int*)ccmalloc(sizeof(int) * (posnum + negnum));\n\tdouble previous_positive_loss = 0, previous_negative_loss = 0, positive_loss = 0, negative_loss = 0, loss = 0;\n\tdouble regz_rate = C;\n\tfor (c = 0; c < relabels; c++)\n\t{\n\t\tint* pos_prog = (int*)alloca(sizeof(int) * model->count);\n\t\tmemset(pos_prog, 0, sizeof(int) * model->count);\n\t\tfor (i = 0; i < posnum; i++)\n\t\t{\n\t\t\tint best = -1;\n\t\t\tdouble best_score = -DBL_MAX;\n\t\t\tfor (k = 0; k < model->count; k++)\n\t\t\t{\n\t\t\t\tccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccv_array_get(posex[k], i);\n\t\t\t\tif (v->root.w == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tdouble score = _ccv_dpm_vector_score(model, v); // the loss for mini-batch method (computed on model)\n\t\t\t\tif (score > best_score)\n\t\t\t\t{\n\t\t\t\t\tbest = k;\n\t\t\t\t\tbest_score = score;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlabel[i] = best;\n\t\t\tif (best >= 0)\n\t\t\t\t++pos_prog[best];\n\t\t}\n\t\tprintf(\" - positive examples divided by components for root model optimizing : %d\", pos_prog[0]);\n\t\tfor (i = 1; i < model->count; i++)\n\t\t\tprintf(\", %d\", pos_prog[i]);\n\t\tprintf(\"\\n\");\n\t\tint* neg_prog = (int*)alloca(sizeof(int) * model->count);\n\t\tmemset(neg_prog, 0, sizeof(int) * model->count);\n\t\tfor (i = 0; i < negnum; i++)\n\t\t{\n\t\t\tint best = gsl_rng_uniform_int(rng, model->count);\n\t\t\tlabel[i + posnum] = best;\n\t\t\t++neg_prog[best];\n\t\t}\n\t\tprintf(\" - negative examples divided by components for root model optimizing : %d\", neg_prog[0]);\n\t\tfor (i = 1; i < model->count; i++)\n\t\t\tprintf(\", %d\", neg_prog[i]);\n\t\tprintf(\"\\n\");\n\t\tccv_dpm_mixture_model_t* _model;\n\t\tdouble alpha = previous_alpha;\n\t\tprevious_positive_loss = previous_negative_loss = 0;\n\t\tfor (t = 0; t < iterations; t++)\n\t\t{\n\t\t\tfor (i = 0; i < posnum + negnum; i++)\n\t\t\t\torder[i] = i;\n\t\t\tgsl_ran_shuffle(rng, order, posnum + negnum, sizeof(int));\n\t\t\tfor (j = 0; j < model->count; j++)\n\t\t\t{\n\t\t\t\tdouble pos_weight = sqrt((double)neg_prog[j] / pos_prog[j] * balance); // positive weight\n\t\t\t\tdouble neg_weight = sqrt((double)pos_prog[j] / neg_prog[j] / balance); // negative weight\n\t\t\t\t_model = _ccv_dpm_model_copy(model);\n\t\t\t\tint l = 0;\n\t\t\t\tfor (i = 0; i < posnum + negnum; i++)\n\t\t\t\t{\n\t\t\t\t\tk = order[i];\n\t\t\t\t\tif (label[k]  == j)\n\t\t\t\t\t{\n\t\t\t\t\t\tassert(label[k] < model->count);\n\t\t\t\t\t\tif (k < posnum)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccv_array_get(posex[label[k]], k);\n\t\t\t\t\t\t\tassert(v->root.w);\n\t\t\t\t\t\t\tdouble score = _ccv_dpm_vector_score(model, v); // the loss for mini-batch method (computed on model)\n\t\t\t\t\t\t\tassert(!isnan(score));\n\t\t\t\t\t\t\tassert(v->id == j);\n\t\t\t\t\t\t\tif (score <= 1)\n\t\t\t\t\t\t\t\t_ccv_dpm_stochastic_gradient_descent(_model, v, 1, alpha * pos_weight, regz_rate, symmetric);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccv_array_get(negex[label[k]], k - posnum);\n\t\t\t\t\t\t\tdouble score = _ccv_dpm_vector_score(model, v);\n\t\t\t\t\t\t\tassert(!isnan(score));\n\t\t\t\t\t\t\tassert(v->id == j);\n\t\t\t\t\t\t\tif (score >= -1)\n\t\t\t\t\t\t\t\t_ccv_dpm_stochastic_gradient_descent(_model, v, -1, alpha * neg_weight, regz_rate, symmetric);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t++l;\n\t\t\t\t\t\tif (l % REGQ == REGQ - 1)\n\t\t\t\t\t\t\t_ccv_dpm_regularize_mixture_model(_model, j, 1.0 - pow(1.0 - alpha / (double)((pos_prog[j] + neg_prog[j]) * (!!symmetric + 1)), REGQ));\n\t\t\t\t\t\tif (l % MINI_BATCH == MINI_BATCH - 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// mimicking mini-batch way of doing things\n\t\t\t\t\t\t\t_ccv_dpm_mixture_model_cleanup(model);\n\t\t\t\t\t\t\tccfree(model);\n\t\t\t\t\t\t\tmodel = _model;\n\t\t\t\t\t\t\t_model = _ccv_dpm_model_copy(model);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t_ccv_dpm_regularize_mixture_model(_model, j, 1.0 - pow(1.0 - alpha / (double)((pos_prog[j] + neg_prog[j]) * (!!symmetric + 1)), (((pos_prog[j] + neg_prog[j]) % REGQ) + 1) % (REGQ + 1)));\n\t\t\t\t_ccv_dpm_mixture_model_cleanup(model);\n\t\t\t\tccfree(model);\n\t\t\t\tmodel = _model;\n\t\t\t}\n\t\t\t// compute the loss\n\t\t\tpositive_loss = negative_loss = loss = 0;\n\t\t\tint posvn = 0;\n\t\t\tfor (i = 0; i < posnum; i++)\n\t\t\t{\n\t\t\t\tif (label[i] < 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tassert(label[i] < model->count);\n\t\t\t\tccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccv_array_get(posex[label[i]], i);\n\t\t\t\tif (v->root.w)\n\t\t\t\t{\n\t\t\t\t\tdouble score = _ccv_dpm_vector_score(model, v);\n\t\t\t\t\tassert(!isnan(score));\n\t\t\t\t\tdouble hinge_loss = ccv_max(0, 1.0 - score);\n\t\t\t\t\tpositive_loss += hinge_loss;\n\t\t\t\t\tdouble pos_weight = sqrt((double)neg_prog[v->id] / pos_prog[v->id] * balance); // positive weight\n\t\t\t\t\tloss += pos_weight * hinge_loss;\n\t\t\t\t\t++posvn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (i = 0; i < negnum; i++)\n\t\t\t{\n\t\t\t\tif (label[i + posnum] < 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tassert(label[i + posnum] < model->count);\n\t\t\t\tccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccv_array_get(negex[label[i + posnum]], i);\n\t\t\t\tdouble score = _ccv_dpm_vector_score(model, v);\n\t\t\t\tassert(!isnan(score));\n\t\t\t\tdouble hinge_loss = ccv_max(0, 1.0 + score);\n\t\t\t\tnegative_loss += hinge_loss;\n\t\t\t\tdouble neg_weight = sqrt((double)pos_prog[v->id] / neg_prog[v->id] / balance); // negative weight\n\t\t\t\tloss += neg_weight * hinge_loss;\n\t\t\t}\n\t\t\tloss = loss / (posvn + negnum);\n\t\t\tpositive_loss = positive_loss / posvn;\n\t\t\tnegative_loss = negative_loss / negnum;\n\t\t\tFLUSH(\" - with loss %.5lf (positive %.5lf, negative %.5f) at rate %.5lf %d | %d -- %d%%\", loss, positive_loss, negative_loss, alpha, posvn, negnum, (t + 1) * 100 / iterations);\n\t\t\t// check symmetric property of generated root feature\n\t\t\tif (symmetric)\n\t\t\t\tfor (i = 0; i < model->count; i++)\n\t\t\t\t{\n\t\t\t\t\tccv_dpm_root_classifier_t* root_classifier = model->root + i;\n\t\t\t\t\t_ccv_dpm_check_root_classifier_symmetry(root_classifier->root.w);\n\t\t\t\t}\n\t\t\tif (fabs(previous_positive_loss - positive_loss) < 1e-5 &&\n\t\t\t\tfabs(previous_negative_loss - negative_loss) < 1e-5)\n\t\t\t{\n\t\t\t\tprintf(\"\\n - aborting iteration at %d because we didn't gain much\", t + 1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprevious_positive_loss = positive_loss;\n\t\t\tprevious_negative_loss = negative_loss;\n\t\t\talpha *= alpha_ratio; // it will decrease with each iteration\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tccfree(order);\n\tccfree(label);\n\treturn model;\n}\n\nvoid ccv_dpm_mixture_model_new(char** posfiles, ccv_rect_t* bboxes, int posnum, char** bgfiles, int bgnum, int negnum, const char* dir, ccv_dpm_new_param_t params)\n{\n\tint t, d, c, i, j, k, p;\n\t_ccv_dpm_check_params(params);\n\tassert(params.negative_cache_size <= negnum && params.negative_cache_size > REGQ && params.negative_cache_size > MINI_BATCH);\n\tprintf(\"with %d positive examples and %d negative examples\\n\"\n\t\t   \"negative examples are are going to be collected from %d background images\\n\",\n\t\t   posnum, negnum, bgnum);\n\tprintf(\"use symmetric property? %s\\n\", params.symmetric ? \"yes\" : \"no\");\n\tprintf(\"use color? %s\\n\", params.grayscale ? \"no\" : \"yes\");\n\tprintf(\"negative examples cache size : %d\\n\", params.negative_cache_size);\n\tprintf(\"%d components and %d parts\\n\", params.components, params.parts);\n\tprintf(\"expected %d root relabels, %d relabels, %d data minings and %d iterations\\n\", params.root_relabels, params.relabels, params.data_minings, params.iterations);\n\tprintf(\"include overlap : %lf\\n\"\n\t\t   \"alpha : %lf\\n\"\n\t\t   \"alpha decreasing ratio : %lf\\n\"\n\t\t   \"C : %lf\\n\"\n\t\t   \"balance ratio : %lf\\n\"\n\t\t   \"------------------------\\n\",\n\t\t   params.include_overlap, params.alpha, params.alpha_ratio, params.C, params.balance);\n\tgsl_rng_env_setup();\n\tgsl_rng* rng = gsl_rng_alloc(gsl_rng_default);\n\tgsl_rng_set(rng, *(unsigned long int*)&params);\n\tccv_dpm_mixture_model_t* model = (ccv_dpm_mixture_model_t*)ccmalloc(sizeof(ccv_dpm_mixture_model_t));\n\tmemset(model, 0, sizeof(ccv_dpm_mixture_model_t));\n\tstruct feature_node* fn = (struct feature_node*)ccmalloc(sizeof(struct feature_node) * posnum);\n\tfor (i = 0; i < posnum; i++)\n\t{\n\t\tassert(bboxes[i].width > 0 && bboxes[i].height > 0);\n\t\tfn[i].value = (float)bboxes[i].width / (float)bboxes[i].height;\n\t\tfn[i].index = i;\n\t}\n\tchar checkpoint[512];\n\tchar initcheckpoint[512];\n\tsprintf(checkpoint, \"%s/model\", dir);\n\tsprintf(initcheckpoint, \"%s/init.model\", dir);\n\t_ccv_dpm_aspect_qsort(fn, posnum, 0);\n\tdouble mean = 0;\n\tfor (i = 0; i < posnum; i++)\n\t\tmean += fn[i].value;\n\tmean /= posnum;\n\tdouble variance = 0;\n\tfor (i = 0; i < posnum; i++)\n\t\tvariance += (fn[i].value - mean) * (fn[i].value - mean);\n\tvariance /= posnum;\n\tprintf(\"global mean: %lf, & variance: %lf\\ninterclass mean(variance):\", mean, variance);\n\tint* mnum = (int*)alloca(sizeof(int) * params.components);\n\tint outnum = posnum, innum = 0;\n\tfor (i = 0; i < params.components; i++)\n\t{\n\t\tmnum[i] = (int)((double)outnum / (double)(params.components - i) + 0.5);\n\t\tdouble mean = 0;\n\t\tfor (j = innum; j < innum + mnum[i]; j++)\n\t\t\tmean += fn[j].value;\n\t\tmean /= mnum[i];\n\t\tdouble variance = 0;\n\t\tfor (j = innum; j < innum + mnum[i]; j++)\n\t\t\tvariance += (fn[j].value - mean) * (fn[j].value - mean);\n\t\tvariance /= mnum[i];\n\t\tprintf(\" %lf(%lf)\", mean, variance);\n\t\toutnum -= mnum[i];\n\t\tinnum += mnum[i];\n\t}\n\tprintf(\"\\n\");\n\tint* areas = (int*)ccmalloc(sizeof(int) * posnum);\n\tfor (i = 0; i < posnum; i++)\n\t\tareas[i] = bboxes[i].width * bboxes[i].height;\n\t_ccv_dpm_area_qsort(areas, posnum, 0);\n\t// so even the object is 1/4 in size, we can still detect them (in detection phase, we start at 2x image)\n\tint area = ccv_clamp(areas[(int)(posnum * 0.2 + 0.5)], params.min_area, params.max_area);\n\tccfree(areas);\n\tinnum = 0;\n\t_ccv_dpm_read_checkpoint(model, checkpoint);\n\tif (model->count <= 0)\n\t{\n\t\t/* initialize root mixture model with liblinear */\n\t\tmodel->count = params.components;\n\t\tmodel->root = (ccv_dpm_root_classifier_t*)ccmalloc(sizeof(ccv_dpm_root_classifier_t) * model->count);\n\t\tmemset(model->root, 0, sizeof(ccv_dpm_root_classifier_t) * model->count);\n\t}\n\tprintf(\"computing root mixture model dimensions: \");\n\tfflush(stdout);\n\tint* poslabels = (int*)ccmalloc(sizeof(int) * posnum);\n\tint* rows = (int*)alloca(sizeof(int) * params.components);\n\tint* cols = (int*)alloca(sizeof(int) * params.components);\n\tfor (i = 0; i < params.components; i++)\n\t{\n\t\tdouble aspect = 0;\n\t\tfor (j = innum; j < innum + mnum[i]; j++)\n\t\t{\n\t\t\taspect += fn[j].value;\n\t\t\tposlabels[fn[j].index] = i; // setup labels\n\t\t}\n\t\taspect /= mnum[i];\n\t\tcols[i] = ccv_max((int)(sqrtf(area / aspect) * aspect / CCV_DPM_WINDOW_SIZE + 0.5), 1);\n\t\trows[i] = ccv_max((int)(sqrtf(area / aspect) / CCV_DPM_WINDOW_SIZE + 0.5), 1);\n\t\tif (i < params.components - 1)\n\t\t\tprintf(\"%dx%d, \", cols[i], rows[i]);\n\t\telse\n\t\t\tprintf(\"%dx%d\\n\", cols[i], rows[i]);\n\t\tfflush(stdout);\n\t\tinnum += mnum[i];\n\t}\n\tccfree(fn);\n\tint corrupted = 1;\n\tfor (i = 0; i < params.components; i++)\n\t\tif (model->root[i].root.w)\n\t\t{\n\t\t\tprintf(\"skipping root mixture model initialization for model %d(%d)\\n\", i + 1, params.components);\n\t\t\tcorrupted = 0;\n\t\t} else\n\t\t\tbreak;\n\tif (corrupted)\n\t{\n\t\tprintf(\"root mixture model initialization corrupted, reboot\\n\");\n\t\tccv_array_t** posex = (ccv_array_t**)alloca(sizeof(ccv_array_t*) * params.components);\n\t\tfor (i = 0; i < params.components; i++)\n\t\t\tposex[i] = _ccv_dpm_summon_examples_by_rectangle(posfiles, bboxes, posnum, i, rows[i], cols[i], params.grayscale);\n\t\tprintf(\"\\n\");\n\t\tccv_array_t** negex = (ccv_array_t**)alloca(sizeof(ccv_array_t*) * params.components);\n\t\t_ccv_dpm_collect_examples_randomly(rng, negex, bgfiles, bgnum, negnum, params.components, rows, cols, params.grayscale);\n\t\tprintf(\"\\n\");\n\t\tint* neglabels = (int*)ccmalloc(sizeof(int) * negex[0]->rnum);\n\t\tfor (i = 0; i < negex[0]->rnum; i++)\n\t\t\tneglabels[i] = gsl_rng_uniform_int(rng, params.components);\n\t\tfor (i = 0; i < params.components; i++)\n\t\t{\n\t\t\tccv_dpm_root_classifier_t* root_classifier = model->root + i;\n\t\t\troot_classifier->root.w = ccv_dense_matrix_new(rows[i], cols[i], CCV_32F | 31, 0, 0);\n\t\t\tprintf(\"initializing root mixture model for model %d(%d)\\n\", i + 1, params.components);\n\t\t\t_ccv_dpm_initialize_root_classifier(rng, root_classifier, i, mnum[i], poslabels, posex[i], neglabels, negex[i], params.C, params.symmetric, params.grayscale);\n\t\t}\n\t\tccfree(neglabels);\n\t\tccfree(poslabels);\n\t\t// check symmetric property of generated root feature\n\t\tif (params.symmetric)\n\t\t\tfor (i = 0; i < params.components; i++)\n\t\t\t{\n\t\t\t\tccv_dpm_root_classifier_t* root_classifier = model->root + i;\n\t\t\t\t_ccv_dpm_check_root_classifier_symmetry(root_classifier->root.w);\n\t\t\t}\n\t\tif (params.components > 1)\n\t\t{\n\t\t\t/* TODO: coordinate-descent for lsvm */\n\t\t\tprintf(\"optimizing root mixture model with coordinate-descent approach\\n\");\n\t\t\tmodel = _ccv_dpm_optimize_root_mixture_model(rng, model, posex, negex, params.root_relabels, params.balance, params.C, params.alpha, params.alpha_ratio, params.iterations, params.symmetric);\n\t\t} else {\n\t\t\tprintf(\"components == 1, skipped coordinate-descent to optimize root mixture model\\n\");\n\t\t}\n\t\tfor (i = 0; i < params.components; i++)\n\t\t{\n\t\t\tfor (j = 0; j < posex[i]->rnum; j++)\n\t\t\t\t_ccv_dpm_feature_vector_cleanup((ccv_dpm_feature_vector_t*)ccv_array_get(posex[i], j));\n\t\t\tccv_array_free(posex[i]);\n\t\t\tfor (j = 0; j < negex[i]->rnum; j++)\n\t\t\t\t_ccv_dpm_feature_vector_cleanup((ccv_dpm_feature_vector_t*)ccv_array_get(negex[i], j));\n\t\t\tccv_array_free(negex[i]);\n\t\t}\n\t} else {\n\t\tccfree(poslabels);\n\t}\n\t_ccv_dpm_write_checkpoint(model, 0, checkpoint);\n\t/* initialize part filter */\n\tprintf(\"initializing part filters\\n\");\n\tfor (i = 0; i < params.components; i++)\n\t{\n\t\tif (model->root[i].count > 0)\n\t\t{\n\t\t\tprintf(\" - skipping part filters initialization for model %d(%d)\\n\", i + 1, params.components);\n\t\t} else {\n\t\t\tprintf(\" - initializing part filters for model %d(%d)\\n\", i + 1, params.components);\n\t\t\t_ccv_dpm_initialize_part_classifiers(model->root + i, params.parts, params.symmetric);\n\t\t\t_ccv_dpm_write_checkpoint(model, 0, checkpoint);\n\t\t\t_ccv_dpm_write_checkpoint(model, 0, initcheckpoint);\n\t\t}\n\t}\n\t_ccv_dpm_write_checkpoint(model, 0, checkpoint);\n\t/* optimize both root filter and part filters with stochastic gradient descent */\n\tprintf(\"optimizing root filter & part filters with stochastic gradient descent\\n\");\n\tchar gradient_progress_checkpoint[512];\n\tsprintf(gradient_progress_checkpoint, \"%s/gradient_descent_progress\", dir);\n\tchar feature_vector_checkpoint[512];\n\tsprintf(feature_vector_checkpoint, \"%s/positive_vectors\", dir);\n\tchar neg_vector_checkpoint[512];\n\tsprintf(neg_vector_checkpoint, \"%s/negative_vectors\", dir);\n\tccv_dpm_feature_vector_t** posv = (ccv_dpm_feature_vector_t**)ccmalloc(posnum * sizeof(ccv_dpm_feature_vector_t*));\n\tint* order = (int*)ccmalloc(sizeof(int) * (posnum + params.negative_cache_size + 64 /* the magical number for maximum negative examples collected per image */));\n\tdouble previous_positive_loss = 0, previous_negative_loss = 0, positive_loss = 0, negative_loss = 0, loss = 0;\n\t// need to re-weight for each examples\n\tc = d = t = 0;\n\tccv_array_t* negv = 0;\n\tif (0 == _ccv_dpm_read_negative_feature_vectors(&negv, params.negative_cache_size, neg_vector_checkpoint))\n\t\tprintf(\" - read collected negative responses from last interrupted process\\n\");\n\t_ccv_dpm_read_gradient_descent_progress(&c, &d, gradient_progress_checkpoint);\n\tfor (; c < params.relabels; c++)\n\t{\n\t\tdouble regz_rate = params.C;\n\t\tccv_dpm_mixture_model_t* _model;\n\t\tif (0 == _ccv_dpm_read_positive_feature_vectors(posv, posnum, feature_vector_checkpoint))\n\t\t{\n\t\t\tprintf(\" - read collected positive responses from last interrupted process\\n\");\n\t\t} else {\n\t\t\tFLUSH(\" - collecting responses from positive examples : 0%%\");\n\t\t\tfor (i = 0; i < posnum; i++)\n\t\t\t{\n\t\t\t\tFLUSH(\" - collecting responses from positive examples : %d%%\", i * 100 / posnum);\n\t\t\t\tccv_dense_matrix_t* image = 0;\n\t\t\t\tccv_read(posfiles[i], &image, (params.grayscale ? CCV_IO_GRAY : 0) | CCV_IO_ANY_FILE);\n\t\t\t\tposv[i] = _ccv_dpm_collect_best(image, model, bboxes[i], params.include_overlap, params.detector);\n\t\t\t\tccv_matrix_free(image);\n\t\t\t}\n\t\t\tFLUSH(\" - collecting responses from positive examples : 100%%\\n\");\n\t\t\t_ccv_dpm_write_positive_feature_vectors(posv, posnum, feature_vector_checkpoint);\n\t\t}\n\t\tint* posvnum = (int*)alloca(sizeof(int) * model->count);\n\t\tmemset(posvnum, 0, sizeof(int) * model->count);\n\t\tfor (i = 0; i < posnum; i++)\n\t\t\tif (posv[i])\n\t\t\t{\n\t\t\t\tassert(posv[i]->id >= 0 && posv[i]->id < model->count);\n\t\t\t\t++posvnum[posv[i]->id];\n\t\t\t}\n\t\tprintf(\" - positive examples divided by components : %d\", posvnum[0]);\n\t\tfor (i = 1; i < model->count; i++)\n\t\t\tprintf(\", %d\", posvnum[i]);\n\t\tprintf(\"\\n\");\n\t\tparams.detector.threshold = 0;\n\t\tfor (; d < params.data_minings; d++)\n\t\t{\n\t\t\t// the cache is used up now, collect again\n\t\t\t_ccv_dpm_write_gradient_descent_progress(c, d, gradient_progress_checkpoint);\n\t\t\tdouble alpha = params.alpha;\n\t\t\tif (negv)\n\t\t\t{\n\t\t\t\tccv_array_t* av = ccv_array_new(sizeof(ccv_dpm_feature_vector_t*), 64, 0);\n\t\t\t\tfor (j = 0; j < negv->rnum; j++)\n\t\t\t\t{\n\t\t\t\t\tccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, j);\n\t\t\t\t\tdouble score = _ccv_dpm_vector_score(model, v);\n\t\t\t\t\tassert(!isnan(score));\n\t\t\t\t\tif (score >= -1)\n\t\t\t\t\t\tccv_array_push(av, &v);\n\t\t\t\t\telse\n\t\t\t\t\t\t_ccv_dpm_feature_vector_free(v);\n\t\t\t\t}\n\t\t\t\tccv_array_free(negv);\n\t\t\t\tnegv = av;\n\t\t\t} else {\n\t\t\t\tnegv = ccv_array_new(sizeof(ccv_dpm_feature_vector_t*), 64, 0);\n\t\t\t}\n\t\t\tFLUSH(\" - collecting negative examples -- (0%%)\");\n\t\t\tif (negv->rnum < params.negative_cache_size)\n\t\t\t\t_ccv_dpm_collect_from_background(negv, rng, bgfiles, bgnum, model, params, 0);\n\t\t\t_ccv_dpm_write_negative_feature_vectors(negv, params.negative_cache_size, neg_vector_checkpoint);\n\t\t\tFLUSH(\" - collecting negative examples -- (100%%)\\n\");\n\t\t\tint* negvnum = (int*)alloca(sizeof(int) * model->count);\n\t\t\tmemset(negvnum, 0, sizeof(int) * model->count);\n\t\t\tfor (i = 0; i < negv->rnum; i++)\n\t\t\t{\n\t\t\t\tccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, i);\n\t\t\t\tassert(v->id >= 0 && v->id < model->count);\n\t\t\t\t++negvnum[v->id];\n\t\t\t}\n\t\t\tif (negv->rnum <= ccv_max(params.negative_cache_size / 2, ccv_max(REGQ, MINI_BATCH)))\n\t\t\t{\n\t\t\t\tfor (i = 0; i < model->count; i++)\n\t\t\t\t\t// we cannot get sufficient negatives, adjust constant and abort for next round\n\t\t\t\t\t_ccv_dpm_adjust_model_constant(model, i, posv, posnum, params.percentile_breakdown);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tprintf(\" - negative examples divided by components : %d\", negvnum[0]);\n\t\t\tfor (i = 1; i < model->count; i++)\n\t\t\t\tprintf(\", %d\", negvnum[i]);\n\t\t\tprintf(\"\\n\");\n\t\t\tprevious_positive_loss = previous_negative_loss = 0;\n\t\t\tuint64_t elapsed_time = _ccv_dpm_time_measure();\n\t\t\tassert(negv->rnum < params.negative_cache_size + 64);\n\t\t\tfor (t = 0; t < params.iterations; t++)\n\t\t\t{\n\t\t\t\tfor (p = 0; p < model->count; p++)\n\t\t\t\t{\n\t\t\t\t\t// if don't have enough negnum or posnum, aborting\n\t\t\t\t\tif (negvnum[p] <= ccv_max(params.negative_cache_size / (model->count * 3), ccv_max(REGQ, MINI_BATCH)) ||\n\t\t\t\t\t\tposvnum[p] <= ccv_max(REGQ, MINI_BATCH))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tdouble pos_weight = sqrt((double)negvnum[p] / posvnum[p] * params.balance); // positive weight\n\t\t\t\t\tdouble neg_weight = sqrt((double)posvnum[p] / negvnum[p] / params.balance); // negative weight\n\t\t\t\t\t_model = _ccv_dpm_model_copy(model);\n\t\t\t\t\tfor (i = 0; i < posnum + negv->rnum; i++)\n\t\t\t\t\t\torder[i] = i;\n\t\t\t\t\tgsl_ran_shuffle(rng, order, posnum + negv->rnum, sizeof(int));\n\t\t\t\t\tint l = 0;\n\t\t\t\t\tfor (i = 0; i < posnum + negv->rnum; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tk = order[i];\n\t\t\t\t\t\tif (k < posnum)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (posv[k] == 0 || posv[k]->id != p)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tdouble score = _ccv_dpm_vector_score(model, posv[k]); // the loss for mini-batch method (computed on model)\n\t\t\t\t\t\t\tassert(!isnan(score));\n\t\t\t\t\t\t\tif (score <= 1)\n\t\t\t\t\t\t\t\t_ccv_dpm_stochastic_gradient_descent(_model, posv[k], 1, alpha * pos_weight, regz_rate, params.symmetric);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, k - posnum);\n\t\t\t\t\t\t\tif (v->id != p)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tdouble score = _ccv_dpm_vector_score(model, v);\n\t\t\t\t\t\t\tassert(!isnan(score));\n\t\t\t\t\t\t\tif (score >= -1)\n\t\t\t\t\t\t\t\t_ccv_dpm_stochastic_gradient_descent(_model, v, -1, alpha * neg_weight, regz_rate, params.symmetric);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t++l;\n\t\t\t\t\t\tif (l % REGQ == REGQ - 1)\n\t\t\t\t\t\t\t_ccv_dpm_regularize_mixture_model(_model, p, 1.0 - pow(1.0 - alpha / (double)((posvnum[p] + negvnum[p]) * (!!params.symmetric + 1)), REGQ));\n\t\t\t\t\t\tif (l % MINI_BATCH == MINI_BATCH - 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// mimicking mini-batch way of doing things\n\t\t\t\t\t\t\t_ccv_dpm_mixture_model_cleanup(model);\n\t\t\t\t\t\t\tccfree(model);\n\t\t\t\t\t\t\tmodel = _model;\n\t\t\t\t\t\t\t_model = _ccv_dpm_model_copy(model);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t_ccv_dpm_regularize_mixture_model(_model, p, 1.0 - pow(1.0 - alpha / (double)((posvnum[p] + negvnum[p]) * (!!params.symmetric + 1)), (((posvnum[p] + negvnum[p]) % REGQ) + 1) % (REGQ + 1)));\n\t\t\t\t\t_ccv_dpm_mixture_model_cleanup(model);\n\t\t\t\t\tccfree(model);\n\t\t\t\t\tmodel = _model;\n\t\t\t\t}\n\t\t\t\t// compute the loss\n\t\t\t\tint posvn = 0;\n\t\t\t\tpositive_loss = negative_loss = loss = 0;\n\t\t\t\tfor (i = 0; i < posnum; i++)\n\t\t\t\t\tif (posv[i] != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble score = _ccv_dpm_vector_score(model, posv[i]);\n\t\t\t\t\t\tassert(!isnan(score));\n\t\t\t\t\t\tdouble hinge_loss = ccv_max(0, 1.0 - score);\n\t\t\t\t\t\tpositive_loss += hinge_loss;\n\t\t\t\t\t\tdouble pos_weight = sqrt((double)negvnum[posv[i]->id] / posvnum[posv[i]->id] * params.balance); // positive weight\n\t\t\t\t\t\tloss += pos_weight * hinge_loss;\n\t\t\t\t\t\t++posvn;\n\t\t\t\t\t}\n\t\t\t\tfor (i = 0; i < negv->rnum; i++)\n\t\t\t\t{\n\t\t\t\t\tccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, i);\n\t\t\t\t\tdouble score = _ccv_dpm_vector_score(model, v);\n\t\t\t\t\tassert(!isnan(score));\n\t\t\t\t\tdouble hinge_loss = ccv_max(0, 1.0 + score);\n\t\t\t\t\tnegative_loss += hinge_loss;\n\t\t\t\t\tdouble neg_weight = sqrt((double)posvnum[v->id] / negvnum[v->id] / params.balance); // negative weight\n\t\t\t\t\tloss += neg_weight * hinge_loss;\n\t\t\t\t}\n\t\t\t\tloss = loss / (posvn + negv->rnum);\n\t\t\t\tpositive_loss = positive_loss / posvn;\n\t\t\t\tnegative_loss = negative_loss / negv->rnum;\n\t\t\t\tFLUSH(\" - with loss %.5lf (positive %.5lf, negative %.5f) at rate %.5lf %d | %d -- %d%%\", loss, positive_loss, negative_loss, alpha, posvn, negv->rnum, (t + 1) * 100 / params.iterations);\n\t\t\t\t// check symmetric property of generated root feature\n\t\t\t\tif (params.symmetric)\n\t\t\t\t\tfor (i = 0; i < params.components; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tccv_dpm_root_classifier_t* root_classifier = model->root + i;\n\t\t\t\t\t\t_ccv_dpm_check_root_classifier_symmetry(root_classifier->root.w);\n\t\t\t\t\t}\n\t\t\t\tif (fabs(previous_positive_loss - positive_loss) < 1e-5 &&\n\t\t\t\t\tfabs(previous_negative_loss - negative_loss) < 1e-5)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"\\n - aborting iteration at %d because we didn't gain much\", t + 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tprevious_positive_loss = positive_loss;\n\t\t\t\tprevious_negative_loss = negative_loss;\n\t\t\t\talpha *= params.alpha_ratio; // it will decrease with each iteration\n\t\t\t}\n\t\t\t_ccv_dpm_write_checkpoint(model, 0, checkpoint);\n\t\t\tprintf(\"\\n - data mining %d takes %.2lf seconds at loss %.5lf, %d more to go (%d of %d)\\n\", d + 1, (double)(_ccv_dpm_time_measure() - elapsed_time) / 1000000.0, loss, params.data_minings - d - 1, c + 1, params.relabels);\n\t\t\tj = 0;\n\t\t\tdouble* scores = (double*)ccmalloc(posnum * sizeof(double));\n\t\t\tfor (i = 0; i < posnum; i++)\n\t\t\t\tif (posv[i])\n\t\t\t\t{\n\t\t\t\t\tscores[j] = _ccv_dpm_vector_score(model, posv[i]);\n\t\t\t\t\tassert(!isnan(scores[j]));\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t_ccv_dpm_score_qsort(scores, j, 0);\n\t\t\tccfree(scores);\n\t\t\tdouble breakdown;\n\t\t\tprintf(\" - threshold breakdown by percentile\");\n\t\t\tfor (breakdown = params.percentile_breakdown; breakdown < 1.0; breakdown += params.percentile_breakdown)\n\t\t\t\tprintf(\" %0.2lf(%.1f%%)\", scores[ccv_clamp((int)(breakdown * j), 0, j - 1)], (1.0 - breakdown) * 100);\n\t\t\tprintf(\"\\n\");\n\t\t\tchar persist[512];\n\t\t\tsprintf(persist, \"%s/model.%d.%d\", dir, c, d);\n\t\t\t_ccv_dpm_write_checkpoint(model, 0, persist);\n\t\t}\n\t\td = 0;\n\t\t// if abort, means that we cannot find enough negative examples, try to adjust constant\n\t\tfor (i = 0; i < posnum; i++)\n\t\t\tif (posv[i])\n\t\t\t\t_ccv_dpm_feature_vector_free(posv[i]);\n\t\tremove(feature_vector_checkpoint);\n\t}\n\tif (negv)\n\t{\n\t\tfor (i = 0; i < negv->rnum; i++)\n\t\t{\n\t\t\tccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, i);\n\t\t\t_ccv_dpm_feature_vector_free(v);\n\t\t}\n\t\tccv_array_free(negv);\n\t}\n\tremove(neg_vector_checkpoint);\n\tccfree(order);\n\tccfree(posv);\n\tprintf(\"root rectangle prediction with linear regression\\n\");\n\t_ccv_dpm_initialize_root_rectangle_estimator(model, posfiles, bboxes, posnum, params);\n\t_ccv_dpm_write_checkpoint(model, 1, checkpoint);\n\tprintf(\"done\\n\");\n\tremove(gradient_progress_checkpoint);\n\t_ccv_dpm_mixture_model_cleanup(model);\n\tccfree(model);\n\tgsl_rng_free(rng);\n}\n#else\nvoid ccv_dpm_mixture_model_new(char** posfiles, ccv_rect_t* bboxes, int posnum, char** bgfiles, int bgnum, int negnum, const char* dir, ccv_dpm_new_param_t params)\n{\n\tfprintf(stderr, \" ccv_dpm_classifier_cascade_new requires libgsl and liblinear support, please compile ccv with them.\\n\");\n}\n#endif\n#else\nvoid ccv_dpm_mixture_model_new(char** posfiles, ccv_rect_t* bboxes, int posnum, char** bgfiles, int bgnum, int negnum, const char* dir, ccv_dpm_new_param_t params)\n{\n\tfprintf(stderr, \" ccv_dpm_classifier_cascade_new requires libgsl and liblinear support, please compile ccv with them.\\n\");\n}\n#endif\n\nstatic int _ccv_is_equal(const void* _r1, const void* _r2, void* data)\n{\n\tconst ccv_root_comp_t* r1 = (const ccv_root_comp_t*)_r1;\n\tconst ccv_root_comp_t* r2 = (const ccv_root_comp_t*)_r2;\n\tint distance = (int)(ccv_min(r1->rect.width, r1->rect.height) * 0.25 + 0.5);\n\n\treturn r2->rect.x <= r1->rect.x + distance &&\n\t\tr2->rect.x >= r1->rect.x - distance &&\n\t\tr2->rect.y <= r1->rect.y + distance &&\n\t\tr2->rect.y >= r1->rect.y - distance &&\n\t\tr2->rect.width <= (int)(r1->rect.width * 1.5 + 0.5) &&\n\t\t(int)(r2->rect.width * 1.5 + 0.5) >= r1->rect.width &&\n\t\tr2->rect.height <= (int)(r1->rect.height * 1.5 + 0.5) &&\n\t\t(int)(r2->rect.height * 1.5 + 0.5) >= r1->rect.height;\n}\n\nstatic int _ccv_is_equal_same_class(const void* _r1, const void* _r2, void* data)\n{\n\tconst ccv_root_comp_t* r1 = (const ccv_root_comp_t*)_r1;\n\tconst ccv_root_comp_t* r2 = (const ccv_root_comp_t*)_r2;\n\tint distance = (int)(ccv_min(r1->rect.width, r1->rect.height) * 0.25 + 0.5);\n\n\treturn r2->classification.id == r1->classification.id &&\n\t\tr2->rect.x <= r1->rect.x + distance &&\n\t\tr2->rect.x >= r1->rect.x - distance &&\n\t\tr2->rect.y <= r1->rect.y + distance &&\n\t\tr2->rect.y >= r1->rect.y - distance &&\n\t\tr2->rect.width <= (int)(r1->rect.width * 1.5 + 0.5) &&\n\t\t(int)(r2->rect.width * 1.5 + 0.5) >= r1->rect.width &&\n\t\tr2->rect.height <= (int)(r1->rect.height * 1.5 + 0.5) &&\n\t\t(int)(r2->rect.height * 1.5 + 0.5) >= r1->rect.height;\n}\n\nccv_array_t* ccv_dpm_detect_objects(ccv_dense_matrix_t* a, ccv_dpm_mixture_model_t** _model, int count, ccv_dpm_param_t params)\n{\n\tint c, i, j, k, x, y;\n\tdouble scale = pow(2.0, 1.0 / (params.interval + 1.0));\n\tint next = params.interval + 1;\n\tint scale_upto = _ccv_dpm_scale_upto(a, _model, count, params.interval);\n\tif (scale_upto < 0) // image is too small to be interesting\n\t\treturn 0;\n\tccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca((scale_upto + next * 2) * sizeof(ccv_dense_matrix_t*));\n\t_ccv_dpm_feature_pyramid(a, pyr, scale_upto, params.interval);\n\tccv_array_t* idx_seq;\n\tccv_array_t* seq = ccv_array_new(sizeof(ccv_root_comp_t), 64, 0);\n\tccv_array_t* seq2 = ccv_array_new(sizeof(ccv_root_comp_t), 64, 0);\n\tccv_array_t* result_seq = ccv_array_new(sizeof(ccv_root_comp_t), 64, 0);\n\tfor (c = 0; c < count; c++)\n\t{\n\t\tccv_dpm_mixture_model_t* model = _model[c];\n\t\tdouble scale_x = 1.0;\n\t\tdouble scale_y = 1.0;\n\t\tfor (i = next; i < scale_upto + next * 2; i++)\n\t\t{\n\t\t\tfor (j = 0; j < model->count; j++)\n\t\t\t{\n\t\t\t\tccv_dpm_root_classifier_t* root = model->root + j;\n\t\t\t\tccv_dense_matrix_t* root_feature = 0;\n\t\t\t\tccv_dense_matrix_t* part_feature[CCV_DPM_PART_MAX];\n\t\t\t\tccv_dense_matrix_t* dx[CCV_DPM_PART_MAX];\n\t\t\t\tccv_dense_matrix_t* dy[CCV_DPM_PART_MAX];\n\t\t\t\t_ccv_dpm_compute_score(root, pyr[i], pyr[i - next], &root_feature, part_feature, dx, dy);\n\t\t\t\tint rwh = (root->root.w->rows - 1) / 2, rww = (root->root.w->cols - 1) / 2;\n\t\t\t\tint rwh_1 = root->root.w->rows / 2, rww_1 = root->root.w->cols / 2;\n\t\t\t\t/* these values are designed to make sure works with odd/even number of rows/cols\n\t\t\t\t * of the root classifier:\n\t\t\t\t * suppose the image is 6x6, and the root classifier is 6x6, the scan area should starts\n\t\t\t\t * at (2,2) and end at (2,2), thus, it is capped by (rwh, rww) to (6 - rwh_1 - 1, 6 - rww_1 - 1)\n\t\t\t\t * this computation works for odd root classifier too (i.e. 5x5) */\n\t\t\t\tfloat* f_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | CCV_C1, root_feature, rwh, 0, 0);\n\t\t\t\tfor (y = rwh; y < root_feature->rows - rwh_1; y++)\n\t\t\t\t{\n\t\t\t\t\tfor (x = rww; x < root_feature->cols - rww_1; x++)\n\t\t\t\t\t\tif (f_ptr[x] + root->beta > params.threshold)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tccv_root_comp_t comp;\n\t\t\t\t\t\t\tcomp.neighbors = 1;\n\t\t\t\t\t\t\tcomp.classification.id = c + 1;\n\t\t\t\t\t\t\tcomp.classification.confidence = f_ptr[x] + root->beta;\n\t\t\t\t\t\t\tcomp.pnum = root->count;\n\t\t\t\t\t\t\tfloat drift_x = root->alpha[0],\n\t\t\t\t\t\t\t\t  drift_y = root->alpha[1],\n\t\t\t\t\t\t\t\t  drift_scale = root->alpha[2];\n\t\t\t\t\t\t\tfor (k = 0; k < root->count; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tccv_dpm_part_classifier_t* part = root->part + k;\n\t\t\t\t\t\t\t\tcomp.part[k].neighbors = 1;\n\t\t\t\t\t\t\t\tcomp.part[k].classification.id = c;\n\t\t\t\t\t\t\t\tint pww = (part->w->cols - 1) / 2, pwh = (part->w->rows - 1) / 2;\n\t\t\t\t\t\t\t\tint offy = part->y + pwh - rwh * 2;\n\t\t\t\t\t\t\t\tint offx = part->x + pww - rww * 2;\n\t\t\t\t\t\t\t\tint iy = ccv_clamp(y * 2 + offy, pwh, part_feature[k]->rows - part->w->rows + pwh);\n\t\t\t\t\t\t\t\tint ix = ccv_clamp(x * 2 + offx, pww, part_feature[k]->cols - part->w->cols + pww);\n\t\t\t\t\t\t\t\tint ry = ccv_get_dense_matrix_cell_value_by(CCV_32S | CCV_C1, dy[k], iy, ix, 0);\n\t\t\t\t\t\t\t\tint rx = ccv_get_dense_matrix_cell_value_by(CCV_32S | CCV_C1, dx[k], iy, ix, 0);\n\t\t\t\t\t\t\t\tdrift_x += part->alpha[0] * rx + part->alpha[1] * ry;\n\t\t\t\t\t\t\t\tdrift_y += part->alpha[2] * rx + part->alpha[3] * ry;\n\t\t\t\t\t\t\t\tdrift_scale += part->alpha[4] * rx + part->alpha[5] * ry;\n\t\t\t\t\t\t\t\try = iy - ry;\n\t\t\t\t\t\t\t\trx = ix - rx;\n\t\t\t\t\t\t\t\tcomp.part[k].rect = ccv_rect((int)((rx - pww) * CCV_DPM_WINDOW_SIZE / 2 * scale_x + 0.5), (int)((ry - pwh) * CCV_DPM_WINDOW_SIZE / 2 * scale_y + 0.5), (int)(part->w->cols * CCV_DPM_WINDOW_SIZE / 2 * scale_x + 0.5), (int)(part->w->rows * CCV_DPM_WINDOW_SIZE / 2 * scale_y + 0.5));\n\t\t\t\t\t\t\t\tcomp.part[k].classification.confidence = -ccv_get_dense_matrix_cell_value_by(CCV_32F | CCV_C1, part_feature[k], iy, ix, 0);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcomp.rect = ccv_rect((int)((x + drift_x) * CCV_DPM_WINDOW_SIZE * scale_x - rww * CCV_DPM_WINDOW_SIZE * scale_x * (1.0 + drift_scale) + 0.5), (int)((y + drift_y) * CCV_DPM_WINDOW_SIZE * scale_y - rwh * CCV_DPM_WINDOW_SIZE * scale_y * (1.0 + drift_scale) + 0.5), (int)(root->root.w->cols * CCV_DPM_WINDOW_SIZE * scale_x * (1.0 + drift_scale) + 0.5), (int)(root->root.w->rows * CCV_DPM_WINDOW_SIZE * scale_y * (1.0 + drift_scale) + 0.5));\n\t\t\t\t\t\t\tccv_array_push(seq, &comp);\n\t\t\t\t\t\t}\n\t\t\t\t\tf_ptr += root_feature->cols;\n\t\t\t\t}\n\t\t\t\tfor (k = 0; k < root->count; k++)\n\t\t\t\t{\n\t\t\t\t\tccv_matrix_free(part_feature[k]);\n\t\t\t\t\tccv_matrix_free(dx[k]);\n\t\t\t\t\tccv_matrix_free(dy[k]);\n\t\t\t\t}\n\t\t\t\tccv_matrix_free(root_feature);\n\t\t\t}\n\t\t\tscale_x *= scale;\n\t\t\tscale_y *= scale;\n\t\t}\n\t\t/* the following code from OpenCV's haar feature implementation */\n\t\tif (params.min_neighbors == 0)\n\t\t{\n\t\t\tfor (i = 0; i < seq->rnum; i++)\n\t\t\t{\n\t\t\t\tccv_root_comp_t* comp = (ccv_root_comp_t*)ccv_array_get(seq, i);\n\t\t\t\tccv_array_push(result_seq, comp);\n\t\t\t}\n\t\t} else {\n\t\t\tidx_seq = 0;\n\t\t\tccv_array_clear(seq2);\n\t\t\t// group retrieved rectangles in order to filter out noise\n\t\t\tint ncomp = ccv_array_group(seq, &idx_seq, _ccv_is_equal_same_class, 0);\n\t\t\tccv_root_comp_t* comps = (ccv_root_comp_t*)ccmalloc((ncomp + 1) * sizeof(ccv_root_comp_t));\n\t\t\tmemset(comps, 0, (ncomp + 1) * sizeof(ccv_root_comp_t));\n\n\t\t\t// count number of neighbors\n\t\t\tfor (i = 0; i < seq->rnum; i++)\n\t\t\t{\n\t\t\t\tccv_root_comp_t r1 = *(ccv_root_comp_t*)ccv_array_get(seq, i);\n\t\t\t\tint idx = *(int*)ccv_array_get(idx_seq, i);\n\n\t\t\t\tcomps[idx].classification.id = r1.classification.id;\n\t\t\t\tcomps[idx].pnum = r1.pnum;\n\t\t\t\tif (r1.classification.confidence > comps[idx].classification.confidence || comps[idx].neighbors == 0)\n\t\t\t\t{\n\t\t\t\t\tcomps[idx].rect = r1.rect;\n\t\t\t\t\tcomps[idx].classification.confidence = r1.classification.confidence;\n\t\t\t\t\tmemcpy(comps[idx].part, r1.part, sizeof(ccv_comp_t) * CCV_DPM_PART_MAX);\n\t\t\t\t}\n\n\t\t\t\t++comps[idx].neighbors;\n\t\t\t}\n\n\t\t\t// calculate average bounding box\n\t\t\tfor (i = 0; i < ncomp; i++)\n\t\t\t{\n\t\t\t\tint n = comps[i].neighbors;\n\t\t\t\tif (n >= params.min_neighbors)\n\t\t\t\t\tccv_array_push(seq2, comps + i);\n\t\t\t}\n\n\t\t\t// filter out large object rectangles contains small object rectangles\n\t\t\tfor (i = 0; i < seq2->rnum; i++)\n\t\t\t{\n\t\t\t\tccv_root_comp_t* r2 = (ccv_root_comp_t*)ccv_array_get(seq2, i);\n\t\t\t\tint distance = (int)(ccv_min(r2->rect.width, r2->rect.height) * 0.25 + 0.5);\n\t\t\t\tfor (j = 0; j < seq2->rnum; j++)\n\t\t\t\t{\n\t\t\t\t\tccv_root_comp_t r1 = *(ccv_root_comp_t*)ccv_array_get(seq2, j);\n\t\t\t\t\tif (i != j &&\n\t\t\t\t\t\tabs(r1.classification.id) == r2->classification.id &&\n\t\t\t\t\t\tr1.rect.x >= r2->rect.x - distance &&\n\t\t\t\t\t\tr1.rect.y >= r2->rect.y - distance &&\n\t\t\t\t\t\tr1.rect.x + r1.rect.width <= r2->rect.x + r2->rect.width + distance &&\n\t\t\t\t\t\tr1.rect.y + r1.rect.height <= r2->rect.y + r2->rect.height + distance &&\n\t\t\t\t\t\t// if r1 (the smaller one) is better, mute r2\n\t\t\t\t\t\t(r2->classification.confidence <= r1.classification.confidence && r2->neighbors < r1.neighbors))\n\t\t\t\t\t{\n\t\t\t\t\t\tr2->classification.id = -r2->classification.id;\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// filter out small object rectangles inside large object rectangles\n\t\t\tfor (i = 0; i < seq2->rnum; i++)\n\t\t\t{\n\t\t\t\tccv_root_comp_t r1 = *(ccv_root_comp_t*)ccv_array_get(seq2, i);\n\t\t\t\tif (r1.classification.id > 0)\n\t\t\t\t{\n\t\t\t\t\tint flag = 1;\n\n\t\t\t\t\tfor (j = 0; j < seq2->rnum; j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tccv_root_comp_t r2 = *(ccv_root_comp_t*)ccv_array_get(seq2, j);\n\t\t\t\t\t\tint distance = (int)(ccv_min(r2.rect.width, r2.rect.height) * 0.25 + 0.5);\n\n\t\t\t\t\t\tif (i != j &&\n\t\t\t\t\t\t\tr1.classification.id == abs(r2.classification.id) &&\n\t\t\t\t\t\t\tr1.rect.x >= r2.rect.x - distance &&\n\t\t\t\t\t\t\tr1.rect.y >= r2.rect.y - distance &&\n\t\t\t\t\t\t\tr1.rect.x + r1.rect.width <= r2.rect.x + r2.rect.width + distance &&\n\t\t\t\t\t\t\tr1.rect.y + r1.rect.height <= r2.rect.y + r2.rect.height + distance &&\n\t\t\t\t\t\t\t(r2.classification.confidence > r1.classification.confidence || r2.neighbors >= r1.neighbors))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflag = 0;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (flag)\n\t\t\t\t\t\tccv_array_push(result_seq, &r1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tccv_array_free(idx_seq);\n\t\t\tccfree(comps);\n\t\t}\n\t}\n\n\tfor (i = 0; i < scale_upto + next * 2; i++)\n\t\tccv_matrix_free(pyr[i]);\n\n\tccv_array_free(seq);\n\tccv_array_free(seq2);\n\n\tccv_array_t* result_seq2;\n\t/* the following code from OpenCV's haar feature implementation */\n\tif (params.flags & CCV_DPM_NO_NESTED)\n\t{\n\t\tresult_seq2 = ccv_array_new(sizeof(ccv_root_comp_t), 64, 0);\n\t\tidx_seq = 0;\n\t\t// group retrieved rectangles in order to filter out noise\n\t\tint ncomp = ccv_array_group(result_seq, &idx_seq, _ccv_is_equal, 0);\n\t\tccv_root_comp_t* comps = (ccv_root_comp_t*)ccmalloc((ncomp + 1) * sizeof(ccv_root_comp_t));\n\t\tmemset(comps, 0, (ncomp + 1) * sizeof(ccv_root_comp_t));\n\n\t\t// count number of neighbors\n\t\tfor(i = 0; i < result_seq->rnum; i++)\n\t\t{\n\t\t\tccv_root_comp_t r1 = *(ccv_root_comp_t*)ccv_array_get(result_seq, i);\n\t\t\tint idx = *(int*)ccv_array_get(idx_seq, i);\n\n\t\t\tif (comps[idx].neighbors == 0 || comps[idx].classification.confidence < r1.classification.confidence)\n\t\t\t{\n\t\t\t\tcomps[idx].classification.confidence = r1.classification.confidence;\n\t\t\t\tcomps[idx].neighbors = 1;\n\t\t\t\tcomps[idx].rect = r1.rect;\n\t\t\t\tcomps[idx].classification.id = r1.classification.id;\n\t\t\t\tcomps[idx].pnum = r1.pnum;\n\t\t\t\tmemcpy(comps[idx].part, r1.part, sizeof(ccv_comp_t) * CCV_DPM_PART_MAX);\n\t\t\t}\n\t\t}\n\n\t\t// calculate average bounding box\n\t\tfor(i = 0; i < ncomp; i++)\n\t\t\tif(comps[i].neighbors)\n\t\t\t\tccv_array_push(result_seq2, &comps[i]);\n\n\t\tccv_array_free(result_seq);\n\t\tccfree(comps);\n\t} else {\n\t\tresult_seq2 = result_seq;\n\t}\n\n\treturn result_seq2;\n}\n\nccv_dpm_mixture_model_t* ccv_dpm_read_mixture_model(const char* directory)\n{\n\tFILE* r = fopen(directory, \"r\");\n\tif (r == 0)\n\t\treturn 0;\n\tint count;\n\tchar flag;\n\tfscanf(r, \"%c\", &flag);\n\tassert(flag == '.');\n\tfscanf(r, \"%d\", &count);\n\tccv_dpm_root_classifier_t* root_classifier = (ccv_dpm_root_classifier_t*)ccmalloc(sizeof(ccv_dpm_root_classifier_t) * count);\n\tmemset(root_classifier, 0, sizeof(ccv_dpm_root_classifier_t) * count);\n\tint i, j, k;\n\tsize_t size = sizeof(ccv_dpm_mixture_model_t) + sizeof(ccv_dpm_root_classifier_t) * count;\n\t/* the format is easy, but I tried to copy all data into one memory region */\n\tfor (i = 0; i < count; i++)\n\t{\n\t\tint rows, cols;\n\t\tfscanf(r, \"%d %d\", &rows, &cols);\n\t\tfscanf(r, \"%f %f %f %f\", &root_classifier[i].beta, &root_classifier[i].alpha[0], &root_classifier[i].alpha[1], &root_classifier[i].alpha[2]);\n\t\troot_classifier[i].root.w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, ccmalloc(ccv_compute_dense_matrix_size(rows, cols, CCV_32F | 31)), 0);\n\t\tsize += ccv_compute_dense_matrix_size(rows, cols, CCV_32F | 31);\n\t\tfor (j = 0; j < rows * cols * 31; j++)\n\t\t\tfscanf(r, \"%f\", &root_classifier[i].root.w->data.f32[j]);\n\t\tccv_make_matrix_immutable(root_classifier[i].root.w);\n\t\tfscanf(r, \"%d\", &root_classifier[i].count);\n\t\tccv_dpm_part_classifier_t* part_classifier = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * root_classifier[i].count);\n\t\tsize += sizeof(ccv_dpm_part_classifier_t) * root_classifier[i].count;\n\t\tfor (j = 0; j < root_classifier[i].count; j++)\n\t\t{\n\t\t\tfscanf(r, \"%d %d %d\", &part_classifier[j].x, &part_classifier[j].y, &part_classifier[j].z);\n\t\t\tfscanf(r, \"%lf %lf %lf %lf\", &part_classifier[j].dx, &part_classifier[j].dy, &part_classifier[j].dxx, &part_classifier[j].dyy);\n\t\t\tfscanf(r, \"%f %f %f %f %f %f\", &part_classifier[j].alpha[0], &part_classifier[j].alpha[1], &part_classifier[j].alpha[2], &part_classifier[j].alpha[3], &part_classifier[j].alpha[4], &part_classifier[j].alpha[5]);\n\t\t\tfscanf(r, \"%d %d %d\", &rows, &cols, &part_classifier[j].counterpart);\n\t\t\tpart_classifier[j].w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, ccmalloc(ccv_compute_dense_matrix_size(rows, cols, CCV_32F | 31)), 0);\n\t\t\tsize += ccv_compute_dense_matrix_size(rows, cols, CCV_32F | 31);\n\t\t\tfor (k = 0; k < rows * cols * 31; k++)\n\t\t\t\tfscanf(r, \"%f\", &part_classifier[j].w->data.f32[k]);\n\t\t\tccv_make_matrix_immutable(part_classifier[j].w);\n\t\t}\n\t\troot_classifier[i].part = part_classifier;\n\t}\n\tfclose(r);\n\tunsigned char* m = (unsigned char*)ccmalloc(size);\n\tccv_dpm_mixture_model_t* model = (ccv_dpm_mixture_model_t*)m;\n\tm += sizeof(ccv_dpm_mixture_model_t);\n\tmodel->count = count;\n\tmodel->root = (ccv_dpm_root_classifier_t*)m;\n\tm += sizeof(ccv_dpm_root_classifier_t) * model->count;\n\tmemcpy(model->root, root_classifier, sizeof(ccv_dpm_root_classifier_t) * model->count);\n\tccfree(root_classifier);\n\tfor (i = 0; i < model->count; i++)\n\t{\n\t\tccv_dpm_part_classifier_t* part_classifier = model->root[i].part;\n\t\tmodel->root[i].part = (ccv_dpm_part_classifier_t*)m;\n\t\tm += sizeof(ccv_dpm_part_classifier_t) * model->root[i].count;\n\t\tmemcpy(model->root[i].part, part_classifier, sizeof(ccv_dpm_part_classifier_t) * model->root[i].count);\n\t\tccfree(part_classifier);\n\t}\n\tfor (i = 0; i < model->count; i++)\n\t{\n\t\tccv_dense_matrix_t* w = model->root[i].root.w;\n\t\tmodel->root[i].root.w = (ccv_dense_matrix_t*)m;\n\t\tm += ccv_compute_dense_matrix_size(w->rows, w->cols, w->type);\n\t\tmemcpy(model->root[i].root.w, w, ccv_compute_dense_matrix_size(w->rows, w->cols, w->type));\n\t\tmodel->root[i].root.w->data.u8 = (unsigned char*)(model->root[i].root.w + 1);\n\t\tccfree(w);\n\t\tfor (j = 0; j < model->root[i].count; j++)\n\t\t{\n\t\t\tw = model->root[i].part[j].w;\n\t\t\tmodel->root[i].part[j].w = (ccv_dense_matrix_t*)m;\n\t\t\tm += ccv_compute_dense_matrix_size(w->rows, w->cols, w->type);\n\t\t\tmemcpy(model->root[i].part[j].w, w, ccv_compute_dense_matrix_size(w->rows, w->cols, w->type));\n\t\t\tmodel->root[i].part[j].w->data.u8 = (unsigned char*)(model->root[i].part[j].w + 1);\n\t\t\tccfree(w);\n\t\t}\n\t}\n\treturn model;\n}\n\nvoid ccv_dpm_mixture_model_free(ccv_dpm_mixture_model_t* model)\n{\n\tccfree(model);\n}\n", "meta": {"hexsha": "33aac11bb7e2029ce73fb6ee038494b9512a3d86", "size": 93337, "ext": "c", "lang": "C", "max_stars_repo_path": "lib/ccv_dpm.c", "max_stars_repo_name": "r3gis3r/ccv", "max_stars_repo_head_hexsha": "bedf2c1ab39f99664067f346986bf07f1c8bd188", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-27T13:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T13:51:53.000Z", "max_issues_repo_path": "lib/ccv_dpm.c", "max_issues_repo_name": "r3gis3r/ccv", "max_issues_repo_head_hexsha": "bedf2c1ab39f99664067f346986bf07f1c8bd188", "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": "lib/ccv_dpm.c", "max_forks_repo_name": "r3gis3r/ccv", "max_forks_repo_head_hexsha": "bedf2c1ab39f99664067f346986bf07f1c8bd188", "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": 39.4993652137, "max_line_length": 442, "alphanum_fraction": 0.6445675348, "num_tokens": 31431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584174871563662, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3951745113246065}}
{"text": "/**\n *\n * @file core_zhegst.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @date 2010-11-15\n * @precisions normal z -> c d s\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex64_t\n *\n *  CORE_zhegst - reduces a complex Hermitian-definite generalized\n *  eigenproblem to standard form.\n *  If PlasmaItype == 1, the problem is A*x = lambda*B*x, and A is\n *  overwritten by inv(U**H)*A*inv(U) or inv(L)*A*inv(L**H)\n *  If PlasmaItype == 2 or 3, the problem is A*B*x = lambda*x or B*A*x\n *  = lambda*x, and A is overwritten by U*A*U**H or L**H*A*L.  B must\n *  have been previously factorized as U**H*U or L*L**H by\n *  CORE_zpotrf.\n *\n *******************************************************************************\n *\n * @param[in] itype\n *          Intended usage:\n *          = 1: A*x=(lambda)*B*x\n *          = 2: A*Bx=(lambda)*x\n *          = 3: B*A*x=(lambda)*x\n *\n * @param[in] uplo\n *          Specifies whether the matrix A is upper triangular or\n *          lower triangular:\n *          = PlasmaUpper: Upper triangle of A is stored;\n *          = PlasmaLower: Lower triangle of A is stored.\n *\n * @param[in] N\n *          The order of the matrices A and B. N >= 0.\n *\n * @param[in,out] A\n *          On entry, the symmetric (or Hermitian) matrix A.\n *          If uplo = PlasmaUpper, the leading N-by-N upper triangular\n *          part of A contains the upper triangular part of the matrix\n *          A, and the strictly lower triangular part of A is not\n *          referenced.\n *          If uplo = PlasmaLower, the leading N-by-N lower triangular\n *          part of A contains the lower triangular part of the matrix\n *          A, and the strictly upper triangular part of A is not\n *          referenced.\n *          On exit, if return value == 0, the transformed matrix,\n *          stored in the same format as A.\n *\n * @param[in] LDA\n *          The leading dimension of the array A. LDA >= max(1,N).\n *\n * @param[in,out] B\n *          On entry, the triangular factor from the Cholesky\n *          factorization of B, as returned by PLASMA_ZPOTRF.\n *\n * @param[in] LDB\n *          The leading dimension of the array B. LDB >= max(1,N).\n *\n * @param[out] INFO\n *          - 0 on successful exit\n *          - <0 if -i, the i-th argument had an illegal value\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zhegst = PCORE_zhegst\n#define CORE_zhegst PCORE_zhegst\n#endif\nvoid CORE_zhegst(int itype, PLASMA_enum uplo, int N,\n                 PLASMA_Complex64_t *A, int LDA,\n                 PLASMA_Complex64_t *B, int LDB, int *INFO)\n{\n    *INFO = LAPACKE_zhegst_work(\n        LAPACK_COL_MAJOR,\n        itype,\n        lapack_const(uplo),\n        N, A, LDA, B, LDB );\n}\n", "meta": {"hexsha": "968e7685968972781eaa38562b2cd9ca515f1646", "size": 3043, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_zhegst.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_zhegst.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_zhegst.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.8111111111, "max_line_length": 80, "alphanum_fraction": 0.5573447256, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936377487305, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3951162609150835}}
{"text": "#include <unistd.h>\n#include \"asf_sar.h\"\n#include \"asf_raster.h\"\n#include \"asf_nan.h\"\n#include \"asf_complex.h\"\n#include <assert.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_eigen.h>\n\n#define EPS 1.E-15\n\ntypedef struct {\n   int current_row;\n   int nrows;  // # in held in memory, not total image rows\n   meta_parameters *meta;\n\n   float *amp; // HH amplitude data\n\n   quadPolS2Float *s2_data_buffer;\n   quadPolS2Float **s2_lines;\n\n  quadPolC3Float *c3_data_buffer;\n  quadPolC3Float **c3_lines;\n\n  quadPolT3Float *t3_data_buffer;\n  quadPolT3Float **t3_lines;\n\n   floatVector *pauli_buffer;\n   floatVector **pauli_lines;\n\n   complexMatrix **coh_buffer;\n   complexMatrix ***coh_lines;\n\n   int amp_band;\n   int hh_amp_band, hh_phase_band;\n   int hv_amp_band, hv_phase_band;\n   int vh_amp_band, vh_phase_band;\n   int vv_amp_band, vv_phase_band;\n  int c11_band, c12_real_band, c12_imag_band;\n  int c13_real_band, c13_imag_band, c22_band;\n  int c23_real_band, c23_imag_band, c33_band;\n  int t11_band, t12_real_band, t12_imag_band;\n  int t13_real_band, t13_imag_band, t22_band;\n  int t23_real_band, t23_imag_band, t33_band;\n} PolarimetricImageRows;\n\n\n//static complexFloat complex_new_gsl(gsl_complex c)\n//{\n//    complexFloat ret;\n//    ret.real = GSL_REAL(c);\n//    ret.imag = GSL_IMAG(c);\n//    return ret;\n//}\n\nstatic quadPolS2Float qual_pol_s2_zero()\n{\n    quadPolS2Float ret;\n    ret.hh = complex_zero();\n    ret.vh = complex_zero();\n    ret.hv = complex_zero();\n    ret.vv = complex_zero();\n    return ret;\n}\n\nstatic quadPolC3Float qual_pol_c3_zero()\n{\n  quadPolC3Float ret;\n  ret.c11 = 0.0;\n  ret.c12_real = 0.0;\n  ret.c12_imag = 0.0;\n  ret.c13_real = 0.0;\n  ret.c13_imag = 0.0;\n  ret.c22 = 0.0;\n  ret.c23_real = 0.0;\n  ret.c23_imag = 0.0;\n  ret.c33 = 0.0;\n  return ret;\n}\n\nstatic quadPolT3Float qual_pol_t3_zero()\n{\n  quadPolT3Float ret;\n  ret.t11 = 0.0;\n  ret.t12_real = 0.0;\n  ret.t12_imag = 0.0;\n  ret.t13_real = 0.0;\n  ret.t13_imag = 0.0;\n  ret.t22 = 0.0;\n  ret.t23_real = 0.0;\n  ret.t23_imag = 0.0;\n  ret.t33 = 0.0;\n  return ret;\n}\n\nstatic PolarimetricImageRows *\npolarimetric_image_rows_new(meta_parameters *meta, int nrows, int multi)\n{\n    PolarimetricImageRows *self = MALLOC(sizeof(PolarimetricImageRows));\n\n    self->nrows = nrows;\n    self->meta = meta;\n\n    // nrows must be odd\n    if (multi) {\n      self->current_row = 0;\n    }\n    else {\n      assert((self->nrows-1)%2==0);\n      self->current_row = -(nrows+1)/2;\n    }\n\n    int ns = meta->general->sample_count;\n\n    self->amp = CALLOC(ns, sizeof(float));\n    if (meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {\n      self->s2_data_buffer = CALLOC(nrows*ns, sizeof(quadPolS2Float));\n      self->s2_lines = CALLOC(nrows, sizeof(quadPolS2Float*));\n    }\n    else if (meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n      self->c3_data_buffer = CALLOC(nrows*ns, sizeof(quadPolC3Float));\n      self->c3_lines = CALLOC(nrows, sizeof(quadPolC3Float*));\n    }\n\n    // initially, the line pointers point at their natural locations in\n    // the buffer\n    int i;\n    if (meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {\n      for (i=0; i<nrows; ++i)\n\tself->s2_lines[i] = &(self->s2_data_buffer[ns*i]);\n    }\n    if (meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n      for (i=0; i<nrows; ++i)\n\tself->c3_lines[i] = &(self->c3_data_buffer[ns*i]);\n    }\n\n    // these guys are the pauli basis elements we've calculated for the\n    // loaded rows\n    self->pauli_buffer = CALLOC(nrows*ns, sizeof(floatVector));\n    self->pauli_lines = CALLOC(nrows, sizeof(floatVector*));\n    for (i=0; i<nrows; ++i)\n        self->pauli_lines[i] = &(self->pauli_buffer[ns*i]);\n\n    // coherency matrix elements for the loaded rows\n    self->coh_buffer = MALLOC(nrows*ns*sizeof(complexMatrix*));\n    for (i=0; i<nrows*ns; ++i)\n        self->coh_buffer[i] = complex_matrix_new(3,3);\n    self->coh_lines = MALLOC(nrows*sizeof(complexMatrix**));\n    for (i=0; i<nrows; ++i)\n        self->coh_lines[i] = &(self->coh_buffer[ns*i]);\n\n    // band numbers in the input file\n    self->amp_band = -1;\n    self->hh_amp_band = self->hh_phase_band = -1;\n    self->hv_amp_band = self->hv_phase_band = -1;\n    self->vh_amp_band = self->vh_phase_band = -1;\n    self->vv_amp_band = self->vv_phase_band = -1;\n    self->c11_band = -1;\n    self->c12_real_band = -1;\n    self->c12_imag_band = -1;\n    self->c13_real_band = -1; \n    self->c13_imag_band = -1;\n    self->c22_band = -1;\n    self->c23_real_band = -1;\n    self->c23_imag_band = -1;\n    self->c33_band = -1;\n    self->t11_band = -1;\n    self->t12_real_band = -1;\n    self->t12_imag_band = -1;\n    self->t13_real_band = -1;\n    self->t13_imag_band = -1;\n    self->t22_band = -1;\n    self->t23_real_band = -1;\n    self->t23_imag_band = -1;\n    self->t33_band = -1;\n\n    return self;\n}\n\nstatic int polarimetric_image_rows_get_bands(PolarimetricImageRows *self)\n{\n    int ok=TRUE;\n    // \"extra\" amplitude band needs to be the first band\n    char *bands = self->meta->general->bands;\n    self->amp_band = strncmp_case(bands, \"AMP\", 3) == 0 ? 0 : -1;\n\n    // polarimetric bands\n    if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {\n      self->hh_amp_band = find_band(self->meta, \"AMP-HH\", &ok);\n      self->hh_phase_band = find_band(self->meta, \"PHASE-HH\", &ok);\n      self->hv_amp_band = find_band(self->meta, \"AMP-HV\", &ok);\n      self->hv_phase_band = find_band(self->meta, \"PHASE-HV\", &ok);\n      self->vh_amp_band = find_band(self->meta, \"AMP-VH\", &ok);\n      self->vh_phase_band = find_band(self->meta, \"PHASE-VH\", &ok);\n      self->vv_amp_band = find_band(self->meta, \"AMP-VV\", &ok);\n      self->vv_phase_band = find_band(self->meta, \"PHASE-VV\", &ok);\n    }\n    else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n      self->c11_band = find_band(self->meta, \"C11\", &ok);\n      self->c12_real_band = find_band(self->meta, \"C12_real\", &ok);\n      self->c12_imag_band = find_band(self->meta, \"C12_imag\", &ok);\n      self->c13_real_band = find_band(self->meta, \"C13_real\", &ok);\n      self->c13_imag_band = find_band(self->meta, \"C13_imag\", &ok);\n      self->c22_band = find_band(self->meta, \"C22\", &ok);\n      self->c23_real_band = find_band(self->meta, \"C23_real\", &ok);\n      self->c23_imag_band = find_band(self->meta, \"C23_imag\", &ok);\n      self->c33_band = find_band(self->meta, \"C33\", &ok);\n    }\n    else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {\n      self->t11_band = find_band(self->meta, \"T11\", &ok);\n      self->t12_real_band = find_band(self->meta, \"T12_real\", &ok);\n      self->t12_imag_band = find_band(self->meta, \"T12_imag\", &ok);\n      self->t13_real_band = find_band(self->meta, \"T13_real\", &ok);\n      self->t13_imag_band = find_band(self->meta, \"T13_imag\", &ok);\n      self->t22_band = find_band(self->meta, \"T22\", &ok);\n      self->t23_real_band = find_band(self->meta, \"T23_real\", &ok);\n      self->t23_imag_band = find_band(self->meta, \"T23_imag\", &ok);\n      self->t33_band = find_band(self->meta, \"T33\", &ok);\n    }\n    return ok;\n}\n\nstatic void calculate_pauli_for_row(PolarimetricImageRows *self, int n)\n{\n    int j, ns=self->meta->general->sample_count;\n    complexFloat cpx_a, cpx_b, cpx_c;\n    float value;\n\n    // HH-VV, HV+VH, HH+VV\n\n    if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {\n      for (j=0; j<ns; ++j) {\n        quadPolS2Float q = self->s2_lines[n][j];\n\tcpx_a = complex_sub(q.hh, q.vv);\n\tcpx_b = complex_add(q.hv, q.vh);\n\tcpx_c = complex_add(q.hh, q.vv);\n        self->pauli_lines[n][j].A = (float) hypot(cpx_a.real, cpx_a.imag);\n        self->pauli_lines[n][j].B = (float) hypot(cpx_b.real, cpx_b.imag);\n        self->pauli_lines[n][j].C = (float) hypot(cpx_c.real, cpx_c.imag);\t\n      }\n    }\n    else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n      for (j=0; j<ns; ++j) {\n\tquadPolC3Float q = self->c3_lines[n][j];\n\n\tvalue = fabs(q.c11 - 2.0*q.c13_real + q.c33) / 2.0;\n\tif (ISNAN(value)) value = EPS;\n\tif (value > 0)\n\t  value = 10 *log10(value);\t\n\tself->pauli_lines[n][j].A = value;\n\n\tvalue = fabs(q.c22);\n\tif (ISNAN(value)) value = EPS;\n\tif (value > 0)\n\t  value = 10 *log10(value);\n\tself->pauli_lines[n][j].B = value;\n\n\tvalue = fabs(q.c11 + 2.0*q.c13_real + q.c33) / 2.0;\n\tif (ISNAN(value)) value = EPS;\n\tif (value > 0)\n\t  value = 10 *log10(value);\n\tself->pauli_lines[n][j].C = value;\n      }\n    }\n    else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {\n      for (j=0; j<ns; ++j) {\n\tquadPolT3Float q = self->t3_lines[n][j];\n\tself->pauli_lines[n][j].A = fabs(q.t22);\n\tself->pauli_lines[n][j].B = fabs(q.t33);\n\tself->pauli_lines[n][j].C = fabs(q.t11);\n      }\n    }\n}\n\nstatic void calculate_coherence_for_row(PolarimetricImageRows *self, int n)\n{\n    // [ A*A  B*A  C*A ]    A = HH + VV\n    // [ A*B  B*B  C*B ]    B = HH - VV\n    // [ A*C  B*C  C*C ]    C = 2*HV\n    int j, ns=self->meta->general->sample_count;\n    if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {\n      for (j=0; j<ns; ++j) {\n        quadPolS2Float q = self->s2_lines[n][j];\n        complexVector v = //complex_vector_normalize(\n          complex_vector_new(\n            complex_add(q.hh, q.vv),\n            complex_sub(q.hh, q.vv),\n            complex_add(q.hv, q.vh))/*)*/;\n        complexVector vc = complex_vector_conj(v);\n\n        complexMatrix *m = self->coh_lines[n][j];\n\n        complex_matrix_set(m,0,0,complex_mul(vc.A, v.A));\n        complex_matrix_set(m,0,1,complex_mul(vc.A, v.B));\n        complex_matrix_set(m,0,2,complex_mul(vc.A, v.C));\n\n        complex_matrix_set(m,1,0,complex_mul(vc.B, v.A));\n        complex_matrix_set(m,1,1,complex_mul(vc.B, v.B));\n        complex_matrix_set(m,1,2,complex_mul(vc.B, v.C));\n\n        complex_matrix_set(m,2,0,complex_mul(vc.C, v.A));\n        complex_matrix_set(m,2,1,complex_mul(vc.C, v.B));\n        complex_matrix_set(m,2,2,complex_mul(vc.C, v.C));\n\n        //complex_matrix_scale(m,1./sqrt(2.0));\n        complex_matrix_scale(m,0.5);\n      }\n    }\n}\n\nstatic void polarimetric_image_rows_load_next_row(PolarimetricImageRows *self,\n                                                  FILE *fin)\n{\n  // we discard the top (0) row, slide all rows up one, then load\n  // the new row into the top position\n\n  // don't actually move any data -- update pointers into the\n  // buffers\n\n  // FIRST -- slide row pointers\n  int k;\n  for (k=0; k<self->nrows-1; ++k) {\n    if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX)\n      self->s2_lines[k] = self->s2_lines[k+1];\n    else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX)\n      self->c3_lines[k] = self->c3_lines[k+1];\n    else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX)\n      self->t3_lines[k] = self->t3_lines[k+1];\n    self->pauli_lines[k] = self->pauli_lines[k+1];\n  }\n  \n  // the next line to load will go into the spot we just dumped\n  int last = self->nrows - 1;\n  if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX)\n    self->s2_lines[last] = self->s2_lines[0];\n  else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX)\n    self->c3_lines[last] = self->c3_lines[0];\n  else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX)\n    self->t3_lines[last] = self->t3_lines[0];\n  self->pauli_lines[last] = self->pauli_lines[0];\n  \n  self->current_row++;\n  \n  // NEXT, load in new row into the final row\n  // if we have moved off the top of the image, we will need to\n  // fill with zeros, instead of loading a row\n  int ns = self->meta->general->sample_count;\n\n  float *amp_buf=NULL, *phase_buf=NULL;\n  float *c11=NULL, *c12_real=NULL, *c12_imag=NULL, *c13_real=NULL;\n  float *c13_imag=NULL, *c22=NULL, *c23_real=NULL, *c23_imag=NULL, *c33=NULL;\n  float *t11=NULL, *t12_real=NULL, *t12_imag=NULL, *t13_real=NULL;\n  float *t13_imag=NULL, *t22=NULL, *t23_real=NULL, *t23_imag=NULL, *t33=NULL;\n  float C11, C12_real, C12_imag, C13_real, C13_imag;\n  float C22, C23_real, C23_imag, C33;\n  float phase, phase12, phase13, phase23;\n\n  amp_buf = MALLOC(sizeof(float)*ns);\n\n  if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {\n    phase_buf = MALLOC(sizeof(float)*ns);\n  }\n  else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n    c11 = MALLOC(sizeof(float)*ns);\n    c12_real = MALLOC(sizeof(float)*ns);\n    c12_imag = MALLOC(sizeof(float)*ns);\n    c13_real = MALLOC(sizeof(float)*ns);\n    c13_imag = MALLOC(sizeof(float)*ns);\n    c22 = MALLOC(sizeof(float)*ns);\n    c23_real = MALLOC(sizeof(float)*ns);\n    c23_imag = MALLOC(sizeof(float)*ns);\n    c33 = MALLOC(sizeof(float)*ns);\n  }\n  else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {\n    t11 = MALLOC(sizeof(float)*ns);\n    t12_real = MALLOC(sizeof(float)*ns);\n    t12_imag = MALLOC(sizeof(float)*ns);\n    t13_real = MALLOC(sizeof(float)*ns);\n    t13_imag = MALLOC(sizeof(float)*ns);\n    t22 = MALLOC(sizeof(float)*ns);\n    t23_real = MALLOC(sizeof(float)*ns);\n    t23_imag = MALLOC(sizeof(float)*ns);\n    t33 = MALLOC(sizeof(float)*ns);\n  }\n\n\n  int row = self->current_row + (self->nrows-1)/2;\n  if (row < self->meta->general->line_count) {\n    // amplitude, we only store the current row\n    if (self->current_row >= 0 && self->amp_band >= 0)\n      get_band_float_line(fin, self->meta, self->amp_band,\n                          self->current_row, self->amp);\n\n    // now the SLC rows\n    if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {\n\n      get_band_float_line(fin, self->meta, self->hh_amp_band, row, amp_buf);\n      get_band_float_line(fin, self->meta, self->hh_phase_band, row, phase_buf);\n      for (k=0; k<ns; ++k)\n\tself->s2_lines[last][k].hh = complex_new_polar(sqrt(amp_buf[k]),\n\t\t\t\t\t\t       phase_buf[k]);\n      \n      get_band_float_line(fin, self->meta, self->hv_amp_band, row, amp_buf);\n      get_band_float_line(fin, self->meta, self->hv_phase_band, row, phase_buf);\n      for (k=0; k<ns; ++k)\n\tself->s2_lines[last][k].hv = complex_new_polar(sqrt(amp_buf[k]),\n\t\t\t\t\t\t       phase_buf[k]);\n      \n      get_band_float_line(fin, self->meta, self->vh_amp_band, row, amp_buf);\n      get_band_float_line(fin, self->meta, self->vh_phase_band, row, phase_buf);\n      for (k=0; k<ns; ++k)\n\tself->s2_lines[last][k].vh = complex_new_polar(sqrt(amp_buf[k]),\n\t\t\t\t\t\t       phase_buf[k]);\n      \n      get_band_float_line(fin, self->meta, self->vv_amp_band, row, amp_buf);\n      get_band_float_line(fin, self->meta, self->vv_phase_band, row, phase_buf);\n      for (k=0; k<ns; ++k)\n\tself->s2_lines[last][k].vv = complex_new_polar(sqrt(amp_buf[k]),\n\t\t\t\t\t\t       phase_buf[k]);\n    }\n    else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n \n      get_band_float_line(fin, self->meta, self->c11_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[last][k].c11 = amp_buf[k];\n\n      get_band_float_line(fin, self->meta, self->c12_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[last][k].c12_real = amp_buf[k];\n\n      get_band_float_line(fin, self->meta, self->c12_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[last][k].c12_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c13_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[last][k].c13_real = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c13_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[last][k].c13_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c22_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[last][k].c22 = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c23_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[last][k].c23_real = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c23_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[last][k].c23_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c33_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[last][k].c33 = amp_buf[k]; \n    }\n    else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {\n \n      get_band_float_line(fin, self->meta, self->t11_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[last][k].t11 = amp_buf[k];\n\n      get_band_float_line(fin, self->meta, self->t12_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[last][k].t12_real = amp_buf[k];\n\n      get_band_float_line(fin, self->meta, self->t12_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[last][k].t12_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t13_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[last][k].t13_real = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t13_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[last][k].t13_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t22_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[last][k].t22 = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t23_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[last][k].t23_real = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t23_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[last][k].t23_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t33_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[last][k].t33 = amp_buf[k]; \n    }\n    \n    calculate_pauli_for_row(self, last);\n    calculate_coherence_for_row(self, last);\n  }\n  else {\n    // window has scrolled off top of image -- fill with zeros\n    for (k=0; k<self->meta->general->sample_count; ++k) {\n      if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX)\n\tself->s2_lines[last][k] = qual_pol_s2_zero();\n      else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX)\n\tself->c3_lines[last][k] = qual_pol_c3_zero();\n      else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX)\n\tself->t3_lines[last][k] = qual_pol_t3_zero();\n      self->pauli_lines[last][k].A = 0.0;\n      self->pauli_lines[last][k].B = 0.0;\n      self->pauli_lines[last][k].C = 0.0;\n    }\n  }\n  \n  free(amp_buf);\n  if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX)\n    free(phase_buf);\n  if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n    free(c11);\n    free(c12_real);\n    free(c12_imag);\n    free(c13_real);\n    free(c13_imag);\n    free(c22);\n    free(c23_real);\n    free(c23_imag);\n    free(c33);\n  }\n  if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {\n    free(t11);\n    free(t12_real);\n    free(t12_imag);\n    free(t13_real);\n    free(t13_imag);\n    free(t22);\n    free(t23_real);\n    free(t23_imag);\n    free(t33);\n  }\n}\n\nstatic void polarimetric_image_rows_load_new_rows(PolarimetricImageRows *self,\n                                                  FILE *fin)\n{\n  int i,k,ns = self->meta->general->sample_count;\n\n  float *amp_buf=NULL, *phase_buf=NULL;\n  float *c11=NULL, *c12_real=NULL, *c12_imag=NULL, *c13_real=NULL;\n  float *c13_imag=NULL, *c22=NULL, *c23_real=NULL, *c23_imag=NULL, *c33=NULL;\n  float *t11=NULL, *t12_real=NULL, *t12_imag=NULL, *t13_real=NULL;\n  float *t13_imag=NULL, *t22=NULL, *t23_real=NULL, *t23_imag=NULL, *t33=NULL;\n  float phase, phase12, phase13, phase23;\n  float C11, C12_real, C12_imag, C13_real, C13_imag;\n  float C22, C23_real, C23_imag, C33;\n\n  amp_buf = MALLOC(sizeof(float)*ns);\n\n  if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {\n    phase_buf = MALLOC(sizeof(float)*ns);\n  }\n  else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n    c11 = MALLOC(sizeof(float)*ns);\n    c12_real = MALLOC(sizeof(float)*ns);\n    c12_imag = MALLOC(sizeof(float)*ns);\n    c13_real = MALLOC(sizeof(float)*ns);\n    c13_imag = MALLOC(sizeof(float)*ns);\n    c22 = MALLOC(sizeof(float)*ns);\n    c23_real = MALLOC(sizeof(float)*ns);\n    c23_imag = MALLOC(sizeof(float)*ns);\n    c33 = MALLOC(sizeof(float)*ns);\n  }\n  else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {\n    t11 = MALLOC(sizeof(float)*ns);\n    t12_real = MALLOC(sizeof(float)*ns);\n    t12_imag = MALLOC(sizeof(float)*ns);\n    t13_real = MALLOC(sizeof(float)*ns);\n    t13_imag = MALLOC(sizeof(float)*ns);\n    t22 = MALLOC(sizeof(float)*ns);\n    t23_real = MALLOC(sizeof(float)*ns);\n    t23_imag = MALLOC(sizeof(float)*ns);\n    t33 = MALLOC(sizeof(float)*ns);\n  }\n\n  int amp_band = self->amp_band;\n  if (amp_band < 0)\n    amp_band = self->hh_amp_band;\n\n  // multilook the amplitude values as we go\n  for (k=0; k<ns; ++k)\n    self->amp[k] = 0.0;\n\n  for (i=0; i<self->nrows; ++i) {\n    int row = self->current_row + i;\n    get_band_float_line(fin, self->meta, amp_band, row, amp_buf);\n    for (k=0; k<ns; ++k)\n      self->amp[k] += amp_buf[k];\n\n    // now the SLC rows\n    if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {\n\n      get_band_float_line(fin, self->meta, self->hh_amp_band, row, amp_buf);\n      get_band_float_line(fin, self->meta, self->hh_phase_band, row, phase_buf);\n      for (k=0; k<ns; ++k)\n\tself->s2_lines[i][k].hh = complex_new_polar(sqrt(amp_buf[k]),\n\t\t\t\t\t\t    phase_buf[k]);\n      \n      get_band_float_line(fin, self->meta, self->hv_amp_band, row, amp_buf);\n      get_band_float_line(fin, self->meta, self->hv_phase_band, row, phase_buf);\n      for (k=0; k<ns; ++k)\n\tself->s2_lines[i][k].hv = complex_new_polar(sqrt(amp_buf[k]),\n\t\t\t\t\t\t    phase_buf[k]);\n      \n      get_band_float_line(fin, self->meta, self->vh_amp_band, row, amp_buf);\n      get_band_float_line(fin, self->meta, self->vh_phase_band, row, phase_buf);\n      for (k=0; k<ns; ++k)\n\tself->s2_lines[i][k].vh = complex_new_polar(sqrt(amp_buf[k]),\n\t\t\t\t\t\t    phase_buf[k]);\n      \n      get_band_float_line(fin, self->meta, self->vv_amp_band, row, amp_buf);\n      get_band_float_line(fin, self->meta, self->vv_phase_band, row, phase_buf);\n      for (k=0; k<ns; ++k)\n\tself->s2_lines[i][k].vv = complex_new_polar(sqrt(amp_buf[k]),\n\t\t\t\t\t\t    phase_buf[k]);\n    }\n    else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n \n      get_band_float_line(fin, self->meta, self->c11_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[i][k].c11 = amp_buf[k];\n\n      get_band_float_line(fin, self->meta, self->c12_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[i][k].c12_real = amp_buf[k];\n\n      get_band_float_line(fin, self->meta, self->c12_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[i][k].c12_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c13_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[i][k].c13_real = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c13_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[i][k].c13_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c22_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[i][k].c22 = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c23_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[i][k].c23_real = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c23_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[i][k].c23_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->c33_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->c3_lines[i][k].c33 = amp_buf[k]; \n    }\n    else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {\n \n      for (k=0; k<ns; ++k)\n\tself->t3_lines[i][k].t11 = amp_buf[k];\n\n      get_band_float_line(fin, self->meta, self->t12_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[i][k].t12_real = amp_buf[k];\n\n      get_band_float_line(fin, self->meta, self->t12_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[i][k].t12_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t13_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[i][k].t13_real = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t13_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[i][k].t13_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t22_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[i][k].t22 = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t23_real_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[i][k].t23_real = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t23_imag_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[i][k].t23_imag = amp_buf[k]; \n\n      get_band_float_line(fin, self->meta, self->t33_band, row, amp_buf);\n      for (k=0; k<ns; ++k)\n\tself->t3_lines[i][k].t33 = amp_buf[k]; \n\n    }\n\n    calculate_pauli_for_row(self, i);\n    calculate_coherence_for_row(self, i);\n  }\n\n  // we multilook the amplitude data now, since we only keep one row\n  // around-- the rest of the stuff is not multilooked since it isn't\n  // the final result (all rows are kept in memory)\n  for (k=0; k<ns; ++k)\n    self->amp[k] /= self->nrows;\n\n  self->current_row += self->nrows;\n\n  free(amp_buf);\n  if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX)\n    free(phase_buf);\n  if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n    free(c11);\n    free(c12_real);\n    free(c12_imag);\n    free(c13_real);\n    free(c13_imag);\n    free(c22);\n    free(c23_real);\n    free(c23_imag);\n    free(c33);\n  }\n  if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {\n    free(t11);\n    free(t12_real);\n    free(t12_imag);\n    free(t13_real);\n    free(t13_imag);\n    free(t22);\n    free(t23_real);\n    free(t23_imag);\n    free(t33);\n  }\n}\n\nstatic void polarimetric_image_rows_free(PolarimetricImageRows* self)\n{\n    free(self->amp);\n    if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {\n      free(self->s2_data_buffer);\n      free(self->s2_lines);\n    }\n    if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {\n      free(self->c3_data_buffer);\n      free(self->c3_lines);\n    }\n    if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {\n      free(self->t3_data_buffer);\n      free(self->t3_lines);\n    }\n    free(self->pauli_buffer);\n    free(self->pauli_lines);\n\n    int i;\n    for (i=0; i<self->nrows*self->meta->general->sample_count; ++i)\n        complex_matrix_free(self->coh_buffer[i]);\n\n    free(self->coh_buffer);\n    free(self->coh_lines);\n\n    // do not free metadata pointer!\n    free(self);\n}\n\nstatic double log3(double v)\n{\n    return log(v)/log(3.);\n}\n\n// Dump a 2D histogram image in entropy-alpha space\n// the array is twice as wide as it is tall -- we use a square histogram,\n// but generate two of them -- the \"left\" one is the 0<anisotropy<.5\n// histogram, and the \"right\" is the .5<anisotropy<1 one.\n\n// For Cloude-Pottier-8, anisotropy is ignored so when the histogram is\n// dumped the two sides are added together, and we only dump the left\n// half of the arrays when generating the histogram and classification map\n\n// For Cloude-Potter-16, we dump the double-wide histograms and\n// classification maps.\n\n#define HIST_SIZE 512\nint hist_vals[HIST_SIZE][HIST_SIZE][HIST_SIZE];\nint class_map[HIST_SIZE][HIST_SIZE*2];\n\n#define ENTROPY_ALPHA 0\n#define ALPHA_ANISOTROPY 1\n#define ANISOTROPY_ENTROPY 2\n\nstatic int get_hist_val(int which, int ii, int jj, int kk)\n{\n  switch (which) {\n    default:\n    case ENTROPY_ALPHA:\n      return hist_vals[jj][ii][kk];\n    case ALPHA_ANISOTROPY:\n      return hist_vals[kk][ii][jj];\n    case ANISOTROPY_ENTROPY:\n      return hist_vals[jj][kk][ii];\n  }\n}\n\nstatic void dump_hist(const char *base_filename, int which)\n{\n  char *filename = NULL;\n  switch (which) {\n    default:\n    case ENTROPY_ALPHA:\n      filename = appendToBasename(base_filename, \"_entropy_alpha_hist\");\n      break;\n    case ALPHA_ANISOTROPY:\n      filename = appendToBasename(base_filename, \"_alpha_anisotropy_hist\");\n      break;\n    case ANISOTROPY_ENTROPY:\n      filename = appendToBasename(base_filename, \"_anisotropy_entropy_hist\");\n      break;\n  }\n\n  int size = HIST_SIZE;\n  meta_parameters *m = raw_init();\n  m->general->line_count = size;\n  m->general->sample_count = size;\n  m->general->data_type = INTEGER16;\n  m->general->no_data = 0;\n  m->general->image_data_type = IMAGE;\n  strcpy(m->general->basename, filename);\n  m->general->band_count = 1;\n\n  switch (which) {\n    default:\n      strcpy(m->general->bands, \"???\");\n      break;\n    case ENTROPY_ALPHA:\n      strcpy(m->general->bands, \"Entropy-Alpha\");\n      break;\n    case ALPHA_ANISOTROPY:\n      strcpy(m->general->bands, \"Anisotropy-Alpha\");\n      break;\n    case ANISOTROPY_ENTROPY:\n      strcpy(m->general->bands, \"Entropy-Anisotropy\");\n      break;\n  }\n\n  char *meta_file = appendExt(filename, \".meta\");\n  char *img_file = appendExt(filename, \".img\");\n  meta_write(m, meta_file);\n\n  FILE *fp = fopenImage(img_file, \"wb\");\n\n  int i,j,k;\n\n    // which= ENTROPY_ALPHA:\n    //   i= alpha index  [VERTICAL]\n    //   j= entropy index [HORIZONTAL]\n    // which= ALPHA_ANISOTROPY:\n    //   i= alpha index  [VERTICAL]\n    //   j= anisotropy index [HORIZONTAL]\n    // which= ANISOTROPY_ENTROPY:\n    //   i= anisotropy index [VERTICAL]\n    //   j= entropy index [HORIZONTAL]\n\n  float *buf = MALLOC(sizeof(float)*size);\n  for (i=0; i<size; ++i) {\n    for (j=0; j<size; ++j) {\n      buf[j] = 0;\n      for (k=0; k<size; ++k)\n        buf[j] += get_hist_val(which,i,j,k);\n      if (buf[j] > 32767) // avoid overflow\n        buf[j] = 32767;\n    }\n    put_float_line(fp,m,i,buf);\n  }\n\n  free(buf);\n  fclose(fp);\n  meta_free(m);\n\n  free(meta_file);\n  free(img_file);\n  free(filename);\n}\n\nstatic void dump_combined_hist(const char *base_filename)\n{\n  char *filename = appendToBasename(base_filename, \"_combined_hist\");\n  int i,j,k,size=HIST_SIZE;\n\n  meta_parameters *m = raw_init();\n  m->general->line_count = size*2;\n  m->general->sample_count = size*2;\n  m->general->data_type = INTEGER16;\n  m->general->image_data_type = IMAGE;\n  m->general->no_data = 0;\n  m->general->band_count = 1;\n  strcpy(m->general->bands, \"Histogram\");\n  strcpy(m->general->basename, filename);\n\n  char *meta_file = appendExt(filename, \".meta\");\n  char *img_file = appendExt(filename, \".img\");\n  meta_write(m, meta_file);\n\n  FILE *fp = fopenImage(img_file, \"wb\");\n  float *buf = MALLOC(sizeof(float)*size*2);\n\n  // for the top size lines:\n  //  left half = anisotropy/alpha\n  //  right half = entropy/alpha\n\n  for (i=0; i<size; ++i) {\n    for (j=0; j<size; ++j) {\n      buf[j] = 0;\n      for (k=0; k<size; ++k)\n        buf[j] += get_hist_val(ALPHA_ANISOTROPY,i,j,k);\n    }\n    for (j=0; j<size; ++j) {\n      int jj = j+size;\n      buf[jj] = 0;\n      for (k=0; k<size; ++k)\n        buf[jj] += get_hist_val(ENTROPY_ALPHA,i,j,k);\n    }\n    // avoid overflow\n    for (j=0; j<size*2; ++j) {\n      if (buf[j] > 32767) \n        buf[j] = 32767;\n    }\n    put_float_line(fp,m,i,buf);\n  }\n\n  // for the bottom size lines:\n  //  left half = zeros\n  //  right half = anisotropy/entropy\n\n  for (j=0; j<size; ++j)\n    buf[j] = 0;\n  for (i=0; i<size; ++i) {\n    for (j=0; j<size; ++j) {\n      int jj = j+size;\n      buf[jj] = 0;\n      for (k=0; k<size; ++k)\n        buf[jj] += get_hist_val(ANISOTROPY_ENTROPY,i,j,k);\n      if (buf[jj] > 32767) \n        buf[jj] = 32767;\n    }\n    put_float_line(fp,m,i+size,buf);\n  }\n\n  free(buf);\n  fclose(fp);\n  meta_free(m);\n\n  free(meta_file);\n  free(img_file);\n  free(filename);\n}\n\nstatic void dump_class_map(const char *base_filename, int wide)\n{\n  char *filename = appendToBasename(base_filename, \"_class_map\");\n\n  int height = HIST_SIZE;\n  int width = wide ? HIST_SIZE*2 : HIST_SIZE;\n\n  meta_parameters *m = raw_init();\n  m->general->line_count = height;\n  m->general->sample_count = width;\n  m->general->data_type = BYTE;\n  m->general->image_data_type = IMAGE;\n  strcpy(m->general->basename, filename);\n\n  char *meta_file = appendExt(filename, \".meta\");\n  char *img_file = appendExt(filename, \".img\");\n  meta_write(m, meta_file);\n\n  FILE *fp = fopenImage(img_file, \"wb\");\n\n  int i,j;\n  float *buf = MALLOC(sizeof(float)*width);\n\n  for (i=0; i<height; ++i) {\n    for (j=0; j<width; ++j)\n      buf[j] = class_map[i][j];\n    put_float_line(fp,m,i,buf);\n  }\n\n  free(buf);\n  fclose(fp);\n  meta_free(m);\n\n  free(meta_file);\n  free(img_file);\n  free(filename);\n}\n\nstatic double calc_alpha_real(double e)\n{\n  // still not entirely clear why we have to put fabs() here\n  double alpha = acos(fabs(e));\n\n  // alpha should be 0-90\n  if (alpha < 0 || alpha > 1.571) {\n    printf(\"Invalid alpha value: %f\\n\", alpha);\n    alpha = 0;\n  }\n\n  return alpha;\n}\n\nstatic double calc_alpha(gsl_complex z)\n{\n  // alpha: acos(e[0]), e=eigenvector of coherence matrix\n  return calc_alpha_real(GSL_REAL(z));\n}\n\nstatic void add_boundary(int wide)\n{\n  const char *boundary_file = \"classifications/ea_boundary.txt\";\n\n  if (share_file_exists(boundary_file)) {\n    FILE *fp = fopen_share_file(boundary_file,\"r\");\n\n    // fopen_share_file() dies if it failed to open\n    assert(fp); \n\n    int k;\n    char line[256];\n\n    // skip past the header line, size line, blank line, headings line\n    for (k=0; k<4; ++k)\n      fgets(line,256,fp); \n\n    // now read the actual points\n    while (fgets(line,256,fp)) {\n      double entropy, alpha;\n      sscanf(line,\"%lf,%lf\", &entropy, &alpha);\n      int i = (HIST_SIZE-1)*(1-alpha/90.);\n      int j = entropy*HIST_SIZE;\n      class_map[i][j] = 255;\n      if (wide)\n        class_map[i][j+HIST_SIZE] = 255;\n    }\n    FCLOSE(fp);\n  }\n  else {\n    asfPrintStatus(\"Boundary map file (ea_boundary.txt) file not found.\"\n        \"\\n*** To get the entropy/alpha feasibilty region boundary on the \"\n        \"classification\\n    map, see asf_calpol.\\n\");\n  }\n}\n\nstatic void do_sinclair_bands(int band1, int band2, int band3,\n                              PolarimetricImageRows *img_rows,\n                              int line, int l, int multi, int chunk_size,\n                              meta_parameters *outMeta, FILE *fout,\n                              float *buf)\n{\n  int j, m;\n  int ns = outMeta->general->sample_count;\n\n  if (multi) {\n    // multilook case -- average all buffered lines to produce a\n    // single output line\n    if (band1 >= 0) {\n      for (j=0; j<ns; ++j) {\n        buf[j] = 0.0;\n        for (m=0; m<chunk_size; ++m)\n          buf[j] += complex_amp(img_rows->s2_lines[m][j].hh);\n        buf[j] /= (float)chunk_size;\n      }\n      put_band_float_line(fout, outMeta, band1, line, buf);\n    }\n    if (band2 >= 0) {\n      for (j=0; j<ns; ++j) {\n        buf[j] = 0.0;\n        for (m=0; m<chunk_size; ++m) {\n          complexFloat c = complex_add(img_rows->s2_lines[m][j].hv,\n                                       img_rows->s2_lines[m][j].vh);\n          buf[j] += complex_amp(complex_scale(c, 0.5));\n        }\n        buf[j] /= (float)chunk_size;\n      }\n      put_band_float_line(fout, outMeta, band2, line, buf);\n    }\n    if (band3 >= 0) {\n      for (j=0; j<ns; ++j) {\n        buf[j] = 0.0;\n        for (m=0; m<chunk_size; ++m)\n          buf[j] += complex_amp(img_rows->s2_lines[m][j].vv);\n        buf[j] /= (float)chunk_size;\n      }\n      put_band_float_line(fout, outMeta, band3, line, buf);\n    }\n  }\n  else {\n    // not multilooking -- no averaging necessary\n    if (band1 >= 0) {\n      for (j=0; j<ns; ++j)\n        buf[j] = complex_amp(img_rows->s2_lines[l][j].hh);\n      put_band_float_line(fout, outMeta, band1, line, buf);\n    }\n    if (band2 >= 0) {\n      for (j=0; j<ns; ++j) {\n        complexFloat c = complex_add(img_rows->s2_lines[l][j].hv,\n                                     img_rows->s2_lines[l][j].vh);\n        buf[j] = complex_amp(complex_scale(c, 0.5));\n      }\n      put_band_float_line(fout, outMeta, band2, line, buf);\n    }\n    if (band3 >= 0) {\n      for (j=0; j<ns; ++j)\n        buf[j] = complex_amp(img_rows->s2_lines[l][j].vv);\n      put_band_float_line(fout, outMeta, band3, line, buf);\n    }\n  }\n}\n\nstatic void do_pauli_bands(int band1, int band2, int band3,\n                           PolarimetricImageRows *img_rows,\n                           int line, int l, int multi, int chunk_size,\n                           meta_parameters *outMeta, FILE *fout,\n                           float *buf)\n{\n  int j, m;\n  int ns = outMeta->general->sample_count;\n\n  if (multi) {\n    // multilook case -- average all buffered lines to produce a\n    // single output line\n    if (band1 >= 0) {\n      for (j=0; j<ns; ++j) {\n        buf[j] = 0.0;\n        for (m=0; m<chunk_size; ++m)\n          buf[j] += img_rows->pauli_lines[m][j].A;\n\t//buf[j] += complex_amp(img_rows->pauli_lines[m][j].A);\n        buf[j] /= (float)chunk_size;\n      }\n      put_band_float_line(fout, outMeta, band1, line, buf);\n    }\n    if (band2 >= 0) {\n      for (j=0; j<ns; ++j) {\n        buf[j] = 0.0;\n        for (m=0; m<chunk_size; ++m)\n          buf[j] += img_rows->pauli_lines[m][j].B;\n\t//buf[j] += complex_amp(img_rows->pauli_lines[m][j].B);\n        buf[j] /= (float)chunk_size;\n      }\n      put_band_float_line(fout, outMeta, band2, line, buf);\n    }\n    if (band3 >= 0) {\n      for (j=0; j<ns; ++j) {\n        buf[j] = 0.0;\n        for (m=0; m<chunk_size; ++m)\n          buf[j] += img_rows->pauli_lines[m][j].C;\n\t//buf[j] += complex_amp(img_rows->pauli_lines[m][j].C);\n        buf[j] /= (float)chunk_size;\n      }\n      put_band_float_line(fout, outMeta, band3, line, buf);\n    }\n  }\n  else {\n    // not multilooking -- no averaging necessary\n    if (band1 >= 0) {\n      for (j=0; j<ns; ++j)\n        buf[j] = img_rows->pauli_lines[l][j].A;\n      //buf[j] = complex_amp(img_rows->pauli_lines[l][j].A);\n      put_band_float_line(fout, outMeta, band1, line, buf);\n    }\n    if (band2 >= 0) {\n      for (j=0; j<ns; ++j)\n        buf[j] = img_rows->pauli_lines[l][j].B;\n      //buf[j] = complex_amp(img_rows->pauli_lines[l][j].B);\n      put_band_float_line(fout, outMeta, band2, line, buf);\n    }\n    if (band3 >= 0) {\n      for (j=0; j<ns; ++j)\n        buf[j] = img_rows->pauli_lines[l][j].C;\n      //buf[j] = complex_amp(img_rows->pauli_lines[l][j].C);\n      put_band_float_line(fout, outMeta, band3, line, buf);\n    }\n  }\n}\n\nstatic void\ndo_coherence_bands(int entropy_band, int anisotropy_band, int alpha_band,\n                   int class_band,\n                   PolarimetricImageRows *img_rows,\n                   int line, int l, int multi, int chunk_size,\n                   gsl_matrix_complex *T, gsl_vector *eval,\n                   gsl_matrix_complex *evec, gsl_eigen_hermv_workspace *ws,\n                   meta_parameters *outMeta, FILE *fout,\n                   float *buf, classifier_t *classifier)\n{\n  if (entropy_band >= 0 || anisotropy_band >= 0 || alpha_band >= 0 || \n      class_band >= 0)\n  {\n    int ns = outMeta->general->sample_count;\n    int onl = outMeta->general->line_count;\n\n    float *entropy = MALLOC(sizeof(float)*ns);\n    float *anisotropy = MALLOC(sizeof(float)*ns);\n    float *alpha = MALLOC(sizeof(float)*ns);\n\n    // size of the horizontal window, used for ensemble averaging\n    // actual window size is hw*2+1\n    int hw;\n    if (multi)\n      hw = 0; // no horizontal averaging\n    else\n      hw = 2; // 5 pixels averaging horizontally\n\n    // coherence -- do ensemble averaging for each element\n    int j;\n    for (j=0; j<ns; ++j) {\n      int ii,jj,m;\n      for (ii=0; ii<3; ++ii) {\n        for (jj=0; jj<3; ++jj) {\n          gsl_complex c = gsl_complex_rect(0,0);\n          int k,n=0;\n          for (m=0; m<chunk_size; ++m) {\n            for (k=j-hw;k<=j+hw;++k) {\n              if (k>=0 && k<ns && m+line>l && m+line<onl-l) {\n                ++n;\n                complexFloat f =\n                  img_rows->coh_lines[m][k]->coeff[ii][jj];\n                c = gsl_complex_add_real(c, f.real);\n                c = gsl_complex_add_imag(c, f.imag);\n              }\n            }\n          }\n          if (n>1) {\n            gsl_complex_div_real(c, (float)n);\n          }\n          gsl_matrix_complex_set(T,ii,jj,c);\n        }\n      }\n      \n      gsl_eigen_hermv(T, eval, evec, ws);\n      gsl_eigen_hermv_sort(eval, evec, GSL_EIGEN_SORT_ABS_DESC);\n      \n      double e1 = gsl_vector_get(eval, 0);\n      double e2 = gsl_vector_get(eval, 1);\n      double e3 = gsl_vector_get(eval, 2);\n      \n      double eT = e1+e2+e3;\n      \n      double P1 = e1/eT;\n      double P2 = e2/eT;\n      double P3 = e3/eT;\n      \n      double P1l3 = log3(P1);\n      double P2l3 = log3(P2);\n      double P3l3 = log3(P3);\n      \n      // If a Pn value is small enough, the log value will be NaN.\n      // In this case, the value of -Pn*log3(Pn) is supposed to be\n      // zero - we have to force it.\n      entropy[j] =\n        (meta_is_valid_double(P1l3) ? -P1*P1l3 : 0) +\n        (meta_is_valid_double(P2l3) ? -P2*P2l3 : 0) +\n        (meta_is_valid_double(P3l3) ? -P3*P3l3 : 0);\n      \n      // mathematically, entropy is limited to be between 0 and 1.\n      // however it sometimes is just a bit out of that range due\n      // to numerical anomalies\n      if (!meta_is_valid_double(entropy[j]))\n        entropy[j] = 0.0;\n      else if (entropy[j] < 0)\n        entropy[j] = 0.0;\n      else if (entropy[j] > 1)\n        entropy[j] = 1.0;\n      \n      if (e2+e3 != 0)\n        anisotropy[j] = (e2-e3)/(e2+e3);\n      else\n        anisotropy[j] = 0;\n      \n      // as for entropy, anisotropy is limited to be between 0 and 1.\n      // guard against numerical anomalies (usually this is due to\n      // one really big eigenvalue)\n      if (!meta_is_valid_double(anisotropy[j]))\n        anisotropy[j] = 0.0;\n      else if (anisotropy[j] < 0)\n        anisotropy[j] = 0.0;\n      else if (anisotropy[j] > 1)\n        anisotropy[j] = 1.0;\n      \n      // calculate the \"mean alpha\" (mean scattering angle)\n      // this is the polar angle when expressing each eigenvector\n      // in spherical coordinates.  the mean alpha is weighted by\n      // the eigenvector (so weight by P1-3)\n      double alpha1 = calc_alpha(gsl_matrix_complex_get(evec, 0, 0));\n      double alpha2 = calc_alpha(gsl_matrix_complex_get(evec, 0, 1));\n      double alpha3 = calc_alpha(gsl_matrix_complex_get(evec, 0, 2));\n      \n      alpha[j] = R2D*(P1*alpha1 + P2*alpha2 + P3*alpha3);\n      if (!meta_is_valid_double(alpha[j]))\n        alpha[j] = 0.0;\n    }\n    \n    if (entropy_band >= 0)\n      put_band_float_line(fout, outMeta, entropy_band, line, entropy);\n    if (anisotropy_band >= 0)\n      put_band_float_line(fout, outMeta, anisotropy_band, line, anisotropy);\n    if (alpha_band >= 0)\n      put_band_float_line(fout, outMeta, alpha_band, line, alpha);\n    \n    if (class_band >= 0) {\n      assert(classifier != NULL);\n      for (j=0; j<ns; ++j) {\n        buf[j] = (float)classify(classifier, entropy[j], anisotropy[j],\n                                 alpha[j]);\n      }\n      put_band_float_line(fout, outMeta, class_band, line, buf);\n    }\n\n    for (j=0; j<ns; ++j) {\n      int entropy_index = entropy[j]*(float)HIST_SIZE;\n      if (entropy_index<0) entropy_index=0;\n      if (entropy_index>HIST_SIZE-1) entropy_index=HIST_SIZE-1;\n            \n      int alpha_index = HIST_SIZE-1-alpha[j]/90.0*(float)HIST_SIZE;\n      if (alpha_index<0) alpha_index=0;\n      if (alpha_index>HIST_SIZE-1) alpha_index=HIST_SIZE-1;\n      \n      //printf(\"%10.1f %10.1f %5d %5d --> %4d\\n\",\n      //       entropy[j], alpha[j],\n      //       entropy_index, alpha_index,\n      //      ea_hist[entropy_index][alpha_index]+1);\n      int anisotropy_index = anisotropy[j]*(float)HIST_SIZE;\n      hist_vals[entropy_index][alpha_index][anisotropy_index] += 1;\n    }\n\n    free(entropy);\n    free(anisotropy);\n    free(alpha);\n  }\n}\n\nstatic int verify_equal_re(const char *id, float lhs, float rhs)\n{\n  if (fabs(lhs - rhs) > .001) {\n    //printf(\"Not equal (%s): %f != %f\\n\", id, lhs, rhs);\n    return FALSE;\n  }\n  return TRUE;\n}\n\nstatic int verify_equal_cpx(const char *id, complexFloat lhs, complexFloat rhs)\n{\n  if (fabs(lhs.real - rhs.real) > .001 ||\n      fabs(lhs.imag - rhs.imag) > .001)\n  {\n    //printf(\"Not equal (%s): (%f,%f) != (%f,%f)\\n\", id,\n    //       lhs.real, lhs.imag, rhs.real, rhs.imag);\n    return FALSE;\n  }\n  return TRUE;\n}\n\nstatic int verify_fd(float hh2, float vv2, complexFloat hhvv, float fs,\n                     float fd, complexFloat alpha, complexFloat beta)\n{\n  int ok1,ok2,ok3;\n\n  // (1) hh2 = fs*beta*beta + fd*alpha*alpha\n  ok1 = verify_equal_re(\"Eq. 1\", hh2, fs*complex_amp_sqr(beta) +\n                                      fd*complex_amp_sqr(alpha));\n  // (2) vv2 = fs + fd\n  ok2 = verify_equal_re(\"Eq. 2\", vv2, fs+fd);\n\n  // (3) hhvv = fs*beta + fd*alpha\n  ok3 = verify_equal_cpx(\"Eq. 3\", hhvv, complex_add(\n                           complex_scale(beta, fs), complex_scale(alpha, fd)));\n\n  return ok1 && ok2 && ok3;\n}\n\nstatic void solve_fd1(float hh2, float vv2, complexFloat hhvv,\n                      float *fs, float *fd, complexFloat *beta)\n{\n  // 3 equations with 3 unknowns: (complex)\n  //   |hh|^2 = fd + |b|^2 * fs\n  //   |vv|^2 = fs + fd\n  //   hh*conj(vv) = b*fs - fd\n  \n  // fs, fd are real.  beta (b) is complex.\n  // splitting beta into br and bi (real and imaginary)\n  // 4 equations and 4 unknown: (real)\n  //   |hh|^2 = fd + |b|^2 * fs\n  //   |vv|^2 = fs + fd\n  //   Re(hh*conj(vv)) = br*fs - fd\n  //   Im(hh*conj(vv)) = bi*fs\n\n  // For brevity:\n  float x = hhvv.real;\n  float y = hhvv.imag;\n  float h = hh2;\n  float v = vv2;\n\n  // Analytic solution of the 4 equations & 4 unknowns:\n  //   fd = (-x^2 - y^2 + hv) / D1\n  //   br = (hx + v^2 + hv + 3xv + 2x^2) / D2 - 1\n  //   bi = D1 * y / D2\n  //   fs = D2 / D1\n  // where\n  //   D1 = h + v + 2x\n  //   D2 = v^2 + 2xv + x^2 + y^2\n  \n  float D1 = h + v + 2.*x;\n  float D2 = v*v + 2.*x*v + x*x + y*y;\n  \n  *fd = (h*v - x*x - y*y) / D1;\n  *fs = D2 / D1;\n     \n  float br = (h*x + v*v + h*v + 3.*x*v + 2.*x*x) / D2 - 1.;\n  float bi = D1 * y / D2;\n     \n  *beta = complex_new(br,bi);\n}\n\nstatic void solve_fd2(float hh2, float vv2, complexFloat hhvv,\n                      float *fs, float *fd, complexFloat *alpha)\n{\n  // 3 equations with 3 unknowns: (complex)\n  //   |hh|^2 = fs + |a|^2 * fd\n  //   |vv|^2 = fs + fd\n  //   hh*conj(vv) = a*fd + fs\n  \n  // fs, fd are real.  alpha (a) is complex.\n  // splitting alpha into ar and ai (real and imaginary)\n  // 4 equations and 4 unknown: (real)\n  //   |hh|^2 = fs + |a|^2 * fd\n  //   |vv|^2 = fs + fd\n  //   Re(hh*conj(vv)) = ar*fd + fs\n  //   Im(hh*conj(vv)) = ai*fd\n\n  // For brevity:\n  float x = hhvv.real;\n  float y = hhvv.imag;\n  float h = hh2;\n  float v = vv2;\n\n  // Analytic solution of the 4 equations & 4 unknowns:\n  //   fs = (-x^2 - y^2 + hv) / D1\n  //   ar = (hx - v^2 - hv + 3xv - 2x^2) / D2 + 1\n  //   ai = D1 * y / D2\n  //   fd = D2 / D1\n  // where\n  //   D1 = h + v - 2x\n  //   D2 = v^2 - 2xv + x^2 + y^2\n  \n  float D1 = h + v - 2.*x;\n  float D2 = v*v - 2.*x*v + x*x + y*y;\n  \n  *fs = (h*v - x*x - y*y) / D1;\n  *fd = D2 / D1;\n     \n  float ar = (h*x - v*v - h*v + 3.*x*v - 2.*x*x) / D2 + 1.;\n  float ai = D1 * y / D2;\n     \n  *alpha = complex_new(ar,ai);\n}\n\nstatic void do_freeman(int band1, int band2, int band3,\n                       PolarimetricImageRows *img_rows,\n                       int line, int l, int multi, int chunk_size,\n                       meta_parameters *outMeta, FILE *fout)\n{\n  if (band1 >= 0 || band2 >= 0 || band3 >= 0)\n  {\n    //if (outMeta->general->radiometry != r_SIGMA) {\n    //  asfPrintError(\"The Freeman/Durden decomposition requires \"\n    //                \"PowerScale (Sigma, non-db) data.\\n\");\n    //}\n\n    int j, m;\n    int ns = outMeta->general->sample_count;\n\n    float *hh2 = MALLOC(sizeof(float)*ns);\n    float *vv2 = MALLOC(sizeof(float)*ns);\n    float *hv2 = MALLOC(sizeof(float)*ns);\n    complexFloat *hhvv = MALLOC(sizeof(complexFloat)*ns);\n    float sf = 1.0 / (float)chunk_size;\n\n    if (multi) {\n      // multilook case -- average all buffered lines to produce a\n      // single output line\n      for (j=0; j<ns; ++j) {\n\n        hh2[j] = 0.0;\n        vv2[j] = 0.0;\n        hhvv[j] = complex_zero();\n        hv2[j] = 0.0;\n\n        for (m=0; m<chunk_size; ++m) {\n          complexFloat hh = img_rows->s2_lines[m][j].hh;\n          hh2[j] += complex_amp_sqr(hh);\n\n          complexFloat vv = img_rows->s2_lines[m][j].vv;\n          vv2[j] += complex_amp_sqr(vv);\n\n          hhvv[j] = complex_add(hhvv[j], complex_mul(hh, complex_conj(vv)));\n\n          hv2[j] += complex_amp_sqr(img_rows->s2_lines[m][j].hv);\n        }\n\n        hh2[j] *= sf;\n        vv2[j] *= sf;\n        hv2[j] *= sf;\n\n        hhvv[j] = complex_scale(hhvv[j], sf);\n      }\n    }\n    else {\n      // not multilooking -- no averaging necessary\n      for (j=0; j<ns; ++j) {\n        complexFloat hh = img_rows->s2_lines[l][j].hh;\n        hh2[j] = complex_amp_sqr(hh);\n\n        complexFloat vv = img_rows->s2_lines[l][j].vv;\n        vv2[j] = complex_amp_sqr(vv);\n\n        hhvv[j] = complex_mul(hh, complex_conj(vv));\n        hv2[j] = complex_amp_sqr(img_rows->s2_lines[l][j].hv);\n      }\n    }\n\n    float *Ps = MALLOC(sizeof(float)*ns);\n    float *Pd = MALLOC(sizeof(float)*ns);\n    float *Pv = MALLOC(sizeof(float)*ns);\n\n    // now calculate fs, fd and alpha or beta for each sample, and\n    // from those we can get the Ps, Pd, and Pv values\n    for (j=0; j<ns; ++j) {\n      float fs, fd;\n      complexFloat alpha, beta;\n      if (hhvv[j].real > 0) {\n        // Re(Shh*conj(Svv))>0 ==> alpha=-1, solve for fs, fd, and beta\n        solve_fd1(hh2[j], vv2[j], hhvv[j], &fs, &fd, &beta);\n        alpha = complex_new(-1, 0);\n      }\n      else {\n        // Re(Shh*conj(Svv))<0 ==> beta=1, solve for fs, fd, and alpha\n        solve_fd2(hh2[j], vv2[j], hhvv[j], &fs, &fd, &alpha);\n        beta = complex_new(1, 0);\n      }\n\n      // double-check the solution\n      verify_fd(hh2[j], vv2[j], hhvv[j], fs, fd, alpha, beta);\n\n      // now calculate the final contributions from each scattering mechanism\n      Ps[j] = fs * (1. + complex_amp_sqr(beta));\n      Pd[j] = fd * (1. + complex_amp_sqr(alpha));\n      Pv[j] = 8. * hv2[j];\n\n      // convert to dB\n      Ps[j] = 10*log10(Ps[j]*Ps[j]);\n      Pd[j] = 10*log10(Pd[j]*Pd[j]);\n      Pv[j] = 10*log10(Pv[j]*Pv[j]);\n    }\n\n    free(hh2);\n    free(vv2);\n    free(hv2);\n    free(hhvv);\n\n    if (band1 >= 0)\n      put_band_float_line(fout, outMeta, band1, line, Ps);\n    if (band2 >= 0)\n      put_band_float_line(fout, outMeta, band2, line, Pd);\n    if (band3 >= 0)\n      put_band_float_line(fout, outMeta, band3, line, Pv);\n\n    free(Pd);\n    free(Ps);\n    free(Pv);\n  }\n}\n\nstatic void do_class_map(classifier_t *classifier, int class_band, int wide,\n                         const char *outFile)\n{\n  // build the class_map array from the hist_vals array.\n  int i, j, k, size = HIST_SIZE;\n  if (class_band >= 0) {\n    if (!wide) {\n      // non-wide: this is the Cloude-Pottier 8 classes case, where\n      // we use only half of the class_map array\n      for (i=0; i<size; ++i) {\n        double alpha = (double)(size-1-i)/(double)size*90.;\n        class_map[i][0] = 0;\n        for (j=1; j<size; ++j) {\n          int count = 0;\n          for (k=0; k<size; ++k)\n            count += hist_vals[j][i][k];\n          if (count > 0) {\n            double entropy = (double)j/(double)size;\n            class_map[i][j] = classify(classifier, entropy, 0, alpha);\n          }\n          else\n            class_map[i][j] = 0;\n        }\n      }\n      // drawing the white border lines -- assumes look-up-tables use\n      // \"255\" as white.  (cloude8.lut)\n      int prev = -1;\n      for (i=0; i<size; ++i) {\n        double alpha = (double)(size-1-i)/(double)size*90.;\n        for (j=0; j<size; ++j) {\n          double entropy = (double)j/(double)size;\n          int curr = classify(classifier, entropy, 0, alpha);\n          if (j>0 && prev != curr)\n            class_map[i][j] = 255;\n          prev = curr;\n        }\n      }\n      prev = -1;\n      for (j=0; j<size; ++j) {\n        double entropy = (double)j/(double)size;\n        for (i=0; i<size; ++i) {\n          double alpha = (double)(size-1-i)/(double)size*90.;\n          int curr = classify(classifier, entropy, 0, alpha);\n          if (i>0 && prev != curr)\n            class_map[i][j] = 255;\n          prev = curr;\n        }\n      }\n      // if we have the file \"ea_boundary.txt\" in the share directory\n      // (this file can be generated by calling make_entropy_alpha_boundary()\n      // defined below, and exposed via asf_calpol)\n      add_boundary(FALSE);\n\n      dump_class_map(outFile, FALSE);\n    }\n    else {\n      // wide: this is the Cloude-Pottier 16 classes case, where\n      // we use the full (double-width) ea_hist array, the left half\n      // being the anisotropy=0 plane, the right half being the\n      // anisotropy=.5 plane (though we actually use .55 below to ensure\n      // we're definitely in the >.5 blocks -- .5 could possibly be\n      // classified in the (0,.5) range depending on use of <= vs < above,\n      // roundoff, etc)\n      for (i=0; i<size; ++i) {\n        double alpha = (double)(size-1-i)/(double)size*90.;\n        for (j=0; j<size*2; ++j) {\n          if (j==0) {\n            class_map[i][j] = 0;\n          }\n          else if (j == size) {\n            class_map[i][j] = 255;\n          }\n          else {\n            int jj = j;\n            if (j>size) jj -= size;\n            int count = 0;\n            for (k=0; k<size; ++k)\n              count += hist_vals[jj][i][k];\n            if (count > 0) {\n              double entropy = (double)jj/(double)size;\n              double aniso = j > size ? 0.55 : 0.0;\n              class_map[i][j] = classify(classifier, entropy, aniso, alpha);\n            }\n            else\n              class_map[i][j] = 0;\n          }\n        }\n      }\n      // drawing the white border lines -- assumes look-up-tables use\n      // \"255\" as white.  (cloude16.lut)\n      int prev = -1;\n      for (i=0; i<size; ++i) {\n        double alpha = (double)(size-1-i)/(double)size*90.;\n        for (j=0; j<size*2; ++j) {\n          double entropy = j > size ?\n            (double)(j-size)/(double)size :\n            (double)j/(double)size;\n          double aniso = j > size ? 0.55 : 0.0;\n          int curr = classify(classifier, entropy, aniso, alpha);\n          if (j>0 && prev != curr)\n            class_map[i][j] = 255;\n          prev = curr;\n        }\n      }\n      prev = -1;\n      for (j=0; j<size*2; ++j) {\n        double entropy = j > size ?\n          (double)(j-size)/(double)size :\n          (double)j/(double)size;\n        double aniso = j > size ? 0.55 : 0.0;\n        for (i=0; i<size; ++i) {\n          double alpha = (double)(size-1-i)/(double)size*90.;\n          int curr = classify(classifier, entropy, aniso, alpha);\n          if (i>0 && prev != curr)\n            class_map[i][j] = 255;\n          prev = curr;\n        }\n      }\n      // if we have the file \"ea_boundary.txt\" in the share directory\n      // (this file can be generated by calling make_entropy_alpha_boundary()\n      // defined below, and exposed via asf_calpol)\n      add_boundary(TRUE);\n      \n      dump_class_map(outFile, TRUE);\n    }\n  }\n}\n\nvoid polarimetric_decomp(const char *inFile, const char *outFile,\n                         int amplitude_band,\n                         int pauli_1_band,\n                         int pauli_2_band,\n                         int pauli_3_band,\n                         int entropy_band,\n                         int anisotropy_band,\n                         int alpha_band,\n                         int sinclair_1_band,\n                         int sinclair_2_band,\n                         int sinclair_3_band,\n                         int freeman_1_band,\n                         int freeman_2_band,\n                         int freeman_3_band,\n                         const char *classFile,\n                         int class_band)\n{\n  int debug_mode = classFile && strcmp_case(classFile, \"DEBUG\")==0;\n  int debug_band = -1;\n  if (debug_mode) {\n    debug_band = class_band;\n    class_band = -1;\n  }\n\n  char *meta_name = appendExt(inFile, \".meta\");\n  meta_parameters *inMeta = meta_read(meta_name);\n  meta_parameters *outMeta = meta_read(meta_name);\n\n  char *in_img_name = appendExt(inFile, \".img\");\n  char *out_img_name = appendExt(outFile, \".img\");\n\n  int i, j, k;\n  //my_randomize();\n\n  // chunk_size represents the number of rows we keep in memory at one\n  // time, centered on the row currently being processed.  This is to\n  // handle the ensemble averaging that we do\n  int chunk_size = 5;\n  assert((chunk_size-1)%2==0); // chunk_size should be odd\n\n  // If the image is not multilooked, we will multilook it here, and use\n  // the multilooked values for the ensemble averaging.  This will result\n  // in much less smoothing of the image.\n  int multi = FALSE;\n  if (inMeta->sar && inMeta->sar->multilook==0) {\n    multi = TRUE;\n    chunk_size = inMeta->sar->look_count;\n  }\n\n  // aliases\n  int nl = inMeta->general->line_count;\n  int ns = inMeta->general->sample_count;\n\n  FILE *fin = fopenImage(in_img_name, \"rb\");\n  FILE *fout = fopenImage(out_img_name, \"wb\");\n\n  // this struct will hold the current row being processed, and\n  // chunk_size/2 rows before & after\n  PolarimetricImageRows *img_rows =\n      polarimetric_image_rows_new(inMeta, chunk_size, multi);\n\n  // make sure all bands we need are there, and find their numbers\n  // and offsets\n  int ok = polarimetric_image_rows_get_bands(img_rows);\n\n  if (!ok)\n      asfPrintError(\"Not all required bands found-- \"\n                    \"is this SLC quad-pol data?\\n\");\n\n  float *buf = MALLOC(sizeof(float)*ns);\n\n  // at the start, we want to load the buffers as follows: (for chunk_size=5)\n  //   *lines[0] = ALL ZEROS\n  //   *lines[1] = ALL ZEROS\n  //   *lines[2] = line 0 of the image\n  //   *lines[3] = line 1 of the image\n  //   *lines[4] = line 2 of the image\n  // next time through the loop:\n  //   *lines[0] = ALL ZEROS\n  //   *lines[1] = line 0 of the image\n  //   *lines[2] = line 1 of the image\n  //   *lines[3] = line 2 of the image\n  //   *lines[4] = line 3 of the image\n  // we don't actually move the data from line n to line n-1, we just move\n  // the pointers.  initially, the pointers will match the buffer (as set\n  // in the loop directly above), but the second time through the pointers\n  // slide down one row (line 3 is loaded into the beginning of the buffer,\n  // but line pointer 4 points at the beginning).\n\n  if (multi) {\n    // multilook case:\n    // preload rows --> load look_count rows, these will all be combined\n    // to produce a single output line\n    polarimetric_image_rows_load_new_rows(img_rows, fin);\n  }\n  else {\n    // non-multilook case:\n    // preload rows --> center of window will be row 0.\n    // the next (chunk_size+1)/2 rows are also loaded, and ready to go.\n    for (i=0; i<(chunk_size+1)/2; ++i)\n      polarimetric_image_rows_load_next_row(img_rows, fin);    \n    assert(img_rows->current_row == 0);\n  }\n\n  // output metadata differs from input only in the number\n  // of bands, and the band names\n  char *out_meta_name = appendExt(outFile, \".meta\");\n  int nBands =\n      (amplitude_band>=0) +\n      (pauli_1_band>=0) + (pauli_2_band>=0) + (pauli_3_band>=0) +\n      (entropy_band>=0) + (anisotropy_band>=0) + (alpha_band>=0) +\n      (sinclair_1_band>=0) + (sinclair_2_band>=0) + (sinclair_3_band>=0) +\n      (class_band >= 0) +\n      (freeman_1_band>=0) + (freeman_2_band>=0) + (freeman_3_band>=0);\n\n  char bands[255];\n  strcpy(bands, \"\");\n\n  for (i=0; i<10; ++i) {\n      if (amplitude_band == i)\n          strcat(bands, \"HH-AMP,\");\n      else if (sinclair_1_band == i)\n          strcat(bands, \"HH,\");\n      else if (sinclair_2_band == i)\n          strcat(bands, \"HV+VH_2,\");\n      else if (sinclair_3_band == i)\n          strcat(bands, \"VV,\");\n      else if (pauli_1_band == i)\n          strcat(bands, \"HH-VV,\");\n      else if (pauli_2_band == i)\n          strcat(bands, \"HV+VH,\");\n      else if (pauli_3_band == i)\n          strcat(bands, \"HH+VV,\");\n      else if (entropy_band == i)\n          strcat(bands, \"Entropy,\");\n      else if (anisotropy_band == i)\n          strcat(bands, \"Anisotro,\"); // abbreviated version, agrees with GUI\n      else if (alpha_band == i)\n          strcat(bands, \"Alpha,\");\n      else if (freeman_1_band == i)\n          strcat(bands, \"Ps,\");\n      else if (freeman_2_band == i)\n          strcat(bands, \"Pd,\");\n      else if (freeman_3_band == i)\n          strcat(bands, \"Pv,\");\n      else if (class_band == i) {\n        if (!classFile)\n          strcat(bands,\"Classified,\");\n        else if (strncmp_case(classFile,\"cloude8\",7)==0)\n          strcat(bands, \"Cloude-Pottier-8,\");\n        else if (strncmp_case(classFile,\"cloude16\",8)==0)\n          strcat(bands, \"Cloude-Pottier-16,\");\n        else {\n          // append the classification filename as the band name (minus .cla)\n          char *s = appendExt(classFile,\"\");\n          strcat(bands, s);\n          strcat(bands, \",\");\n          free(s);\n        }\n      }\n      else\n          break;\n  }\n\n  if (strlen(bands) > 0) // chop last comma\n      bands[strlen(bands)-1] = '\\0';\n\n  outMeta->general->band_count = nBands;\n  strcpy(outMeta->general->bands, bands);\n\n  // for multilooking, the number of output lines shrinks by look_count\n  int onl = multi ? nl/chunk_size : nl;\n\n  if (multi) {\n    outMeta->sar->multilook = 1;\n    outMeta->general->line_count = onl;\n    outMeta->general->y_pixel_size *= outMeta->sar->look_count;\n    outMeta->sar->azimuth_time_per_pixel *= outMeta->sar->look_count;\n  }\n\n  outMeta->general->image_data_type = POLARIMETRIC_IMAGE;\n  meta_write(outMeta, out_meta_name);\n  free(out_meta_name);\n\n  // set up the classification, if needed\n  classifier_t *classifier = NULL;\n  if (classFile != NULL && class_band >= 0)\n    classifier = read_classifier(classFile);\n\n  // population histogram image, in entropy-alpha space\n  for (i=0; i<HIST_SIZE; ++i)\n    for (j=0; j<HIST_SIZE; ++j)\n      for (k=0; k<HIST_SIZE; ++k)\n        hist_vals[i][j][k] = 0;\n\n  //-----------------------------------------------------------------------\n  // done setting up metadata, now write the data\n\n  // gsl infrastructure for calculating eigen- vals & vecs for the\n  // coherence matrix\n  gsl_matrix_complex *T = gsl_matrix_complex_alloc(3,3);\n  gsl_vector *eval = gsl_vector_alloc(3);\n  gsl_matrix_complex *evec = gsl_matrix_complex_alloc(3,3);\n  gsl_eigen_hermv_workspace *ws = gsl_eigen_hermv_alloc(3);\n\n  // now loop through the lines of the output image\n  for (i=0; i<onl; ++i) {\n\n      // Indicates which line in the various *lines arrays contains\n      // what corresponds to line i in the output. since the line pointers\n      // slide, this never changes.\n      const int l = (chunk_size-1)/2;\n\n      // normal amplitude band (usually, this is added to allow terrcorr)\n      if (amplitude_band >= 0)\n        put_band_float_line(fout, outMeta, amplitude_band, i, img_rows->amp);\n\n      // if requested, generate sinlair output\n      do_sinclair_bands(sinclair_1_band, sinclair_2_band, sinclair_3_band,\n                        img_rows, i, l, multi, chunk_size, outMeta, fout, buf);\n\n      // calculate the pauli output (magnitude of already-calculated\n      // complex pauli basis elements), and save the requested pauli\n      // bands in the output\n      do_pauli_bands(pauli_1_band, pauli_2_band, pauli_3_band,\n                     img_rows, i, l, multi, chunk_size, outMeta, fout, buf);\n\n\n      // Freeman-Durden\n      do_freeman(freeman_1_band, freeman_2_band, freeman_3_band,\n                 img_rows, i, l, multi, chunk_size, outMeta, fout);\n\n      // do any polarimetry that uses the coherence matrix\n      do_coherence_bands(entropy_band, anisotropy_band, alpha_band, class_band,\n                         img_rows, i, l, multi, chunk_size, T, eval, evec, ws,\n                         outMeta, fout, buf, classifier);\n                         \n\n      // load the next row, if there are still more to go\n      if (i<onl-1) {\n          if (multi) {\n              polarimetric_image_rows_load_new_rows(img_rows, fin);\n          }\n          else {\n              polarimetric_image_rows_load_next_row(img_rows, fin);\n              assert(img_rows->current_row == i+1);\n          }\n      }\n\n      asfLineMeter(i,onl);\n  }\n\n  if (entropy_band >= 0 || anisotropy_band >= 0 || alpha_band >= 0 || \n      class_band >= 0)\n  {\n\n    if (entropy_band >= 0 || anisotropy_band >= 0 || alpha_band >= 0)\n      asfPrintStatus(\"Generating population histogram...\\n\");\n    else\n      asfPrintStatus(\"Generating population histograms and \"\n                     \"classification map...\\n\");\n\n    // dump population graph & class map\n    int wide = FALSE;\n    if (class_band >= 0)\n      wide = strncmp_case(classFile,\"cloude16\",8) == 0;\n\n    // dump projections of the 3-d histogram\n    dump_hist(outFile, ENTROPY_ALPHA);\n    dump_hist(outFile, ALPHA_ANISOTROPY);\n    dump_hist(outFile, ANISOTROPY_ENTROPY);\n    dump_combined_hist(outFile);\n\n    // dump classification map (entropy/alpha)\n    do_class_map(classifier, class_band, wide, outFile);\n  }\n\n  gsl_vector_free(eval);\n  gsl_eigen_hermv_free(ws);\n  gsl_matrix_complex_free(evec);\n  gsl_matrix_complex_free(T);\n\n  polarimetric_image_rows_free(img_rows);\n\n  fclose(fin);\n  fclose(fout);\n\n  free(buf);\n\n  free(out_img_name);\n  free(in_img_name);\n  free(meta_name);\n  free_classifier(classifier);\n\n  meta_free(inMeta);\n  meta_free(outMeta);\n}\n\nstatic int has_amp_band(const char *inFile)\n{\n    int ret = FALSE;\n    char *mfile = appendExt(inFile, \".meta\");\n    if (fileExists(mfile)) {\n      meta_parameters *meta = meta_read(mfile);\n      if (strncmp_case(meta->general->bands, \"AMP\", 3) == 0)\n        ret = TRUE;\n      meta_free(meta);\n    }\n    free(mfile);\n    return ret;\n}\n\nvoid cpx2classification(const char *inFile, const char *outFile,\n                        int tc_flag, const char *classFile)\n{\n  if (tc_flag && has_amp_band(inFile))\n    polarimetric_decomp(inFile, outFile,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n                        -1,-1,-1,classFile, 1);\n  else\n    polarimetric_decomp(inFile, outFile,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n                        -1,-1,-1,classFile, 0);\n}\n\nvoid cpx2sinclair(const char *inFile, const char *outFile, int tc_flag)\n{\n  asfPrintStatus(\"\\n\\nGenerating Sinclair decomposition channels\\n\");\n  if (tc_flag && has_amp_band(inFile))\n    polarimetric_decomp(inFile,outFile,0,-1,-1,-1,-1,-1,-1,1,2,3,-1,-1,-1,\n                        NULL,-1);\n  else\n    polarimetric_decomp(inFile,outFile,-1,-1,-1,-1,-1,-1,-1,0,1,2,-1,-1,-1,\n                        NULL,-1);\n}\n\nvoid cpx2pauli(const char *inFile, const char *outFile, int tc_flag)\n{\n  asfPrintStatus(\"\\n\\nGenerating Pauli decomposition channels\\n\");\n  if (tc_flag && has_amp_band(inFile))\n    polarimetric_decomp(inFile,outFile,0,1,2,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n                        NULL,-1);\n  else\n    polarimetric_decomp(inFile,outFile,-1,0,1,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n                        NULL,-1);\n}\n\nvoid cpx2cloude_pottier(const char *inFile, const char *outFile, int tc_flag)\n{\n  asfPrintStatus(\"\\n\\nCalculating entropy, anisotropy and alpha \"\n\t\t \"for Cloude-Pottier classification\\n\");\n  cpx2classification(inFile, outFile, tc_flag, \"cloude8.cla\");\n}\n\nvoid cpx2cloude_pottier8(const char *inFile, const char *outFile, int tc_flag)\n{\n  asfPrintStatus(\"\\n\\nCalculating entropy, anisotropy and alpha \"\n\t\t \"for Cloude-Pottier classification (8 classes)\\n\");\n  cpx2classification(inFile, outFile, tc_flag, \"cloude8.cla\");\n}\n\nvoid cpx2cloude_pottier16(const char *inFile, const char *outFile, int tc_flag)\n{\n  asfPrintStatus(\"\\n\\nCalculating entropy, anisotropy and alpha \"\n\t\t \"for Cloude-Pottier classification (16 classes)\\n\");\n  cpx2classification(inFile, outFile, tc_flag, \"cloude16.cla\");\n}\n\nvoid cpx2entropy_anisotropy_alpha(const char *inFile, const char *outFile,\n                                  int tc_flag)\n{\n  asfPrintStatus(\"\\n\\nCalculating entropy, anisotropy and alpha.\\n\");\n  if (tc_flag && has_amp_band(inFile))\n    polarimetric_decomp(inFile,outFile,0,-1,-1,-1,1,2,3,-1,-1,-1,-1,-1,-1,\n                        NULL,-1);\n  else \n    polarimetric_decomp(inFile,outFile,-1,-1,-1,-1,0,1,2,-1,-1,-1,-1,-1,-1,\n                        NULL,-1);\n}\n\nvoid cpx2freeman_durden(const char *inFile, const char *outFile, int tc_flag)\n{\n  asfPrintStatus(\"\\n\\nGenerating Freeman/Durden decomposition channels\\n\");\n  if (tc_flag && has_amp_band(inFile))\n    polarimetric_decomp(inFile,outFile,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,2,3,\n                        NULL,-1);\n  else\n    polarimetric_decomp(inFile,outFile,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,\n                        NULL,-1);\n}\n\nstatic gsl_matrix *make_diag3(double e00, double e11, double e22)\n{\n  gsl_matrix *mat = gsl_matrix_calloc(3, 3);\n  gsl_matrix_set(mat, 0, 0, e00);\n  gsl_matrix_set(mat, 1, 1, e11);\n  gsl_matrix_set(mat, 2, 2, e22);\n  return mat;\n}\n\nstatic void calc_entropy_alpha(gsl_matrix *mat, double *entropy, double *alpha)\n{\n  gsl_vector *eval = gsl_vector_alloc(3);\n  gsl_matrix *evec = gsl_matrix_alloc(3,3);\n\n  gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(3);\n  gsl_eigen_symmv(mat, eval, evec, w);\n  gsl_eigen_symmv_free(w);\n\n  gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_ABS_ASC);\n\n  double e1 = gsl_vector_get(eval, 0);\n  double e2 = gsl_vector_get(eval, 1);\n  double e3 = gsl_vector_get(eval, 2);\n\n  double eT = e1+e2+e3;\n\n  double P1 = e1/eT;\n  double P2 = e2/eT;\n  double P3 = e3/eT;\n\n  double P1l3 = log3(P1);\n  double P2l3 = log3(P2);\n  double P3l3 = log3(P3);\n\n  // If a Pn value is small enough, the log value will be NaN.\n  // In this case, the value of -Pn*log3(Pn) is supposed to be\n  // zero - we have to force it.\n  *entropy =\n    (meta_is_valid_double(P1l3) ? -P1*P1l3 : 0) +\n    (meta_is_valid_double(P2l3) ? -P2*P2l3 : 0) +\n    (meta_is_valid_double(P3l3) ? -P3*P3l3 : 0);\n\n  // calculate the \"mean alpha\" (mean scattering angle)\n  // this is the polar angle when expressing each eigenvector\n  // in spherical coordinates.  the mean alpha is weighted by\n  // the eigenvector (so weight by P1-3)\n  double alpha1 = calc_alpha_real(gsl_matrix_get(evec, 0, 0));\n  double alpha2 = calc_alpha_real(gsl_matrix_get(evec, 0, 1));\n  double alpha3 = calc_alpha_real(gsl_matrix_get(evec, 0, 2));\n\n  *alpha = R2D*(P1*alpha1 + P2*alpha2 + P3*alpha3);\n  if (!meta_is_valid_double(*alpha))\n    *alpha = 0.0;\n\n  gsl_vector_free(eval);\n  gsl_matrix_free(evec);\n}\n\nvoid make_entropy_alpha_boundary(const char *fname, int size)\n{\n  FILE *fp = FOPEN(fname, \"w\");\n\n  fprintf(fp, \"Entropy/Alpha Feasible Region Boundary\\n\");\n  fprintf(fp, \"File Size: %d\\n\\n\", size);\n  fprintf(fp, \"Entropy,Alpha\\n\");\n\n  // number of points generated in each curve's section\n  int numtop = size/2;\n  int numbot1 = size/4;\n  int numbot2 = size/4;\n\n  // fix any roundoff problems, while ensuring that numbot1 & numbot2\n  // are equal\n  while (numtop+numbot1+numbot2 < size) {\n    ++numbot2; ++numbot1;\n  }\n  while (numtop+numbot1+numbot2 > size) {\n    --numtop;\n  }\n\n  assert(numtop+numbot1+numbot2 == size);\n \n  int i;\n  double entropy, alpha;\n\n  // Generate the top curve by finding the eigenvalues of\n  // the matrix:\n  //   [ 1 0 0 ]\n  //   [ 0 m 0 ]\n  //   [ 0 0 m ]\n  // for 0 <= m <= 1\n\n  for (i=0; i<numtop; ++i) {\n    double m = (double)i / (double)(numtop-1);\n    gsl_matrix *mat = make_diag3(1, m, m);\n    calc_entropy_alpha(mat, &entropy, &alpha);\n    fprintf(fp,\"%f,%f\\n\",entropy,alpha);\n    gsl_matrix_free(mat);\n    asfPercentMeter((double)i/size);\n  }\n\n  // Generate the first part of the bottom curve by finding the eigenvalues\n  // of the matrix:\n  //  [ 1 0 0  ]\n  //  [ 0 1 0  ]\n  //  [ 0 0 2m ]\n  // for 0 <= m <= 0.5\n  // ==> We just use m instead of 2m, and let m go from 0 to 1.\n\n  for (i=0; i<numbot1; ++i) {\n    double m = (double)i / (double)(numbot1-1);\n    gsl_matrix *mat = make_diag3(1, 1, m);\n    calc_entropy_alpha(mat, &entropy, &alpha);\n    fprintf(fp,\"%f,%f\\n\",entropy,alpha);\n    gsl_matrix_free(mat);\n    asfPercentMeter((double)(i+numtop)/size);\n  }\n\n  // Generate the second part of the bottom curve by finding the eigenvalues\n  // of the matrix:\n  //  [ 2m-1 0 0 ]\n  //  [ 0    1 0 ]\n  //  [ 0    0 1 ]\n  // for 0.5 <= m <= 1\n  // ==> We just use m instead of 2m-1, and let m go from 0 to 1.\n\n  for (i=0; i<numbot2; ++i) {\n    double m = (double)i / (double)(numbot2-1);\n    gsl_matrix *mat = make_diag3(m, 1, 1);\n    calc_entropy_alpha(mat, &entropy, &alpha);\n    fprintf(fp,\"%f,%f\\n\",entropy,alpha);    \n    gsl_matrix_free(mat);\n    asfPercentMeter((double)(i+numtop+numbot1)/size);\n  }\n\n  asfPercentMeter(1.0);\n  FCLOSE(fp);\n}\n", "meta": {"hexsha": "bdd59a6dc3f5abccffc3b68174300c44363a7351", "size": 72760, "ext": "c", "lang": "C", "max_stars_repo_path": "src/libasf_sar/polarimetry.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/libasf_sar/polarimetry.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libasf_sar/polarimetry.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 32.4531668153, "max_line_length": 80, "alphanum_fraction": 0.6008521165, "num_tokens": 23088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3949458894335354}}
{"text": "#pragma once\n#include \"Sampler.h\"\n#include \"GradUtil.h\"\n#ifndef _NOGSL\n#include <gsl/gsl_vector.h>\n#else\n#include \"FakeGSL.h\"\n#endif\n#include \"ActualEvaluators.h\"\n\nclass BasicSampler : public Sampler {\n\tInterface* interf;\n\tBooleanDAG* dag;\n\tActualEvaluators* actualEval;\n\tdoublereal* xlow;\n    doublereal* xupp;\n    int ncontrols;\n\n\tgsl_vector* tmp;\n\tint RANDOM_SEARCH = 10;\n\n    set<int> assertConstraints; \n\tint minimizeNode;\n\npublic:\n\n    BasicSampler(BooleanDAG* dag_, Interface* interf_, ActualEvaluators* actualEval_, int ncontrols_,  doublereal* xlow_, doublereal* xupp_): dag(dag_), interf(interf_), actualEval(actualEval_), ncontrols(ncontrols_), xlow(xlow_), xupp(xupp_) {\n\n    \tminimizeNode = -1;\n\n\t    for (int i = 0; i < dag->size(); i++) { // TODO: this should also be set by caller class\n\t    \tbool_node* n = (*dag)[i];\n\t    \tif (n->type == bool_node::ASSERT && ((ASSERT_node*)n)->isHard()) {\n\t    \t\tminimizeNode = i;\n\t    \t} else if (n->type == bool_node::ASSERT || Util::isSqrt(n)) {\n\t    \t\tassertConstraints.insert(i);\n\t    \t} else if (n->type == bool_node::CTRL && n->getOtype() == OutType::BOOL) {\n\t    \t\tassertConstraints.insert(i);\n\t    \t}\n\t    }\n\n\t    tmp = gsl_vector_alloc(ncontrols);\n    }\n\n\tvirtual void sampleState(gsl_vector* state) { \n\t\tdouble best = GradUtil::MAXVAL;\n        bool foundValid = false;\n        for (int i = 0; i < RANDOM_SEARCH; i++) {\n            randomize(tmp);\n            cout << \"Trying: \";\n            for (int j = 0; j < tmp->size; j++) {\n                cout << gsl_vector_get(tmp, j) << \", \";\n            }\n            actualEval->run(tmp);\n            double error = getError();\n            cout << \"Error: \" << error << endl;\n            \n            if (error < best) {\n                best = error;\n                gsl_vector_memcpy(state, tmp);\n            }\n        }\n    }\n    \n    void randomize(gsl_vector* state) {\n        for (int i = 0; i < state->size; i++) {\n            double low = xlow[i];\n            double high = xupp[i];\n            double r = low + (rand() % (int)((high - low) * 10.0))/10.0;\n            gsl_vector_set(state, i, r);\n        }\n    }\n\n    double getError() {\n        double error = 0.0;\n        double e;\n        if (minimizeNode >= 0) {\n            e = actualEval->getErrorOnConstraint(minimizeNode);\n            if (e > 0.0) {\n                error += e; // TODO : change this\n            }\n        }\n        for (auto it = assertConstraints.begin(); it != assertConstraints.end(); it++) {\n            e = actualEval->getErrorOnConstraint(*it);\n            if (e < 0.0) {\n                error += -e;\n            }\n        }\n        return error;\n    }\n};\n", "meta": {"hexsha": "04e1ee83898f0b0bd9e98a0fa348b4d2ae8b7517", "size": 2651, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Samplers/BasicSampler.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Samplers/BasicSampler.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Samplers/BasicSampler.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "avg_line_length": 28.8152173913, "max_line_length": 244, "alphanum_fraction": 0.5345152773, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.39480866938073506}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include \"compearth.h\"\n#ifdef COMPEARTH_USE_MKL\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"\n#pragma clang diagnostic ignored \"-Wstrict-prototypes\"\n#endif\n#include <mkl_cblas.h>\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include <cblas.h>\n#endif\n\n#define CHKERR(t1, t2, tol, name, str)\\\n{\\\n   if (fabs(t1-t2) > tol){\\\n       printf(\"%s: %s %e %e\\n\", name, str, t1, t2);\\\n       return EXIT_FAILURE;\\\n   }\\\n}\n\nint check_lam2nualpha(void);\nint check_Udetcheck(void);\nint check_Uorth(void);\nint check_lam2lune(void);\nint check_CMTdecom(void);\nint check_fangleSigned(void);\nint check_CMT2faultpar(void);\nint check_CMT2TT(void);\nint check_TT2CMT(void);\nint check_normal2strdip(void);\nint check_CMT2omega(void);\n\nint main(void)\n{\n    int ierr;\n\n    ierr = check_lam2nualpha();\n    if (ierr != 0){printf(\"failed lam2nualpha\\n\"); return EXIT_FAILURE;}\n    printf(\"lam2nualpha was successful\\n\");\n\n    ierr = check_fangleSigned();\n    if (ierr != 0){printf(\"failed fangleSigned\\n\"); return EXIT_FAILURE;}\n    printf(\"fangleSigned was successful\\n\");\n\n    ierr = check_Udetcheck();\n    if (ierr != 0){printf(\"failed Udetcheck\\n\"); return EXIT_FAILURE;}\n    printf(\"udetcheck was successful\\n\");\n\n    ierr = check_Uorth();\n    if (ierr != 0){printf(\"failed Uorth\\n\"); return EXIT_FAILURE;}\n    printf(\"Uorth was successful\\n\");\n\n    ierr = check_lam2lune(); \n    if (ierr != 0){printf(\"failed lam2lune\\n\"); return EXIT_FAILURE;}\n    printf(\"lam2lune was succesful\\n\");\n\n    ierr = check_CMTdecom();\n    if (ierr != 0){printf(\"failed CMTdecom\\n\"); return EXIT_FAILURE;}\n    printf(\"CMTdecom was successful\\n\");\n\n    ierr = check_CMT2TT();\n    if (ierr != 0){printf(\"failed CMT2TT\\n\"); return EXIT_FAILURE;}\n    printf(\"CMT2TT was successful\\n\");\n\n    ierr = check_TT2CMT();\n    if (ierr != 0){printf(\"failed TT2CMT\\n\"); return EXIT_FAILURE;} \n    printf(\"TT2CMT was successful\\n\"); \n\n    ierr = check_CMT2faultpar();\n    if (ierr != 0){printf(\"failed CMT2faultpar\\n\"); return EXIT_FAILURE;}\n    printf(\"CMT2faultpar was successful\\n\");\n\n    ierr = check_normal2strdip();\n    if (ierr != 0){printf(\"failed noraml2strdip\\n\"); return EXIT_FAILURE;}\n    printf(\"normal2strdip was successful\\n\");\n\n    ierr = check_CMT2omega();\n    if (ierr != 0){printf(\"failed CMT2Omega\\n\"); return EXIT_FAILURE;}\n    printf(\"CMT2Omega was successful\\n\");\n\n    return EXIT_SUCCESS;\n}\n//============================================================================//\nint check_fangleSigned(void)\n{\n    const char *fcnm = \"check_fangleSigned\\0\"; \n    const double va[3] = {1, 0, 0};\n    const double vb[3] = {0, 0, 3};\n    const double vnor[3] = {0, -2, 0};\n    int ierr;\n    double stheta;\n    stheta = compearth_eulerUtil_fangleSigned(3, va,vb,vnor, &ierr);\n    if (fabs(stheta - 90.0) > 1.e-14 || ierr != 0)\n    {\n        printf(\"%s: failed test 1 %f %d\\n\", fcnm, stheta, ierr);\n        return EXIT_FAILURE;\n    }\n    const double vnor2[3] =  {0, 2, 0};\n    stheta = compearth_eulerUtil_fangleSigned(3, va,vb,vnor2, &ierr);\n    if (fabs(stheta + 90.0) > 1.e-14 || ierr != 0)\n    {\n        printf(\"%s: failed test 2 %f %d\\n\", fcnm, stheta, ierr);\n        return EXIT_FAILURE;\n    }\n    return EXIT_SUCCESS;\n}\n//============================================================================//\nint check_Udetcheck(void)\n{\n    const char *fcnm = \"check_Udetcheck\\0\";\n    const double U[9] = {0.6948,   0.3171,   0.9502,  // col 1\n                         0.0344,   0.4387,   0.3816,  // col 2\n                         0.7655,   0.7952,   0.1869}; // col 3\n    const double Ur[9] = {0.6948,  0.3171,   0.9502,  // col 1\n                         -0.0344, -0.4387,  -0.3816,  // col 2 negated\n                          0.7655,  0.7952,   0.1869};\n    double Un[9], Un2[9];\n    int i, ierr;\n    ierr = compearth_Udetcheck(1, U, Un);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error in Udetcheck1\\n\", fcnm);\n        return EXIT_FAILURE;\n    }\n    ierr = compearth_Udetcheck(1, Un, Un2);\n    if (ierr != 0)\n    {   \n        printf(\"%s: Error in Udetcheck2\\n\", fcnm);\n        return EXIT_FAILURE;\n    }\n    for (i=0; i<9; i++)\n    {\n        if (fabs(Ur[i] - Un[i]) > 1.e-12)\n        {\n            printf(\"%s: Udetcheck failed; %f %f\\n\", fcnm, Ur[i], Un[i]);\n            return EXIT_FAILURE;\n        }\n        if (fabs(Un[i] - Un2[i]) > 1.e-12)\n        {\n            printf(\"%s: Udetcheck2 failed; %f %f\\n\", fcnm, Un[i], Un2[i]);\n            return EXIT_FAILURE;\n        }\n    } \n    return EXIT_SUCCESS;\n}\n//============================================================================//\nint check_lam2nualpha(void)\n{ \n    const char *fcnm = \"check_lam2nualpha\\0\";\n    // example from TT2013, App A.\n    double lam[3] = { 8.802, 2.584, -1.851};\n    double lamcheck[3], nu, alpha, mag; \n    const double nu1 = 0.371745072651417;\n    const double alpha1 = 80.365019327257144;\n    int ierr;\n    ierr = compearth_lam2nualpha(1, lam, &nu, &alpha);\n    if (ierr != 0)\n    {\n        printf(\"%s: error calling lam2nualpha\\n\", fcnm);\n        return EXIT_FAILURE;\n    }\n    CHKERR(nu, nu1, 1.e-10, fcnm, \"error computing nu 1\");\n    CHKERR(alpha, alpha1, 1.e-10, fcnm, \"error computing alpha 1\"); \n    ierr = compearth_nualpha2lam(1, &nu, &alpha, lamcheck);\n    if (ierr != 0)\n    {\n        printf(\"%s: error caling nualpha2lam\\n\", fcnm);\n        return EXIT_FAILURE;\n    } \n    mag = cblas_dnrm2(3, lam, 1);\n    lam[0] = lam[0]/mag;\n    lam[1] = lam[1]/mag;\n    lam[2] = lam[2]/mag;\n    CHKERR(lam[0], lamcheck[0], 1.e-10, fcnm, \"error computing lam 1\");\n    CHKERR(lam[1], lamcheck[1], 1.e-10, fcnm, \"error computing lam 2\");\n    CHKERR(lam[2], lamcheck[2], 1.e-10, fcnm, \"error computing lam 3\");\n    //lam / norm(lam)\n    return EXIT_SUCCESS;\n}\n//============================================================================//\nint check_CMT2faultpar(void)\n{\n    const double M[6] = {3.108304932835845, 3.044425632830430, 3.382269434333724,\n                     -4.855033301709626,-1.949280336439431, 1.110527600460120};\n    double nu, alpha, N1[3], N2[3], lam[3];\n    const double nuRef = 0.371745072651417;\n    const double alphaRef = 80.365019327257144;\n    const double N1ref[3] = {-0.050351975426048, 0.930119048707825, 0.363790095799137};\n    const double N2ref[3] = {-0.977452142939121, 0.046467470073259, 0.205980781843140};\n    const double lamref[3] = { 8.802000000000001, 2.584000000000001, -1.851000000000002};\n    int ierr;\n    int nmt = 1;\n    ierr = compearth_CMT2faultpar(nmt, M, \n                                  &nu, &alpha, N1, N2, lam);\n    if (ierr != 0)\n    {\n        fprintf(stderr, \"Error calling CMT2faultpar\\n\");\n        return EXIT_FAILURE;\n    }\n    CHKERR(nu,    nuRef,    1.e-10, __func__, \"error computing nu\");\n    CHKERR(alpha, alphaRef, 1.e-10, __func__, \"error computing alpha\");\n    CHKERR(N1[0], N1ref[0], 1.e-10, __func__, \"error checking N1[0]\");\n    CHKERR(N1[1], N1ref[1], 1.e-10, __func__, \"error checking N1[1]\");\n    CHKERR(N1[2], N1ref[2], 1.e-10, __func__, \"error checking N1[2]\");\n    CHKERR(N2[0], N2ref[0], 1.e-10, __func__, \"error checking N2[0]\");\n    CHKERR(N2[1], N2ref[1], 1.e-10, __func__, \"error checking N2[1]\");\n    CHKERR(N2[2], N2ref[2], 1.e-10, __func__, \"error checking N2[2]\");\n    CHKERR(lam[0], lamref[0], 1.e-10, __func__, \"error checking lam[0]\");\n    CHKERR(lam[1], lamref[1], 1.e-10, __func__, \"error checking lam[1]\");\n    CHKERR(lam[2], lamref[2], 1.e-10, __func__, \"error checking lam[2]\");\n    return EXIT_SUCCESS;\n}\n//============================================================================//\nint check_TT2CMT(void)\n{\n    const double M01[1] = {1.0};\n    const double delta1[1] = {0.0};\n    const double gamma1[1] = {0.0};\n    const double kappa1[1] = {320.0};\n    const double theta1[1] = {10.0};\n    const double sigma1[1] = {20.0};\n    const double lam1Ref[3] = {1.0, 0.0, -1.0};\n    const double M61Ref[6] = { 0.116977778440511,\n                               0.112364502228240,\n                              -0.229342280668750,\n                              -0.502322271868946,\n                              -0.841048248646006,\n                               0.029265111955970};\n    const double U1Ref[9] = {-0.434841577578901, -0.515496946820204,\n                              0.738360142632131,  0.856848940622339,\n                             -0.489063917059259,  0.163175911166535,\n                              0.276988619555150,  0.703618776646631,\n                              0.654368338007907};\n    double M61[6], lam1[3], U91[9];\n    int i, ierr, j;\n    memset(U91, 0, 9*sizeof(double));\n    ierr = compearth_TT2CMT(1, gamma1, delta1, M01, kappa1, theta1, sigma1,\n                            M61, lam1, U91);\n    if (ierr != 0)\n    {\n        fprintf(stderr, \"%s: error calling TT2CMT\\n\", __func__);\n        return EXIT_FAILURE;\n    }\n    CHKERR(M61[0], M61Ref[0], 1.e-10, __func__, \"error checking M61[0]\");\n    CHKERR(M61[1], M61Ref[1], 1.e-10, __func__, \"error checking M61[1]\");\n    CHKERR(M61[2], M61Ref[2], 1.e-10, __func__, \"error checking M61[2]\");\n    CHKERR(M61[3], M61Ref[3], 1.e-10, __func__, \"error checking M61[3]\");\n    CHKERR(M61[4], M61Ref[4], 1.e-10, __func__, \"error checking M61[4]\");\n    CHKERR(M61[5], M61Ref[5], 1.e-10, __func__, \"error checking M61[5]\");\n\n    CHKERR(lam1[0], lam1Ref[0], 1.e-10, __func__, \"error checking lam[0]\");\n    CHKERR(lam1[1], lam1Ref[1], 1.e-10, __func__, \"error checking lam[1]\");\n    CHKERR(lam1[2], lam1Ref[2], 1.e-10, __func__, \"error checking lam[2]\");\n\n    CHKERR(U91[0], U1Ref[0], 1.e-10, __func__, \"error checking U1[0]\");\n    CHKERR(U91[1], U1Ref[1], 1.e-10, __func__, \"error checking U1[1]\");\n    CHKERR(U91[2], U1Ref[2], 1.e-10, __func__, \"error checking U1[2]\");\n    CHKERR(U91[3], U1Ref[3], 1.e-10, __func__, \"error checking U1[3]\");\n    CHKERR(U91[4], U1Ref[4], 1.e-10, __func__, \"error checking U1[4]\");\n    CHKERR(U91[5], U1Ref[5], 1.e-10, __func__, \"error checking U1[5]\");\n    CHKERR(U91[6], U1Ref[6], 1.e-10, __func__, \"error checking U1[6]\");\n    CHKERR(U91[7], U1Ref[7], 1.e-10, __func__, \"error checking U1[7]\");\n    CHKERR(U91[8], U1Ref[8], 1.e-10, __func__, \"error checking U1[8]\");\n    // At this stage in the game CMT2TT works.  So let's use it to verify\n    // its inverse operator.\n    int ng = 3;\n    double gamLoc[3] = {-29.0, 0.0, 29.0};\n    int nd = 3;\n    double deltaLoc[3] = {-89, 0.0, 89.0};\n    int nk = 5;\n    double kappaLoc[5] = {1.0, 90.0, 180.0, 270.0, 359.};\n    int ns = 3;\n    double sigmaLoc[3] = {-179.0, 1.0, 179.0};\n    int nt = 3;\n    double thetaLoc[3] = {10.0, 45.0, 80.0}; \n    int nm = 3;\n    double M0loc[3] = {1.0, 2.0, 3.0};\n    int nmt = ng*nd*nk*ns*nt*nm;\n    double *gamma, *delta, *kappa, *sigma, *theta, *M0, *M, *U, *lam;\n    gamma = (double *) calloc((size_t) nmt, sizeof(double));\n    delta = (double *) calloc((size_t) nmt, sizeof(double));\n    kappa = (double *) calloc((size_t) nmt, sizeof(double));\n    sigma = (double *) calloc((size_t) nmt, sizeof(double));\n    theta = (double *) calloc((size_t) nmt, sizeof(double));\n    M0 = (double *) calloc((size_t) nmt, sizeof(double));\n    int ig, id, ik, is, im, imt, it; \n    imt = 0;\n    for (im=0; im<nm; im++)\n    {\n        for (ig=0; ig<ng; ig++)\n        {\n            for (id=0; id<nd; id++)\n            {\n                for (ik=0; ik<nk; ik++)\n                {\n                    for (it=0; it<nt; it++)\n                    {\n                        for (is=0; is<ns; is++)\n                        {\n                            gamma[imt] = gamLoc[ig];\n                            delta[imt] = deltaLoc[id];\n                            kappa[imt] = kappaLoc[ik];\n                            sigma[imt] = sigmaLoc[is];\n                            theta[imt] = thetaLoc[it];\n                            M0[imt] = M0loc[im]; \n                            imt = imt + 1;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    M = (double *) calloc((size_t) (6*nmt), sizeof(double));\n    lam = (double *) calloc((size_t) (3*nmt), sizeof(double));\n    U = (double *) calloc((size_t) (9*nmt), sizeof(double));\n    ierr = compearth_TT2CMT(nmt, gamma, delta, M0, kappa, theta, sigma,\n                            M, lam, U);\n    if (ierr != 0)\n    {   \n        fprintf(stderr, \"%s: error calling TT2CMT\\n\", __func__);\n        return EXIT_FAILURE;\n    }\n/*\nprintf(\"\\n\");\nfor (i=0; i<nmt; i++)\n{\nprintf(\"%d\\n\", 6*i);\n printf(\"%e %e %e %e %e %e\\n\", M[6*i], M[6*i+1], M[6*i+2], M[6*i+3], M[6*i+4], M[6*i+5]);\n}\ngetchar();\n*/\n    bool ldisplay = false;\n    double *gammaNew = (double *) calloc((size_t) nmt, sizeof(double));\n    double *deltaNew = (double *) calloc((size_t) nmt, sizeof(double));\n    double *M0New = (double *) calloc((size_t) nmt, sizeof(double));\n    double *kappaNew = (double *) calloc((size_t) nmt, sizeof(double));\n    double *thetaNew = (double *) calloc((size_t) nmt, sizeof(double));\n    double *sigmaNew = (double *) calloc((size_t) nmt, sizeof(double)); \n    double *K = (double *) calloc((size_t) (3*nmt), sizeof(double));\n    double *N = (double *) calloc((size_t) (3*nmt), sizeof(double));\n    double *S = (double *) calloc((size_t) (3*nmt), sizeof(double));\n    double *thetadc = (double *) calloc((size_t) nmt, sizeof(double)); \n    double *lamNew = (double *) calloc((size_t) (3*nmt), sizeof(double));\n    double *UNew = (double *) calloc((size_t) (9*nmt), sizeof(double));\n    ierr = compearth_CMT2TT(nmt, M, ldisplay,\n                            gammaNew, deltaNew, M0New,\n                            kappaNew, thetaNew, sigmaNew,\n                            K, N, S, thetadc,\n                            lamNew, UNew); \n    if (ierr != 0)\n    {\n        fprintf(stderr, \"%s: Error calling CMT2TT\\n\", __func__);\n        return EXIT_FAILURE;\n    }\n    double kappa2, theta2, sigma2;\n    for (i=0; i<nmt; i++)\n    {\n        ierr = compearth_auxiliaryPlane(1,\n                                        &kappaNew[i], &thetaNew[i], &sigmaNew[i],\n                                        &kappa2, &theta2, &sigma2);\n        if (fabs(gammaNew[i] - gamma[i]) > 1.e-10)\n        {\n            fprintf(stderr, \"%s: Failed to compute gamma %e %e %d\\n\",\n                    __func__, gamma[i], gammaNew[i], i);\n            return -1;\n        }\n        if (fabs(deltaNew[i] - delta[i]) > 1.e-10)\n        {\n            fprintf(stderr, \"%s: Failed to compute delta %e %e %d\\n\",\n                    __func__, delta[i], deltaNew[i], i);\n            return -1;\n        }\n        if (fabs(M0[i] - M0New[i]) > 1.e-10)\n        {\n            fprintf(stderr, \"%s: Failed to compute M0 %e %e %d\\n\",\n                    __func__, M0[i], M0New[i], i);\n            return -1;\n        }\n        if (fabs(kappaNew[i] - kappa[i]) > 1.e-10 &&\n            fabs(kappa2 - kappa[i]) > 1.e-10)\n        {\n            fprintf(stderr, \"%s: Failed to compute kappa %e %e %e %d\\n\",\n                    __func__, kappa[i], kappaNew[i], kappa2, i);\n            return -1;\n        }\n        if (fabs(thetaNew[i] - theta[i]) > 1.e-10 &&\n            fabs(theta2 - theta[i]) > 1.e-10)\n        {\n            fprintf(stderr, \"%s: Failed to compute theta %e %e %d\\n\",\n                    __func__, theta[i], thetaNew[i], i);\n            return -1;\n        }\n        if (fabs(sigmaNew[i] - sigma[i]) > 1.e-10 &&\n            fabs(sigma2 - sigma[i]) > 1.e-10)\n        {\n            fprintf(stderr, \"%s: Failed to compute sigma %e %e %d\\n\",\n                    __func__, sigma[i], sigmaNew[i], i); \n            return -1;\n        }\n        for (j=0; j<3; j++)\n        {\n            if (fabs(lamNew[3*i+j] - lam[3*i+j]) > 1.e-10)\n            {\n                fprintf(stderr, \"%s: Failed to compute lam %e %e %d\\n\",\n                        __func__, lam[3*i+j], lamNew[3*i+j], i);\n                return -1;\n            }\n        }\n        for (j=0; j<9; j++)\n        {\n            // Can be off up to a sign factor\n            if (fabs(UNew[9*i+j] - U[9*i+j]) > 1.e-10 &&\n                fabs(UNew[9*i+j] + U[9*i+j]) > 1.e-10)\n            {\n                fprintf(stderr, \"%s: Failed to compute U %e %e %d\\n\",\n                        __func__, UNew[9*i+j], U[9*i+j], i);\n            }\n        }\n    }\n    // Free space\n    free(gammaNew);\n    free(deltaNew);\n    free(M0New);\n    free(kappaNew);\n    free(thetaNew);\n    free(sigmaNew);\n    free(K);\n    free(N);\n    free(S);\n    free(thetadc);\n    free(lamNew);\n    free(UNew);\n    free(gamma);\n    free(delta);\n    free(kappa);\n    free(sigma);\n    free(theta);\n    free(M0);\n    free(M);\n    free(U);\n    free(lam);\n    return EXIT_SUCCESS;\n}\n\n//============================================================================//\nint check_CMT2TT(void)\n{\n    const char *fcnm = \"check_CMT2TT\\0\";\n    const double M[6] = {3.108304932835845, 3.044425632830430,\n                         3.382269434333724,-4.855033301709626,\n                        -1.949280336439431, 1.110527600460120};\n    double U[9], lam[3];\n    bool ldisplay;\n    double gamma, delta, M0, kappa, sigma, theta, thetadc;\n    double K[3], N[3], S[3];\n    const double gamma1 = -5.519441015228609;\n    const double delta1 = 36.032871051674995;\n    const double M01 = 6.617343160211657;\n    const double kappa1 = 69.492561954605137;\n    const double theta1 = 88.144957350922951;\n    const double sigma1 = -79.788954797632840;\n    const double thetadc1 = 36.396475670817210;\n    const double KR1[3] = {-0.350328975576259, 0.936626718000127, 0};\n    const double NR1[3] = {0.936135854045508, 0.350145376429380, 0.032370945856051};\n    const double SR1[3] = {-0.032265105849630, 0.177200864349715, -0.983645676358224};\n    const double lam1[3] = {8.802000000000000, 2.584000000000003, -1.851000000000001};\n    const double UR1[9] = {-0.639133135365464,-0.372890102888132, 0.672652812709492,\n                            0.350155145207092,-0.919781533321278,-0.177181560118875,\n                            0.684762885649414, 0.122290237260530, 0.718432243365964};\n    // Test 2; problem child of horizontal fault\n    const double M2[6] = {0, 0, 0, -sqrt(3)/2., .5, 0};\n    const double gamma2 = 0.0; const double delta2 = 0.0;\n    const double M02 = 1.0; const double kappa2 = 300.0;\n    const double theta2 = 90.0; const double sigma2 = 90.0;\n    const double thetadc2 = 1.207418269725733e-06;\n    const double KR2[3] = {-0.500000000000000, -0.866025403784439, 0};\n    const double NR2[3] = {-0.866025403784439, 0.500000000000000,  0};\n    const double SR2[3] = {0, 0, 1};\n    const double lam2[3] = {1, 0, -1};\n    const double UR2[9] = {-0.612372435695794,0.353553390593274,0.707106781186547,\n                            0.500000000000000,0.866025403784439,0,\n                           -0.612372435695794,0.353553390593274,-0.707106781186547};\n    \n    int i, ierr;\n    ldisplay = false;\n    ierr = compearth_CMT2TT(1, M, ldisplay,\n                            &gamma, &delta, &M0, &kappa, &theta, &sigma,\n                            K, N, S, &thetadc,\n                            lam, U);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error calling CMT2TT test 1\\n\", fcnm);\n        return EXIT_FAILURE;\n    }\n    CHKERR(gamma, gamma1, 1.e-10, fcnm, \"error computing gamma 1\"); \n    CHKERR(delta, delta1, 1.e-10, fcnm, \"error computing delta 1\");\n    CHKERR(M0, M01, 1.e-10, fcnm, \"error computing M0 1\");\n    CHKERR(kappa, kappa1, 1.e-10, fcnm, \"error computing kappa 1\");\n    CHKERR(theta, theta1, 1.e-10, fcnm, \"error computing theta 1\");\n    CHKERR(sigma, sigma1, 1.e-10, fcnm, \"error computing sigma 1\");\n    CHKERR(thetadc, thetadc1, 1.e-10, fcnm, \"error computing thetadc 1\");\n    for (i=0; i<3; i++)\n    {\n        if (fabs(KR1[i] - K[i]) > 1.e-10)\n        {\n            printf(\"%s: Error computing K 1\\n\", fcnm);\n            return EXIT_FAILURE;\n        }\n        if (fabs(NR1[i] - N[i]) > 1.e-10)\n        {\n            printf(\"%s: Error computing N 1\\n\", fcnm);\n            return EXIT_FAILURE;\n        }\n        if (fabs(SR1[i] - S[i]) > 1.e-10)\n        {\n            printf(\"%s: Error computing S 1\\n\", fcnm);\n            return EXIT_FAILURE;\n        }\n        if (fabs(lam1[i] - lam[i]) > 1.e-10)\n        {\n            printf(\"%s: Error computing lam 1\\n\", fcnm);\n            return EXIT_FAILURE;\n        }\n    }\n    for (i=0; i<9; i++)\n    {\n        if (fabs(U[i] - UR1[i]) > 1.e-10)\n        {\n            printf(\"%s: Error computing U 1\\n\", fcnm);\n            return EXIT_FAILURE;\n        }\n    }\n\n    ierr = compearth_CMT2TT(1, M2, ldisplay,\n                            &gamma, &delta, &M0, &kappa, &theta, &sigma,\n                            K, N, S, &thetadc,\n                            lam, U);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error calling CMT2TT horizontal fault\\n\", fcnm);\n        return EXIT_FAILURE;\n    }\n    CHKERR(gamma, gamma2, 1.e-10, fcnm, \"error computing gamma 2\"); \n    CHKERR(delta, delta2, 1.e-10, fcnm, \"error computing delta 2\");\n    CHKERR(M0, M02, 1.e-10, fcnm, \"error computing M0 2\");\n    CHKERR(kappa, kappa2, 1.e-10, fcnm, \"error computing kappa 2\");\n    CHKERR(theta, theta2, 1.e-10, fcnm, \"error computing theta 2\");\n    CHKERR(sigma, sigma2, 1.e-10, fcnm, \"error computing sigma 2\");\n    CHKERR(thetadc, thetadc2, 1.e-10, fcnm, \"error computing thetadc 2\");\n    for (i=0; i<3; i++)\n    {   \n        if (fabs(KR2[i] - K[i]) > 1.e-10)\n        {\n            printf(\"%s: Error computing K 2\\n\", fcnm);\n            return EXIT_FAILURE;\n        }\n        if (fabs(NR2[i] - N[i]) > 1.e-10)\n        {\n            printf(\"%s: Error computing N 2\\n\", fcnm);\n            return EXIT_FAILURE;\n        }\n        if (fabs(SR2[i] - S[i]) > 1.e-10)\n        {\n            printf(\"%s: Error computing S 2\\n\", fcnm);\n            return EXIT_FAILURE;\n        }\n        if (fabs(lam2[i] - lam[i]) > 1.e-10)\n        {\n            printf(\"%s: Error computing lam 2\\n\", fcnm);\n            return EXIT_FAILURE;\n        }\n    }\n    for (i=0; i<9; i++)\n    {\n        if (fabs(U[i] - UR2[i]) > 1.e-10)\n        {\n            printf(\"%s: Error computing U 2\\n\", fcnm);\n            return EXIT_FAILURE;\n        }\n    }\n    return EXIT_SUCCESS;\n}\n//============================================================================//\nint check_CMTdecom(void)\n{\n    const char *fcnm = \"check_CMTdecom\\0\";\n    const double M[6] = {3.108304932835845, 3.044425632830430,\n                         3.382269434333724,-4.855033301709626,\n                        -1.949280336439431, 1.110527600460120};\n    double U[9], lam[3];\n    double lamRef1[3] = {8.8020000000e+00, 2.5840000000e+00, -1.8510000000e+00};\n    double lamRef2[3] = {-1.851000000000002, 2.584000000000001, 8.802000000000001};\n    double *lamRef3 = lamRef1;\n    double *lamRef4 = lamRef2;\n    double URef1[9] = {-0.672652812709492, 0.639133135365464, 0.372890102888132,\n                        0.177181560118875,-0.350155145207092, 0.919781533321279,\n                        0.718432243365964, 0.684762885649414, 0.122290237260530};\n    double URef2[9] = { 0.718432243365964, 0.684762885649414, 0.122290237260530,\n                       -0.177181560118875, 0.350155145207092,-0.919781533321279,\n                       -0.672652812709492, 0.639133135365464, 0.372890102888132};\n    double *URef3 = URef1;\n    double *URef4 = URef2;\n    int i, ierr;\n    ierr = compearth_CMTdecom(1,  M, 1, lam, U);\n    if (ierr != 0)\n    {\n        printf(\"%s: Error 1 calling CMTdecom\\n\", fcnm);\n        return EXIT_FAILURE;\n    } \n    for (i=0; i<3; i++)\n    {\n        if (fabs(lam[i] - lamRef1[i]) > 1.e-13)\n        {\n            printf(\"%s: lam 1 is wrong %e %e\\n\", fcnm, lam[i], lamRef1[i]);\n            return EXIT_FAILURE;\n        }\n    }\n    for (i=0; i<9; i++)\n    {\n        if (fabs(U[i] - URef1[i]) > 1.e-13)\n        {\n            printf(\"%s: U 1 is wrong %d %e %e\\n\", fcnm, i, U[i], URef1[i]);\n            return EXIT_FAILURE;\n        }\n    }\n\n    ierr = compearth_CMTdecom(1,  M, 2, lam, U); \n    if (ierr != 0)\n    {   \n        printf(\"%s: Error 2 calling CMTdecom\\n\", fcnm);\n        return EXIT_FAILURE;\n    }   \n    for (i=0; i<3; i++)\n    {\n        if (fabs(lam[i] - lamRef2[i]) > 1.e-13)\n        {\n            printf(\"%s: lam 2 is wrong %e %e\\n\", fcnm, lam[i], lamRef2[i]);\n            return EXIT_FAILURE;\n        }\n    }\n    for (i=0; i<9; i++)\n    {\n        if (fabs(U[i] - URef2[i]) > 1.e-13)\n        {\n            printf(\"%s: U 2 is wrong %d %e %e\\n\", fcnm, i, U[i], URef2[i]);\n            return EXIT_FAILURE;\n        }\n    }\n\n    ierr = compearth_CMTdecom(1,  M, 3, lam, U); \n    if (ierr != 0)\n    {   \n        printf(\"%s: Error calling CMTdecom 3\\n\", fcnm);\n        return EXIT_FAILURE;\n    }   \n    for (i=0; i<3; i++)\n    {   \n        if (fabs(lam[i] - lamRef3[i]) > 1.e-13)\n        {\n            printf(\"%s: lam 3 is wrong %e %e\\n\", fcnm, lam[i], lamRef3[i]);\n            return EXIT_FAILURE;\n        }\n    }   \n    for (i=0; i<9; i++)\n    {\n        if (fabs(U[i] - URef3[i]) > 1.e-13)\n        {\n            printf(\"%s: U 3 is wrong %d %e %e\\n\", fcnm, i, U[i], URef3[i]);\n            return EXIT_FAILURE;\n        }\n    }\n\n    ierr = compearth_CMTdecom(1,  M, 4, lam, U); \n    if (ierr != 0)\n    {   \n        printf(\"%s: Error calling CMTdecom 4\\n\", fcnm);\n        return EXIT_FAILURE;\n    }   \n    for (i=0; i<3; i++)\n    {   \n        if (fabs(lam[i] - lamRef4[i]) > 1.e-13)\n        {\n            printf(\"%s: lam 4 is wrong %e %e\\n\", fcnm, lam[i], lamRef4[i]);\n            return EXIT_FAILURE;\n        }\n    }   \n    for (i=0; i<9; i++)\n    {   \n        if (fabs(U[i] - URef4[i]) > 1.e-13)\n        {\n            printf(\"%s: U 4 is wrong %d %e %e\\n\", fcnm, i, U[i], URef4[i]);\n            return EXIT_FAILURE;\n        }\n    }\n    return EXIT_SUCCESS;\n}\n//============================================================================//\nint check_lam2lune(void)\n{\n    const char *fcnm = \"check_lam2lune\\0\";\n    const double lamRef1[6] = {\n        -7.9621992143e+15,-8.2644837610e+15,-8.2644837610e+15,\n        -7.5915701171e+15,-8.4370629711e+15,-8.4370629711e+15};\n    double *gamma0, *gamma, *delta, *delta0, *lam, *M0, *M00;\n    double *thetadc, *lamdev, *lamiso;\n    int i, ib, ierr, ig, indx;\n    const int ng = 100;\n    const int nb = 100;\n    int nmt = ng*nb;\n    const double dg = (30.0 - -30.0)/(double) (ng - 1);\n    const double db = (89.0 - -89.0)/(double) (nb - 1);\n    gamma0 = (double *) calloc((size_t) nmt, sizeof(double));\n    delta0 = (double *) calloc((size_t) nmt, sizeof(double));\n    M00    = (double *) calloc((size_t) nmt, sizeof(double));\n    gamma  = (double *) calloc((size_t) nmt, sizeof(double));\n    delta  = (double *) calloc((size_t) nmt, sizeof(double));\n    M0     = (double *) calloc((size_t) nmt, sizeof(double)); \n    lam  = (double *) calloc((size_t) (3*nmt), sizeof(double)); \n    for (ig=0; ig<ng; ig++)\n    {\n        for (ib=0; ib<nb; ib++)\n        {\n            indx = ig*nb + ib;\n            gamma0[indx] =-30.0 + (double) ig*dg;\n            delta0[indx] =-89.0 + (double) ib*db; // use latitude instead of colat\n            M00[indx] = 1.e16;\n        }\n    }\n    compearth_lune2lam(nmt, gamma0, delta0, M00, lam);\n    // Verify the first two computations are right\n    for (i=0; i<6; i++)\n    {\n        if (fabs(lam[i] - lamRef1[i])/1.e16 > 1.e-10)\n        {\n            printf(\"%s: error in lune2lam: %.10e %.10e\\n\",\n                   fcnm, lam[i], lamRef1[i]);\n            return EXIT_FAILURE;\n        }\n    }\n    // Now perform the inverse operation\n    thetadc = NULL;\n    lamdev = NULL;\n    lamiso = NULL;\n    ierr = compearth_lam2lune(nmt, lam,\n                              gamma, delta, M0,\n                              thetadc, lamdev, lamiso);\n    if (ierr != 0)\n    {\n        printf(\"%s: error calling lam2lune\\n\", fcnm);\n        return EXIT_FAILURE;\n    }\n    // See how close i was\n    for (i=0; i<nmt; i++)\n    {\n        if (fabs(gamma[i] - gamma0[i]) > 1.e-12)\n        {\n            printf(\"%s: gamma[%d] different %e %e %e\\n\",\n                   __func__, i, gamma[i], gamma0[i],\n                   fabs(gamma[i] - gamma0[i]));\n            return EXIT_FAILURE;\n        }\n        if (fabs(delta[i] - delta0[i]) > 1.e-12)\n        {\n            printf(\"%s: delta[%d] different %e %e %e\\n\",\n                   __func__, i, delta[i], delta0[i],\n                   fabs(delta[i] - delta0[i]));\n            return EXIT_FAILURE;\n        }\n        if (fabs(M0[i] - M00[i])/1.e15 > 1.e-12)\n        {\n            printf(\"%s: M0[%d] different %e %e %e\\n\",\n                   __func__, i, M0[i], M00[i], fabs(M0[i] - M00[i]));\n           return EXIT_FAILURE;\n        }\n    }\n    free(gamma0);\n    free(delta0);\n    free(M00);\n    free(gamma);\n    free(delta);\n    free(M0);\n    free(lam);\n    return EXIT_SUCCESS;\n}\n\nint check_CMT2omega(void)\n{\n    const double M1[6] = {1, 0, -1, 0, 0, 0};\n    const double M2[6] = {1, 2,  3, 4, 5, 6};\n    double *Mvec1, *Mvec2, *omega, *refOmega, om1;\n    const double omRef1 = 96.263952719927232;\n    int i, ierr, j, nmt1, nmt2;\n    ierr = compearth_CMT2omega(1, M1, 1, M2, &om1);\n    if (ierr != 0)\n    {\n        fprintf(stderr, \"%s: Error calling CMT2omega 1\\n\", __func__);\n        return EXIT_FAILURE;\n    }\n    CHKERR(om1, omRef1, 1.e-10, __func__, \"error computing CMT2Omega1\");\n    nmt2 = 80;\n    Mvec1 = (double *) calloc((size_t) (6*nmt2), sizeof(double));\n    Mvec2 = (double *) calloc((size_t) (6*nmt2), sizeof(double));\n    omega = (double *) calloc((size_t) nmt2, sizeof(double));\n    refOmega = (double *) calloc((size_t) nmt2, sizeof(double));\n    for (i=0; i<nmt2; i++)\n    {\n        cblas_dcopy(6, M2, 1, &Mvec2[6*i], 1); \n    }\n    // one to many\n    ierr = compearth_CMT2omega(1, M1, nmt2, Mvec2, omega);\n    if (ierr != 0)\n    {\n        fprintf(stderr, \"%s: Error calling CMT2omega 2\\n\", __func__);\n        return EXIT_FAILURE;\n    }\n    for (i=0; i<nmt2; i++)\n    {\n         CHKERR(omega[i], omRef1, 1.e-10, __func__,\n                \"error computing CMT2Omega2\");\n    } \n    // flip roles\n    ierr = compearth_CMT2omega(nmt2, Mvec2, 1, M1, omega);\n    if (ierr != 0)\n    {   \n        fprintf(stderr, \"%s: Error calling CMT2omega 3\\n\", __func__);\n        return EXIT_FAILURE;\n    }\n    for (i=0; i<nmt2; i++)\n    {   \n         CHKERR(omega[i], omRef1, 1.e-10, __func__,\n                \"error computing CMT2Omega3\");\n    }\n    // many to many\n    nmt1 = nmt2;\n    srand(4093);\n    for (i=0; i<nmt1; i++)\n    {\n        for (j=0; j<6; j++)\n        {\n            Mvec1[6*i+j] = ((double) (rand())/RAND_MAX - 0.5)*2.0;\n            Mvec2[6*i+j] = ((double) (rand())/RAND_MAX - 0.5)*2.0;\n        }\n        compearth_CMT2omega(1, &Mvec1[6*i], 1, &Mvec2[6*i], &refOmega[i]);\n    }\n    ierr = compearth_CMT2omega(nmt1, Mvec1, nmt2, Mvec2, omega); \n    if (ierr != 0)\n    {   \n        fprintf(stderr, \"%s: Error calling CMT2omega 4\\n\", __func__);\n        return EXIT_FAILURE;\n    }   \n    for (i=0; i<nmt2; i++)\n    {\n         CHKERR(omega[i], refOmega[i], 1.e-10, __func__,\n                \"error computing CMT2Omega4\");\n    } \n\n    free(Mvec1);\n    free(Mvec2); \n    free(omega);\n    free(refOmega);\n    return EXIT_SUCCESS;\n} \n\nint check_normal2strdip(void)\n{\n    const double Xin[3] = {-0.171010071662835, 0.969846310392954,\n                            0.173648177666930};\n    double Xout[2];\n    compearth_normal2strdip(1, Xin, Xout);\n    CHKERR(Xout[0], 350.0, 1.e-10, __func__, \"error computing Xout[0]\"); \n    CHKERR(Xout[1], 80.0,  1.e-10, __func__, \"error computing Xout[1]\");\n    return EXIT_SUCCESS;\n}\n\nint check_Uorth(void)\n{\n    const double T[9] = {0.998800000000000, 0.047900000000000, 0.017300000000000,\n             -0.048200000000000, 0.998800000000000, 0.015900000000000, \n             -0.016500000000000,-0.016700000000000, 0.999800000000000};\n    const double Tref[9] = { 0.998702105045258, 0.047907730990670, 0.017290306229078,\n             -0.048183355871821, 0.998712063377127, 0.015892724182219,\n             -0.016506653055635, -0.016705202073855,  0.999724195280165};\n    const double detInRef1 = 1.000261915677000;\n    const double detOutRef1 = 1.0;\n    double Tout[9], detIn, detOut;\n    int i, j, ierr;\n    ierr = compearth_Uorth(1, CE_ORTH_SVD, T, Tout, &detIn, &detOut);\n    if (ierr != 0)\n    {\n        fprintf(stderr, \"%s: Error calling Uorth_svd\\n\", __func__);\n        return EXIT_FAILURE;\n    }\n    for (i=0; i<3; i++)\n    {\n        for (j=0; j<3; j++)\n        {\n            if (fabs(Tout[3*j+i] - Tref[3*j+i]) > 1.e-14)\n            {\n                printf(\"%s: Failed calculating T(%d,%d)=%f \",\n                       __func__, i+1,j+1, Tout[3*j+i] - Tref[3*j+i]);\n                return EXIT_FAILURE;\n            }\n        }\n    }\n    CHKERR(detIn, detInRef1, 1.e-10, __func__, \"error computing detIn1\");\n    CHKERR(detOut, detOutRef1, 1.e-10, __func__, \"error computing detOUt1\");\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "3daf615666ea4e0ae60fe7636ede859a15eee727", "size": 32813, "ext": "c", "lang": "C", "max_stars_repo_path": "momenttensor/c_src/unit_tests/checks.c", "max_stars_repo_name": "bakerb845/compearth", "max_stars_repo_head_hexsha": "53e75a00bf5be939730ec02ede49e65ef140ee41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "momenttensor/c_src/unit_tests/checks.c", "max_issues_repo_name": "bakerb845/compearth", "max_issues_repo_head_hexsha": "53e75a00bf5be939730ec02ede49e65ef140ee41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z", "max_forks_repo_path": "momenttensor/c_src/unit_tests/checks.c", "max_forks_repo_name": "bakerb845/compearth", "max_forks_repo_head_hexsha": "53e75a00bf5be939730ec02ede49e65ef140ee41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-10-26T19:49:45.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-26T19:49:45.000Z", "avg_line_length": 35.8220524017, "max_line_length": 89, "alphanum_fraction": 0.5216834791, "num_tokens": 11085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.39479273547228544}}
{"text": "/* rng/slatec.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/**\n\n* ======================================================================\n* NIST Guide to Available Math Software.\n* Source for module RAND from package CMLIB.\n* Retrieved from TIBER on Fri Oct 11 11:43:42 1996.\n* ======================================================================\n      FUNCTION RAND(R)\nC***BEGIN PROLOGUE  RAND\nC***DATE WRITTEN   770401   (YYMMDD)\nC***REVISION DATE  820801   (YYMMDD)\nC***CATEGORY NO.  L6A21\nC***KEYWORDS  RANDOM NUMBER,SPECIAL FUNCTION,UNIFORM\nC***AUTHOR  FULLERTON, W., (LANL)\nC***PURPOSE  Generates a uniformly distributed random number.\nC***DESCRIPTION\nC\nC      This pseudo-random number generator is portable among a wide\nC variety of computers.  RAND(R) undoubtedly is not as good as many\nC readily available installation dependent versions, and so this\nC routine is not recommended for widespread usage.  Its redeeming\nC feature is that the exact same random numbers (to within final round-\nC off error) can be generated from machine to machine.  Thus, programs\nC that make use of random numbers can be easily transported to and\nC checked in a new environment.\nC      The random numbers are generated by the linear congruential\nC method described, e.g., by Knuth in Seminumerical Methods (p.9),\nC Addison-Wesley, 1969.  Given the I-th number of a pseudo-random\nC sequence, the I+1 -st number is generated from\nC             X(I+1) = (A*X(I) + C) MOD M,\nC where here M = 2**22 = 4194304, C = 1731 and several suitable values\nC of the multiplier A are discussed below.  Both the multiplier A and\nC random number X are represented in double precision as two 11-bit\nC words.  The constants are chosen so that the period is the maximum\nC possible, 4194304.\nC      In order that the same numbers be generated from machine to\nC machine, it is necessary that 23-bit integers be reducible modulo\nC 2**11 exactly, that 23-bit integers be added exactly, and that 11-bit\nC integers be multiplied exactly.  Furthermore, if the restart option\nC is used (where R is between 0 and 1), then the product R*2**22 =\nC R*4194304 must be correct to the nearest integer.\nC      The first four random numbers should be .0004127026,\nC .6750836372, .1614754200, and .9086198807.  The tenth random number\nC is .5527787209, and the hundredth is .3600893021 .  The thousandth\nC number should be .2176990509 .\nC      In order to generate several effectively independent sequences\nC with the same generator, it is necessary to know the random number\nC for several widely spaced calls.  The I-th random number times 2**22,\nC where I=K*P/8 and P is the period of the sequence (P = 2**22), is\nC still of the form L*P/8.  In particular we find the I-th random\nC number multiplied by 2**22 is given by\nC I   =  0  1*P/8  2*P/8  3*P/8  4*P/8  5*P/8  6*P/8  7*P/8  8*P/8\nC RAND=  0  5*P/8  2*P/8  7*P/8  4*P/8  1*P/8  6*P/8  3*P/8  0\nC Thus the 4*P/8 = 2097152 random number is 2097152/2**22.\nC      Several multipliers have been subjected to the spectral test\nC (see Knuth, p. 82).  Four suitable multipliers roughly in order of\nC goodness according to the spectral test are\nC    3146757 = 1536*2048 + 1029 = 2**21 + 2**20 + 2**10 + 5\nC    2098181 = 1024*2048 + 1029 = 2**21 + 2**10 + 5\nC    3146245 = 1536*2048 +  517 = 2**21 + 2**20 + 2**9 + 5\nC    2776669 = 1355*2048 + 1629 = 5**9 + 7**7 + 1\nC\nC      In the table below LOG10(NU(I)) gives roughly the number of\nC random decimal digits in the random numbers considered I at a time.\nC C is the primary measure of goodness.  In both cases bigger is better.\nC\nC                   LOG10 NU(I)              C(I)\nC       A       I=2  I=3  I=4  I=5    I=2  I=3  I=4  I=5\nC\nC    3146757    3.3  2.0  1.6  1.3    3.1  1.3  4.6  2.6\nC    2098181    3.3  2.0  1.6  1.2    3.2  1.3  4.6  1.7\nC    3146245    3.3  2.2  1.5  1.1    3.2  4.2  1.1  0.4\nC    2776669    3.3  2.1  1.6  1.3    2.5  2.0  1.9  2.6\nC   Best\nC    Possible   3.3  2.3  1.7  1.4    3.6  5.9  9.7  14.9\nC\nC             Input Argument --\nC R      If R=0., the next random number of the sequence is generated.\nC        If R .LT. 0., the last generated number will be returned for\nC          possible use in a restart procedure.\nC        If R .GT. 0., the sequence of random numbers will start with\nC          the seed R mod 1.  This seed is also returned as the value of\nC          RAND provided the arithmetic is done exactly.\nC\nC             Output Value --\nC RAND   a pseudo-random number between 0. and 1.\nC***REFERENCES  (NONE)\nC***ROUTINES CALLED  (NONE)\nC***END PROLOGUE  RAND\n      DATA IA1, IA0, IA1MA0 /1536, 1029, 507/\n      DATA IC /1731/\n      DATA IX1, IX0 /0, 0/\nC***FIRST EXECUTABLE STATEMENT  RAND\n      IF (R.LT.0.) GO TO 10\n      IF (R.GT.0.) GO TO 20\nC\nC           A*X = 2**22*IA1*IX1 + 2**11*(IA1*IX1 + (IA1-IA0)*(IX0-IX1)\nC                   + IA0*IX0) + IA0*IX0\nC\n      IY0 = IA0*IX0\n      IY1 = IA1*IX1 + IA1MA0*(IX0-IX1) + IY0\n      IY0 = IY0 + IC\n      IX0 = MOD (IY0, 2048)\n      IY1 = IY1 + (IY0-IX0)/2048\n      IX1 = MOD (IY1, 2048)\nC\n 10   RAND = IX1*2048 + IX0\n      RAND = RAND / 4194304.\n      RETURN\nC\n 20   IX1 = AMOD(R,1.)*4194304. + 0.5\n      IX0 = MOD (IX1, 2048)\n      IX1 = (IX1-IX0)/2048\n      GO TO 10\nC\n      END\n\n  **/\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n\nstatic inline unsigned long int slatec_get (void *vstate);\nstatic double slatec_get_double (void *vstate);\nstatic void slatec_set (void *state, unsigned long int s);\n\ntypedef struct\n  {\n    long int x0, x1;\n  }\nslatec_state_t;\n\nstatic const long P = 4194304;\nstatic const long a1 = 1536;\nstatic const long a0 = 1029;\nstatic const long a1ma0 = 507;\nstatic const long c = 1731;\n\nstatic inline unsigned long int\nslatec_get (void *vstate)\n{\n  long y0, y1;\n  slatec_state_t *state = (slatec_state_t *) vstate;\n\n  y0 = a0 * state->x0;\n  y1 = a1 * state->x1 + a1ma0 * (state->x0 - state->x1) + y0;\n  y0 = y0 + c;\n  state->x0 = y0 % 2048;\n  y1 = y1 + (y0 - state->x0) / 2048;\n  state->x1 = y1 % 2048;\n\n  return state->x1 * 2048 + state->x0;\n}\n\nstatic double \nslatec_get_double (void *vstate)\n{\n  return slatec_get (vstate) / 4194304.0 ;\n}\n\nstatic void\nslatec_set (void *vstate, unsigned long int s)\n{\n  slatec_state_t *state = (slatec_state_t *) vstate;\n\n  /* Only eight seeds are permitted.  This is pretty limiting, but\n     at least we are guaranteed that the eight sequences are different */\n\n  s = s % 8;\n  s *= P / 8;\n\n  state->x0 = s % 2048;\n  state->x1 = (s - state->x0) / 2048;\n}\n\nstatic const gsl_rng_type slatec_type =\n{\"slatec\",\t\t\t/* name */\n 4194303,\t\t\t/* RAND_MAX */\n 0,\t\t\t\t/* RAND_MIN */\n sizeof (slatec_state_t),\n &slatec_set,\n &slatec_get,\n &slatec_get_double};\n\nconst gsl_rng_type *gsl_rng_slatec = &slatec_type;\n", "meta": {"hexsha": "aa82a414357334dea5993bc29acba8004dfd4c4e", "size": 7476, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/slatec.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/slatec.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/rng/slatec.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 36.2912621359, "max_line_length": 73, "alphanum_fraction": 0.6523542001, "num_tokens": 2584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.39445217447188863}}
{"text": "/* bspline/gsl_bspline.h\n * \n * Copyright (C) 2006 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_BSPLINE_H__\n#define __GSL_BSPLINE_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct\n{\n  size_t k;      /* spline order */\n  size_t km1;    /* k - 1 (polynomial order) */\n  size_t l;      /* number of polynomial pieces on interval */\n  size_t nbreak; /* number of breakpoints (l + 1) */\n  size_t n;      /* number of bspline basis functions (l + k - 1) */\n\n  gsl_vector *knots;  /* knots vector */\n  gsl_vector *deltal; /* left delta */\n  gsl_vector *deltar; /* right delta */\n  gsl_vector *B;      /* temporary spline results */\n} gsl_bspline_workspace;\n\ngsl_bspline_workspace *\ngsl_bspline_alloc(const size_t k, const size_t nbreak);\n\nvoid gsl_bspline_free(gsl_bspline_workspace *w);\n\nsize_t gsl_bspline_ncoeffs (gsl_bspline_workspace * w);\nsize_t gsl_bspline_order (gsl_bspline_workspace * w);\nsize_t gsl_bspline_nbreak (gsl_bspline_workspace * w);\ndouble gsl_bspline_breakpoint (size_t i, gsl_bspline_workspace * w);\n\nint\ngsl_bspline_knots(const gsl_vector *breakpts, gsl_bspline_workspace *w);\n\nint gsl_bspline_knots_uniform(const double a, const double b,\n                              gsl_bspline_workspace *w);\n\nint\ngsl_bspline_eval(const double x, gsl_vector *B,\n                 gsl_bspline_workspace *w);\n\n__END_DECLS\n\n#endif /* __GSL_BSPLINE_H__ */\n", "meta": {"hexsha": "26794ecb9b28ef924b2af48bf7a09ef89db5b651", "size": 2328, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/bspline/gsl_bspline.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/bspline/gsl_bspline.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/bspline/gsl_bspline.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 30.6315789474, "max_line_length": 81, "alphanum_fraction": 0.7259450172, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.6297745935070808, "lm_q1q2_score": 0.3943170904116578}}
{"text": "/* ode-initval/gear1.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Gear 1 */\n\n/* Author:  G. Jungman\n */\n#include <config.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_odeiv.h>\n\n#include \"odeiv_util.h\"\n\ntypedef struct\n{\n  double *k;\n  double *y0;\n}\ngear1_state_t;\n\nstatic void *\ngear1_alloc (size_t dim)\n{\n  gear1_state_t *state = (gear1_state_t *) malloc (sizeof (gear1_state_t));\n\n  if (state == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for gear1_state\", GSL_ENOMEM);\n    }\n\n  state->k = (double *) malloc (dim * sizeof (double));\n\n  if (state->k == 0)\n    {\n      free (state);\n      GSL_ERROR_NULL (\"failed to allocate space for k\", GSL_ENOMEM);\n    }\n\n  state->y0 = (double *) malloc (dim * sizeof (double));\n\n  if (state->y0 == 0)\n    {\n      free (state->k);\n      free (state);\n      GSL_ERROR_NULL (\"failed to allocate space for y0\", GSL_ENOMEM);\n    }\n\n  return state;\n}\n\nstatic int\ngear1_apply(void * vstate,\n            size_t dim,\n            double t,\n            double h,\n            double y[],\n            double yerr[],\n            const double dydt_in[],\n            double dydt_out[],\n            const gsl_odeiv_system * sys)\n{\n  gear1_state_t *state = (gear1_state_t *) vstate;\n\n  const int iter_steps = 3;\n  int status = 0;\n  int nu;\n  size_t i;\n\n  double * const k = state->k;\n  double * const y0 = state->y0;\n\n  DISCARD_POINTER(dydt_in); /* prevent warning about unused parameter */\n\n  DBL_MEMCPY(y0, y, dim);\n\n  /* iterative solution */\n  for(nu=0; nu<iter_steps; nu++) {\n    int s = GSL_ODEIV_FN_EVAL(sys, t + h, y, k);\n    GSL_STATUS_UPDATE(&status, s);\n    for(i=0; i<dim; i++) {\n      y[i] = y0[i] + h * k[i];\n    }\n  }\n\n  /* fudge the error estimate */\n  for(i=0; i<dim; i++) {\n    yerr[i] = h * h * k[i];\n  }\n\n  if(dydt_out != NULL) {\n    DBL_MEMCPY(dydt_out, k, dim);\n  }\n\n  return status;\n}\n\nstatic int\ngear1_reset (void *vstate, size_t dim)\n{\n  gear1_state_t *state = (gear1_state_t *) vstate;\n\n  DBL_ZERO_MEMSET (state->k, dim);\n  DBL_ZERO_MEMSET (state->y0, dim);\n\n  return GSL_SUCCESS;\n}\n\nstatic unsigned int\ngear1_order (void *vstate)\n{\n  gear1_state_t *state = (gear1_state_t *) vstate;\n  state = 0; /* prevent warnings about unused parameters */\n  return 2;\n}\n\nstatic void\ngear1_free (void *vstate)\n{\n  gear1_state_t *state = (gear1_state_t *) vstate;\n  free (state->k);\n  free (state->y0);\n  free (state);\n}\n\nstatic const gsl_odeiv_step_type gear1_type = { \"gear1\",        /* name */\n  1,                            /* can use dydt_in */\n  0,                            /* gives exact dydt_out */\n  &gear1_alloc,\n  &gear1_apply,\n  &gear1_reset,\n  &gear1_order,\n  &gear1_free\n};\n\nconst gsl_odeiv_step_type *gsl_odeiv_step_gear1 = &gear1_type;\n", "meta": {"hexsha": "3967f13d63f72157e093cdf16f61b7d32e285b0c", "size": 3501, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl_subset/ode-initval/gear1.c", "max_stars_repo_name": "pvnuffel/test_repos", "max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z", "max_issues_repo_path": "gsl_subset/ode-initval/gear1.c", "max_issues_repo_name": "pvnuffel/test_repos", "max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z", "max_forks_repo_path": "gsl_subset/ode-initval/gear1.c", "max_forks_repo_name": "pvnuffel/test_repos", "max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z", "avg_line_length": 22.5870967742, "max_line_length": 78, "alphanum_fraction": 0.6292487861, "num_tokens": 1030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3942721204902749}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <omp.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_sf_erf.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n/* Begin constants */\n#define VERBOSE 0 //when set to 1, running smc_sampler(...) will generate A LOT of output.\n#define M 200\n#define MH_STEPS 10\n#define N_MIXTURE_COMPONENTS 4\n#define SIGMA 0.55\n#define HLINE printf(\"\\n--------------------------------------------------------------------------------\\n\")\n\nconst double MIXTURE_WEIGHTS[N_MIXTURE_COMPONENTS] = {0.25,0.25,0.25,0.25};\nstatic double* xNew; //an array used for swapping\n\n/* begin function-signatures */\nint test(void);\nvoid allocateParticle_swap(void);\ndouble dnorm(const double x,const double mu);\ndouble log_likelihood(const double * y, const int N_y, const double* mu);\n_Bool ESS_is_largeEnough(const double * W,const int N_W);\ndouble pi_updateStep(const double* y,const int N_y, const double* x, const int n);\nvoid smc_sampler(const double* yObs,const int N_yObs ,const int n_particles , double** particles, double* weights);\nvoid randParticle(double * x);\nvoid resample(double ** particles, double * weights,const int n_particles, const double w0, gsl_rng * r, gsl_ran_discrete_t * wSampler);\nvoid propagate_particle(double * x,const int n, const double* yObs,const int N_yObs,gsl_rng * r);\nvoid smc_sampler_for_R( double* yObs, int* N_yObs, int* N_particles, double* X_vec, double* W, double* time);\nvoid freeParticle_swap(void);\n\n\nint main(){\n  allocateParticle_swap();\n  return test();\n  freeParticle_swap();\n}\n\n/* a wrapper function for calling smc_sampler from R */\nvoid smc_sampler_for_R(\n  double* yObs,\n  int* N_yObs,\n  int* N_particles,\n  double* X_vec,\n  double* W,\n  double* t_SMC )\n  {\n\n  // allocate memmory for swapping\n  allocateParticle_swap();\n\n  // Generate an (N_particles x N_MIXTURE_COMPONENTS) array used to\n  // internally represent particles\n  double** X;\n  X = (double**) malloc(sizeof(double *) * (*N_particles));\n  size_t i = 0;\n  for(i=0 ; i < *N_particles ; ++i){\n    X[i] = (double*) malloc(sizeof(double)*N_MIXTURE_COMPONENTS);\n  }\n\n  //start timer\n  time_t t0 = time(NULL);\n\n  //run sampler\n  smc_sampler(yObs,*N_yObs,*N_particles,X,W);\n\n  //stop timer\n  time_t t1 = time(NULL);\n\n  //return runtime in secconds\n  *t_SMC = difftime(t1,t0);\n\n  //write to output vector\n  size_t j;\n  for( i = 0 ; i < (*N_particles) ; ++i){\n    for( j = 0 ; j < N_MIXTURE_COMPONENTS ;  ++j){\n      X_vec[N_MIXTURE_COMPONENTS * i + j] = X[i][j];\n    }\n  }\n\n  //free up memory;\n  for(i=0 ; i < *N_particles ; ++i){\n    free(X[i]);\n  }\n  free(X);\n\n  freeParticle_swap();\n\n  /* //for debugging.\n  int i;\n  for(i=0 ; i < *N_particles ; ++i){\n    X_vec[i] = (double) i;\n  }\n  */\n}\n\n/* Main function for running SMC sampler\n yObs is an a vector of N_yObs observations\n\n n_particles is the desired number of particles to be simulated\n\n particles should be a double[n_particles][N_MIXTURE_COMPONENTS] array.\n It will be used for storing results and doing computaations.\n\n weights should be a double[n_particles] array.\n It will be used for storing results and doing computations.\n*/\nvoid smc_sampler(\n  const double* yObs,\n  const int N_yObs,\n  const int n_particles,\n  double** particles,\n  double* weights)\n  {\n\n  time_t t0 = time(NULL);\n  time_t t1;\n  size_t i; //summation indices\n\n  gsl_rng * r = gsl_rng_alloc(gsl_rng_mt19937);\n  gsl_ran_discrete_t * wSampler;\n\n  if(VERBOSE) printf(\"Initializinng...\");\n  /* Initialize  weights and particles*/\n  double w0 = 1 / (double) n_particles; // default weight\n  for(i=0; i < n_particles ; ++i){\n    weights[i] = w0;\n    randParticle(particles[i]);\n  }\n  if(VERBOSE) printf(\"DONE!\\n\");\n\n  if(VERBOSE) time(&t1);\n  if(VERBOSE) printf(\"Elapsed time = %.0f sec\\n\",difftime(t1,t0));\n\n  if(VERBOSE) printf(\"Running sampling steps from 1 to 200...\\n\");\n\n  /* Iterate from n=1 to n=M */\n  int n = 1;\n  unsigned int resampleCounter = 0;\n  while(1){\n\n    // for diagnosing running time and output\n    if((n-1)%10 == 0){\n      if(VERBOSE) time(&t1);\n      if(VERBOSE) printf(\"Running steps %i...%i; \\t\",n,n+9);\n      if(VERBOSE) printf(\"elapsed time so far = %.0f sec\\n\",difftime(t1,t0));\n\n      if(VERBOSE){\n        printf(\"Printing the first 10 particles to check validity of output:\\n\");\n        size_t j;\n        for(i=0;i<10;++i){\n          printf(\"  x[%i]_(%i) = \",(int) i,n);\n          for(j=0; j<N_MIXTURE_COMPONENTS ; ++j){\n            if(particles[i][j] >= 0) printf(\" \");\n            if(fabs(particles[i][j]) < 10) printf(\" \");\n            printf(\"%.3f\\t\",particles[i][j]);\n          }\n          printf(\" \\tW[%i](%i) = %f\",(int) i , n, weights[i]);\n          printf(\"\\n\");\n        }\n      }\n\n      double sumW = 0;\n      for(i = 0 ; i < n_particles ; ++i){\n        sumW += weights[i];\n      }\n      if(VERBOSE) printf(\"sum of weights = %f\",sumW);\n      if(VERBOSE) HLINE;\n\n     }\n\n    /* Resample and reset weights, if nessecary */\n    if(!(ESS_is_largeEnough(weights,n_particles))){\n      if(VERBOSE) ++resampleCounter;\n      if(VERBOSE) HLINE;\n      if(VERBOSE) printf(\"resampling in step n = %i\\n\",n);\n      if(VERBOSE) HLINE;\n      //Preprocessing for sampling from a discrete distribution\n      wSampler = gsl_ran_discrete_preproc (n_particles,weights);\n\n      //Resample (AND reset) weights\n      resample(particles,weights,n_particles,w0,r,wSampler);\n    }\n\n    /* Update particle weights */\n    double sumW = 0;\n    for(i = 0 ; i<n_particles ; ++i){\n      weights[i] *= pi_updateStep(yObs, N_yObs, particles[i] ,n);\n      sumW += weights[i];\n    }\n    double Z = (double) 1 / sumW;\n    for(i = 0 ; i<n_particles ; ++i){\n      weights[i] *= Z;\n    }\n\n\n\n    /* break out when n == M */\n    if(n==M) break;\n\n\n    /* Propagate particles */\n    for(i=0; i<n_particles ; ++i){\n      propagate_particle(particles[i], n, yObs, N_yObs,r);\n    }\n\n    /*increment counter*/\n    ++n;\n  }\n  if(VERBOSE) printf(\"total number of resampling-steps = %i\\n\",resampleCounter);\n  gsl_rng_free(r);\n  // gsl_ran_discrete_free(wSampler);\n}\n\n\n\n\n\n\n/**********************\n* Auxiliary Functions *\n**********************/\n\nvoid allocateParticle_swap(void){\n  //modify in case of parralelization\n  xNew = (double*) malloc(sizeof(double)*N_MIXTURE_COMPONENTS);\n}\n\nvoid freeParticle_swap(void){\n  //modify in case of parralelization\n  free(xNew);\n}\n\ndouble dnorm(const double x, const double mu){\n  return  gsl_sf_erf_Z((x - mu)/SIGMA)/SIGMA;\n}\n\n/* returns log( p( y | mu , sigma , weights ) )\n y should be a vector of doubles corresponding to observations\n N_y corresponds to the length of y\n mu coresponds to a vector of modes of length N_MIXTURE_COMPONENTS */\ndouble log_likelihood(const double* y, const int N_y,const double* mu){\n  int i; int j; // initialize summation-indices\n\n  /* Verify that all modes are in [-10,10] */\n  for(i=0; i<N_MIXTURE_COMPONENTS; ++i){\n    //INFINITY is a macro defined in math.h\n    if( mu[i] > 10.0 || mu[i] < -10.0 ){\n      if(VERBOSE) printf(\"WOAH! particle out of range\\n\");\n      return -INFINITY;\n    }\n  }\n  /* Compute the log-likelihood iteratively */\n  double sum; // inner summation (over mu)\n  double Sum = 0; //outer summation (over y)\n  for(i = 0;i < N_y; ++i){\n    sum = 0;\n    for(j = 0 ; j < N_MIXTURE_COMPONENTS ; ++j){\n      sum += MIXTURE_WEIGHTS[j] * dnorm(y[i], mu[j]);\n    }\n    Sum += log(sum);\n  }\n  return Sum;\n}\n\n/* Generates a ranodm particle ie. 4 ind. samples uniformly from -10 to 10 */\n/* Results are stored in x */\nvoid randParticle(double* x){\n  unsigned char i;\n  for(i=0 ; i<N_MIXTURE_COMPONENTS; ++i){\n    x[i] = (double) -10 + (double) 20 * (double) rand() / (double) RAND_MAX;\n  }\n}\n\n_Bool ESS_is_largeEnough(const double * W,const int N_W){\n  double sumSq = 0;\n  int i;\n  for(i = 0 ; i < N_W ; ++i){\n    sumSq += W[i] * W[i];\n  }\n  return (_Bool) 1 >= sumSq * N_W / 2.0;\n}\n\nvoid resample(\n  double ** particles,\n  double * weights,\n  const int n_particles,\n  const double w0,\n  gsl_rng * r,\n  gsl_ran_discrete_t * wSampler)\n  {\n  size_t i; size_t j;\n  for(i=0; i< n_particles; ++i){\n    //iterate over particles\n\n    size_t i_new = gsl_ran_discrete(r,wSampler);\n    // copy the particle in question\n    for(j = 0 ; j < N_MIXTURE_COMPONENTS ; ++j){\n      particles[i][j] = particles[i_new][j];\n    }\n  }\n  //reset particle weights\n  for(i=0; i < n_particles ; ++i){\n    weights[i] = w0;\n  }\n}\n\n/*\nA n auxiliary function for computing pi_n(x_(n-1)) / pi_(n-1)(x_(n-1))\n\\eqn{\\propto} p( x_(n-1) | y ) ^ ((2n -1)/M^2). Used when updating weights.\n@param y Observed data\n@param x Our proposed value for Mu (a vector of modes)\n*/\ndouble pi_updateStep(const double* y,const int N_y, const double* x,const int n){\n  return exp( ( ((float) 2*n -1)/((float) (M*M)) ) * log_likelihood(y,N_y,x));\n}\n\nvoid propagate_particle(double * x,const int n, const double* yObs,const int N_yObs,gsl_rng * r){\n\n  //NOTE: xNew MUST have been allocated before calling this method!\n\n  size_t i = 0; size_t j;\n  for(i = 0 ; i < MH_STEPS ; ++i){\n\n    // Generate new observation\n    for(j = 0 ; j < N_MIXTURE_COMPONENTS ; ++j){\n      xNew[j] = x[j] + gsl_ran_gaussian(r,SIGMA);\n    }\n\n/*\n    // REMOVE WHEN COMPILING FOR SPEED!\n    if(VERBOSE){\n      // printf(\"Acceptance! alpha = %0.3f\\n\",alpha);\n      printf(\"  x\\t= \");\n      for(j=0; j<N_MIXTURE_COMPONENTS ; ++j){\n        if(x[j] >= 0) printf(\" \");\n        if(fabs(x[j]) < 10) printf(\" \");\n        printf(\"%.3f\\t\",x[j]);\n      }\n      printf(\"\\n  x_new\\t=\");\n      for(j=0; j<N_MIXTURE_COMPONENTS ; ++j){\n        if(xNew[j] >= 0) printf(\" \");\n        if(fabs(xNew[j]) < 10) printf(\" \");\n        printf(\"%.3f\\t\",xNew[j]);\n      }\n      printf(\"\\n\");\n    }\n*/\n\n    // double logL_new = log_likelihood(yObs, N_yObs, xNew);\n    // double logL_old = log_likelihood(yObs, N_yObs, x);\n    double logL_Diff = log_likelihood(yObs, N_yObs, xNew) - log_likelihood(yObs, N_yObs, x);\n    double alpha = 1;\n    _Bool autoAccept = 1;\n\n    // Iff logL_Diff < 0 true, the sign of the argument fo exp() will be <1.\n    if(logL_Diff < 0){\n      double exponent = (double) n / (double) M;\n      exponent *= exponent; // square the exponent\n      alpha = exp(exponent * logL_Diff );\n      autoAccept = 0;\n      if(VERBOSE) printf(\"alpha = %.4f\",alpha);\n    }\n\n    if( autoAccept || ((double) rand() / (double) RAND_MAX) < alpha){\n      if( VERBOSE && !autoAccept ) printf(\"\\t new point accepted anyway\\n\");\n      for(j = 0 ; j < N_MIXTURE_COMPONENTS ; ++j){\n        x[j] = xNew[j];\n      }\n    } else {\n      if(VERBOSE) printf(\"\\n\");\n    }\n  }\n  if(VERBOSE) printf(\"\\n\");\n}\n\n/* A generic function to test during development\nReturns 0 if test succcessfull*/\nint test(void){\n/*\n  double x = 1; double y;\n  double mu = 0; double sigma = 5;\n  y = dnorm(x,mu,sigma);\n  printf(\"Hello World!\\nNormal(1;0,5) = %.10f\\n\",y);\n*/\n\n/*\n  double y[2] = {0,2};\n  double mu[4] = {-3,0,3,6};\n  double x = log_likelihood(y,2,mu);\n  printf(\"Hello World!\\nx = %.10f\\n\",x);\n*/\n\n/*\n  double mu[4] = {-3,0,3,6};\n  if( mu[2] < 10 ) printf(\"Hello World!\\n\");\n*/\n\n/*\n  int N_W = 6;\n  double W1[6] = {1,0,0,0,0,0};\n  double W2[6] = {0.2,0.2,0.2,0.2,0.2,0};\n\n  if(!(ESS_is_largeEnough(W1,N_W))) printf(\"ESS1 is too small!\\n\");\n  if(ESS_is_largeEnough(W2,N_W)) printf(\"ESS2 on the other hand is groovy!\\n\");\n*/\n\n/*\n  double y[2] = {0,2};\n  double mu[4] = {-3,0,3,6};\n  double x = pi_updateStep(y,2,mu,180);\n  printf(\"Hello World!\\nx = %.10f\\n\",x);\n*/\n\n/*\n  int i; int j;\n  double particles[10][4];\n  for(i = 0 ; i<10; ++i){\n    randParticle(particles[i]);\n  }\n\n  for(i=0 ; i<10 ; ++i){\n    printf(\"rand particles = (\");\n    for(j=0 ; j< 4 ; ++j){\n      printf(\" %.2f \",particles[i][j]);\n    }\n    printf( \")\\n\");\n  }\n*/\n/*\n  int N = 1000;\n\n  double* W;\n  W = (double*) malloc(sizeof(double)*N);\n\n  double** X;\n  X = (double**) malloc(sizeof(double *) * N);\n  size_t i = 0;\n  for(i=0 ; i < N ; ++i){\n    X[i] = (double*) malloc(sizeof(double*)*N_MIXTURE_COMPONENTS);\n  }\n\n  // double W;\n  // double* X[N][N_MIXTURE_COMPONENTS];\n\n  // data pasted in from R\n  // generated using sampleMM(100) from mixtureModel_SMC.R\n  int N_yObs = 100;\n  double yObs[100] =\n   {0.270469630282116 , 0.0948544266135598 , 4.82353957890236 ,\n    2.71176569013062 , -2.10140287048951 , -2.4639397242585 ,\n    -2.47096320311181 , 5.59163596897931 , -3.50775981783882 ,\n    3.26972797997964 , 3.32256384988976 , 5.73616849148524 ,\n    5.74816296903159 , -2.97620992270215 , -0.211030444261816 ,\n    5.56902016608288 , -3.69397287391297 , 5.71718272922272 ,\n    -0.375056085230512 , 0.290727561775271 , 3.53116678441137 ,\n    -2.92396872511173 , 5.44623183851942 , 5.60306594746839 ,\n    5.56855197639855 , 2.28105552916777 , 2.71638272346431 ,\n    3.7321825583144 , 6.10978497180474 , 6.7089442115652 ,\n    3.14182326021059 , -2.72341774114777 , -0.0919451805310823 ,\n    -3.05334875104901 , 6.00697089830724 , -2.81827687988051 ,\n    6.03028599825704 , 3.77081092101111 , -0.17554472859167 ,\n    5.57845673340545 , 6.25654424410659 , 6.40046681340197 ,\n    -2.39322730700275 , 0.937990298556008 , -3.61930611127869 ,\n    2.99419558349795 , -2.95427533963002 , 2.53999917081115 ,\n    -4.35170347149833 , 2.56389630336686 , 2.78219272857881 ,\n    -2.53796084626858 , 2.75783249644654 , 0.265653681397089 ,\n    -4.08489661583957 , 0.141285949971235 , -3.09744117607388 ,\n    -3.29683116823359 , -0.56348650880506 , 2.13298104427159 ,\n    5.81313774243827 , 2.90131666078861 , -0.870942485382193 ,\n    -0.653182465687133 , 3.24697479240955 , 3.46323186816872 ,\n    3.70853665171654 , -3.79582094987125 , 6.55169236217858 ,\n    -3.63836564940765 , 0.132152004366257 , 5.24827155186988 ,\n    2.53806422373366 , 5.6550753862474 , 2.42737960470922 ,\n    5.88968129179486 , 6.83133504027115 , -0.473386824297909 ,\n    -0.883286661476473 , 6.94044430889499 , 2.73913195305667 ,\n    3.02781182874733 , 6.53392928375413 , 6.53623960926176 ,\n    6.44586265929949 , 0.737757409838858 , -2.81327223680057 ,\n    0.534431297323472 , -3.28504638650391 , -0.0839400339092673 ,\n    -3.30271081947717 , 5.97247453668681 , -3.55468774001656 ,\n    -0.211152666301356 , 6.12181217531004 , 2.56643856048767 ,\n    0.200557127297898 , -3.97176332345347 , 0.0176492920069539 ,\n    2.87381823065611};\n\n  printf(\"Running SMC-sampler with %i particles, based on %i observations.\\n\",N,N_yObs);\n  time_t t1 = time(NULL);\n  smc_sampler(yObs,N_yObs,N,X,W);\n  time_t t2 = time(NULL);\n  printf(\"DONE!\\nTotal elapsed time = %.0f\\n\",difftime(t2,t1));\n\n  HLINE;\n\n  printf(\"Printing the first 10 particles to check validity of output:\\n\");\n  size_t j;\n  for(i=0;i<10;++i){\n    printf(\"  x[%i] = \",(int) i);\n    for(j=0; j<N_MIXTURE_COMPONENTS ; ++j){\n      if(X[i][j] >= 0) printf(\" \");\n      if(fabs(X[i][j]) < 10) printf(\" \");\n      printf(\"%.3f\\t\",X[i][j]);\n    }\n    printf(\"\\n\");\n  }\n\n  free(W);\n  // free(X)\n  for(i=0 ; i<N; ++i){\n    free(X[i]);\n  }\n  free(X);\n*/\n\n/*\n  int N_yObs = 100;\n\n  //DATA from R, so that the S-method and the .c method can be directly compated\n  double yObs[100] = {6.42614409154078,0.260646235868524,6.20077626783781,-3.54124388162526,3.16810352365003,-3.02631343546788,6.22743478871312,6.8131742684717,6.24776924281844,3.65204896173014,6.01102502511306,-2.78204404408537,6.54496067301763,2.86661732139087,6.41368106980899,-2.54549938986914,6.08430821908108,2.65819528014716,-4.10369954335742,-3.70836228135375,3.55973960494948,-3.99408019214758,-3.06751044524848,-0.560058224387682,0.625592793169344,2.58052593365431,0.689049384542289,0.494930560119956,0.390397430673082,2.87213201595585,6.08140477180053,-3.63073724259346,1.76368358083185,0.0978387885170348,6.49576360025151,6.65592881975105,-2.31116539097971,6.69822824187681,0.0197128170022586,-3.6584094557839,6.37219590110012,5.98608504754753,5.76477302651333,-2.49473884182791,3.68861876383596,6.71753596416937,-2.86065603329243,2.36234293889529,-2.13229209410826,-3.1821797074668,3.67640450999392,2.35200323180728,-2.90422204445312,3.85237110998024,5.73406945312462,3.61994874049274,-4.0561902744938,5.66696946993138,5.96245114627653,6.59816990256299,0.231879318383607,2.34472949459441,2.72937582033292,-0.444334698629388,2.22482121394123,3.15359838488669,5.79310254628412,2.95627482456672,0.0754282164405023,-3.27128946837834,-2.77302236660845,7.25710145940199,6.2324724323204,5.9296066592542,5.60999425487975,-0.286465744070193,0.587073138580418,-2.67791031284446,6.98129381109518,3.36137498170339,-3.16490919686681,-3.62156309636938,5.41982668735859,-3.07991914749654,-2.89255426727392,5.61010574600101,-3.10612256078391,3.48991878214866,2.58896632171936,0.703862729104843,4.72001741709978,-0.244802119787893,6.45395925612269,0.253461730596016,2.69213945052578,-2.90338536462303,3.28208239426602,-2.57167632631676,0.920364746339414,0.993277872559861};\n\n  int N_X = 5;\n  double X[5][4] = {\n    {0,3,-3,6},\n    {-3,0,3,6},\n    {0,0,0,0},\n    {9,9,9,9},\n    {0,6,3,15}\n  };\n\n  size_t i;\n  for(i = 0 ; i<N_X ; ++i){\n    double LL = log_likelihood(yObs,N_yObs,X[i]);\n    printf(\"log_L(X[%i]) = %f\\n\",(int) i,LL);\n  }\n*/\n  return 0;\n}\n", "meta": {"hexsha": "fe6b7a838ae429c840e8f32acda2a933f4c59c88", "size": 17008, "ext": "c", "lang": "C", "max_stars_repo_path": "parallelComparisonpkg/src/SMC_sampler.c", "max_stars_repo_name": "Cronjaeger/OxWaSP-Project7", "max_stars_repo_head_hexsha": "cd7b6846905d8374936dde5835d5732aa90fd56e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parallelComparisonpkg/src/SMC_sampler.c", "max_issues_repo_name": "Cronjaeger/OxWaSP-Project7", "max_issues_repo_head_hexsha": "cd7b6846905d8374936dde5835d5732aa90fd56e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parallelComparisonpkg/src/SMC_sampler.c", "max_forks_repo_name": "Cronjaeger/OxWaSP-Project7", "max_forks_repo_head_hexsha": "cd7b6846905d8374936dde5835d5732aa90fd56e", "max_forks_repo_licenses": ["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.4962962963, "max_line_length": 1769, "alphanum_fraction": 0.643991063, "num_tokens": 5874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.39427212023292296}}
{"text": "#pragma once\n#include \"GradUtil.h\"\n#include \"DistanceGrad.h\"\n\n#ifndef _NOGSL\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#else\n#include \"CustomSolver.h\"\n#endif\n\n#include <limits>\n#include <math.h>\n#include <vector>\n#include \"BasicError.h\"\n\nusing namespace std;\n\nclass ValueGrad {\n\tdouble val;\n\tgsl_vector* grad;\npublic:\n\tbool set;\n\tValueGrad(double _val, gsl_vector* _grad): val(_val), grad(_grad), set(false) {}\n\t~ValueGrad(void) {\n\t\tgsl_vector_free(grad);\n\t}\n\tdouble getVal() const { return val; }\n\tgsl_vector* getGrad() const { return grad; }\n\tvoid update(double _val) {\n\t\tval = _val;\n\t}\n\tstatic double vg_plus(ValueGrad* m, ValueGrad* f, gsl_vector* ograd);\n\tstatic void vg_plus(ValueGrad* m, ValueGrad* f, ValueGrad* o); // o = m + f\n\tstatic double vg_times(ValueGrad* m, ValueGrad* f, gsl_vector* ograd);\n\tstatic void vg_times(ValueGrad* m, ValueGrad* f, ValueGrad* o); // o = m * f\n\tstatic double vg_div(ValueGrad* m, ValueGrad* f, gsl_vector* o);\n\tstatic void vg_div(ValueGrad* m, ValueGrad* f, ValueGrad* o); // o = m / f\n\tstatic void vg_neg(ValueGrad* m, ValueGrad* o); // o = -m\n\tstatic void vg_equal(ValueGrad* m, ValueGrad* f, DistanceGrad* o); // o = m == f\n\tstatic void vg_lt(ValueGrad* m, ValueGrad* f, DistanceGrad* o); // o = m < f\n\tstatic double vg_lt(ValueGrad* m, ValueGrad* f, gsl_vector* o);\n\tstatic void vg_lt(ValueGrad* m, ValueGrad* f, ValueGrad* o);\n\tstatic void vg_square(ValueGrad* m, ValueGrad* o); // o = m * m\n\tstatic void vg_arctan(ValueGrad* m, ValueGrad* o); // o = arctan(m)\n\tstatic void vg_sin(ValueGrad* m, ValueGrad* o); // o = sin(m)\n\tstatic void vg_cos(ValueGrad* m, ValueGrad* o); // o = cos(m)\n\tstatic void vg_tan(ValueGrad* m, ValueGrad* o); // o = tan(m)\n\tstatic void vg_sqrt(ValueGrad* m, ValueGrad* o); // o = sqrt(m)\n\tstatic void vg_exp(ValueGrad* m, ValueGrad* o);\n\tstatic double vg_copy(ValueGrad* m, gsl_vector* ograd);\n\tstatic void vg_copy(ValueGrad* i1, ValueGrad* i2); // copy i1 into i2\n\tstatic void vg_cast_int_float(ValueGrad* m, ValueGrad* o);\n\t\n\tstatic void vg_ite(ValueGrad* m, ValueGrad* f, DistanceGrad* d, ValueGrad* o); // o = ite(d, m, f)\n\tstatic void vg_ite(ValueGrad* m, ValueGrad* f, ValueGrad* d, ValueGrad* o); // o = ite(d, m, f)\n\tstatic void vg_ite(DistanceGrad* m, DistanceGrad* f, ValueGrad* d, DistanceGrad* o);\n    static void vg_ite(ValueGrad* m, ValueGrad* f, double dval, gsl_vector* dgrad, ValueGrad* o);\n    static double vg_ite(ValueGrad* m, ValueGrad* f, double cval, gsl_vector* cgrad,  gsl_vector* ograd);\n\t\n\tstatic double vg_or(ValueGrad* m, ValueGrad* f, gsl_vector* ograd);\n\tstatic void vg_or(ValueGrad* m, ValueGrad* f, ValueGrad* o);\n\tstatic double vg_and(ValueGrad* m, ValueGrad* f, gsl_vector* ograd);\n\tstatic void vg_and(ValueGrad* m, ValueGrad* f, ValueGrad* o);\n\tstatic void vg_not(ValueGrad* m, ValueGrad* o);\n\t\n\tstring print() {\n\t\tstringstream str;\n\t\tstr << \"Val: \" << val;\n\t\treturn str.str();\n\t}\n\t\n\tstring printFull() {\n\t\tstringstream str;\n\t\tstr << \"Val: \" << val << endl;\n\t\tstr << \"Grads: \";\n\t\tfor (int i = 0; i < grad->size; i++) {\n\t\t str << gsl_vector_get(grad, i) << \", \";\n\t\t}\n\t\tstr << endl;\n        if (val > 1e5 || gsl_blas_dnrm2(grad) > 1e5) {\n            str << \"LARGE VALUES\" << endl;\n        }\n\t\treturn str.str();\n\t}\n\t\n#ifdef _NOGSL\n\tvoid bound() {\n\t\tdouble oldVal = val;\n\t\tval = GradUtil::bound(val);\n\t\tif (oldVal != val) {\n\t\t\tGradUtil::default_grad(grad);\n\t\t}\n\t\tint sz = grad->size;\n\t\tdouble* it = grad->data;\n\t\tfor (int i = 0; i < sz; i++) {\n\t\t\t*it = GradUtil::bound(*it);\n\t\t\t++it;\n\t\t}\n\t}\n\n#else\n\tvoid bound() {\n\t\tdouble oldVal = val;\n\t\tval = GradUtil::bound(val);\n\t\tif (oldVal != val) {\n\t\t\tGradUtil::default_grad(grad);\n\t\t}\n\t\tfor (int i = 0; i < grad->size; i++) {\n\t\t\tgsl_vector_set(grad, i, GradUtil::bound(gsl_vector_get(grad, i)));\n\t\t}\n\t}\n#endif\n\n};\n", "meta": {"hexsha": "cfeb598918c5c7d11566450f5fba03dc85b4dd3f", "size": 3775, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/ValueGrad.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/ValueGrad.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/ValueGrad.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "avg_line_length": 32.5431034483, "max_line_length": 105, "alphanum_fraction": 0.6585430464, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3940911037981591}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <stdint.h>\n#include <limits.h> // for int limits etc.\n#include <assert.h>\n#include <time.h>\n#include <gsl/gsl_histogram.h>\n#include <omp.h>\n\n#include \"main.h\"\n#include \"dSFMT-src-2.1/dSFMT.h\"\n//#include \"ziggurat/ziggurat.h\"\n\n//#define STATS\n#define MULTIPLIER 1000000  // seperates the coordiantes (poor man's hash) \n\nint main (int argc, char * argv[]) {\n\tint num_particles = DSFMT_N64*4;\n\tint num_defects = 1024*4;\n\tint box_size = 128;\n\tlong long nsteps = 1024*1024*2;\n\t\n\t//omp_init_lock(&omplock);\n\t//omp_set_num_threads(1);\n\tif (argc == 5) {\n\t\tnum_particles = atoi(argv[1]);\n\t\tnum_defects = atoi(argv[2]);\n\t\tbox_size = atoi(argv[3]);\t\n\t\tnsteps = atoll(argv[4]);\t\n\t}\n\telse {\n\t\tprintf(\"\\n# ***** Using default values! *****\\n\\n\");\n\t\tprintf(\"# usage: rw #particles #defects #box #steps\\n\");\n\t\t\n\t}\n\t\n\t// Information:\n\tprintf(\"#-------------------- Paramters --------------------\\n\");\n\tprintf(\"# Particles: %i\\n\", num_particles);\n\tprintf(\"# Box size: %i\\n\", box_size);\n\tprintf(\"# Defects: %i (Density: %.2e)\\n\", num_defects, (float) num_defects/pow(box_size,3) );\n\tprintf(\"# Steps: %lli\\n\", nsteps);\n\tprintf(\"#---------------------------------------------------\\n\");\n\t\n\tassert( (box_size & (box_size - 1)) == 0 ); // check if box_size is power of two\n\t//zigset(1);\n\tdsfmt_t dsfmt;\n\t\n\tint seed = 1;\n\t\n\t// int num_random  = (num_particles < 1024) ? 1024: num_particles;\n\t// int  *correlation_times = malloc(num_particles * sizeof(int)); // random distribution of correlation times\n\t// char *directions = malloc(nsteps*sizeof(char)); // directions\n\tint **particles = malloc2D_i(num_particles, 4); // 2d array for particles: x,y,z,mag\n\tint **defects = malloc2D_i(num_defects, 3); // 2d array for defect coordinates\n\t\n\t//int *particle;\n\t//int direction;\n\t\n\t\n\t// init random number generator\n\tdsfmt_init_gen_rand(&dsfmt, seed);\n\t\n\t// check if we can create the hashes\n\t//assert(box_size < MULTIPLIER);\n\tassert(num_defects < pow(box_size,3));\n\t\n#ifdef STATS\n\t// statistics\n\t// histogram of diretions\n\tgsl_histogram * h = gsl_histogram_alloc (6);\n\tgsl_histogram_set_ranges_uniform (h, 0, 6);\n\t\n\t// histogram of visits\n\tgsl_histogram * hvisits = gsl_histogram_alloc (10000);\n\tgsl_histogram_set_ranges_uniform (hvisits, 0, 10000);\n\t\n\t// gsl histogram seems not to be thread safe, allow only 1 thread\n\tomp_set_num_threads(1);\n#endif\n\t\n\t// Start simulation\n\t\n\t// distribute particles from 0 to +box_size\n\tfor (int j = 0; j < 3; j++) {\n\t\tfor (int i=0 ;i < num_particles; i++) {\n\t\t\tparticles[i][j] = (int) (dsfmt_genrand_close_open(&dsfmt)*box_size);\n\t\t}\n\t}\n\t\n\t\n\t// distribute defects from 0 to +box_size\n\tfor (int j = 0; j < 3; j++) {\n\t\tfor (int i=0 ; i < num_defects; i++) {\n\t\t\tint val = (int) (dsfmt_genrand_close_open(&dsfmt)*box_size);\n\t\t\tdefects[i][j] = val;\n\t\t}\n\t}\n\t\n\t// METHOD 1: now create a hashed list to find them later\n\t// This will be a fallback to METHOD 2, in case memory is not enough\n\tint64_t *hash_list = malloc( num_defects*sizeof(int64_t) );\n\tfor (int i = 0; i < num_defects; i++) {\n\t\thash_list[i] = hash(defects[i][0],defects[i][1],defects[i][2]);\n\t}\n\t\n\tqsort(hash_list, num_defects, sizeof(int64_t), int64_cmp);\n\t\n\t// METHOD 2: create lookup table for x -> lookup table for y -> lookup table for z \n\t// The smart thing is that the pointers are NULL if there is no defect in the corresponding slab,\n\t// so only the z coordinates are really arrays\n\t//\n\t// If I need more space one could use the chars as bit fields,\n\t// One needs to calculate the offset (or index of char) to get to the proper group though.\n\t// get offset: offset = coord/sizeof(char) oder coord >> log2(sizeof(char))\n\t// set bit: array[offset] |= 1 << coord%sizeof(char)\n\t\n\t// in check_defekt_3d:\n\t// check bit: array[offset] & 1 << coord%sizeof(char)  > 1\n\t//\n/*\n\tint mem_size_table = 0;\n\t// first coordinate (x) will be an array of pointers to an array of pointers\n\tchar ***lookup_table = malloc(box_size * sizeof(char**));\n\tmem_size_table += box_size * sizeof(char**);\n\t// initialize the arrays to NULL pointer\n\tfor (int i = 0; i < box_size; i++) {\n\t\tlookup_table[i]=NULL;\n\t}\n\t\n\tfor (int i = 0; i < num_defects; i++) {\n\t\tint x_index = defects[i][0];\n\t\tint y_index = defects[i][1];\n\t\tint z_index = defects[i][2] / sizeof(char);\n\t\t// check if there  is already an array at x_index ...\n\t\tif (lookup_table[x_index] == NULL) {\n\t\t\t// ... it's not! Create an array of pointers for the second coordinate\n\t\t\tlookup_table[x_index] = malloc(box_size * sizeof(char*)); // malloc second coordinate pointers\n\t\t\tmem_size_table += box_size * sizeof(char*);\n\t\t\tfor (int i = 0; i < box_size; i++) \n\t\t\t\tlookup_table[x_index][i]=NULL; // initialize the second coordiante pointers to NULL\n\t\t}\n\t\t\n\t\t// check if there is already an array at [x_index][y_index]\t\t\n\t\tif (lookup_table[x_index][y_index] == NULL) { // check if third coordinate array exists\n\t\t\tlookup_table[x_index][y_index] = malloc(box_size * sizeof(char)); // malloc third coordinate array\n\t\t\tmem_size_table += box_size * sizeof(char);\n\t\t\tfor (int i = 0; i < box_size; i++) \n\t\t\t\tlookup_table[x_index][y_index][i]=0; // initialize the third array to zero\n\t\t\t\n\t\t}\n\t\t// set the defect coordinate\n\t\tlookup_table[x_index][y_index][z_index] = 1;\n\n\t\t }\n\n\tint test_particle[4];\n\tdouble start = omp_get_wtime();\n\tfor (int i = 0; i < 1024*1024*128; i++) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\ttest_particle[j] = (int) (dsfmt_genrand_close_open(&dsfmt)*box_size);\n\t\t}\n\t\tcheck_defect_3d(test_particle, lookup_table, 10);\n\t}\n\tdouble stop = omp_get_wtime();\n\tprintf(\"# Time Method 2: %.2fs\\n\", stop-start);\n\tprintf(\"# Lookup table size M1: %10.1fkB %i %i\\n\",  mem_size_table/((float) (1024)), num_defects, box_size);\n\n*/\n\t\n\t// Method 3: Using the scheme above but for x,y,z seperately\n\tint ltb_N = (int) ceil( ( (double)box_size ) / sizeof(int));\n\tint xltb[ltb_N];\n\tint yltb[ltb_N];\n\tint zltb[ltb_N];\n\tfor (int i = 0; i < ltb_N; i++) {\n\t\txltb[i]=0;\n\t\tyltb[i]=0;\n\t\tzltb[i]=0;\n\t}\n\tfor (int i = 0; i < num_defects; i++) {\n\t\tint xi =  defects[i][0] / sizeof(int);\n\t\tint xbit = defects[i][0] % sizeof(int);\n\t\t//printf(\"x %i %i %i %i\\n\",i, defects[i][0], xi, xbit);\n\n\t\txltb[xi] |= 1 << xbit;\n\n\t\tint yi = defects[i][1] / sizeof(int);\n\t\tint ybit = defects[i][1] % sizeof(int);\n\t\tyltb[yi] |= 1 << ybit;\n\t\t//printf(\"y %i %i %i %i\\n\",i, defects[i][1], yi, ybit);\n\n\t\tint zi = defects[i][2] / sizeof(int);\n\t\tint zbit = defects[i][2] % sizeof(int);\n\t\tzltb[zi] |= 1 << zbit;\n\t\t//printf(\"z %i %i %i %i\\n\",i, defects[i][2], zi, zbit);\n\t}\n\n/*\n\tstart = omp_get_wtime();\n\tfor (int i = 0; i < 1024*1024*128; i++) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\ttest_particle[j] = (int) (dsfmt_genrand_close_open(&dsfmt)*box_size);\n\t\t}\n\t\tcheck_defect_ltb(test_particle, xltb, yltb, zltb , 0);\n\t}\n\tstop = omp_get_wtime();\n\tprintf(\"Time Method 3: %.2fs\\n\", stop-start);\n*/\t\n\t\n\tprintf(\"# Lookup table size M2: %10.1fkB %i %i\\n\",  3*ltb_N*sizeof(int) / ((float) (1024)), num_defects, box_size);\n\n\t// check if the lookup table is correct\n\tfor (int i = 0; i < num_defects; i++) {\n\n\t\tint x = defects[i][0];\n\t\tint y = defects[i][1];\n\t\tint z = defects[i][2];\n\t\t//printf(\"Test: %i\\n\",lookup_table[x][y][z]);\n/*\n\t\tassert(lookup_table[x][y][z] == 1); // Method 2\n*/\n\t\t// Method 3\n\t\tint xi = x/ sizeof(int);\n\t\tint xbit = x % sizeof(int);\n\t\tassert( (xltb[xi] & (1<<xbit)) != 0 ); \n\n\t\tint yi = y/ sizeof(int);\n\t\tint ybit = y % sizeof(int);\n\t\tassert( (yltb[yi] & (1<<ybit)) != 0 ); \n\n\n\t\tint zi = z/ sizeof(int);\n\t\tint zbit  = z % sizeof(int);\n\t\tassert( (zltb[zi] & (1<<zbit)) != 0 ); \n\n\t\t\n\t}\n\n\t\n\t\n\t/*\n\t for (int i = 0; i < num_particles; i++) {\n\t if (particles[i][3] == 1) printf(\"%i\\n\", i);\n\t }\n\t */\n\t\n\t\n\t\n\t/******************************* loop *********************************/\n\t// exchange outer with inner loop\n\tprintf(\"\\n# Starting ...\\n\");\n\t\n\tint  *mags = malloc(nsteps * sizeof(int)); // magnetization per step\n\tfor (int i = 0; i < nsteps; i++) {\n\t\tmags[i] = 0;\n\t}\n\t\n\t\n\t// loop over particles\n\tdouble calc_time=0;\n\tprintf(\"MinSize: %i\\n\", DSFMT_N64);\n\tdouble *dir_pool = malloc(DSFMT_N64 * sizeof(double));\n#pragma omp parallel for reduction(+:calc_time) firstprivate(dir_pool)\n\tfor (int i = 0; i < num_particles; i+=DSFMT_N64) {\n\t\t// every thread gets its own RNG\n\t\tdsfmt_t dsfmt;\n\t\tdsfmt_init_gen_rand(&dsfmt, i);\n\t\t\n\t\t/*\n\t\t double *random_numbers_steps = malloc(nsteps * sizeof(double));\t\t\n\t\t // create random numbers for the movements (directions 1..6)\n\t\t dsfmt_fill_array_open_close(&dsfmt, random_numbers_steps, nsteps);\n\t\t \n\t\t // scale the to 0,1,2,3,4,5 (the 6 directions)\n\t\t for (int i=0 ;i < nsteps; i++) {\n\t\t directions[i] = (short) (random_numbers_steps[i]*6);\n\t\t }\n\t\t free(random_numbers_steps);\n\t\t */\n\t\t\n\t\t// distribution of correlation times, rexp,rnor are NOT thread safe!\n\t\t//for (int i=0 ;i < num_particles; i++) {\n\t\t//\tcorrelation_times[i] = (int) rexp()*30;\n\t\t//}\n\t\t\n\t\t// loop over steps\n\t\tfor (int step = 0; step < nsteps; step++) {\n\t\t\tdsfmt_fill_array_open_close(&dsfmt, dir_pool, DSFMT_N64);\n\t\t\tdouble start = omp_get_wtime();\n\t\t\t// doing batches of particles\n\t\t\tfor (int j = 0; j < DSFMT_N64; j++) { \n\t\t\t\tint* particle = particles[i+j];\n\t\t\t\tint direction = dir_pool[j];\n\t\t\t\t//int direction = (int) (dsfmt_genrand_close_open(&dsfmt)*6); \n\t\t\t\t// only move particles which have not met defect yet == 0\n\t\t\t\t// or see how often they met a defefct >= 0\n\t\t\t\tif (particle[3] == 0) { \n\t\t\t\t\t\n\t\t\t\t\t// random step\n\t\t\t\t\tmove_particle(particle, direction);\n\t\t\t\t\t\n\t\t\t\t\t// obey periodic boundary conditions, i.e. fold back\n\t\t\t\t\tcheck_pbc(particle, box_size);\n\t\t\t\t\t\n\t\t\t\t\tint tc = 10;\n\t\t\t\t\t\n\t\t\t\t\t// check_defect(particle, tc , hash_list, num_defects);\n\t\t\t\t\t// check_defect_tlb(particle, tc, hash_min, span, defekt_ltb);\n\t\t\t\t\t// check_defect_3d(particle, lookup_table, tc);\n\t\t\t\t\tcheck_defect_ltb(particle, xltb, yltb, zltb , tc);\n\n\t\t\t\t\t// ref_check_defect(particle, defects, num_defects);\n\t\t\t\t}\n\t\t\t\telse { // particle is trapped, decrease the residual waiting time\n\t\t\t\t\tparticle[3] -= 1;\n\t\t\t\t}\n\t\t\t\t#pragma omp atomic\n\t\t\t\tmags[step] += particle[3];\n\t\t\t\t//gsl_histogram_increment (hvisits, particle[3]);\n\t\t\t\t//if (magnetization == num_particles) main_loop_break = 1;\n\t\t\t\t//int tid = omp_get_thread_num();\n\t\t\t\t//printf(\"Thread %i:  %i %i\\n\", id, i, direction);\n\t\t\t\t/*if (step%2000 == 0) {\n\t\t\t\t printf(\"# Step: %8i (MAG: %5i)\\r\", step, magnetization);\n\t\t\t\t fflush(stdout);\n\t\t\t\t }*/\n\t\t\t\t//printf(\"%8i %8i %8i %8i\\n\",particle[0],particle[1],particle[2],particle[3]);\n\t\t\t\t\n\t\t\t} // end sub particle loop\n\t\t\tdouble stop = omp_get_wtime();\n\t\t\tcalc_time += (stop-start);\n\n\t\t} // end steps loop\n\t\t/*\n\t\t if (i%32 == 0) {\n\t\t double stop = omp_get_wtime();\n\t\t printf(\"# Particle: %8i (%8.3f s) Magnetization: %8i\\r\",i , (stop-start)/32 , magnetization);\n\t\t fflush(stdout);\n\t\t }\n\t\t */\n\t\t// open the file we are writing to\n\t\t\n\t\t\n\t\t//#pragma omp critical\n\t\t//printf(\"# Particle: %8i (%8.3f s) \\n\",i , stop-start);\t\t\n\t} // end particle loop\n\tprintf(\"Speed: %.2e s/particle \\n\", calc_time/num_particles);\n\t\n\tFILE *outFile;\n\tchar fname[] = \"binout.omp\";\n\tsprintf(fname, \"binout.om%i\",0);\n\toutFile = fopen(fname, \"w\");\n\t// use fwrite to write binary data to the file\n\tfwrite(mags, sizeof(mags[0]), nsteps, outFile);\n\tfclose(outFile);\n\tprint_array(particles, 10, 3);\n\t\n\t\n\t//print_array(particles, num_particles, 4);\n\tfree(mags);\n\tfree2D_i(particles);\n\tfree2D_i(defects);\n#ifdef STATS\n\tprintf(\"Directions drawn:\\n\");\n\tgsl_histogram_fprintf (stdout, h, \"%g\", \"%g\");\n\tprintf(\"\\n\");\n\tgsl_histogram_free (h);\n#endif\n\t//omp_destroy_lock(&omplock);\n\treturn 0;\n}\n\n\n\n/***************************************************************************************************************/\n\n/* qsort C-string comparison function */ \nint cstring_cmp(const void *a, const void *b) \n{ \n\t//    const char **ia = (const char **)a;\n\t//    const char **ib = (const char **)b;\n\t//    return strcmp(*ia, *ib);\n\treturn strcmp ( (const char*)a, (const char*)b);\n\t\n\t/* strcmp functions works exactly as expected from\n\t comparison function */ \n} \n\n\n/* asm long long comparison function */ \n/*\n int asm64_comp(const void *a, const void *b) {\n int i=0;\n __asm__(\n \"mov (%%rdi), %%rdx\\n\\t\"    // Subtract low word \n \"sub (%%rsi), %%rdx\\n\\t\" \n \"mov 8(%%rdi), %%rdi\\n\\t\"    // Subtract high word \n \"sbb 8(%%rsi), %%rdi\\n\\t\" \n \"sbb %%eax, %%eax\\n\\t\"    // %eax = -1 if below, zero otherwise \n \"or %%rdx, %%rdi\\n\\t\"    // %rdi is non-zero if comparison is non-zero \n \"neg %%rdi\\n\\t\"    // carry flag is 1 if comparison is non-zero \n \"adc %%eax, %%eax\\n\\t\" // Result in %eax \n \"movl %%eax, %0\\n\\t\"\n : \"=a\" (i)\n :\"r\" (a), \"r\" (b)\n );\n return i;\n }\n */\n\n\nint int64_cmp(const void *a, const void *b) \n{ \n\tconst int64_t *x = a, *y = b;\n\tif(*x > *y)\n\t\treturn 1;\n\telse\n\t\treturn (*x < *y) ? -1 : 0;\n} \n\n/* qsort int comparison function */ \nint int_cmp(const void *a, const void *b) \n{ \n\t//    const int *ia = (const int *)a; // casting pointer types \n\t//    const int *ib = (const int *)b;\n    //return *ia  - *ib; \n\t/* integer comparison: returns negative if b > a \n\t and positive if a > b */ \n\treturn ( *(int*)a - *(int*)b );\n} \n\nstatic inline int64_t hash(int x, int y, int z) {\n\treturn  (int64_t) MULTIPLIER* (int64_t) MULTIPLIER * (int64_t) x + (int64_t) MULTIPLIER * (int64_t) y + (int64_t) z;\n}\n\n\nint** malloc2D_i(long nrows, long ncolumns){\n\tint **array = malloc(nrows * sizeof(int *));\n\tarray[0] = malloc(nrows * ncolumns * sizeof(int));\n\tif (array[0] == NULL) printf(\"Could not allocate memory\");\n\tfor(int i = 1; i < nrows; i++)\n\t\tarray[i] = array[0] + i * ncolumns;\n\t\n\t// set all elements to 0\n\tfor (int i = 0; i < nrows; i++) {\n\t\tfor (int j = 0; j < ncolumns; j++) {\n\t\t\tarray[i][j] = 0;\n\t\t}\n\t}\n\treturn array; \n}\n\n/*\n char** malloc2D_char(long nrows, long ncolumns){\n char **array = malloc(nrows * sizeof(char *));\n array[0] = malloc(nrows * ncolumns * sizeof(char));\n if (array[0] == NULL) printf(\"Could not allocate memory\");\n for(int i = 1; i < nrows; i++)\n array[i] = array[0] + i * ncolumns;\n return array; \n }\n */\nchar** malloc2D_char(long nrows, long ncolumns){\n\tchar **array = malloc(nrows * sizeof(char *));\n\tfor(int i = 0; i < nrows; i++)\n\t\tarray[i] = malloc(ncolumns * sizeof(char));\n\treturn array; \n}\n\n\n\nvoid free2D_i(int** array) {\n\t//free(&array[0]);\n\tfree(array);\n}\n\nvoid print_array(int **array, int nrows, int ncolumns){\n\tfor (int i = 0; i < nrows; i++) {\n\t\tfor (int j = 0; j < ncolumns-1; j++) {\n\t\t\tprintf(\"%i \",array[i][j]);\n\t\t}\n\t\tprintf(\"%i\\n\",array[i][ncolumns-1]);\n\t}\n}\n\nvoid move_particle(int *particle, int direction){\n\tswitch (direction) {\n\t\tcase 0:\n\t\t\tparticle[0] += 1;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tparticle[0] -= 1;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tparticle[1] += 1;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tparticle[1] -= 1;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tparticle[2] += 1;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tparticle[2] -= 1;\n\t\t\tbreak;\n\t} // end switch statement\t\n}\n\nstatic inline void check_pbc(int* particle, int box_size) {\n\tfor (int i = 0; i < 3; i++) {\n\t\t// % is NOT the mod operator, but the REMAINDER, it is not working for negative numbers (of course in C only)\n\t\t//particle[i] = particle[i] % box_size + (particle[i]<0?box_size:0);\n\t\tparticle[i] &= (box_size - 1);\n\t}\n}\n/* binary search */\nvoid check_defect(int* particle, int correlation_time, int64_t* hash_list, int num_defects ){\n\tint64_t hash_val;\n\thash_val = hash(particle[0],particle[1],particle[2]);\n\tint * ptr;\n\tptr = bsearch( &hash_val, hash_list, num_defects , sizeof(int64_t), int64_cmp);\n\tif (ptr != NULL)\n\t\tparticle[3] = correlation_time;\n}\n\n/* lookup table 1 */\n\nvoid check_defect_hash(int* particle, int correlation_time, int64_t hash_list_min, int64_t span, char* defekt_ltb){\n\tint64_t hash_val, offset;\n\thash_val = hash(particle[0],particle[1],particle[2]);\n\toffset = hash_val -  hash_list_min;\n\tif ((offset >= 0) && (offset < span)) {\n\t\tif (defekt_ltb[ offset ] == 1)\n\t\t\tparticle[3] = correlation_time;\n\t}\n}\n\n\n/* check Method 3 */\n\nvoid check_defect_3d(int* particle, char*** lookup, int correlation_time){\n\tint x = particle[0];\n\tint y = particle[1];\n\tint z = particle[2];\n\tif (lookup[x] != NULL) {\n\t\tif (lookup[x][y] != NULL) {\n\t\t\tif (lookup[x][y][z] == 1) {\n\t\t\t\tparticle[3] = correlation_time;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid check_defect_ltb(int* particle, int* x, int* y, int* z, int correlation_time){\n\tint i = particle[0] / sizeof(int);\n\tint bit = 1<< particle[0] % sizeof(int);\n\tif (  (x[i] & 1 << bit) > 0) {\n\t\ti = particle[1] / sizeof(int);\n\t\tbit = 1<< particle[1] % sizeof(int);\n\t\tif (  (y[i] & 1 << bit) > 0) {\n\t\t\ti = particle[2] / sizeof(int);\n\t\t\tbit = 1<< particle[2] % sizeof(int);\n\t\t\tif (  (z[i] & 1 << bit) > 0) {\n\t\t\t\tparticle[3] = correlation_time;\n\t\t\t}\n\t\t}\n\t}\n\t\t/*\n\t switch ( (x[particle[0] / sizeof(int)]) & (1<< particle[0] % sizeof(int))  ) {\n\t\t case 0:\n\t\t\t break;\n\t\t default:\n\t\t\t switch ( (y[particle[1] / sizeof(int)]) & (1<< particle[1] % sizeof(int))  ) {\n\t\t\t\t case 0:\n\t\t\t\t\t break;\n\t\t\t\t default:\n\t\t\t\t\t switch ( (z[particle[2] / sizeof(int)]) & (1<< particle[2] % sizeof(int))  ) {\n\t\t\t\t\t\t case 0:\n\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t default:\n\t\t\t\t\t\t\t particle[3] = correlation_time;\t\t\t\t\t\t\t \n\t\t\t\t\t }\n\t\t\t }\n\t }*/\n}\n\n\n\n/*\n void check_defect(int* particle, int correlation_time, int64_t* hash_list, int num_defects ){\n int64_t hash_val;\n hash_val = hash(particle[0],particle[1],particle[2]);\n \n \n int bsearch = 0;\n int left = 0;\n int right = num_defects-1;\n \n while (bsearch == 0 && left <= right) {\n // int middle = (left + right) / 2;\n // better: avoid integer overflow\n int middle = left + (right-left) / 2;\n \n if (hash_val == hash_list[middle]) {\n bsearch = 1;\n particle[3] = correlation_time;\n } \n else {\n if (hash_val < hash_list[middle]) right = middle - 1;\n if (hash_val > hash_list[middle]) left = middle + 1;\n }\n }\n }\n \n */\n\n// REFERENCE METHOD\nvoid ref_check_defect(int* particle, int** defect_coords, int num_defects){\n\tint isDefect = 0; \n\tfor (int i = 0; (i < num_defects) && (isDefect == 0); i++) {\n\t\tfor (int j=0; j<3; j++ ){\n\t\t\tif (particle[j] != defect_coords[i][j]) {\n\t\t\t\tbreak; // coordinate mismatch, go to next particle (break loop over coordinates)\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (j==2) { // x,y and z ccordinate match\n\t\t\t\t\tparticle[3] = (int) (rexp()*3) ; // set scalar value\n\t\t\t\t\tisDefect = 1; // break outer loop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n\n/*\n \n void HT_check_defect(int* particle, Fnv64_t* hash_list, int num_defects ){\n int* pItem;\n char hash_string[18];\n Fnv64_t hash_val;\n snprintf(hash_string, sizeof(hash_string), \"%5i %5i %5i\", particle[0], particle[1], particle[2]);\n hash_val = fnv_64_str(hash_string, FNV0_64_INIT);\n pItem = (int*) bsearch (&hash_val, hash_list, num_defects, sizeof (Fnv64_t), fnv64_cmp);\n if (pItem != 0) particle[3] = 1; // set scalar value\n \n }\n \n */\n\n\n\n/*\n // now create a hashed list to find them easier (hopefully)\n Fnv64_t hash_val;\n \n Fnv64_t *hash_list = malloc( num_defects*sizeof(Fnv64_t) );\n for (int i = 0; i < num_defects; i++) {\n snprintf(hash_string, sizeof(hash_string), \"%5i %5i %5i\", defects[i][0], defects[i][1], defects[i][2]);\n hash_val = fnv_64_str(hash_string, FNV1_64_INIT);\n hash_list[i] = hash_val;\n }\n qsort(hash_list, num_defects,sizeof(Fnv64_t), fnv64_cmp);\n */\n\n\n\n\n/* mit chars\n char **hash_list = malloc2D_char(num_defects, 18);\n //char hash_list[20][18];\n for (int i = 0; i < num_defects; i++) {\n snprintf(hash_string, sizeof(hash_string), \"%5i %5i %5i\", defects[i][0], defects[i][1], defects[i][2]);\n hash_list[i] = hash_string;\n printf(\"%03i %s\\n\",i, hash_list[i]);\n }\n \n \n printf(\"Sorted\\n\");\n \n qsort(hash_list, num_defects, sizeof(hash_list[0]), cstring_cmp);//cmpstring_up);\n */\n\n", "meta": {"hexsha": "f24d2e60b714cea428f0f33c9ea703d49730f4e3", "size": 19399, "ext": "c", "lang": "C", "max_stars_repo_path": "RW/main.c", "max_stars_repo_name": "mrosenstihl/projects", "max_stars_repo_head_hexsha": "199ef6bb3afe12f9b509061d867c7304a864fccd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T13:02:56.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-03T13:02:56.000Z", "max_issues_repo_path": "RW/main.c", "max_issues_repo_name": "mrosenstihl/projects", "max_issues_repo_head_hexsha": "199ef6bb3afe12f9b509061d867c7304a864fccd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RW/main.c", "max_forks_repo_name": "mrosenstihl/projects", "max_forks_repo_head_hexsha": "199ef6bb3afe12f9b509061d867c7304a864fccd", "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.1552975327, "max_line_length": 117, "alphanum_fraction": 0.6133305841, "num_tokens": 6312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3939253045541359}}
{"text": "#include \"stdio.h\"\n#include \"gsl/gsl_integration.h\"\n#include \"gsl/gsl_errno.h\"\n#include \"limber.h\"\n#include <gsl/gsl_interp2d.h>\n//#include <gsl/gsl_spline2d.h>\n//#include <gsl/gsl_spline.h>\n\n// This is a workspace size for the gsl integrator\n#define LIMBER_FIXED_TABLE_SIZE 4096\n\n\n// data that is passed into the integrator\n// This is everything we need to compute the\n// integrand\ntypedef struct IntegrandData{\n\tdouble chimin;\n\tdouble chimax;\n\tdouble ell;\n\tgsl_spline * WbX; //K1\n\tgsl_spline * WfX; //K2\n\tgsl_spline * WmX; //K3\n\tgsl_spline * WbY; //K4\n\tgsl_spline * WfY; //K5\n\tgsl_spline * WmY; //K6\n\tInterpolator2D * P;\n\tInterpolator2D * f; //for the f(k,z(x))\n\tInterpolator2D * D; //for the D(k,z(x))\n\tInterpolator2D * BB; //for the b(k,z(x))\n\tgsl_interp_accel * accelerator_xb;\n\tgsl_interp_accel * accelerator_yb;\n\tgsl_interp_accel * accelerator_xf;\n\tgsl_interp_accel * accelerator_yf;\n\tgsl_interp_accel * accelerator_xm;\n\tgsl_interp_accel * accelerator_ym;\n} IntegrandData;\n\n\n// the integrand for all \nstatic double integrand(double chi, void * data_void)\n{\n\tIntegrandData * data = (IntegrandData*) data_void;\n\t// Return 0 if outside range, for convenience.\n\t// Important to ensure that ranges are wide enough.\n\tif(chi < data->chimin || chi > data->chimax) return 0.0;\n\n//exactly the same notation of paperIII\n\n\tdouble wx0 = gsl_spline_eval(data->WbX,chi,data->accelerator_xb);\n\tdouble wy0 = gsl_spline_eval(data->WbY,chi,data->accelerator_yb);\n\n\tdouble wx0m = gsl_spline_eval(data->WmX,chi,data->accelerator_xm);\n\tdouble wy0m = gsl_spline_eval(data->WmY,chi,data->accelerator_ym);\n\n\tdouble wx1 = gsl_spline_eval(data->WfX,chi,data->accelerator_xf);\n\tdouble wy1 = gsl_spline_eval(data->WfY,chi,data->accelerator_yf);\n\n\tdouble wx2 = gsl_spline_eval(data->WfX,chi*(2.0*data->ell-3.0)/(2.0*data->ell+1.0),data->accelerator_xf);\n\tdouble wy2 = gsl_spline_eval(data->WfY,chi*(2.0*data->ell-3.0)/(2.0*data->ell+1.0),data->accelerator_yf);\n\n\tdouble chi5 = chi*(2.0*data->ell+5.0)/(2.0*data->ell+1.0) < data->chimax ? chi*(2.0*data->ell+5.0)/(2.0*data->ell+1.0) : 0.0;\n\tdouble wx3 = gsl_spline_eval(data->WfX, chi5, data->accelerator_xf);\n\tdouble wy3 = gsl_spline_eval(data->WfY, chi5, data->accelerator_yf);\n\n        double c1 = (2.*data->ell*data->ell+2.*data->ell-1.)/((2.*data->ell-1.)*(2.*data->ell+3.));   \n        double c2 = -((data->ell*(data->ell-1.))/((2.*data->ell-1.)*sqrt((2.*data->ell+1.)*(2.*data->ell-3.))));\n        double c3 = -(((data->ell+1.)*(data->ell+2.))/((2.*data->ell+3.)*sqrt((2.*data->ell+1.)*(2.*data->ell+5.))));\n\n\t// Get P(k,0) using k=ell/chi.\n\t// The interp_2d interpolator returns 0 if either \n\t// parameter is outside its range\n\tdouble ka = (data->ell+0.5) / chi;\n\tdouble pa = interp_2d(ka, chi, data->P);\n\n        //for the scale dependent bias b(k,z)\n        double b0 = interp_2d(ka, chi, data->BB);\n\n        //for the scale dependent growth factor D(k,z)\n        double d0 = interp_2d(ka, chi, data->D);\n        double d1 = d0;\n\tdouble d2 = interp_2d(ka, chi*(2.0*data->ell-3.0)/(2.0*data->ell+1.0), data->D);\n\tdouble d3 = interp_2d(ka, chi5, data->D);\n\n        //for the scale dependent growth rate f(k,z)\n        double f1 = interp_2d(ka, chi, data->f);\n\tdouble f2 = interp_2d(ka, chi*(2.0*data->ell-3.0)/(2.0*data->ell+1.0), data->f);\n\tdouble f3 = interp_2d(ka, chi5, data->f);\n\n        double WWX= (wx0*b0*d0 + wx0m*d0 + c1*wx1*f1*d1 + c2*wx2*f2*d2 + c3*wx3*f3*d3);\n        double WWY= (wy0*b0*d0 + wy0m*d0 + c1*wy1*f1*d1 + c2*wy2*f2*d2 + c3*wy3*f3*d3);\n\n\tdouble result = WWX * WWY * pa / chi / chi;\n\n\treturn result;\n\n}\n\n\n// These two convenience functions\n// peer into the internals of the gsl_spline.\n// This is probably a bit naughty, since they could\n// in theory change the internals.\nstatic double inline limber_gsl_spline_min_x(gsl_spline * s)\n{\n\treturn s->x[0];\n}\nstatic double inline limber_gsl_spline_max_x(gsl_spline * s)\n{\n\treturn s->x[s->size-1];\n}\n\n\n\ndouble get_kernel_peak(gsl_spline * WbX, gsl_spline * WbY, int n_chi)\n{\n  double chimin_x = limber_gsl_spline_min_x(WbX);\n  double chimin_y = limber_gsl_spline_min_x(WbY);\n  double chimax_x = limber_gsl_spline_max_x(WbX);\n  double chimax_y = limber_gsl_spline_max_x(WbY);\n  double chimin = chimin_x>chimin_y ? chimin_x : chimin_y;\n  double chimax = chimax_x<chimax_y ? chimax_x : chimax_y;\n  double dchi = (chimax - chimin)/n_chi;\n  double chi_peak = chimin;\n  double chi;\n  double kernel_val=0.;\n  double kernel_peak=0.;\n  for (int i_chi=0; i_chi<=n_chi; i_chi++){\n    chi=chimin+i_chi*dchi;\n    kernel_val = gsl_spline_eval(WbX,chi,NULL) * gsl_spline_eval(WbY,chi,NULL) / chi / chi;\n    if (kernel_val>kernel_peak){\n      kernel_peak = kernel_val;\n      chi_peak = chi;\n    }\n  }\n  // printf(\"chi_peak = %f\\n\",chi_peak);\n  return chi_peak;\n}\n\n\n\ngsl_integration_workspace * W = NULL;\ngsl_integration_glfixed_table *table = NULL;\n\nvoid setup_integration_workspaces(){\n\tif (W==NULL){\n\t\tW = gsl_integration_workspace_alloc(LIMBER_FIXED_TABLE_SIZE);\n\t}\n\tif (table==NULL){\n\t\ttable = gsl_integration_glfixed_table_alloc((size_t) LIMBER_FIXED_TABLE_SIZE);\n\t}\n}\n\n\nstatic\nvoid limber_gsl_fallback_integrator(gsl_function * F, double chimin, double chimax, \n\tdouble abstol, double reltol, double * c_ell, double * error){\n\n\t// Only one warning per process\n\tstatic int fallback_warning_given = 0;\n\n\t// Deactivate error handling - if this one fails we will fall back to a more reliable but slower integrator\n\tgsl_error_handler_t * old_handler = gsl_set_error_handler_off();\n\n\t// Try the fast but flaky integrator.\n\tint status = gsl_integration_qag(F, chimin, chimax, abstol, reltol, LIMBER_FIXED_TABLE_SIZE, GSL_INTEG_GAUSS61, W, c_ell, error);\n\n\t// Restore the old error handler\n\tgsl_set_error_handler(old_handler); \n\n\t// If the fast integrator failed fall back to the old one.\n\tif (status){\n\t\tIntegrandData * data = (IntegrandData*) F->params;\n\t\tdouble ell = data->ell;\n\t\tif (fallback_warning_given==0){\n\t\t\tfprintf(stderr, \"Falling back to the old integrator for ell=%lf (status=%d)\\n\", ell,status);\n\t\t\tfallback_warning_given=1;\n\t\t}\n\t\t*c_ell = gsl_integration_glfixed(F,chimin,chimax,table);\n\t}\n\n}\n\n\n// The only function in this little library callable from the outside\n// world.  The limber_config structure is defined in limber.h but is fairly\n// obvious.  The splines and the interpolator need to be functions of \n// chi NOT z.\ngsl_spline * limber_integral(limber_config * config, gsl_spline * WbX,  gsl_spline * WfX,  gsl_spline * WmX, gsl_spline * WbY,\n\t                 gsl_spline * WfY, gsl_spline * WmY, Interpolator2D * P, Interpolator2D * f, Interpolator2D * D, Interpolator2D * BB)\n\n{\n\n    config->status = LIMBER_STATUS_ERROR;\n    int any_parameter_error=0;\n    if (WbX==NULL){\n        fprintf(stderr, \"NULL WbX parameter in limber_integral\\n\");\n        any_parameter_error = 1;\n    }\n    if (WbY==NULL){\n        fprintf(stderr, \"NULL WbY parameter in limber_integral\\n\");\n        any_parameter_error = 1;\n    }\n    if (WfX==NULL){\n        fprintf(stderr, \"NULL WfX parameter in limber_integral\\n\");\n        any_parameter_error = 1;\n    }\n    if (WfY==NULL){\n        fprintf(stderr, \"NULL WfY parameter in limber_integral\\n\");\n        any_parameter_error = 1;\n    }\n    if (WmX==NULL){\n        fprintf(stderr, \"NULL WmX parameter in limber_integral\\n\");\n        any_parameter_error = 1;\n    }\n    if (WmY==NULL){\n        fprintf(stderr, \"NULL WmY parameter in limber_integral\\n\");\n        any_parameter_error = 1;\n    }\n    if (P==NULL){\n        fprintf(stderr, \"NULL P parameter in limber_integral\\n\");\n        any_parameter_error = 1;\n    }\n    if (f==NULL){\n        fprintf(stderr, \"NULL f parameter in limber_integral\\n\");\n        any_parameter_error = 1;\n    }\n    if (D==NULL){\n        fprintf(stderr, \"NULL D parameter in limber_integral\\n\");\n        any_parameter_error = 1;\n    }\n    if (config->n_ell<0){\n        fprintf(stderr, \"Negative n_ell parameter in limber_integral\\n\");\n        any_parameter_error = 1;\n    }\n    if (config->n_ell==0){\n        fprintf(stderr, \"Error: n_ell=0 in limber calculation.\\n\");\n        any_parameter_error = 1;\n    }\n    if (any_parameter_error){\n        return NULL;\n    }\n\n\tconfig->status = LIMBER_STATUS_OK;\n\n\n\t// Get the appropriate ranges over which to integrate\n\t// It is assumed that (at least one of) the kernel\n\t// splines should go to zero in some kind of reasonable\n\t// place, so we just use the range they specify\n\tIntegrandData data;\n\tdouble chimin_xb = limber_gsl_spline_min_x(WbX);\n\tdouble chimin_yb = limber_gsl_spline_min_x(WbY);\n\tdouble chimax_xb = limber_gsl_spline_max_x(WbX);\n\tdouble chimax_yb = limber_gsl_spline_max_x(WbY);\n\n\tdouble chimin_xf = limber_gsl_spline_min_x(WfX);\n\tdouble chimin_yf = limber_gsl_spline_min_x(WfY);\n\tdouble chimax_xf = limber_gsl_spline_max_x(WfX);\n\tdouble chimax_yf = limber_gsl_spline_max_x(WfY);\n\n\tdouble chimin_xm = limber_gsl_spline_min_x(WmX);\n\tdouble chimin_ym = limber_gsl_spline_min_x(WmY);\n\tdouble chimax_xm = limber_gsl_spline_max_x(WmX);\n\tdouble chimax_ym = limber_gsl_spline_max_x(WmY);\n\n        //my ifs here\n        double chimin_x = chimin_xb > chimin_xf ? chimin_xb : chimin_xf;\n        double chimin_y = chimin_yb > chimin_yf ? chimin_yb : chimin_yf;\n        double chimax_x = chimax_xb < chimax_xf ? chimax_xb : chimax_xf;\n        double chimax_y = chimax_yb < chimax_yf ? chimax_yb : chimax_yf;  \n\tdouble c_ell, error;\n\n\t// Workspaces for the main and falback integrators.\n\t// Static, so only allocated once as it has a fixed size.\n\tsetup_integration_workspaces();\n\n\tdouble reltol = config->relative_tolerance;\n\tdouble abstol = config->absolute_tolerance;\n\t// double reltol = 0.001;\n\t// double abstol = 0.00001;\n\t// printf(\"TOLS: %le %le\\n\",reltol,abstol);\n\n\n\t// Take the smallest range since we want both the\n\t// splines to be valid there.\n\t// This range as well as all the data needed to compute\n\t// the integrand is put into a struct to be passed\n\t// through the integrator to the function above.\n\tdata.chimin = chimin_x>chimin_y ? chimin_x : chimin_y;\n\tdata.chimax = chimax_x<chimax_y ? chimax_x : chimax_y;\n\tdata.WbX = WbX;\n\tdata.WfX = WfX;\n\tdata.WmX = WmX;\n\tdata.WbY = WbY;\n\tdata.WfY = WfY;\n\tdata.WmY = WmY;\n\tdata.P = P;\n\tdata.f = f;//new\n\tdata.D = D;//new\n\tdata.BB = BB;//new\n\tdata.accelerator_xb = gsl_interp_accel_alloc();\n\tdata.accelerator_xf = gsl_interp_accel_alloc();\n\tdata.accelerator_xm = gsl_interp_accel_alloc();\n\tdata.accelerator_yb = gsl_interp_accel_alloc();\n\tdata.accelerator_yf = gsl_interp_accel_alloc();\n\tdata.accelerator_ym = gsl_interp_accel_alloc();\n\n\t// Set up the workspace and inputs to the integrator.\n\t// Not entirely sure what the table is.\n\tgsl_function F;\n\tF.function = integrand;\n\tF.params = &data;\n\n\t//gsl_integration_workspace * workspace = gsl_integration_workspace_alloc(2048);\n\n\t// results of the integration go into these arrays.\n\tdouble c_ell_vector[config->n_ell];\n\tdouble ell_vector[config->n_ell];\n\n\t// loop through ell values according to the input configuration\n\tfor (int i_ell = 0; i_ell<config->n_ell; i_ell++){\n\t\tdouble ell = config->ell[i_ell];\n\t\tdata.ell=ell;\n\n\t\t// Perform the main integration.\n\t\t// This particular function is used because that's what Matt Becker \n\t\t// found to work best.\n\t\t//c_ell = gsl_integration_glfixed(&F,data.chimin,data.chimax,table);\n\t\t// New function still attributable to the legacy of Matt Becker's integrator wisdom.\n\t\t// gsl_integration_qag(&F, data.chimin, data.chimax, abstol, reltol, LIMBER_FIXED_TABLE_SIZE, GSL_INTEG_GAUSS61, W, table, &c_ell, &error);\n\t\t//printf(\"%d %f %f\\n\",i_ell,c_ell_old,c_ell);\n\t\tlimber_gsl_fallback_integrator(&F, data.chimin, data.chimax, \n\t\t\tabstol, reltol, &c_ell, &error);\n\n\t\t//Include the prefactor scaling\n\t\tc_ell *= config->prefactor;\n\n\t\t// Record the results into arrays\n\t\tc_ell_vector[i_ell] = c_ell;\n\t\tell_vector[i_ell] = ell;\n\t}\n\n\t\t// It is often useful to interpolate into the logs of the functions\n\t\t// This is optional in the config. We move this outside the main loop\n\t\t// since we may have all zeros in the output\n\t\tif (config->xlog) {\n\t\t\tfor (int i_ell = 0; i_ell<config->n_ell; i_ell++){\n\t\t\t\tell_vector[i_ell] = log(ell_vector[i_ell]);\n\t\t\t}\n\t\t}\n\t\tif (config->ylog){\n\t\t\tfor (int i_ell = 0; i_ell<config->n_ell; i_ell++){\n\t\t\t\tif (c_ell_vector[i_ell]<0){\n\t\t\t\t\tconfig->status = LIMBER_STATUS_NEGATIVE;\n\t\t\t\t}\n\t\t\t\t\t// negative is worse than zero so only set to zero it not already negative\n\t\t\t\telse if ((c_ell_vector[i_ell]==0) && (config->status<LIMBER_STATUS_ZERO)){\n\t\t\t\t\tconfig->status = LIMBER_STATUS_ZERO;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If none of the values are <= 0 then we are okay to go ahead and take the logs.\n\t\t\tif (config->status == LIMBER_STATUS_OK){\n\t\t\t\tfor (int i_ell = 0; i_ell<config->n_ell; i_ell++) c_ell_vector[i_ell] = log(c_ell_vector[i_ell]);\n\t\t\t}\n\n\t\t}\n\n\t// Create a spline of the arrays as the output\n\tgsl_spline * output = gsl_spline_alloc(gsl_interp_akima, (size_t) config->n_ell);\n\tgsl_spline_init(output, ell_vector, c_ell_vector, (size_t) config->n_ell);\n\n\t// Tidy up\n\tgsl_interp_accel_free(data.accelerator_xb);\n\tgsl_interp_accel_free(data.accelerator_yb);\n\tgsl_interp_accel_free(data.accelerator_xf);\n\tgsl_interp_accel_free(data.accelerator_yf);\n\tgsl_interp_accel_free(data.accelerator_xm);\n\tgsl_interp_accel_free(data.accelerator_ym);\n\n\t// These two are not deallocated because they are static and only initialized once.\n\t// gsl_integration_glfixed_table_free(table);\t\n\t// gsl_integration_workspace_free(W);\n\n\t// And that's it\n\treturn output;\n}\n", "meta": {"hexsha": "4a64ea7f76e1b8def2916d857b95842d2f210e5a", "size": 13415, "ext": "c", "lang": "C", "max_stars_repo_path": "cosmosis-standard-library/structure/projection/src/limber.c", "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_issues_repo_path": "cosmosis-standard-library/structure/projection/src/limber.c", "max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cosmosis-standard-library/structure/projection/src/limber.c", "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "avg_line_length": 34.6640826873, "max_line_length": 141, "alphanum_fraction": 0.699739098, "num_tokens": 4231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3938987746918778}}
{"text": "/**\n *\n * @file core_slauum.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Julien Langou\n * @author Henricus Bouwmeester\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated s Tue Jan  7 11:44:46 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_float\n *\n *  CORE_slauum - Computes the product U * U' or L' * L, where the triangular\n *  factor U or L is stored in the upper or lower triangular part of\n *  the array A.\n *\n *  If UPLO = 'U' or 'u' then the upper triangle of the result is stored,\n *  overwriting the factor U in A.\n *  If UPLO = 'L' or 'l' then the lower triangle of the result is stored,\n *  overwriting the factor L in A.\n *\n *******************************************************************************\n *\n * @param[in] uplo\n *          = PlasmaUpper: Upper triangle of A is stored;\n *          = PlasmaLower: Lower triangle of A is stored.\n *\n * @param[in] N\n *          The order of the triangular factor U or L.  N >= 0.\n *\n * @param[in,out] A\n *          On entry, the triangular factor U or L.\n *          On exit, if UPLO = 'U', the upper triangle of A is\n *          overwritten with the upper triangle of the product U * U';\n *          if UPLO = 'L', the lower triangle of A is overwritten with\n *          the lower triangle of the product L' * L.\n *\n * @param[in] LDA\n *          The leading dimension of the array A. LDA >= max(1,N).\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_slauum = PCORE_slauum\n#define CORE_slauum PCORE_slauum\n#endif\nvoid CORE_slauum(PLASMA_enum uplo, int N, float *A, int LDA)\n{\n    LAPACKE_slauum_work(LAPACK_COL_MAJOR, lapack_const(uplo), N, A, LDA );\n}\n", "meta": {"hexsha": "166c5ee81acfd749a2feb83b5464aa5f133bebf0", "size": 1960, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_slauum.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_slauum.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_slauum.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.131147541, "max_line_length": 80, "alphanum_fraction": 0.5658163265, "num_tokens": 526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3938963228916901}}
{"text": "/****************************************************************************\n *                                                                          *\n * Copyright (C) 2005 ~ 2015 Neutrino International Inc.                    *\n *                                                                          *\n * Author : Brian Lin <lin.foxman@gmail.com>, Skype: wolfram_lin            *\n *                                                                          *\n * QtGSL acts as an interface between Qt and GNU GSL library.               *\n * Please keep QtGSL as simple as possible.                                 *\n *                                                                          *\n * Qt Version   : 5.4.1                                                     *\n * CIOS Version : 1.6.0                                                     *\n *                                                                          *\n ****************************************************************************/\n\n#ifndef QT_GSL_H\n#define QT_GSL_H\n\n#include <QtCore>\n#include <Essentials>\n\nextern \"C\" {\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_inline.h>\n#include <gsl/gsl_const.h>\n#include <gsl/gsl_const_cgs.h>\n#include <gsl/gsl_const_cgsm.h>\n#include <gsl/gsl_const_mks.h>\n#include <gsl/gsl_const_mksa.h>\n#include <gsl/gsl_const_num.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_cdf.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_qrng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_sum.h>\n#include <gsl/gsl_poly.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_permute.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_combination.h>\n#include <gsl/gsl_multiset.h>\n#include <gsl/gsl_statistics.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_sort_vector.h>\n#include <gsl/gsl_heapsort.h>\n#include <gsl/gsl_dht.h>\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_histogram2d.h>\n#include <gsl/gsl_fit.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_deriv.h>\n#include <gsl/gsl_chebyshev.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_complex_math.h>\n}\n\nQT_BEGIN_NAMESPACE\n\n#ifndef QT_STATIC\n#  if defined(QT_BUILD_QTGSL_LIB)\n#    define Q_GSL_EXPORT Q_DECL_EXPORT\n#  else\n#    define Q_GSL_EXPORT Q_DECL_IMPORT\n#  endif\n#else\n#    define Q_GSL_EXPORT\n#endif\n\nclass Q_GSL_EXPORT vcomplex\n{ // GSL complex number\n  public:\n\n    double x ;\n    double y ;\n\n    explicit vcomplex      (void) ;\n    explicit vcomplex      (double x,double y) ;\n             vcomplex      (const vcomplex & complex) ;\n    virtual ~vcomplex      (void) ;\n\n    double real            (void) ;\n    double imaginary       (void) ;\n    double argument        (void) ;\n    double magnitude       (void) ; // abs ,  |z|\n    double squared         (void) ; // squared magnitude ,  |z|^2\n    double logabs          (void) ; // log|z|\n\n    vcomplex & operator  = (vcomplex & complex) ;\n    vcomplex & operator += (vcomplex & complex) ;\n    vcomplex & operator -= (vcomplex & complex) ;\n    vcomplex & operator *= (vcomplex & complex) ;\n    vcomplex & operator /= (vcomplex & complex) ;\n\n    vcomplex & rectangular (double x,double y) ; // equal to operator =\n    vcomplex & polar       (double r,double theta) ;\n    vcomplex & conjugate   (void) ; // z^* = x - i y\n    vcomplex & inverse     (void) ; // 1/z = (x - i y)/(x^2 + y^2)\n    vcomplex & negative    (void) ; // -z = (-x) + i(-y)\n\n    void sin               (vcomplex & value) ;\n    void cos               (vcomplex & value) ;\n    void tan               (vcomplex & value) ;\n    void sec               (vcomplex & value) ;\n    void csc               (vcomplex & value) ;\n    void cot               (vcomplex & value) ;\n\n    void arcsin            (vcomplex & value) ;\n    void arccos            (vcomplex & value) ;\n    void arctan            (vcomplex & value) ;\n    void arcsec            (vcomplex & value) ;\n    void arccsc            (vcomplex & value) ;\n    void arccot            (vcomplex & value) ;\n\n    void sinh              (vcomplex & value) ;\n    void cosh              (vcomplex & value) ;\n    void tanh              (vcomplex & value) ;\n    void sech              (vcomplex & value) ;\n    void csch              (vcomplex & value) ;\n    void coth              (vcomplex & value) ;\n\n    void arcsinh           (vcomplex & value) ;\n    void arccosh           (vcomplex & value) ;\n    void arctanh           (vcomplex & value) ;\n    void arcsech           (vcomplex & value) ;\n    void arccsch           (vcomplex & value) ;\n    void arccoth           (vcomplex & value) ;\n\n  protected:\n\n  private:\n\n};\n\ntypedef QList < vcomplex > vcomplexes ;\n\n\nnamespace N\n{\n\nclass Q_GSL_EXPORT Random         ;\nclass Q_GSL_EXPORT Histogram      ;\nclass Q_GSL_EXPORT Chebyshev      ;\nclass Q_GSL_EXPORT Permutation    ;\nclass Q_GSL_EXPORT Combination    ;\nclass Q_GSL_EXPORT Multisets      ;\nclass Q_GSL_EXPORT MultiFit       ;\nclass Q_GSL_EXPORT BSplines       ;\nclass Q_GSL_EXPORT Interpolation  ;\nclass Q_GSL_EXPORT Vector         ;\nclass Q_GSL_EXPORT Matrix         ;\nclass Q_GSL_EXPORT LevinWithError ;\nclass Q_GSL_EXPORT Levin          ;\n\nnamespace Math\n{\n\nQ_GSL_EXPORT QList<int>       Differential                  (QList<int>       & discrete);\nQ_GSL_EXPORT QList<long long> Differential                  (QList<long long> & discrete);\nQ_GSL_EXPORT QList<float>     Differential                  (QList<float>     & discrete);\nQ_GSL_EXPORT QList<double>    Differential                  (QList<double>    & discrete);\nQ_GSL_EXPORT QList<double>    VectorMultiply                (QList<double>    & discrete,double v);\nQ_GSL_EXPORT double           SquareSigma                   (QList<double>    & discrete);\nQ_GSL_EXPORT double           VectorMin                     (QList<double>    & discrete);\nQ_GSL_EXPORT double           VectorMax                     (QList<double>    & discrete);\nQ_GSL_EXPORT QByteArray       VectorByteArray               (QList<double>    & discrete);\nQ_GSL_EXPORT QList<double>    VectorFromByteArray           (QByteArray       & B);\nQ_GSL_EXPORT double           Average                       (int total,double * values) ;\nQ_GSL_EXPORT int              AddValues                     (int total,double * values,double value) ;\nQ_GSL_EXPORT int              Multiply                      (int total,double * values,double value) ;\nQ_GSL_EXPORT int              FaPb                          (int total,double * values,double a,double b) ; // F = a * ( x[i] + b )\nQ_GSL_EXPORT int              FaXb                          (int total,double * values,double a,double b) ; // F = a * x[i] + b\nQ_GSL_EXPORT int              Divide                        (int total,double * values,double value) ;\nQ_GSL_EXPORT void             CutOff                        (int total,double * values,double minimum,double maximum) ;\n\nQ_GSL_EXPORT int              toByteArray                   (const vcomplexes & complexes,QByteArray & body) ;\nQ_GSL_EXPORT int              toComplexes                   (const QByteArray & body,vcomplexes & complexes) ;\nQ_GSL_EXPORT int              toDouble                      (int items,char           * CHARS  ,double * DOUBLEs) ;\nQ_GSL_EXPORT int              toDouble                      (int items,unsigned char  * UCHARS ,double * DOUBLEs) ;\nQ_GSL_EXPORT int              toDouble                      (int items,short          * SHORTS ,double * DOUBLEs) ;\nQ_GSL_EXPORT int              toDouble                      (int items,unsigned short * USHORTS,double * DOUBLEs) ;\nQ_GSL_EXPORT int              toDouble                      (int items,int            * INTS   ,double * DOUBLEs) ;\nQ_GSL_EXPORT int              toDouble                      (int items,unsigned int   * UINTS  ,double * DOUBLEs) ;\nQ_GSL_EXPORT int              toDouble                      (int items,float          * FLOATS ,double * DOUBLEs) ;\nQ_GSL_EXPORT int              Addition                      (int items,double * A,double * B           ) ; // A += B\nQ_GSL_EXPORT int              Addition                      (int items,double * A,double * B,double * C) ; // A  = B + C\nQ_GSL_EXPORT int              Subtract                      (int items,double * A,double * B           ) ; // A -= B\nQ_GSL_EXPORT int              Subtract                      (int items,double * A,double * B,double * C) ; // A  = B - C\nQ_GSL_EXPORT int              Multiply                      (int items,double * A,double * B           ) ; // A *= B\nQ_GSL_EXPORT int              Multiply                      (int items,double * A,double * B,double * C) ; // A  = B * C\nQ_GSL_EXPORT int              Divide                        (int items,double * A,double * B           ) ; // A /= B\nQ_GSL_EXPORT int              Divide                        (int items,double * A,double * B,double * C) ; // A  = B / C\n\nQ_GSL_EXPORT void             Sort                          (double * data,const size_t stride,size_t n) ;\nQ_GSL_EXPORT void             Sort                          (float  * data,const size_t stride,size_t n) ;\nQ_GSL_EXPORT void             Sort                          (int    * data,const size_t stride,size_t n) ;\nQ_GSL_EXPORT void             SortIndex                     (size_t * p,const double * data,size_t stride,size_t n) ;\nQ_GSL_EXPORT void             SortIndex                     (size_t * p,const float  * data,size_t stride,size_t n) ;\nQ_GSL_EXPORT void             SortIndex                     (size_t * p,const int    * data,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortSmallest                  (double * dest,size_t k,const double * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortSmallest                  (float  * dest,size_t k,const float  * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortSmallest                  (int    * dest,size_t k,const int    * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortLargest                   (double * dest,size_t k,const double * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortLargest                   (float  * dest,size_t k,const float  * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortLargest                   (int    * dest,size_t k,const int    * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortSmallestIndex             (size_t * p,size_t k,const double * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortSmallestIndex             (size_t * p,size_t k,const float  * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortSmallestIndex             (size_t * p,size_t k,const int    * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortLargestIndex              (size_t * p,size_t k,const double * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortLargestIndex              (size_t * p,size_t k,const float  * src,size_t stride,size_t n) ;\nQ_GSL_EXPORT int              SortLargestIndex              (size_t * p,size_t k,const int    * src,size_t stride,size_t n) ;\n\nQ_GSL_EXPORT double           Mean                          (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           Variance                      (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           VarianceMean                  (const double data [],size_t stride,size_t n,double mean) ;\nQ_GSL_EXPORT double           StandardDeviation             (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           StandardDeviationMean         (const double data [],size_t stride,size_t n,double mean) ;\nQ_GSL_EXPORT double           TotalSumSquares               (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           TotalSumSquaresMean           (const double data [],size_t stride,size_t n,double mean) ;\nQ_GSL_EXPORT double           VarianceFixedMean             (const double data [],size_t stride,size_t n,double mean) ;\nQ_GSL_EXPORT double           StandardDeviationFixedMean    (const double data [],size_t stride,size_t n,double mean) ;\nQ_GSL_EXPORT double           AbsoluteDeviation             (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           AbsoluteDeviationMean         (const double data [],size_t stride,size_t n,double mean) ;\nQ_GSL_EXPORT double           Skew                          (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           SkewMeanSD                    (const double data [],size_t stride,size_t n,double mean,double sd) ;\nQ_GSL_EXPORT double           Kurtosis                      (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           KurtosisMeanSD                (const double data [],size_t stride,size_t n,double mean,double sd) ;\nQ_GSL_EXPORT double           Lag1AutoCorrelation           (const double data [],const size_t stride,const size_t n);\nQ_GSL_EXPORT double           Lag1AutoCorrelationMean       (const double data [],const size_t stride,const size_t n,const double mean) ;\nQ_GSL_EXPORT double           Covariance                    (const double data1[],const size_t stride1,const double data2[],const size_t stride2,const size_t n) ;\nQ_GSL_EXPORT double           CovarianceMean                (const double data1[],const size_t stride1,const double data2[],const size_t stride2,const size_t n,const double mean1,const double mean2) ;\nQ_GSL_EXPORT double           Correlation                   (const double data1[],const size_t stride1,const double data2[],const size_t stride2,const size_t n) ;\nQ_GSL_EXPORT double           WeightedMean                  (const double w    [],size_t wstride,const double data[],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           WeightedVariance              (const double w    [],size_t wstride,const double data[],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           WeightedVarianceMean          (const double w    [],size_t wstride,const double data[],size_t stride,size_t n,double wmean) ;\nQ_GSL_EXPORT double           WeightedSd                    (const double w    [],size_t wstride,const double data[],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           WeightedSdMean                (const double w    [],size_t wstride,const double data[],size_t stride,size_t n,double wmean) ;\nQ_GSL_EXPORT double           WeightedVarianceFixedMean     (const double w    [],size_t wstride,const double data[],size_t stride,size_t n,const double mean) ;\nQ_GSL_EXPORT double           WeightedSdFixedMean           (const double w    [],size_t wstride,const double data[],size_t stride,size_t n,const double mean) ;\nQ_GSL_EXPORT double           WeightedTss                   (const double w    [],const size_t wstride,const double data[],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           WeightedTssMean               (const double w    [],const size_t wstride,const double data[],size_t stride,size_t n,double wmean) ;\nQ_GSL_EXPORT double           WeightedAbsoluteDeviation     (const double w    [],size_t wstride,const double data[],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           WeightedAbsoluteDeviationMean (const double w    [],size_t wstride,const double data[],size_t stride,size_t n,double wmean) ;\nQ_GSL_EXPORT double           WeightedSkew                  (const double w    [],size_t wstride,const double data[],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           WeightedSkewMeanSd            (const double w    [],size_t wstride,const double data[],size_t stride,size_t n,double wmean,double wsd) ;\nQ_GSL_EXPORT double           WeightedKurtosis              (const double w    [],size_t wstride,const double data[],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           WeightedKurtosisMeanSd        (const double w    [],size_t wstride,const double data[],size_t stride,size_t n,double wmean,double wsd) ;\nQ_GSL_EXPORT double           MaxValue                      (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           MinValue                      (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT size_t           MaxIndex                      (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT size_t           MinIndex                      (const double data [],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           MedianFromSorted              (const double sorted_data[],size_t stride,size_t n) ;\nQ_GSL_EXPORT double           QuantileFromSorted            (const double sorted_data[],size_t stride,size_t n,double f) ;\nQ_GSL_EXPORT void             MinMax                        (double * min,double * max,const double data[],size_t stride,size_t n) ;\nQ_GSL_EXPORT void             MinMaxIndex                   (size_t * min_index,size_t * max_index,const double data[],size_t stride,size_t n) ;\n\nQ_GSL_EXPORT int              FitLinear                     (const double * x,const size_t xstride,const double * y,const size_t ystride,size_t n,double * c0,double * c1,double * cov00,double * cov01,double * cov11,double * sumsq) ;\nQ_GSL_EXPORT int              FitMul                        (const double * x,const size_t xstride,const double * y,const size_t ystride,size_t n,double * c1,double * cov11,double * sumsq) ;\nQ_GSL_EXPORT int              WeightedFitLinear             (const double * x,const size_t xstride,const double * w,const size_t wstride,const double * y,const size_t ystride,size_t n,double * c0,double * c1,double * cov00,double * cov01,double * cov11,double * chisq) ;\nQ_GSL_EXPORT int              WeightedFitMul                (const double * x,const size_t xstride,const double * w,const size_t wstride,const double * y,const size_t ystride,size_t n,double * c1,double * cov11,double * sumsq) ;\nQ_GSL_EXPORT int              FitLinearest                  (double x,double c0,double c1,double cov00,double cov01,double cov11,double * y,double * y_err) ;\nQ_GSL_EXPORT int              FitMulest                     (double x,double c1,double cov11,double * y,double * y_err) ;\n\nQ_GSL_EXPORT int              DerivativeCentral             (double x,double h,double * result,double * abserr,MathFunction function,void * params) ;\nQ_GSL_EXPORT int              DerivativeForward             (double x,double h,double * result,double * abserr,MathFunction function,void * params) ;\nQ_GSL_EXPORT int              DerivativeBackward            (double x,double h,double * result,double * abserr,MathFunction function,void * params) ;\n\nQ_GSL_EXPORT void             IntegerMiddleArray            (int items,unsigned char * array,int gaps,void * funcdata) ;\n\n}\n\nnamespace Polynomial\n{\n\nQ_GSL_EXPORT double   Eval        (const double c[]    ,const int len,const double   x) ;\nQ_GSL_EXPORT vcomplex Eval        (const double c[]    ,const int len,const vcomplex z) ;\nQ_GSL_EXPORT vcomplex Eval        (const vcomplexes & c,const int len,const vcomplex z) ;\nQ_GSL_EXPORT int      Derivatives (const double c[],const size_t lenc,const double x,double res[],const size_t lenres) ;\nQ_GSL_EXPORT int      ddInit      (double dd[],const double xa[],const double ya[],size_t size) ;\nQ_GSL_EXPORT double   ddEval      (const double dd[],const double xa[],const size_t size,const double x) ;\nQ_GSL_EXPORT int      ddTaylor    (double c[],double xp,const double dd[],const double xa[],size_t size,double w[]) ;\nQ_GSL_EXPORT int      Quadratic   (double a,double b,double c,double * x0,double * x1) ;\nQ_GSL_EXPORT int      Quadratic   (double a,double b,double c,vcomplex & z0,vcomplex & z1) ;\nQ_GSL_EXPORT int      Cubic       (double a,double b,double c,double * x0,double * x1,double * x2) ;\nQ_GSL_EXPORT int      Cubic       (double a,double b,double c,vcomplex & z0,vcomplex & z1,vcomplex & z2) ;\n\n}\n\nnamespace Cpp\n{\n\nQ_GSL_EXPORT int SizeOf (Cpp::ValueTypes type) ;\n\n}\n\n/*****************************************************************************\n *                                                                           *\n *                                  Statistics                               *\n *                                                                           *\n *****************************************************************************/\n\nclass Q_GSL_EXPORT Random\n{\n  public:\n\n    gsl_rng_type  * Type      ;\n    gsl_rng       * Generator ;\n    gsl_qrng_type * qType     ;\n    gsl_qrng      * Quasi     ;\n\n    explicit Random (unsigned long int seed = 0) ;\n    explicit Random (gsl_rng_type  * type,unsigned long int seed = 0 ) ;\n    explicit Random (gsl_qrng_type * type,unsigned int      dimension) ;\n    virtual ~Random (void) ;\n\n    static const gsl_rng_type ** All        (void) ;\n    QString                      Name       (void) ;\n    unsigned long int            Max        (void) ;\n    unsigned long int            Min        (void) ;\n    bool                         State      (QByteArray & state) ;\n\n    bool                         Create     (gsl_rng_type * type,unsigned long int seed = 0 ) ;\n    unsigned long int            Get        (void) ; // [min,max]\n    unsigned long int            Get        (unsigned long int n) ; // [0,n-1]\n    double                       Uniform    (void) ; // [0,1)\n    double                       Positive   (void) ; // (0,1)\n\n    bool                         Create     (gsl_qrng_type * type,unsigned int dimension) ;\n    int                          QuasiGet   (double x[]) ;\n    QString                      QuasiName  (void) ;\n    bool                         QuasiState (QByteArray & state) ;\n    void                         QuasiReset (void) ;\n\n    Random &                     operator = (Random & source) ;\n\n    double       Gaussian                   (double sigma) ;\n    double       GaussianPDF                (double x,double sigma) ;\n    double       GaussianZiggurat           (double sigma) ;\n    double       GaussianRatioMethod        (double sigma) ;\n    double       UnitGaussian               (void) ;\n    double       UnitGaussianPDF            (double x) ;\n    double       UnitGaussianRatioMethod    (void) ;\n    double       CdfGaussianP               (double x,double sigma) ;\n    double       CdfGaussianQ               (double x,double sigma) ;\n    double       CdfGaussianPinv            (double P,double sigma) ;\n    double       CdfGaussianQinv            (double Q,double sigma) ;\n    double       CdfUnitGaussianP           (double x) ;\n    double       CdfUnitGaussianQ           (double x) ;\n    double       CdfUnitGaussianPinv        (double P) ;\n    double       CdfUnitGaussianQinv        (double Q) ;\n    double       GaussianTail               (double a,double sigma) ;\n    double       GaussianTailPDF            (double x,double a,double sigma) ;\n    double       UnitGaussianTail           (double a) ;\n    double       UnitGaussianTailPDF        (double x, double a) ;\n    bool         BivariateGaussian          (double   sigma_x ,\n                                             double   sigma_y ,\n                                             double   rho     ,\n                                             double & x       ,\n                                             double & y     ) ;\n    double       BivariateGaussianPDF          (double x         ,\n                                             double y         ,\n                                             double sigma_x   ,\n                                             double sigma_y   ,\n                                             double rho     ) ;\n    double       Exponential                (double mu) ;\n    double       ExponentialPDF             (double x,double mu) ;\n    double       CdfExponentialP            (double x,double mu) ;\n    double       CdfExponentialQ            (double x,double mu) ;\n    double       CdfExponentialPinv         (double P,double mu) ;\n    double       CdfExponentialQinv         (double Q,double mu) ;\n    double       Laplace                    (double a) ;\n    double       LaplacePDF                 (double x,double a) ;\n    double       CdfLaplaceP                (double x,double a) ;\n    double       CdfLaplaceQ                (double x,double a) ;\n    double       CdfLaplacePinv             (double P,double a) ;\n    double       CdfLaplaceQinv             (double Q,double a) ;\n    double       ExpPow                     (double a,double b) ;\n    double       ExpPowPDF                  (double x,double a,double b) ;\n    double       CdfExpPowP                 (double x,double a,double b) ;\n    double       CdfExpPowQ                 (double x,double a,double b) ;\n    double       Cauchy                     (double a) ;\n    double       CauchyPDF                  (double x,double a) ;\n    double       CdfCauchyP                 (double x,double a) ;\n    double       CdfCauchyQ                 (double x,double a) ;\n    double       CdfCauchyPinv              (double P,double a) ;\n    double       CdfCauchyQinv              (double Q,double a) ;\n    double       Rayleigh                   (double sigma) ;\n    double       RayleighPDF                (double x,double sigma) ;\n    double       CdfRayleighP               (double x,double sigma) ;\n    double       CdfRayleighQ               (double x,double sigma) ;\n    double       CdfRayleighPinv            (double P,double sigma) ;\n    double       CdfRayleighQinv            (double Q,double sigma) ;\n    double       RayleighTail               (double a,double sigma) ;\n    double       RayleighTailPDF            (double x,double a, double sigma) ;\n    double       Landau                     (void) ;\n    double       LandauPDF                  (double x) ;\n    double       Levy                       (double c,double alpha) ;\n    double       LevySkew                   (double c,double alpha,double beta) ;\n    double       Gamma                      (double a,double b) ;\n    double       GammaKnuth                 (double a,double b) ;\n    double       GammaKnuthPDF              (double x,double a,double b) ;\n    double       CdfGammaP                  (double x,double a,double b) ;\n    double       CdfGammaQ                  (double x,double a,double b) ;\n    double       CdfGammaPinv               (double P,double a,double b) ;\n    double       CdfGammaQinv               (double Q,double a,double b) ;\n    double       Flat                       (double a,double b) ;\n    double       FlatPDF                    (double x,double a,double b) ;\n    double       CdfFlatP                   (double x,double a,double b) ;\n    double       CdfFlatQ                   (double x,double a,double b) ;\n    double       CdfFlatPinv                (double P,double a,double b) ;\n    double       CdfFlatQinv                (double Q,double a,double b) ;\n    double       LogNormal                  (double zeta,double sigma) ;\n    double       LogNormalPDF               (double x,double zeta,double sigma) ;\n    double       CdfLogNormalP              (double x,double zeta,double sigma) ;\n    double       CdfLogNormalQ              (double x,double zeta,double sigma) ;\n    double       CdfLogNormalPinv           (double P,double zeta,double sigma) ;\n    double       CdfLogNormalQinv           (double Q,double zeta,double sigma) ;\n    double       ChiSquared                 (double nu) ;\n    double       ChiSquaredPDF              (double x,double nu) ;\n    double       CdfChiSquaredP             (double x,double nu) ;\n    double       CdfChiSquaredQ             (double x,double nu) ;\n    double       CdfChiSquaredPinv          (double P,double nu) ;\n    double       CdfChiSquaredQinv          (double Q,double nu) ;\n    double       Fdist                      (double a,double b) ;\n    double       FdistPDF                   (double x,double a,double b) ;\n    double       CdfFdistP                  (double x,double a,double b) ;\n    double       CdfFdistQ                  (double x,double a,double b) ;\n    double       CdfFdistPinv               (double P,double a,double b) ;\n    double       CdfFdistQinv               (double Q,double a,double b) ;\n    double       Tdist                      (double a) ;\n    double       TdistPDF                   (double x,double a) ;\n    double       CdfTdistP                  (double x,double a) ;\n    double       CdfTdistQ                  (double x,double a) ;\n    double       CdfTdistPinv               (double P,double a) ;\n    double       CdfTdistQinv               (double Q,double a) ;\n    double       Beta                       (double a,double b) ;\n    double       BetaPDF                    (double x,double a,double b) ;\n    double       CdfBetaP                   (double x,double a,double b) ;\n    double       CdfBetaQ                   (double x,double a,double b) ;\n    double       CdfBetaPinv                (double P,double a,double b) ;\n    double       CdfBetaQinv                (double Q,double a,double b) ;\n    double       Logistic                   (double a) ;\n    double       LogisticPDF                (double x,double a) ;\n    double       CdfLogisticP               (double x,double a) ;\n    double       CdfLogisticQ               (double x,double a) ;\n    double       CdfLogisticPinv            (double P,double a) ;\n    double       CdfLogisticQinv            (double Q,double a) ;\n    double       Pareto                     (double a,double b) ;\n    double       ParetoPDF                  (double x,double a,double b) ;\n    double       CdfParetoP                 (double x,double a,double b) ;\n    double       CdfParetoQ                 (double x,double a,double b) ;\n    double       CdfParetoPinv              (double P,double a,double b) ;\n    double       CdfParetoQinv              (double Q,double a,double b) ;\n    double       Weibull                    (double a,double b) ;\n    double       WeibullPDF                 (double x,double a,double b) ;\n    double       CdfWeibullP                (double x,double a,double b) ;\n    double       CdfWeibullQ                (double x,double a,double b) ;\n    double       CdfWeibullPinv             (double P,double a,double b) ;\n    double       CdfWeibullQinv             (double Q,double a,double b) ;\n    double       Gumbell                    (double a,double b) ;\n    double       GumbellPDF                 (double x,double a,double b) ;\n    double       CdfGumbellP                (double x,double a,double b) ;\n    double       CdfGumbellQ                (double x,double a,double b) ;\n    double       CdfGumbellPinv             (double P,double a,double b) ;\n    double       CdfGumbellQinv             (double Q,double a,double b) ;\n    double       Gumbell2                   (double a,double b) ;\n    double       Gumbell2PDF                (double x,double a,double b) ;\n    double       CdfGumbell2P               (double x,double a,double b) ;\n    double       CdfGumbell2Q               (double x,double a,double b) ;\n    double       CdfGumbell2Pinv            (double P,double a,double b) ;\n    double       CdfGumbell2Qinv            (double Q,double a,double b) ;\n    unsigned int Poisson                    (double mu) ;\n    double       PoissonPDF                 (unsigned int k,double mu) ;\n    double       CdfPoissonP                (unsigned int k,double mu) ;\n    double       CdfPoissonQ                (unsigned int k,double mu) ;\n    unsigned int Bernoulli                  (double p) ;\n    double       BernoulliPDF               (unsigned int k,double p) ;\n    unsigned int Binomial                   (double p,unsigned int n) ;\n    double       BinomialPDF                (unsigned int k,double p,unsigned int n) ;\n    double       CdfBinomialP               (unsigned int k,double p,unsigned int n) ;\n    double       CdfBinomialQ               (unsigned int k,double p,unsigned int n) ;\n    void         Multinomial                (size_t       K     ,\n                                             unsigned int N     ,\n                                             const double p[]   ,\n                                             unsigned int n[] ) ;\n    double       MultinomialPDF             (size_t             K     ,\n                                             const double       p[]   ,\n                                             const unsigned int n[] ) ;\n    double       MultinomialLnPDF           (size_t             K     ,\n                                             const double       p[]   ,\n                                             const unsigned int n[] ) ;\n    unsigned int NegativeBinomial           (double p,double n) ;\n    double       NegativeBinomialPDF        (unsigned int k,double p,double n) ;\n    double       CdfNegativeBinomialP       (unsigned int k,double p,double n) ;\n    double       CdfNegativeBinomialQ       (unsigned int k,double p,double n) ;\n    unsigned int Pascal                     (double p,unsigned int n) ;\n    double       PascalPDF                  (unsigned int k,double p,unsigned int n) ;\n    double       CdfPascalP                 (unsigned int k,double p,unsigned int n) ;\n    double       CdfPascalQ                 (unsigned int k,double p,unsigned int n) ;\n    unsigned int Geometric                  (double p) ;\n    double       GeometricPDF               (unsigned int k,double p) ;\n    double       CdfGeometricP              (unsigned int k,double p) ;\n    double       CdfGeometricQ              (unsigned int k,double p) ;\n    unsigned int Hypergeometric             (unsigned int n1          ,\n                                             unsigned int n2          ,\n                                             unsigned int t         ) ;\n    double       HypergeometricPDF          (unsigned int k           ,\n                                             unsigned int n1          ,\n                                             unsigned int n2          ,\n                                             unsigned int t         ) ;\n    double       CdfHypergeometricP         (unsigned int k           ,\n                                             unsigned int n1          ,\n                                             unsigned int n2          ,\n                                             unsigned int t         ) ;\n    double       CdfHypergeometricQ         (unsigned int k           ,\n                                             unsigned int n1          ,\n                                             unsigned int n2          ,\n                                             unsigned int t         ) ;\n    unsigned int Logarithmic                (double p) ;\n    double       LogarithmicPDF             (unsigned int k, double p) ;\n    void         Dirichlet                  (int K,const double alpha[],double theta[]) ;\n    double       DirichletPDF               (int K,const double alpha[],const double theta[]) ;\n    double       DirichletLnPDF             (int K,const double alpha[],const double theta[]) ;\n    void         SphericalDir2D             (double & x,double & y) ;\n    void         SphericalDir2DTrigMethod   (double & x,double & y) ;\n    void         SphericalDir3D             (double & x,double & y,double & z) ;\n    void         SphericalDirN              (int n, double * x) ;\n    gsl_ran_discrete_t * PrepareDiscrete    (int K,const double * P) ;\n    size_t               Discrete           (const gsl_ran_discrete_t * g) ;\n    double               DiscretePDF        (size_t k,const gsl_ran_discrete_t * g) ;\n    void                 DiscreteFree       (gsl_ran_discrete_t * g) ;\n    void         Shuffle                    (void * base,size_t n,size_t size) ;\n    void         Choose                     (void * dest,size_t k,void * src,size_t n,size_t size) ;\n    void         Sample                     (void * dest,size_t k,void * src,size_t n,size_t size) ;\n\n};\n\nclass Q_GSL_EXPORT Histogram\n{\n  public:\n\n    gsl_histogram       * histo      ;\n    gsl_histogram_pdf   * histoPdf   ;\n    gsl_histogram2d     * histo2d    ;\n    gsl_histogram2d_pdf * histo2dPdf ;\n\n    explicit Histogram        (void) ;\n    explicit Histogram        (int n) ;\n             Histogram        (const Histogram & histogram) ;\n    virtual ~Histogram        (void) ;\n\n    bool   allocate           (int n) ;\n    int    setRanges          (const double range[],int size) ;\n    int    uniformRanges      (double xmin, double xmax) ;\n    int    increment          (double x) ;\n    int    accumulate         (double x,double weight) ;\n    double get                (int i) ;\n    int    getRange           (int i,double * lower,double * upper) ;\n    double Max                (void) ;\n    double Min                (void) ;\n    int    bins               (void) ;\n    void   reset              (void) ;\n    int    find               (double x,size_t * i) ;\n    double maxValue           (void) ;\n    double minValue           (void) ;\n    double mean               (void) ;\n    double sigma              (void) ;\n    double sum                (void) ;\n    int    maxBin             (void) ;\n    int    minBin             (void) ;\n    int    scale              (double scale) ;\n    int    shift              (double offset) ;\n    bool   equalBins          (Histogram & histogram) ;\n    int    add                (Histogram & histogram) ;\n    int    sub                (Histogram & histogram) ;\n    int    mul                (Histogram & histogram) ;\n    int    div                (Histogram & histogram) ;\n\n    bool   allocatePdf        (int n) ;\n    double sample             (double r) ;\n\n    bool   allocate2d         (int nx,int ny) ;\n    int    setRanges2d        (const double xrange[],int xsize,const double yrange[],int ysize) ;\n    int    uniformRanges2d    (double xmin,double xmax,double ymin,double ymax) ;\n    int    increment2d        (double x,double y) ;\n    int    accumulate2d       (double x,double y,double weight) ;\n    double get2d              (int i,int j) ;\n    int    getXrange2d        (int i,double * xlower,double * xupper) ;\n    int    getYrange2d        (int j,double * ylower,double * yupper) ;\n    double xmax2d             (void) ;\n    double xmin2d             (void) ;\n    int    nx2d               (void) ;\n    int    ny2d               (void) ;\n    double ymax2d             (void) ;\n    double ymin2d             (void) ;\n    void   reset2d            (void) ;\n    int    find2d             (double x,double y,size_t * i,size_t * j) ;\n    double maxValue2d         (void) ;\n    double minValue2d         (void) ;\n    void   maxBin2d           (size_t * i,size_t * j) ;\n    void   minBin2d           (size_t * i,size_t * j) ;\n    double xmean2d            (void) ;\n    double ymean2d            (void) ;\n    double xsigma2d           (void) ;\n    double ysigma2d           (void) ;\n    double cov2d              (void) ;\n    double sum2d              (void) ;\n    int    scale2d            (double scale) ;\n    int    shift2d            (double offset);\n    bool   equalBins2d        (Histogram & histogram) ;\n    int    add2d              (Histogram & histogram) ;\n    int    sub2d              (Histogram & histogram) ;\n    int    mul2d              (Histogram & histogram) ;\n    int    div2d              (Histogram & histogram) ;\n\n    bool   allocatePdf2d      (int nx,int ny) ;\n    int    sample2d           (double r1,double r2,double * x,double * y) ;\n\n  protected:\n\n  private:\n\n};\n\nclass Q_GSL_EXPORT Chebyshev\n{\n  public:\n\n    gsl_cheb_series * chebyshev ;\n    gsl_function    * function  ;\n\n    explicit Chebyshev    (void) ;\n    explicit Chebyshev    (int n) ;\n             Chebyshev    (const Chebyshev & cheb) ;\n    virtual ~Chebyshev    (void) ;\n\n    bool     Allocate     (int n) ;\n    int      Initialize   (const double   a         ,\n                           const double   b         ,\n                           MathFunction   equation  ,\n                           void         * params  ) ;\n\n    size_t   Order        (void) ;\n    size_t   Size         (void) ;\n    double * Coefficients (void) ;\n    double   Eval         (double x) ;\n    double   EvalN        (size_t         order    ,\n                           double         x      ) ;\n    int      EvalAbsErr   (const double   x        ,\n                           double       * result   ,\n                           double       * abserr ) ;\n    int      EvalNAbserr  (const size_t   order    ,\n                           const double   x        ,\n                           double       * result   ,\n                           double       * abserr ) ;\n\n    int      Derivative   (Chebyshev & cheb) ;\n    int      Integral     (Chebyshev & cheb) ;\n\n  protected:\n\n  private:\n\n};\n\n/*****************************************************************************\n *                                                                           *\n *                        Permutation and Combination                        *\n *                                                                           *\n *****************************************************************************/\n\nclass Q_GSL_EXPORT Permutation : public QByteArray\n{\n  public:\n\n    explicit Permutation          (void) ;\n    explicit Permutation          (int size) ;\n    explicit Permutation          (QString m) ;\n             Permutation          (const Permutation & permutation) ;\n    virtual ~Permutation          (void) ;\n\n    int           isValid         (void) ; // gsl_permutation_valid\n    int           toCUIDs         (CUIDs & Cuids) ;\n    QString       toString        (void) ;\n    int           toByteArray     (QByteArray & blob) ;\n    int           setElements     (int size) ;\n    int           elements        (void) const ;\n    size_t *      array           (void) const ;\n    Permutation & operator =      (const Permutation & permutation) ;\n    Permutation & assign          (const Permutation & permutation) ;\n    Permutation & toIdentity      (void) ; // gsl_permutation_init\n    Permutation & Reverse         (void) ; // gsl_permutation_reverse\n    void          swap            (int a,int b) ; // gsl_permutation_swap\n    void          setValue        (int index,int   value) ;\n    void          setValue        (int index,char  value) ;\n    void          setValue        (int index,QChar value) ;\n    void          setValue        (QString m) ;\n    int           operator []     (int index) ; // gsl_permutation_get\n    int           next            (void) ; // gsl_permutation_next\n    int           previous        (void) ; // gsl_permutation_prev\n    int           inverse         (Permutation & inv) ; // gsl_permutation_inverse(inv,this)\n    int           toCanonical     (Permutation & canonical); //gsl_permutation_linear_to_canonical(canonical,this)\n    int           toLinear        (Permutation & linear); //gsl_permutation_canonical_to_linear(linear,this)\n    int           inversions      (void) ; // gsl_permutation_inversions\n    int           linearCycles    (void) ; // gsl_permutation_linear_cycles\n    int           canonicalCycles (void) ; // gsl_permutation_canonical_cycles\n    static int    permute         (const size_t * p,double * data,size_t stride,size_t n) ; // gsl_permute\n    static int    inverse         (const size_t * p,double * data,size_t stride,size_t n) ; // gsl_permute_inverse\n\n    // gsl_permute_vector\n    // gsl_permute_vector_inverse\n    // gsl_permutation_mul\n\n  protected:\n\n  private:\n\n};\n\nclass Q_GSL_EXPORT Combination : public QByteArray\n{\n  public:\n\n    explicit Combination      (void) ;\n    explicit Combination      (int n,int k) ;\n             Combination      (const Combination & combination) ;\n    virtual ~Combination      (void) ;\n\n    int           isValid     (void) ; // gsl_combination_valid\n    int           toCUIDs     (CUIDs & Cuids) ;\n    int           toByteArray (QByteArray & blob) ;\n    int           setElements (int n,int k) ;\n    int           setChosen   (int k) ;\n    int           elements    (void) const ;\n    int           chosen      (void) const ;\n    size_t *      array       (void) const ;\n    Combination & operator =  (const Combination & combination) ;\n    Combination & assign      (const Combination & combination) ;\n    Combination & toFirst     (void) ; // gsl_combination_init_first\n    Combination & toLast      (void) ; // gsl_combination_init_last\n    void          setValue    (int index,int   value) ;\n    void          setValue    (int index,char  value) ;\n    void          setValue    (int index,QChar value) ;\n    int           operator [] (int index) ; // gsl_combination_get\n    int           next        (void) ; // gsl_combination_next\n    int           previous    (void) ; // gsl_combination_prev\n\n  protected:\n\n  private:\n\n};\n\nclass Q_GSL_EXPORT Multisets : public QByteArray\n{\n  public:\n\n    explicit Multisets      (void) ;\n    explicit Multisets      (int n,int k) ;\n             Multisets      (const Multisets & multisets) ;\n    virtual ~Multisets      (void) ;\n\n    int         isValid     (void) ; // gsl_combination_valid\n    int         toCUIDs     (CUIDs & Cuids) ;\n    int         toByteArray (QByteArray & blob) ;\n    int         setElements (int n,int k) ;\n    int         setChosen   (int k) ;\n    int         elements    (void) const ;\n    int         chosen      (void) const ;\n    size_t    * array       (void) const ;\n    Multisets & operator =  (const Multisets & multisets) ;\n    Multisets & assign      (const Multisets & multisets) ;\n    Multisets & toFirst     (void) ; // gsl_combination_init_first\n    Multisets & toLast      (void) ; // gsl_combination_init_last\n    void        setValue    (int index,int   value) ;\n    void        setValue    (int index,char  value) ;\n    void        setValue    (int index,QChar value) ;\n    int         operator [] (int index) ; // gsl_combination_get\n    int         next        (void) ; // gsl_combination_next\n    int         previous    (void) ; // gsl_combination_prev\n\n  protected:\n\n  private:\n\n};\n\n/*****************************************************************************\n *                                                                           *\n *                               Linear algebra                              *\n *                                                                           *\n *****************************************************************************/\n\nclass Q_GSL_EXPORT MultiFit\n{\n  public:\n\n    gsl_multifit_linear_workspace * work ;\n\n    explicit MultiFit      (void) ;\n    explicit MultiFit      (int n,int p) ;\n             MultiFit      (const MultiFit & fit) ;\n    virtual ~MultiFit      (void) ;\n\n    bool Allocate          (int n,int p) ;\n\n    int Linear             (const gsl_matrix * X       ,\n                            const gsl_vector * y       ,\n                                  gsl_vector * c       ,\n                                  gsl_matrix * cov     ,\n                            double           * chisq ) ;\n    int WeightedLinear     (const gsl_matrix * X       ,\n                            const gsl_vector * w       ,\n                            const gsl_vector * y       ,\n                                  gsl_vector * c       ,\n                                  gsl_matrix * cov     ,\n                            double           * chisq ) ;\n    int svdLinear          (const gsl_matrix * X     ) ;\n    int svdWeightedLinear  (const gsl_matrix * X       ,\n                            const gsl_vector * w       ,\n                            const gsl_vector * y       ,\n                            double             tol     ,\n                            size_t           * rank    ,\n                                  gsl_vector * c       ,\n                                  gsl_matrix * cov     ,\n                            double           * chisq ) ;\n    int usvdWeightedLinear (const gsl_matrix * X       ,\n                            const gsl_vector * w       ,\n                            const gsl_vector * y       ,\n                            double             tol     ,\n                            size_t           * rank    ,\n                                  gsl_vector * c       ,\n                                  gsl_matrix * cov     ,\n                            double           * chisq ) ;\n\n    int Linearest          (const gsl_vector * x       ,\n                            const gsl_vector * c       ,\n                            const gsl_matrix * cov     ,\n                            double           * y       ,\n                            double           * y_err ) ;\n    int Residuals          (const gsl_matrix * X       ,\n                            const gsl_vector * y       ,\n                            const gsl_vector * c       ,\n                                  gsl_vector * r     ) ;\n\n  protected:\n\n  private:\n\n};\n\nclass Q_GSL_EXPORT BSplines\n{\n  public:\n\n    gsl_bspline_workspace * work ;\n\n    explicit BSplines            (void) ;\n    explicit BSplines            (int k,int nbreak) ;\n             BSplines            (const BSplines & bsplines) ;\n    virtual ~BSplines            (void) ;\n\n    bool   Allocate              (int k,int nbreak) ;\n\n    int    Knots                 (const gsl_vector * breakpts) ;\n    int    uniformKnots          (const double a,const double b) ;\n    int    Eval                  (const double x,gsl_vector * B) ;\n    int    EvalNonZero           (const double   x       ,\n                                  gsl_vector   * Bk      ,\n                                  size_t       * istart  ,\n                                  size_t       * iend  ) ;\n    int    Coefficients          (void) ;\n    double GrevilleAbscissa      (int i) ;\n\n    int    DerivativeEval        (const double   x       ,\n                                  const int      nderiv  ,\n                                  gsl_matrix   * dB    ) ;\n    int    DerivativeEvalNonZero (const double   x       ,\n                                  const int      nderiv  ,\n                                  gsl_matrix   * dB      ,\n                                  size_t       * istart  ,\n                                  size_t       * iend  ) ;\n\n  protected:\n\n  private:\n\n};\n\nclass Q_GSL_EXPORT Interpolation\n{\n  public:\n\n    gsl_interp       * work   ;\n    gsl_interp_accel * accel  ;\n    gsl_spline       * spline ;\n\n    explicit Interpolation              (void) ;\n    explicit Interpolation              (const gsl_interp_type * T,int size) ;\n             Interpolation              (const Interpolation & interpolation) ;\n    virtual ~Interpolation              (void) ;\n\n    bool         Allocate               (const gsl_interp_type * T,int size) ;\n    bool         AllocateAccel          (void) ;\n    bool         AllocateSpline         (const gsl_interp_type * T,int size) ;\n\n    int          Initialize             (const double xa[]   ,\n                                         const double ya[]   ,\n                                         int          size ) ;\n    int          InitializeSpline       (const double xa[]   ,\n                                         const double ya[]   ,\n                                         int          size ) ;\n\n    QString      Name                   (void) ;\n    QString      SplineName             (void) ;\n    unsigned int MinSize                (void) ;\n    unsigned int MinSize                (const gsl_interp_type * T) ;\n    unsigned int SplineMinSize          (void) ;\n\n    int          BSearch                (const double x_array[]  ,\n                                               double x          ,\n                                               int    index_lo   ,\n                                               int    index_hi ) ;\n    int          Find                   (const double x_array[]  ,\n                                               int    size       ,\n                                               double x        ) ;\n    int          Reset                  (void) ;\n\n    double       Eval                   (const double   xa[]  ,\n                                         const double   ya[]  ,\n                                               double   x   ) ;\n    int          EvalE                  (const double   xa[]  ,\n                                         const double   ya[]  ,\n                                               double   x     ,\n                                               double * y   ) ;\n    double       EvalDerivative         (const double xa[]    ,\n                                         const double ya[]    ,\n                                               double x     ) ;\n    double       EvalDerivative2        (const double xa[]    ,\n                                         const double ya[]    ,\n                                               double x     ) ;\n    double       EvalIntegral           (const double xa[]    ,\n                                         const double ya[]    ,\n                                               double a       ,\n                                               double b     ) ;\n    double       SplineEval             (double x) ;\n    double       SplineEvalDerivative   (double x) ;\n    double       SplineEvalDerivative2  (double x) ;\n    double       SplineEvalIntegral     (double a,double b) ;\n    int          EvalDerivativeE        (const double   xa[] ,\n                                         const double   ya[] ,\n                                               double   x    ,\n                                               double * d  ) ;\n    int          EvalDerivative2E       (const double   xa[] ,\n                                         const double   ya[] ,\n                                               double   x    ,\n                                               double * d2 ) ;\n    int          EvalIntegralE          (const double   xa[]     ,\n                                         const double   ya[]     ,\n                                               double   a        ,\n                                               double   b        ,\n                                               double * result ) ;\n    int          SplineEvalE            (double x,double * y) ;\n    int          SplineEvalDerivativeE  (double x,double * d) ;\n    int          SplineEvalDerivative2E (double x,double * d2) ;\n    int          SplineEvalIntegralE    (double a,double b,double * result) ;\n\n  protected:\n\n  private:\n\n};\n\nclass Q_GSL_EXPORT Vector : public QByteArray\n{\n  public:\n\n    explicit Vector              (void) ;\n    explicit Vector              (Cpp::ValueTypes type,int items) ;\n             Vector              (const Vector & vector) ;\n    virtual ~Vector              (void) ;\n\n    Cpp::ValueTypes Type         (void);\n    int             BytesPerCell (void) ;\n\n    Vector & operator =          (const Vector & vector) ;\n\n    bool     subVector           (Vector & vector,int offset,int items) ; // get sub-vector\n    bool     setVector           (int offset,Vector & vector) ;\n\n    void     reset               (void);\n    void     set                 (Cpp::ValueTypes type,int items) ;\n\n    void *   array               (void);\n\n    int      count               (void) ;\n    void     setZero             (void) ;\n    void     setAll              (double x) ;\n    void     setBasis            (int index) ;\n    bool     swap                (int i,int j) ;\n    bool     reverse             (void) ;\n    int      take                (int pos,int items) ;\n    int      append              (int items,const char * source) ;\n    int      append              (int items,int gap,const char * source) ;\n    int      insert              (int pos,int items,const char * source) ;\n    int      insert              (int pos,int items,int gap,const char * source) ;\n\n    Vector & operator +=         (Vector & vector) ;\n    Vector & operator -=         (Vector & vector) ;\n    Vector & operator *=         (Vector & vector) ;\n    Vector & operator /=         (Vector & vector) ;\n\n    Vector & operator +=         (double x) ;\n    Vector & operator -=         (double x) ;\n    Vector & operator *=         (double x) ;\n\n    QString  toCpp               (void) ;\n    QString  toCpp               (QString variableName) ;\n\n    // P(x) = c[0] + c[1] x + c[2] x^2 + ... + c[len-1] x^{len-1}\n    double   polynomial          (double x) ;\n    bool     polynomial          (vcomplex & x,vcomplex & result) ;\n    int      derivatives         (double x,int length,double * results) ;\n\n  protected:\n\n  private:\n\n};\n\nclass Q_GSL_EXPORT Matrix : public QByteArray\n{\n  public:\n\n    explicit Matrix        (void);\n    explicit Matrix        (Cpp::ValueTypes type,int rows,int columns) ;\n             Matrix        (const Matrix & matrix) ;\n    virtual ~Matrix        (void);\n\n    Cpp::ValueTypes Type   (void);\n\n    Matrix & operator  =   (const Matrix & matrix) ;\n\n    Matrix & operator +=   (const Matrix & matrix) ;\n    Matrix & operator +=   (int value) ;\n    Matrix & operator +=   (double value) ;\n    Matrix & operator -=   (const Matrix & matrix) ;\n    Matrix & operator -=   (int value) ;\n    Matrix & operator -=   (double value) ;\n    Matrix & operator *=   (int value) ;\n    Matrix & operator *=   (double value) ;\n    Matrix & operator /=   (int value) ;\n    Matrix & operator /=   (double value) ;\n\n    void   reset           (void);\n    void   assign          (const Matrix & matrix) ;\n    void   set             (Cpp::ValueTypes type,int rows,int columns);\n    void   zerofill        (void);\n\n    int    Rows            (void);\n    int    Columns         (void);\n    int    at              (int row,int column) ;\n\n    void * array           (void);\n\n    bool   swapRows        (int i,int j) ;\n    bool   swapColumns     (int i,int j) ;\n\n    bool   transpose       (void) ;\n    bool   transpose       (const Matrix & T) ;\n    bool   inverse         (Matrix & T) ;\n\n    static double sum      (double * v,int items) ;\n    static void   dispatch (int shift,int column,int items,double * R,double * S) ;\n    static double multiple (int length,double * a,double * b) ;\n    static double multiple (int length,double * R,double * a,double * b) ;\n\n    QString toCpp          (void) ;\n    QString toCpp          (QString variableName) ;\n\n    void    vertical       (double * R,double * V) ;\n\n  protected:\n\n  private:\n\n};\n\n/*****************************************************************************\n *                                                                           *\n *               Fourier, Wavelet, and other series transformation           *\n *                                                                           *\n *****************************************************************************/\n\nclass Q_GSL_EXPORT LevinWithError\n{\n  public:\n\n    gsl_sum_levin_u_workspace * work ;\n\n    explicit LevinWithError (void) ;\n    explicit LevinWithError (int n) ;\n             LevinWithError (const LevinWithError & levin) ;\n    virtual ~LevinWithError (void) ;\n\n    bool Allocate           (int n) ;\n    int  Acceleration       (const double * array       ,\n                             const size_t   n           ,\n                             double       * sum_accel   ,\n                             double       * abserr    ) ;\n    int  MinMax             (const double * array       ,\n                             const size_t   n           ,\n                             const size_t   min_terms   ,\n                             const size_t   max_terms   ,\n                             double       * sum_accel   ,\n                             double       * abserr    ) ;\n    int  Step               (const double   term        ,\n                             const size_t   n           ,\n                             const size_t   nmax        ,\n                             double       * sum_accel ) ;\n\n  protected:\n\n  private:\n\n};\n\nclass Q_GSL_EXPORT Levin\n{\n  public:\n\n    gsl_sum_levin_utrunc_workspace * work ;\n\n    explicit Levin    (void) ;\n    explicit Levin    (int n) ;\n             Levin    (const Levin & levin) ;\n    virtual ~Levin    (void) ;\n\n    bool Allocate     (int n) ;\n    int  Acceleration (const double * array          ,\n                       const size_t   n              ,\n                       double       * sum_accel      ,\n                       double       * abserr_trunc ) ;\n    int  MinMax       (const double * array          ,\n                       const size_t   n              ,\n                       const size_t   min_terms      ,\n                       const size_t   max_terms      ,\n                       double       * sum_accel      ,\n                       double       * abserr_trunc ) ;\n    int  Step         (const double   term           ,\n                       const size_t   n              ,\n                       double       * sum_accel    ) ;\n\n  protected:\n\n  private:\n\n};\n\n}\n\nQ_DECLARE_METATYPE(vcomplex)\nQ_DECLARE_METATYPE(vcomplexes)\nQ_DECLARE_METATYPE(N::Random)\nQ_DECLARE_METATYPE(N::Histogram)\nQ_DECLARE_METATYPE(N::Chebyshev)\nQ_DECLARE_METATYPE(N::Permutation)\nQ_DECLARE_METATYPE(N::Combination)\nQ_DECLARE_METATYPE(N::Multisets)\nQ_DECLARE_METATYPE(N::MultiFit)\nQ_DECLARE_METATYPE(N::BSplines)\nQ_DECLARE_METATYPE(N::Interpolation)\nQ_DECLARE_METATYPE(N::Vector)\nQ_DECLARE_METATYPE(N::Matrix)\nQ_DECLARE_METATYPE(N::LevinWithError)\nQ_DECLARE_METATYPE(N::Levin)\n\nQT_END_NAMESPACE\n\n#endif\n", "meta": {"hexsha": "adc5ceeb3167f1bff5eaca3db0de1acea5863d47", "size": 61220, "ext": "h", "lang": "C", "max_stars_repo_path": "include/QtGSL/qtgsl.h", "max_stars_repo_name": "Vladimir-Lin/QtGSL", "max_stars_repo_head_hexsha": "e5c9ebb3344edf6197c94cae7f3613e33e9125b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/QtGSL/qtgsl.h", "max_issues_repo_name": "Vladimir-Lin/QtGSL", "max_issues_repo_head_hexsha": "e5c9ebb3344edf6197c94cae7f3613e33e9125b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/QtGSL/qtgsl.h", "max_forks_repo_name": "Vladimir-Lin/QtGSL", "max_forks_repo_head_hexsha": "e5c9ebb3344edf6197c94cae7f3613e33e9125b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.7060810811, "max_line_length": 270, "alphanum_fraction": 0.4870793858, "num_tokens": 13259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.39389631511764434}}
{"text": "#ifndef SPARSE_AUC_AUC_OPT_METHODS_H\n#define SPARSE_AUC_AUC_OPT_METHODS_H\n\n#include <time.h>\n#include <stdbool.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n#include <limits.h>\n// These are the third part library needed.\n#include <cblas.h>\n#include \"fast_pcst.h\"\n#include \"loss.h\"\n\n#define PI 3.14159265358979323846\n#define sign(x) (x > 0) - (x < 0)\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n#define swap(a, b) { register double temp=(a);(a)=(b);(b)=temp; }\n#define is_posi(x) ( x > 0.0 ? 1.0 : 0.0)\n#define is_nega(x) ( x < 0.0 ? 1.0 : 0.0)\n\ntypedef struct {\n    double *wt;\n    double *wt_prev;\n    double *aucs;\n    double *rts;\n    int auc_len; // how many auc evaluated.\n    int total_iterations; // total iterations\n    int total_epochs; // total epochs executed.\n} AlgoResults;\n\n\ntypedef struct {\n    int num_passes;\n    int verbose;\n    int step_len;\n    int record_aucs;\n    double stop_eps;\n} GlobalParas;\n\nAlgoResults *make_algo_results(int data_p, int total_num_eval);\n\nbool free_algo_results(AlgoResults *re);\n\n\ntypedef struct {\n    Array *re_nodes;\n    Array *re_edges;\n    double *prizes;\n    double *costs;\n    int num_pcst;\n    double run_time;\n    int num_iter;\n} GraphStat;\n\ntypedef struct {\n    const double *x_tr_vals;\n    const int *x_tr_inds;\n    const int *x_tr_poss;\n    const int *x_tr_lens;\n    const double *y_tr;\n    bool is_sparse;\n    int n;\n    int p;\n    // this is only for the graph operator.\n    bool is_graph;\n    int m; // number of edges.\n    EdgePair *edges;\n    double *weights;\n    int g;\n    double *proj_prizes;\n    GraphStat *graph_stat;\n} Data;\n\nGraphStat *make_graph_stat(int p, int m);\n\nbool free_graph_stat(GraphStat *graph_stat);\n\ntypedef struct {\n    double val;\n    int index;\n} data_pair;\n\nbool head_tail_binsearch(\n        const EdgePair *edges, const double *costs, const double *prizes,\n        int n, int m, int target_num_clusters, int root, int sparsity_low,\n        int sparsity_high, int max_num_iter, PruningMethod pruning,\n        int verbose, GraphStat *stat);\n\n/**\n * SOLAM: Stochastic Online AUC Maximization\n * ---\n * BibTEX:\n * @inproceedings{ying2016stochastic,\n * title={Stochastic online AUC maximization},\n * author={Ying, Yiming and Wen, Longyin and Lyu, Siwei},\n * booktitle={Advances in neural information processing systems},\n * pages={451--459},\n * year={2016}\n * }\n * @param data\n * @param paras\n * @param re\n * @param para_xi\n * @param para_r\n * @author --- (Email: ---)\n * @return\n */\nbool _algo_solam(Data *data,\n                 GlobalParas *paras,\n                 AlgoResults *re,\n                 double para_xi,\n                 double para_r);\n\n/**\n * This function implements the algorithm proposed in the following paper.\n * Stochastic Proximal Algorithms for AUC Maximization.\n * ---\n * @inproceedings{natole2018stochastic,\n * title={Stochastic proximal algorithms for AUC maximization},\n * author={Natole, Michael and Ying, Yiming and Lyu, Siwei},\n * booktitle={International Conference on Machine Learning},\n * pages={3707--3716},\n * year={2018}}\n * ---\n * Do not use the function directly. Instead, call it by Python Wrapper.\n * @param data\n * @param paras\n * @param re\n * @param para_xi\n * @param para_l1_reg\n * @param para_l2_reg\n * @author --- (Email: ---)\n */\nvoid _algo_spam(Data *data,\n                GlobalParas *paras,\n                AlgoResults *re,\n                double para_xi,\n                double para_l1_reg,\n                double para_l2_reg);\n\n/**\n * Stochastic Hard Thresholding for AUC maximization.\n * @param data\n * @param paras\n * @param re\n * @param para_s\n * @param para_b\n * @param para_c\n * @param para_l2_reg\n */\nvoid _algo_sht_auc(Data *data,\n                   GlobalParas *paras,\n                   AlgoResults *re,\n                   int version,\n                   int operator_id,\n                   int para_s,\n                   int para_b,\n                   double para_c,\n                   double para_l2_reg);\n\nvoid _algo_sto_iht(Data *data,\n                   GlobalParas *paras,\n                   AlgoResults *re,\n                   int para_s,\n                   int para_b,\n                   double para_xi,\n                   double para_l2_reg);\n\n/**\n *\n * @param data\n * @param paras\n * @param re\n * @param para_s\n * @param para_tau\n * @param para_zeta\n * @param para_step_init\n * @param para_l2\n */\nvoid _algo_hsg_ht(Data *data,\n                  GlobalParas *paras,\n                  AlgoResults *re,\n                  int para_s,\n                  double para_tau,\n                  double para_zeta,\n                  double para_step_init,\n                  double para_l2);\n\nint _hard_thresholding(double *arr, int n, int k);\n\n/**\n *\n * @param data\n * @param paras\n * @param re\n * @param para_tau\n * @param para_eta\n * @param para_lambda\n */\nvoid _algo_opauc(Data *data,\n                 GlobalParas *paras,\n                 AlgoResults *re,\n                 int para_tau,\n                 double para_eta,\n                 double para_lambda);\n\n/**\n * This function implements the algorithm, FSAUC, proposed in the following paper:\n * ---\n * @inproceedings{liu2018fast,\n * title={Fast stochastic AUC maximization with O (1/n)-convergence rate},\n * author={Liu, Mingrui and Zhang, Xiaoxuan and Chen, Zaiyi and Wang, Xiaoyu and Yang, Tianbao},\n * booktitle={International Conference on Machine Learning},\n * pages={3195--3203},\n * year={2018}}\n * ---\n * @param data\n * @param paras\n * @param re\n * @param para_r\n * @param para_g\n */\nvoid _algo_fsauc(Data *data,\n                 GlobalParas *paras,\n                 AlgoResults *re,\n                 double para_r,\n                 double para_g);\n\n#endif //SPARSE_AUC_AUC_OPT_METHODS_H\n", "meta": {"hexsha": "c83abbe86a98df2c07cdee776e98f096812af650", "size": 5747, "ext": "h", "lang": "C", "max_stars_repo_path": "algo_wrapper/auc_opt_methods.h", "max_stars_repo_name": "baojianzhou/sparse-auc", "max_stars_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-13T13:45:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T13:45:14.000Z", "max_issues_repo_path": "algo_wrapper/auc_opt_methods.h", "max_issues_repo_name": "baojianzhou/sparse-auc", "max_issues_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0", "max_issues_repo_licenses": ["MIT"], "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_wrapper/auc_opt_methods.h", "max_forks_repo_name": "baojianzhou/sparse-auc", "max_forks_repo_head_hexsha": "2f338cdd9188dc6464c2efb3770d55fd964d1bd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-08T11:52:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T11:52:16.000Z", "avg_line_length": 24.7715517241, "max_line_length": 96, "alphanum_fraction": 0.6069253524, "num_tokens": 1532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.393667433819755}}
{"text": "/* multifit/lmniel.c\n * \n * Copyright (C) 2014 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_multifit_nlin.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_blas.h>\n\n#define SCALE 0\n\n/*\n * This module contains an implementation of the Levenberg-Marquardt\n * algorithm for nonlinear optimization problems. This implementation\n * closely follows the following works:\n *\n * [1] H. B. Nielsen, K. Madsen, Introduction to Optimization and\n *     Data Fitting, Informatics and Mathematical Modeling,\n *     Technical University of Denmark (DTU), 2010.\n */\n\ntypedef struct\n{\n  gsl_matrix *A;             /* J^T J */\n  gsl_matrix *A_copy;        /* copy of J^T J */\n  gsl_matrix *J;             /* Jacobian J(x) */\n  gsl_vector *diag;          /* D = diag(J^T J) */\n  gsl_vector *rhs;           /* rhs vector = -g = -J^T f */\n  gsl_vector *x_trial;       /* trial parameter vector */\n  gsl_vector *f_trial;       /* trial function vector */\n  gsl_vector *work;          /* workspace length p */\n  long nu;                   /* nu */\n  double mu;                 /* LM damping parameter mu */\n  double tau;                /* initial scale factor for mu */\n} lmniel_state_t;\n\n#include \"lmmisc.c\"\n\n#define LM_ONE_THIRD         (0.333333333333333)\n\nstatic int lmniel_alloc (void *vstate, const size_t n, const size_t p);\nstatic void lmniel_free(void *vstate);\nstatic int lmniel_set(void *vstate, const gsl_vector * swts,\n                      gsl_multifit_function_fdf *fdf,\n                      gsl_vector *x, gsl_vector *f, gsl_vector *dx);\nstatic int lmniel_iterate(void *vstate, const gsl_vector *swts,\n                          gsl_multifit_function_fdf *fdf,\n                          gsl_vector *x, gsl_vector *f, gsl_vector *dx);\n\nstatic int\nlmniel_alloc (void *vstate, const size_t n, const size_t p)\n{\n  lmniel_state_t *state = (lmniel_state_t *) vstate;\n\n  state->A = gsl_matrix_alloc(p, p);\n  if (state->A == NULL)\n    {\n      GSL_ERROR (\"failed to allocate space for A\", GSL_ENOMEM);\n    }\n\n  state->J = gsl_matrix_alloc(n, p);\n  if (state->J == NULL)\n    {\n      GSL_ERROR (\"failed to allocate space for J\", GSL_ENOMEM);\n    }\n\n  state->diag = gsl_vector_alloc(p);\n  if (state->diag == NULL)\n    {\n      GSL_ERROR (\"failed to allocate space for diag\", GSL_ENOMEM);\n    }\n\n  state->rhs = gsl_vector_alloc(p);\n  if (state->rhs == NULL)\n    {\n      GSL_ERROR (\"failed to allocate space for rhs\", GSL_ENOMEM);\n    }\n\n  state->work = gsl_vector_alloc(p);\n  if (state->work == NULL)\n    {\n      GSL_ERROR (\"failed to allocate space for work\", GSL_ENOMEM);\n    }\n\n  state->A_copy = gsl_matrix_alloc(p, p);\n  if (state->A_copy == NULL)\n    {\n      GSL_ERROR (\"failed to allocate space for A_copy\", GSL_ENOMEM);\n    }\n\n  state->x_trial = gsl_vector_alloc(p);\n  if (state->x_trial == NULL)\n    {\n      GSL_ERROR (\"failed to allocate space for x_trial\", GSL_ENOMEM);\n    }\n\n  state->f_trial = gsl_vector_alloc(n);\n  if (state->f_trial == NULL)\n    {\n      GSL_ERROR (\"failed to allocate space for f_trial\", GSL_ENOMEM);\n    }\n\n  state->tau = 1.0e-3;\n\n  return GSL_SUCCESS;\n} /* lmniel_alloc() */\n\nstatic void\nlmniel_free(void *vstate)\n{\n  lmniel_state_t *state = (lmniel_state_t *) vstate;\n\n  if (state->A)\n    gsl_matrix_free(state->A);\n\n  if (state->J)\n    gsl_matrix_free(state->J);\n\n  if (state->diag)\n    gsl_vector_free(state->diag);\n\n  if (state->rhs)\n    gsl_vector_free(state->rhs);\n\n  if (state->work)\n    gsl_vector_free(state->work);\n\n  if (state->A_copy)\n    gsl_matrix_free(state->A_copy);\n\n  if (state->x_trial)\n    gsl_vector_free(state->x_trial);\n\n  if (state->f_trial)\n    gsl_vector_free(state->f_trial);\n} /* lmniel_free() */\n\nstatic int\nlmniel_set(void *vstate, const gsl_vector *swts,\n           gsl_multifit_function_fdf *fdf, gsl_vector *x,\n           gsl_vector *f, gsl_vector *dx)\n{\n  int status;\n  lmniel_state_t *state = (lmniel_state_t *) vstate;\n  const size_t p = x->size;\n  size_t i;\n\n  /* initialize counters for function and Jacobian evaluations */\n  fdf->nevalf = 0;\n  fdf->nevaldf = 0;\n\n  /* evaluate function and Jacobian at x and apply weight transform */\n  status = gsl_multifit_eval_wf(fdf, x, swts, f);\n  if (status)\n   return status;\n\n  if (fdf->df)\n    status = gsl_multifit_eval_wdf(fdf, x, swts, state->J);\n  else\n    status = gsl_multifit_fdfsolver_dif_df(x, swts, fdf, f, state->J);\n  if (status)\n    return status;\n\n  /* compute rhs = -J^T f */\n  gsl_blas_dgemv(CblasTrans, -1.0, state->J, f, 0.0, state->rhs);\n\n#if SCALE\n  gsl_vector_set_zero(state->diag);\n#else\n  gsl_vector_set_all(state->diag, 1.0);\n#endif\n\n  /* set default parameters */\n  state->nu = 2;\n\n#if SCALE\n  state->mu = state->tau;\n#else\n  /* compute mu_0 = tau * max(diag(J^T J)) */\n  state->mu = -1.0;\n  for (i = 0; i < p; ++i)\n    {\n      gsl_vector_view c = gsl_matrix_column(state->J, i);\n      double result; /* (J^T J)_{ii} */\n\n      gsl_blas_ddot(&c.vector, &c.vector, &result);\n      state->mu = GSL_MAX(state->mu, result);\n    }\n\n  state->mu *= state->tau;\n#endif\n\n  return GSL_SUCCESS;\n} /* lmniel_set() */\n\n/*\nlmniel_iterate()\n  This function performs 1 iteration of the LM algorithm 6.18\nfrom [1]. The algorithm is slightly modified to loop until we\nfind an acceptable step dx, in order to guarantee that each\nfunction call contains a new input vector x.\n\nArgs: vstate - lm workspace\n      swts   - data weights (NULL if unweighted)\n      fdf    - function and Jacobian pointers\n      x      - on input, current parameter vector\n               on output, new parameter vector x + dx\n      f      - on input, f(x)\n               on output, f(x + dx)\n      dx     - (output only) parameter step vector\n\nNotes:\n1) On input, the following must be initialized in state:\nnu, mu, rhs, J\n\n2) On output, the following are updated with the current iterates:\nnu, mu, rhs, J\n\nrhs needs to be set on each output, so that lmniel_gradient supplies\nthe correct g = J^T f\n*/\n\nstatic int\nlmniel_iterate(void *vstate, const gsl_vector *swts,\n               gsl_multifit_function_fdf *fdf, gsl_vector *x,\n               gsl_vector *f, gsl_vector *dx)\n{\n  int status;\n  lmniel_state_t *state = (lmniel_state_t *) vstate;\n  gsl_matrix *J = state->J;                   /* Jacobian J(x) */\n  gsl_matrix *A = state->A;                   /* J^T J */\n  gsl_vector *rhs = state->rhs;               /* -g = -J^T f */\n  gsl_vector *x_trial = state->x_trial;       /* trial x + dx */\n  gsl_vector *f_trial = state->f_trial;       /* trial f(x + dx) */\n  gsl_vector *diag = state->diag;             /* diag(D) */\n  double dF;                                  /* F(x) - F(x + dx) */\n  double dL;                                  /* L(0) - L(dx) */\n  int foundstep = 0;                          /* found step dx */\n\n  /* compute A = J^T J */\n  status = gsl_blas_dsyrk(CblasLower, CblasTrans, 1.0, J, 0.0, A);\n  if (status)\n    return status;\n\n  /* copy lower triangle to upper */\n  gsl_matrix_transpose_tricpy('L', 0, A, A);\n\n#if SCALE\n  lmniel_update_diag(J, diag);\n#endif\n\n  /* loop until we find an acceptable step dx */\n  while (!foundstep)\n    {\n      /* solve (A + mu*I) dx = g */\n      status = lmniel_calc_dx(state->mu, A, rhs, dx, state);\n      if (status)\n        return status;\n\n      /* compute x_trial = x + dx */\n      lmniel_trial_step(x, dx, x_trial);\n\n      /* compute f(x + dx) */\n      status = gsl_multifit_eval_wf(fdf, x_trial, swts, f_trial);\n      if (status)\n       return status;\n\n      /* compute dF = F(x) - F(x + dx) */\n      dF = lmniel_calc_dF(f, f_trial);\n\n      /* compute dL = L(0) - L(dx) = dx^T (mu*dx - g) */\n      dL = lmniel_calc_dL(state->mu, diag, dx, rhs);\n\n      /* check that rho = dF/dL > 0 */\n      if ((dL > 0.0) && (dF >= 0.0))\n        {\n          /* reduction in error, step acceptable */\n\n          double tmp;\n\n          /* update LM parameter mu */\n          tmp = 2.0 * (dF / dL) - 1.0;\n          tmp = 1.0 - tmp*tmp*tmp;\n          state->mu *= GSL_MAX(LM_ONE_THIRD, tmp);\n          state->nu = 2;\n\n          /* compute J <- J(x + dx) */\n          if (fdf->df)\n            status = gsl_multifit_eval_wdf(fdf, x_trial, swts, J);\n          else\n            status = gsl_multifit_fdfsolver_dif_df(x_trial, swts, fdf, f_trial, J);\n          if (status)\n            return status;\n\n          /* update x <- x + dx */\n          gsl_vector_memcpy(x, x_trial);\n\n          /* update f <- f(x + dx) */\n          gsl_vector_memcpy(f, f_trial);\n\n          /* compute new rhs = -J^T f */\n          gsl_blas_dgemv(CblasTrans, -1.0, J, f, 0.0, rhs);\n\n          foundstep = 1;\n        }\n      else\n        {\n          long nu2;\n\n          /* step did not reduce error, reject step */\n          state->mu *= (double) state->nu;\n          nu2 = state->nu << 1; /* 2*nu */\n          if (nu2 <= state->nu)\n            {\n              gsl_vector_view d = gsl_matrix_diagonal(A);\n\n              /*\n               * nu has wrapped around / overflown, reset mu and nu\n               * to original values and break to force another iteration\n               */\n              /*GSL_ERROR(\"nu parameter has overflown\", GSL_EOVRFLW);*/\n              state->nu = 2;\n              state->mu = state->tau * gsl_vector_max(&d.vector);\n              break;\n            }\n          state->nu = nu2;\n        }\n    } /* while (!foundstep) */\n\n  return GSL_SUCCESS;\n} /* lmniel_iterate() */\n\nstatic int\nlmniel_gradient(void *vstate, gsl_vector * g)\n{\n  lmniel_state_t *state = (lmniel_state_t *) vstate;\n  gsl_vector_memcpy(g, state->rhs);\n  gsl_vector_scale(g, -1.0);\n  return GSL_SUCCESS;\n}\n\nstatic int\nlmniel_jac(void *vstate, gsl_matrix * J)\n{\n  lmniel_state_t *state = (lmniel_state_t *) vstate;\n  int s = gsl_matrix_memcpy(J, state->J);\n\n  return s;\n}\n\nstatic const gsl_multifit_fdfsolver_type lmniel_type =\n{\n  \"lmniel\",\n  sizeof(lmniel_state_t),\n  &lmniel_alloc,\n  &lmniel_set,\n  &lmniel_iterate,\n  &lmniel_gradient,\n  &lmniel_jac,\n  &lmniel_free\n};\n\nconst gsl_multifit_fdfsolver_type *gsl_multifit_fdfsolver_lmniel = &lmniel_type;\n", "meta": {"hexsha": "1c3f7891f745e68609cdb2e109a4663fad04ba41", "size": 10781, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/multifit/lmniel.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/lmniel.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "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/BaselineMethods/MNE/C++/gsl-2.4/multifit/lmniel.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.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.1488250653, "max_line_length": 83, "alphanum_fraction": 0.6025415082, "num_tokens": 3099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3935143909420168}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <dc1394/dc1394.h>\n#include <math.h>\n#include <fitsio.h>\n#include <gsl/gsl_statistics.h>\n#include <xpa.h>\n#include <sys/time.h>\n#include <string.h>\n#include <inttypes.h>\n\n#define NXPA 10\n\ntypedef struct _Box {\n    double  x;\n    double  y;\n    double  fwhm;\n    double  cenx;\n    double  ceny;\n    double  counts;\n    double  background;\n    double  noise;\n    double  sigmaxythresh;\n    double  sigmaxy;\n    double  sigmafwhmthresh;\n    double  sigmafwhm;\n    int     r;\n} Box;\n\ntypedef struct _Back {\n    double x;\n    double y;\n    double background;\n    double sigma;\n    int r;\n    int width;\n} Back;\n\nBox box[3];\nBack back;\nlong nelements, naxes[2], fpixel;\nint boxsize = 30;\ndouble pixel_scale = 1.22;\n\ndouble stardist(int i, int j) {\n    return( sqrt( (box[i].cenx-box[j].cenx)*(box[i].cenx-box[j].cenx) +\n\t\t  (box[i].ceny-box[j].ceny)*(box[i].ceny-box[j].ceny) ) );\n}\n\n/* this routine uses a. tokovinin's modified equation given in\n   2002, PASP, 114, 1156\n*/\ndouble seeing(double var, double d, double r) {\n    double lambda;\n    double b, K, seeing;\n\n    lambda = 0.65e-6;\n    b = r/d;\n    \n    /* pixel scale in \"/pixel, convert to rad */\n    var = var*pow(pixel_scale/206265.0,2);\n    \n    K = 0.364*(1.0 - 0.532*pow(b, -1/3) - 0.024*pow(b, -7/3));\n\n    seeing = 206265.0*0.98*pow(d/lambda, 0.2)*pow(var/K, 0.6);\n\n    return seeing;\n}\n\n/* this routine uses the classic DIMM equation */\ndouble old_seeing(double var, double d, double r) {\n    double lambda;\n    double r0;\n\n    lambda = 0.65e-6;\n\n    /* pixel scale in \"/pixel, convert to rad */\n    var = var*pow(pixel_scale/206265.0,2);\n    \n    r0 = pow(2.0*(lambda*lambda)*( \n\t\t ( 0.1790*pow(d, (-1.0/3.0)) - \n\t\t   0.0968*pow(r, (-1.0/3.0)) )/var \n\t\t ), 0.6);\n\n    return 206265.0*0.98*lambda/r0;\n}\n\n/* measure the background in an annulus around the spot pattern */\nint background(char *image, int imwidth, int imheight) {\n\n    int i, j, backpix;\n    int low_y, up_y, low_x, up_x;\n    double dist, sum, sumsq;\n    \n    backpix = 0;\n    sum = 0.0;\n    sumsq = 0.0;\n\n    low_y = back.y - back.r - back.width;\n    up_y  = back.y + back.r + back.width;\n    low_x = back.x - back.r - back.width;\n    up_x  = back.x + back.r + back.width;\n    if (low_y < 0) {\n\tlow_y = 0;\n    }\n    if (up_y >= imheight) {\n\tup_y = imheight;\n    }\n    if (low_x < 0) {\n\tlow_x = 0;\n    }\n    if (up_x >= imwidth) {\n\tup_x = imwidth;\n    }\n\n    for (i=low_y; i<up_y; i++) {\n\tfor (j=low_x; j<up_x; j++) {\n\t    dist = sqrt(pow(back.x-j, 2) + pow(back.y-i, 2));\n\t    if (dist >= back.r && dist <= back.r+back.width) {\n\t\tsum += image[i*naxes[0]+j];\n\t\tbackpix++;\n\t    }\n\t}\n    }\n\n    back.background = sum/backpix;\n    //back.background = 0.0;\n\n    for (i=low_y; i<up_y; i++) {\n\tfor (j=low_x; j<up_x; j++) {\n\t    dist = sqrt(pow(back.x-j, 2) + pow(back.y-i, 2));\n\t    if (dist >= back.r && dist <= back.r+back.width) {\n\t\tsumsq += (image[i*naxes[0]+j]-back.background)*\n\t\t    (image[i*naxes[0]+j]-back.background);\n\t    }\n\t}\n    }\n\n    back.sigma = sqrt(sumsq/backpix);\n    //back.sigma = 1.0;\n\n    return 1;\n\n}\n\n/* measure centroid using center-of-mass algorithm */\nint centroid(char *image, int imwidth, int imheight, int num) {\n\n    int i, j;\n    double  sum    = 0.0;\n    double  sumx   = 0.0;\n    double  sumxx  = 0.0;\n    double  sumy   = 0.0;\n    double  sumyy  = 0.0;\n    double  val = 0.0;\n    double  gain = 0.5;\n    double  rmom;\n    double  dist;\n    double nsigma = 5.0;\n    int low_y, up_y, low_x, up_x;\n    int sourcepix = 0;\n\n    low_y = box[num].y - box[num].r;\n    up_y  = box[num].y + box[num].r;\n    low_x = box[num].x - box[num].r;\n    up_x  = box[num].x + box[num].r;\n    if (low_y < 0) {\n\tlow_y = 0;\n    }\n    if (up_y >= imheight) {\n\tup_y = imheight;\n    }\n    if (low_x < 0) {\n\tlow_x = 0;\n    }\n    if (up_x >= imwidth) {\n\tup_x = imwidth;\n    }\n    \n    for (i=low_y; i<up_y; i++) {\n\tfor (j=low_x; j<up_x; j++) {\n\t    \n\t    dist = sqrt(pow(box[num].x-j, 2) + pow(box[num].y-i, 2));\n\t    if (dist <= box[num].r) {\n\t\tval = image[i*naxes[0]+j] - back.background;\n\t\tif (val >= nsigma*back.sigma) {\n\t\t    sum   += val;\n\t\t    sumx  += val*j;\n\t\t    sumxx += val*j*j;\n\t\t    sumy  += val*i;\n\t\t    sumyy += val*i*i;\n\t\t    sourcepix++;\n\t\t}\n\t    }\n\t    \n\t}\n    }\n\n    if ( sum <= 0.0 ) {\n\tbox[num].sigmaxy = -1.0;\n\tbox[num].sigmafwhm = -1.0;\n\t//box[num].x = imwidth/2.0;\n\t//box[num].y = imheight/2.0;\n\tbox[num].fwhm = -1.0;\n    } else {\n\trmom = ( sumxx - sumx * sumx / sum + sumyy - sumy * sumy / sum ) / sum;\n\t\n\tif ( rmom <= 0 ) {\n\t    box[num].fwhm = -1.0;\n\t} else {\n\t    box[num].fwhm = sqrt(rmom)  * 2.354 / sqrt(2.0);\n\t}\n\n\tbox[num].counts = sum;\n\tbox[num].cenx   = sumx / sum;\n\tbox[num].ceny   = sumy / sum;\n\tbox[num].x += gain*(box[num].cenx - box[num].x);\n\tbox[num].y += gain*(box[num].ceny - box[num].y);\n\tbox[num].sigmaxy= box[num].noise * sourcepix / box[num].counts / sqrt(6.0);\n\tbox[num].sigmafwhm = box[num].noise * pow(sourcepix,1.5) / 10.\n\t    / box[num].fwhm / box[num].counts\n\t    * 2.354 * 2.354 / 2.0;\n    }  \n\n    return 1;\n\n}\n\nint grab_frame(dc1394camera_t *cam, char *buf, int nbytes) {\n    dc1394video_frame_t *frame=NULL;\n    dc1394error_t err;\n\n    err = dc1394_capture_dequeue(cam, DC1394_CAPTURE_POLICY_WAIT, &frame);\n    if (err != DC1394_SUCCESS) {\n\tdc1394_log_error(\"Unable to capture.\");\n\tdc1394_capture_stop(cam);\n\tdc1394_camera_free(cam);\n\texit(1);\n    }\n\n    memcpy(buf, frame->image, nbytes);\n    dc1394_capture_enqueue(cam, frame);\n    return 1;\n}\n\nint add_gaussian(char *buffer, float cenx, float ceny, float a, float sigma) {\n    float gauss, rsq;\n    int i, j, low_x, up_x, low_y, up_y, size;\n\n    size = 30;\n    low_x = (int)(cenx-size);\n    up_x = (int)(cenx+size);\n    low_y = (int)(ceny-size);\n    up_y = (int)(ceny+size);\n\n    for (i=low_y; i<up_y; i++) {\n\tfor (j=low_x; j<up_x; j++) {\n\t    rsq = (cenx - j)*(cenx - j) + (ceny - i)*(ceny - i);\n\t    gauss = a*expf(-1.0*rsq/(sigma*sigma));\n\t    if (gauss > 255) \n\t\tgauss = 255;\n\t    buffer[i*naxes[0]+j] += (char)gauss;\n\t}\n    }\n\n    return 1;\n}\n\nint main() {\n    \n    dc1394camera_t *camera;\n    char *buffer, *buffer2, *average;\n    fitsfile *fptr;\n    int i, j, f, status, nimages, anynul, nboxes, test;\n    char fitsfile[256], xpastr[256];\n    char *froot, *timestr;\n    FILE *init, *out;\n    float xx = 0.0, yy = 0.0, xsum = 0.0, ysum = 0.0;\n    double dist[2000], sig[2000], dist_l[2000], sig_l[2000];\n    double mean, var, var_l, avesig;\n    double seeing_short, seeing_long, seeing_ave;\n    struct timeval start_time, end_time;\n    time_t start_sec, end_sec;\n    suseconds_t start_usec, end_usec;\n    float elapsed_time, fps;\n\n    dc1394_t * dc;\n    dc1394camera_list_t * list;\n    dc1394error_t err;\n    \n    unsigned int min_bytes, max_bytes, max_height, max_width;\n    unsigned int actual_bytes, winleft, wintop;\n    uint64_t total_bytes = 0;\n    char *names[NXPA];\n    char *messages[NXPA];\n\n    double d = 0.060;\n    double r = 0.130;\n\n    XPA xpa;\n    xpa = XPAOpen(NULL);\n\n    stderr = freopen(\"measure_seeing.log\", \"w\", stderr);\n\n    status = 0;\n    anynul = 0;\n    naxes[0] = 320;\n    naxes[1] = 240;\n    fpixel = 1;\n  \n    nelements = naxes[0]*naxes[1];\n    \n    dc = dc1394_new();\n    if (!dc)\n\treturn 1;\n    err = dc1394_camera_enumerate(dc, &list);\n    DC1394_ERR_RTN(err, \"Failed to enumerate cameras.\");\n\n    if (list->num == 0) {\n\tdc1394_log_error(\"No cameras found.\");\n\treturn 1;\n    }\n\n    camera = dc1394_camera_new(dc, list->ids[0].guid);\n    if (!camera) {\n\tdc1394_log_error(\"Failed to initialize camera with guid %\"PRIx64\".\", \n\t\t\t list->ids[0].guid);\n\treturn 1;\n    }\n    dc1394_camera_free_list(list);\n\n    printf(\"Using camera with GUID %\"PRIx64\"\\n\", camera->guid);\n\n    // need to use legacy firewire400 mode for now.  800 not quite reliable.\n    dc1394_video_set_iso_speed(camera, DC1394_ISO_SPEED_400);\n\n    // configure camera for format7\n    err = dc1394_video_set_mode(camera, DC1394_VIDEO_MODE_FORMAT7_1);\n    DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Can't choose format7_0\");\n    printf(\"I: video mode is format7_0\\n\");\n\n    err = dc1394_format7_get_max_image_size(camera, DC1394_VIDEO_MODE_FORMAT7_1, \n\t\t\t\t\t    &max_width, &max_height);\n    DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),\"cannot get max image size for format7_0\");\n    printf (\"I: max image size is: height = %d, width = %d\\n\", max_height, max_width);\n    printf (\"I: current image size is: height = %ld, width = %ld\\n\", naxes[1], naxes[0]);\n\n    //winleft = (max_width - naxes[0])/2;\n    //wintop = (max_height - naxes[1])/2;\n    winleft = 0;\n    wintop = 0;\n\n    err = dc1394_format7_set_roi(camera,\n\t\t\t\t DC1394_VIDEO_MODE_FORMAT7_1,\n\t\t\t\t DC1394_COLOR_CODING_MONO8,\n\t\t\t\t DC1394_USE_MAX_AVAIL,\n\t\t\t\t winleft, wintop, // left, top\n\t\t\t\t naxes[0], naxes[1]);\n    DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Can't set ROI.\");\n    printf(\"I: ROI is (%d, %d) - (%ld, %ld)\\n\", \n\t   winleft, wintop, winleft+naxes[0], wintop+naxes[1]);\n\n    err = dc1394_format7_get_total_bytes(camera, DC1394_VIDEO_MODE_FORMAT7_1, &total_bytes);\n    DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Can't get total bytes.\");\n    printf(\"I: total bytes per frame are %\"PRIu64\"\\n\", total_bytes);\n\n    err = dc1394_capture_setup(camera, 16, DC1394_CAPTURE_FLAGS_DEFAULT);\n    DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), \"Error capturing.\");\n\n    // start the camera up\n    err = dc1394_video_set_transmission(camera, DC1394_ON);\n    if (err != DC1394_SUCCESS) {\n\tdc1394_log_error(\"Unable to start camera iso transmission.\");\n\tdc1394_capture_stop(camera);\n\tdc1394_camera_free(camera);\n\texit(1);\n    }\n\n    out = fopen(\"seeing.dat\", \"a\");\n    init = fopen(\"init_cen_all\", \"r\");\n    i = 0;\n    while (fscanf(init, \"%f %f\\n\", &xx, &yy) != EOF) {\n\tbox[i].x = xx;\n\tbox[i].cenx = xx;\n\tbox[i].y = yy;\n\tbox[i].ceny = yy;\n\tbox[i].r = boxsize/2.0;\n\ti++;\n    }\n    nboxes = i;\n    fclose(init); \n\n    back.r = 80;\n    back.width = 10;\n\n    /* allocate the buffers */\n    if (!(buffer = malloc(nelements*sizeof(char)))) {\n\tprintf(\"Couldn't Allocate Image Buffer\\n\");\n\texit(-1);\n    }\n    if (!(buffer2 = malloc(nelements*sizeof(char)))) {\n\tprintf(\"Couldn't Allocate 2nd Image Buffer\\n\");\n\texit(-1);\n    }\n    if (!(average = malloc(nelements*sizeof(char)))) {\n\tprintf(\"Couldn't Allocate Average Image Buffer\\n\");\n\texit(-1);\n    }\n\n    nimages = 2000;\n    froot = \"seeing.fits\";\n\n    gettimeofday(&start_time, NULL);\n\n    for (f=0; f<nimages; f++) {\n\t/* first do a single exposure */\n\tgrab_frame(camera, buffer, nelements*sizeof(char));\n\t// add_gaussian(buffer, 175.0, 130.0, 50.0, 3.0);\n\t// add_gaussian(buffer, 155.0, 115.0, 50.0, 3.0);\n\n\t// find center of star images and calculate background\n\txsum = 0.0;\n\tysum = 0.0;\n\tfor (i=0; i<nboxes; i++) {\n\t    xsum += box[i].cenx;\n\t    ysum += box[i].ceny;\n\t}\n\tback.x = xsum/nboxes;\n\tback.y = ysum/nboxes;\n\tbackground(buffer, naxes[0], naxes[1]);\n\t\n\tfor (i=0; i<nboxes; i++) {\n\t    box[i].noise = back.sigma;\n\t    box[i].r = boxsize/2.0;\n\t    //centroid(buffer, i);\n\t    //box[i].r = boxsize/3.0;\n\t    //centroid(buffer, i);\n\t    //box[i].r = boxsize/4.0;\n\t    centroid(buffer, naxes[0], naxes[1], i);\n\t}\n\n\tdist[f] = stardist(0, 1);\n\tsig[f] = box[0].sigmaxy*box[0].sigmaxy + box[1].sigmaxy*box[1].sigmaxy;\n\n\t/* now average two exposures */\n\tgrab_frame(camera, buffer, nelements*sizeof(char));\n\tgrab_frame(camera, buffer2, nelements*sizeof(char));\n\n\tfor (j=0; j<nelements; j++) {\n\t    test = buffer[j]+buffer2[j];\n\t    if (test <= 254) {\n\t\taverage[j] = buffer[j]+buffer2[j];\n\t    } else {\n\t\taverage[j] = 254;\n\t    }\n\t}\n\t// add_gaussian(average, 175.0, 130.0, 50.0, 3.0);\n\t// add_gaussian(average, 155.0, 115.0, 50.0, 3.0);\n\n\txsum = 0.0;\n\tysum = 0.0;\n\tfor (i=0; i<nboxes; i++) {\n\t    xsum += box[i].cenx;\n\t    ysum += box[i].ceny;\n\t}\n\tback.x = xsum/nboxes;\n\tback.y = ysum/nboxes;\n\tbackground(average, naxes[0], naxes[1]);\n\n\tfor (i=0; i<nboxes; i++) {\n\t    box[i].noise = back.sigma;\n\t    box[i].r = boxsize/2.0;\n\t    //centroid(average, i);\n\t    //box[i].r = boxsize/3.0;\n\t    //centroid(average, i);\n\t    //box[i].r = boxsize/4.0;\n\t    centroid(average, naxes[0], naxes[1], i);\n\t}\n\n\tdist_l[f] = stardist(0, 1);\n\tsig_l[f] = box[0].sigmaxy*box[0].sigmaxy + box[1].sigmaxy*box[1].sigmaxy;\n\t\n\tif (f % 40 == 0) {\n\t    status = XPASet(xpa, \"ds9\", \"array [xdim=320,ydim=240,bitpix=8]\", \"ack=false\",\n\t\t\t    average, nelements, names, messages, NXPA);\n\t    sprintf(xpastr, \"image; box %f %f %d %d 0.0\", \n\t\t    box[0].x, box[0].y, boxsize, boxsize); \n\t    status = XPASet(xpa, \"ds9\", \"regions\", \"ack=false\", \n\t\t\t    xpastr, strlen(xpastr), names, messages, NXPA);\n\t    sprintf(xpastr, \"image; box %f %f %d %d 0.0\", \n\t\t    box[1].x, box[1].y, boxsize, boxsize); \n\t    status = XPASet(xpa, \"ds9\", \"regions\", \"ack=false\", \n\t\t\t    xpastr, strlen(xpastr), names, messages, NXPA);\n\t}\n\t\n    }\n\n    gettimeofday(&end_time, NULL);\n    printf(\"End capture.\\n\");\n\n    /*-----------------------------------------------------------------------\n     *  stop data transmission\n     *-----------------------------------------------------------------------*/\n    start_sec = start_time.tv_sec;\n    start_usec = start_time.tv_usec;\n    end_sec = end_time.tv_sec;\n    end_usec = end_time.tv_usec;\n\n    elapsed_time = (float)((end_sec + 1.0e-6*end_usec) - (start_sec + 1.0e-6*start_usec));\n    fps = 3*nimages/elapsed_time;\n    printf(\"Elapsed time = %g seconds.\\n\", elapsed_time);\n    printf(\"Framerate = %g fps.\\n\", fps);\n\n    err=dc1394_video_set_transmission(camera,DC1394_OFF);\n    DC1394_ERR_RTN(err,\"couldn't stop the camera?\");\n    \n    /*\n    sprintf(fitsfile, \"!%s\", froot);\n    fits_create_file(&fptr, fitsfile, &status);\n    fits_create_img(fptr, BYTE_IMG, 2, naxes, &status);\n    fits_write_img(fptr, TBYTE, fpixel, nelements, buffer, &status);\n    fits_close_file(fptr, &status);\n    fits_report_error(stderr, status);\n    */\n\n    /* analyze short exposure */\n    printf(\"\\t SHORT EXPOSURE\\n\");\n    mean = gsl_stats_mean(dist, 1, nimages);\n    avesig = gsl_stats_mean(sig, 1, nimages);\n    printf(\"mean = %f, avesig = %f\\n\", mean, avesig);\n    \n    printf(\"\\n\");\n\n    var = gsl_stats_variance_m(dist, 1, nimages, mean);\n    var = var - avesig;\n    seeing_short = seeing(var, d, r);\n    printf(\"sigma = %f, seeing = %f\\n\", sqrt(var), seeing_short);\n\n    /* analyze long exposure */\n    printf(\"\\t LONG EXPOSURE\\n\");\n    mean = gsl_stats_mean(dist_l, 1, nimages);\n    avesig = gsl_stats_mean(sig_l, 1, nimages);\n    printf(\"mean_l = %f, avesig_l = %f\\n\", mean, avesig);\n\n    printf(\"\\n\");\n\n    var_l = gsl_stats_variance_m(dist_l, 1, nimages, mean);\n    var_l = var_l - avesig;\n    seeing_long = seeing(var_l, d, r);\n    printf(\"sigma_l = %f, seeing_l = %f\\n\", sqrt(var_l), seeing_long);\n\n    seeing_ave = pow(seeing_short, 1.75)*pow(seeing_long,-0.75);\n    printf(\"Exposure corrected seeing = %4.2f\\\"\\n\\n\", seeing_ave);\n\n    timestr = ctime(&end_sec);\n    fprintf(out, \"%s %f %f %f %f %f\\n\", timestr, var, var_l, seeing_short, seeing_long, seeing_ave);\n\n    init = fopen(\"init_cen_all\", \"w\");\n    for (i=0; i<nboxes; i++) {\n\tfprintf(init, \"%f %f\\n\", box[i].cenx, box[i].ceny);\n    }\n    fclose(init);\n\n    fclose(out);\n\n    return (status);\n}\n", "meta": {"hexsha": "28638d9912e9714201c79a140ba0f31603bba87e", "size": 15181, "ext": "c", "lang": "C", "max_stars_repo_path": "src/measure_seeing_16bpp.c", "max_stars_repo_name": "marissakotze/timDIMM", "max_stars_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-06T15:26:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T15:26:36.000Z", "max_issues_repo_path": "src/measure_seeing_16bpp.c", "max_issues_repo_name": "marissakotze/timDIMM", "max_issues_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/measure_seeing_16bpp.c", "max_forks_repo_name": "marissakotze/timDIMM", "max_forks_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-07-29T15:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-01T13:02:36.000Z", "avg_line_length": 26.6801405975, "max_line_length": 100, "alphanum_fraction": 0.5892892431, "num_tokens": 5206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.39345141976290676}}
{"text": "///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/*\n Contains implementations of AdaDIF, TunedRwR, and PPR.\n \n\n Dimitris Berberidis \n University of Minnesota 2017-2018\n*/\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <cblas.h>\n#include <inttypes.h>\n#include <pthread.h>\n#include <sys/sysinfo.h>\n#include <stdbool.h>\n\n#include \"comp_engine.h\"\n#include \"csr_handling.h\"\n#include \"my_defs.h\"\n#include \"parameter_opt.h\"\n#include \"my_utils.h\"\n\n\nstatic sz_short get_threads_and_width(sz_short* , sz_short ); \nstatic double* get_coef_A(sz_long , sz_med , sz_med , sz_long* , double* ,double* , const sz_long* , double );\nstatic double* get_coef_b(sz_long , sz_med , sz_med ,sz_med , sz_long* , double* , sz_long* );\n\n\n//Multi-threaded AdaDIF method (output is soft labels)\nvoid AdaDIF_core_multi_thread( double* soft_labels, csr_graph graph, sz_med num_seeds, \n\t\t\t       const sz_long* seed_indices, sz_short num_class, sz_short* class_ind,\n\t\t\t       sz_med* num_per_class, sz_med walk_length, double lambda, bool no_constr, bool single_thread){\n\n\tsz_short NUM_THREADS, width;\n\n\tNUM_THREADS = get_threads_and_width(&width, num_class);\n\t\n\tif(single_thread) NUM_THREADS = 1;\n\t\n\tprintf(\"NUMBER OF THREADS: %\"PRIu16\" \\n\", (uint16_t) NUM_THREADS);\t\n\n\t#if DEBUG\n\tprintf(\"WIDTH= %\"PRIu16\"\\n\", (uint16_t) width);\n\t#endif\t\n\n\tclock_t begin = clock();\n\n\t//The following three blocks create copies of the CSR matrix \n\t//Each copy will be used by a thread \n\n\tcsr_graph* graph_copies = csr_mult_deep_copy( graph, NUM_THREADS );\t\n\n\tclock_t end = clock();\n\tdouble time_spent = (double)(end - begin) / CLOCKS_PER_SEC;               \n\n\tprintf(\"Time spent copying csr_matrix: %lf\\n\",time_spent);\n\n\t//MAIN LOOP\n\t//Prepare data to be passed to each thread\n\n\tpthread_t tid[NUM_THREADS];\t\t\t\n\tpass_to_thread_type_2* data= (pass_to_thread_type_2*)malloc(NUM_THREADS*sizeof(pass_to_thread_type_2));\t\n\tfor(sz_short i=0;i<NUM_THREADS;i++){\t\t\n\t\t(*(data+i))= (pass_to_thread_type_2) {.soft_labels=soft_labels, \n\t\t\t     \t\t\t      .num_seeds=num_seeds,\n\t\t\t\t\t\t      .num_per_class=num_per_class,\n\t\t\t\t\t\t      .class_ind=class_ind,\n\t\t\t\t\t\t      .graph = graph_copies[i],\n\t\t\t\t\t\t      .seeds=seed_indices,\n\t\t\t\t\t\t      .walk_length=walk_length,\n\t\t\t\t\t\t      .lambda=lambda,\n\t\t\t\t\t\t      .from=i*width, \n\t\t\t\t\t\t      .no_constr = no_constr };\n\t\t\t     \n\t\tif(i==NUM_THREADS-1){\t\t\n\t\t\t(data+i)->to=NUM_THREADS;\n\t\t\t(data+i)->num_local_classes= num_class -i*width;\t\t\t\n\t\t}else{\n\t\t\t(data+i)->to=(i+1)*width;\t\n\t\t\t(data+i)->num_local_classes=width;\t\n\t\t}\n\t}\n\n\t//Spawn threads and start running\n\tfor(sz_short i=0;i<NUM_THREADS;i++){\n\t\tpthread_create(&tid[i],NULL,AdaDIF_squezze_to_one_thread,(void*)(data+i));\t\t\n\t}\n\n\t//Wait for all threads to finish before continuing\t\n\tfor(sz_short i=0;i<NUM_THREADS;i++){pthread_join(tid[i], NULL);}\n\n\t//Free copies and temporary arrays\n\n\tcsr_array_destroy(graph_copies,(sz_short)NUM_THREADS);\n\tfree(data);           \n\n}\n\n\n\n//Here I slice the output(soft labels) and input (class_ind)\n//Using aliasing on the shifted pointers such that single threaded AdaDIF_core is compeltely \"blind\" to the slicing process\nvoid* AdaDIF_squezze_to_one_thread( void* param){\n\tpass_to_thread_type_2* data = param;\n\n\tdouble* soft_labels = data->soft_labels + (data->graph.num_nodes * data->from);\n\tsz_short* class_ind = data->class_ind + data->num_seeds*data->from;\n\tsz_med* num_per_class = data->num_per_class + data->from;\n\n\tclock_t begin = clock(); \t\n\n\tAdaDIF_core( soft_labels, data->graph,  data->num_seeds, data->seeds, data->num_local_classes, class_ind, num_per_class,\n\t\t     data->walk_length, data->lambda, data->no_constr);\n\n\tclock_t end = clock();\n\tdouble time_spent = (double)(end - begin) / CLOCKS_PER_SEC;  \t\t\n\n\tprintf(\"Thread from classes with index %\"PRIu16\" to %\"PRIu16\" finished in %lf sec \\n\",(uint16_t) data->from, (uint16_t) data->to, time_spent);\n\n\tpthread_exit(0);\n\n}\n\n//Core of AdaDIF method that runs on single thread (output is soft labels)\nvoid AdaDIF_core( double* soft_labels, csr_graph graph, sz_med num_seeds,\n\t\t  const sz_long* seed_indices, sz_short num_class, sz_short* class_ind,\n\t\t  sz_med* num_per_class, sz_med walk_length, double lambda, bool no_constr){       \n\t\n\tfor(sz_short i=0;i<num_class;i++){\t\t\n\t\n\t\tdouble* land_prob = (double*) malloc(walk_length*graph.num_nodes*sizeof(double));\n\t\tdouble* dif_land_prob = (double*) malloc(walk_length*graph.num_nodes*sizeof(double));\n\t\tsz_long* local_seeds =(sz_long*)malloc(num_per_class[i] *sizeof(sz_long));    \t\t\n\n\t\tsz_med k=0;\n\t\tfor(sz_med j=0;j<num_seeds;j++){ \n\t\t\tif( class_ind[i*num_seeds + j] ==1 )\t\t\t\n\t\t\t\tlocal_seeds[k++] = seed_indices[j];\n\t\t}\n\n\t\tperform_random_walk(land_prob, dif_land_prob, graph , walk_length , local_seeds , num_per_class[i] );\n\n\t\t\t\t\n\t\tdouble* theta = get_AdaDIF_parameters(graph.num_nodes,graph.degrees,land_prob,dif_land_prob,seed_indices,local_seeds,\n\t\t                                      class_ind+i*num_seeds,walk_length,num_seeds,num_per_class[i],lambda,no_constr );\n\t\t#if PRINT_THETAS\n\t\tprintf(\"THETA: \");\n\t\tfor(int n=0;n<walk_length;n++) printf(\" %.3lf\",theta[n]);\n\t\tprintf(\"\\n\");\t\t\n\t\t#endif\n\t \n\t\tmatvec_trans_long( soft_labels+i*graph.num_nodes , land_prob, theta, graph.num_nodes, walk_length );\n\n\t\t//free landing probabilities\n\t\tfree(local_seeds);\n\t\tfree(land_prob);\n\t\tfree(dif_land_prob);\t\n\t\tfree(theta);\n\t} \n}\n\n\n//Extract landing and dif probabilities by performing K steps of simple random walk on graph \n\nvoid perform_random_walk(double* land_prob, double* dif_land_prob, csr_graph graph,\n\t\t\t sz_med walk_length , sz_long* seeds , sz_med num_seeds ){\n\n\tdouble* seed_vector = (double*) malloc(graph.num_nodes* sizeof(double));\n\tdouble one_over_num_seeds = 1.0f /(double) num_seeds ;\n\n\t//prepare seed vector\n\tfor(sz_long i=0;i<graph.num_nodes;i++) seed_vector[i] = 0.0f ;\n\t\n\tfor(sz_med j=0;j<num_seeds;j++) seed_vector[seeds[j]] = one_over_num_seeds ;\n\n\t//do the random walk\n\tmy_CSR_matvec( land_prob, seed_vector , graph);  \n\n\tfor(sz_med j=1;j<walk_length;j++){\n\t\tmy_CSR_matvec( land_prob+j*graph.num_nodes, land_prob+(j-1)*graph.num_nodes , graph);\t\n\t\tmy_array_sub( dif_land_prob+(j-1)*graph.num_nodes, land_prob+(j-1)*graph.num_nodes,\n\t\t\t      land_prob+j*graph.num_nodes, graph.num_nodes);\n\t}\n\n\t#if DEBUG\n\tprintf(\"LAST LAND PROBs: \\n\");\n\tfor(sz_long i=0;i<=100;i++) printf(\" %lf \",land_prob[(walk_length-1)*graph.num_nodes + i ]) ;\n\tprintf(\"...................... \\n\");\n\t#endif\t\t\n\n\t//do one final step to obtain the last differential\n\n\tdouble* extra_step = (double*) malloc(graph.num_nodes* sizeof(double));\n\tmy_CSR_matvec( extra_step, land_prob+ (walk_length -1)*graph.num_nodes , graph);\t\n\tmy_array_sub( dif_land_prob+(walk_length-1)*graph.num_nodes, land_prob+(walk_length-1)*graph.num_nodes,\n\t\t      extra_step, graph.num_nodes);\t\n\n        //free\n\tfree(seed_vector);\n\tfree(extra_step);\n}\n\n//Extract the AdaDIF diffusion coefficients \n\ndouble* get_AdaDIF_parameters( sz_long N, sz_long* degrees, double* land_prob, \n\t\t\t       double* dif_land_prob, const sz_long* seed_indices,\n\t\t\t       sz_long* local_seeds, sz_short* class_ind, sz_med walk_length,\n\t\t\t        sz_med num_seeds, sz_med num_pos,double lambda, bool no_constr){\n\t\n\tdouble* theta = (double*) malloc(walk_length*sizeof(double));\n\n        //A and b are the Hessian and linear component of the quadratic cost\n        \t\n\tdouble* A = get_coef_A(N,walk_length,num_seeds,degrees, land_prob, dif_land_prob,seed_indices,lambda);\n\t\n\tdouble* b = get_coef_b(N,walk_length,num_seeds,num_pos,degrees, land_prob, local_seeds);\t\n\t\n\tif(!no_constr){\n\t\tsimplex_constr_QP_with_PG(theta,A,b,walk_length);\n\t}else{\n\t\thyperplane_constr_QP(theta,A,b,walk_length);\n\t}\n\n        //free\n\tfree(b);\n\tfree(A);\n\t\t\n\treturn theta;\n}\n\n\n\n\n\n\n\n// This function computes how many threads will be used and how many classes will be allocated per thread\nstatic sz_short get_threads_and_width(sz_short* width ,sz_short num_class){\n\tsz_short num_procs=get_nprocs();\n\tsz_short num_threads;\n\n\tif(num_class<=num_procs){\n\t\tnum_threads = num_class;\n\t\t*width=1;\n\t}else{\n\t\tnum_threads = num_procs;\n\t\t*width = (sz_short)ceil((double)(num_class/(double)num_threads));\n\t}\n\n\treturn num_threads;\n}\n\n\n//Obtain slice of G  as stationary distributions. (Unweighted) Seed set must be defined \n//Returns numbr of itrations untill convergence\nsz_med get_slice_of_G( double* G_s, sz_long* seeds, sz_med num_seeds, double tel_prob, \n\t\t\t csr_graph graph, bool single_thread ){\n\n\t//Do it SMART: Use a temporary G_s_next where you store the left hand side of iteration\n\t//Then at eah iteration just flip pointers between G_s and G_s_next\n\t//Multiple threads compute different slices of G_s\n\tsz_short NUM_THREADS = get_nprocs();\n\tprintf(\"NUMBER OF THREADS: %\"PRIu16\" \\n\",(uint16_t) NUM_THREADS);\n\t\n\tif(single_thread) NUM_THREADS = 1;\n\n\tsz_med iter[NUM_THREADS];\n\n\tcsr_graph graph_scaled = csr_deep_copy_and_scale(graph,1.0f-tel_prob);\n\n\tdouble* G_s_next=malloc(graph.num_nodes*num_seeds*sizeof(double));\n\n\t//Initialization\n\tfor(sz_long i=0;i<graph.num_nodes*num_seeds;i++) G_s[i]=0.0f;\n\n\tfor(sz_med j=0;j<num_seeds;j++) G_s[ num_seeds*seeds[j] +j]=1.0f; \n\n\tclock_t begin = clock();\n\n\t//The following three blocks create copies of the CSR matrix \n\t//Each copy will be used by a thread \n\n\tcsr_graph* graph_copies = csr_mult_deep_copy( graph_scaled, (sz_short) NUM_THREADS );\t\n\n\tclock_t end = clock();\n\tdouble time_spent = (double)(end - begin) / CLOCKS_PER_SEC;               \n\n\tprintf(\"Time spent copying csr_matrix: %lf\\n\",time_spent);\n\n\t//MAIN LOOP\n\t//Prepare data to be passed to each thread\n\tsz_med width;\t\n\twidth=(sz_med)floor((double)(num_seeds/(double)NUM_THREADS));\n\tpthread_t tid[NUM_THREADS];\t\t\t\n\tpass_to_thread_type_1* data= (pass_to_thread_type_1*)malloc(NUM_THREADS*sizeof(pass_to_thread_type_1));\t\n\tfor(sz_short i=0;i<NUM_THREADS;i++){\t\t\n\n\t        (*(data+i))= (pass_to_thread_type_1) {.G_s=G_s,\n\t\t\t \t\t\t      .G_s_next=G_s_next,\n\t\t\t\t\t\t      .graph = graph_copies[i],\n\t\t\t\t\t\t      .seeds=seeds,\n\t\t\t\t\t\t      .M=num_seeds,\n\t\t\t\t\t\t      .tel_prob=tel_prob,\n\t\t\t\t\t\t      .from=i*width };\n\n\t\tif(i==NUM_THREADS-1){\t\t\n\t\t\t(data+i)->to=num_seeds;\n\t\t}else{\n\t\t\t(data+i)->to=(i+1)*width;\t\t\n\t\t}\n\t\t(data+i)->iter=&iter[i];\n\t}\n\n\t//Spawn threads and start running\n\tfor(sz_short i=0;i<NUM_THREADS;i++){\n\t\tpthread_create(&tid[i],NULL,my_power_iter,(void*)(data+i));\t\t\n\t}\n\n\t//Wait for all threads to finish before continuing\t\n\tfor(sz_short i=0;i<NUM_THREADS;i++){pthread_join(tid[i], NULL);}\n\n\t//Free copies and temporary arrays\n\tcsr_destroy(graph_scaled);\n\tcsr_array_destroy(graph_copies,(sz_short)NUM_THREADS);\n\tfree(G_s_next);\n\tfree(data);\n\n\treturn iter[0];\n}\n\n\n//Power iteration that computes a subset (from,to) of the collumns of G_s\n//Data are passed via struct that can be readily used by thread\nvoid* my_power_iter(void* param){\n\n\tpass_to_thread_type_1* data = param;\n\n\n\tsz_long* seeds=data->seeds;\n\tdouble* G_s=data->G_s;\n\tdouble* G_s_next= data->G_s_next;\n\tcsr_graph graph=data->graph;\n\n\t//Iterate using this \"back and forth method\" to minimize memory access\n\tclock_t begin = clock();\n\n\tsz_med iter=0;\n\tsz_short flag=0;\t\n\t\n\tdo{\n\t\titer++;\t\n\t\tflag=(flag==1) ? 0 : 1 ;\n\t\tif(flag==1){\n\t\t\tmy_CSR_matmat( G_s_next , G_s  , graph , data->M , data->from, data->to);\n\t\t\tfor(sz_med j=data->from;j<data->to;j++) G_s_next[data->M*seeds[j] +j]+=data->tel_prob; \n\t\t}\n\t\telse{\n\t\t\tmy_CSR_matmat( G_s, G_s_next  , graph , data->M, data->from, data->to);\n\t\t\tfor(sz_med j=data->from;j<data->to;j++) G_s[data->M*seeds[j] +j]+= data->tel_prob; \n\t\t}\n\t}while(iter<MAXIT && max_seed_val_difference( G_s, G_s_next , seeds ,data->M, data->from, data->to) >TOL);\n\n\tif(flag==1){\n\t\tfor(sz_long i=0;i<graph.num_nodes;i++){\n\t\t\tfor(sz_med j=data->from;j<data->to;j++)\n\t\t\t\tG_s[i*data->M + j]=G_s_next[i*data->M + j];\n\t\t}\n\t}\n\n\t*(data->iter)=iter;\n\n\tclock_t end = clock();\n\tdouble time_spent = (double)(end - begin) / CLOCKS_PER_SEC;        \n\n\tprintf(\"Thread from column %\"PRIu32\" to %\"PRIu32\" finished in %lf sec \\n\", (uint32_t) data->from, (uint32_t) data->to, time_spent);\n\n\tpthread_exit(0);\n}\n\n\n//Personalized-Pagerank single thread\nvoid my_PPR_single_thread( double* soft_labels, csr_graph graph, sz_med num_seeds,\n\t\t\t   const sz_long* seed_indices, sz_short num_class, sz_short* class_ind,\n\t\t\t   sz_med* num_per_class, sz_med walk_length, double tel_prob){\n\n\tcsr_graph graph_scaled = csr_deep_copy_and_scale(graph,1.0f-tel_prob);\n\t \n\tfor(sz_short i=0;i<num_class;i++){\t\t\n\t\tsz_long* local_seeds =(sz_long*)malloc(num_per_class[i] *sizeof(sz_long));    \t\t\n\n\t\tsz_med k = 0;\n\t\tfor(sz_med j=0;j<num_seeds;j++){ \n\t\t\tif( class_ind[i*num_seeds + j] ==1 )\t\t\t\n\t\t\t\tlocal_seeds[k++] = seed_indices[j];\n\t\t}\n\n\t\t//prepare seed vector\n\t\tdouble* soft = soft_labels + i*graph.num_nodes;\n\t\tdouble one_over_num_seeds = 1.0f /(double) num_per_class[i] ;\n\t\tfor(sz_long n=0;n<graph.num_nodes;n++)  soft[n] = 0.0f ;\n\t\tfor(sz_med j=0;j<num_per_class[i];j++) soft[local_seeds[j]] = one_over_num_seeds ;\n\n\t\t//perform random walk with restart\n\t\tsz_short flag=0;\n\t\tdouble* soft_next=malloc(graph.num_nodes*sizeof(double));\n\t\tfor(sz_med j=0;j<walk_length;j++){\n\t\t\tflag=(flag==1) ? 0 : 1 ;\n\t\t\tif(flag==1){\n\t\t\t\tmy_CSR_matvec(soft_next, soft, graph_scaled );\n\t\t\t\tfor(sz_med k=0;k<num_per_class[i] ;k++)\n\t\t\t\t\tsoft_next[local_seeds[k]] += tel_prob*one_over_num_seeds; \n\t\t\t}\n\t\t\telse{\n\t\t\t\tmy_CSR_matvec(soft, soft_next, graph_scaled );\n\t\t\t\tfor(sz_med k=0;k<num_per_class[i] ;k++)\n\t\t\t\t\tsoft[local_seeds[k]] += tel_prob*one_over_num_seeds; \n\t\t\t}\n\n\t\t}\n\n\t\tif(flag==1){\n\t\t\tmemcpy(soft, soft_next, graph.num_nodes*sizeof(double));\n\t\t}\t\t\n\n\t\t\n\t\tfree(soft_next);\n\t\tfree(local_seeds);\n\n\t} \n\tcsr_destroy(graph_scaled);\n}\n\n\n\n//find l_max norm between vecors of known length\ndouble max_seed_val_difference(double* A, double* B, sz_long* points , sz_med num_points, sz_med from, sz_med to){ \n\tdouble dif;\n\tdouble max_dif=0.0f;\n\tfor(sz_med i=from;i<to;i++){\n\t\tdif=fabs( A[ num_points*points[i] + i] - B[ num_points*points[i] + i] );\n\t\tmax_dif = ( dif > max_dif ) ? dif : max_dif ;\n\t}\n\treturn max_dif;\n}\n\n\n//Extract square submatrix of slice G_l that corresponds to labeled only\nvoid extract_G_ll(double* G_ll, double* G_s, sz_long* seeds, sz_med num_seeds){ \n\n\tfor(sz_long i=0;i<num_seeds;i++){\n\t\tfor(sz_med j=0;j<num_seeds;j++)\n\t\t\tG_ll[i*num_seeds + j]=G_s[seeds[i]*num_seeds + j];\n\t}\n}\n\n\n\n//The following two functions generate the coefficients required by the AdaDIF QP\nstatic double* get_coef_A(sz_long N, sz_med K, sz_med L , sz_long* d , \n\t\t\t  double* P ,double* P_dif , const sz_long* L_ind , double lambda ){ \n\t\n\tdouble* A = (double*) malloc(K*K*sizeof(double));\n\t\n\tdouble* d_inv_times_lambda = (double*)malloc(N*sizeof(double));\n\t\n\tfor(sz_long i=0;i<N;i++) d_inv_times_lambda[i] =lambda/(double)d[i];  \n\t\n\t\n\tdouble* P_temp =(double*) malloc(K*N*sizeof(double));\n\n\tfor(sz_long i=0;i<N;i++){ \n\t\tfor(sz_med j=0;j<K;j++)\n\t\t\tP_temp[j*N+i]=d_inv_times_lambda[i]*P_dif[j*N+i];\t\t\t\n\t}\n\t\n\t\n\tfor(sz_med i=0;i<L;i++){ \n\t\tfor(sz_med j=0;j<K;j++)\n\t\t\tP_temp[j*N + L_ind[i] ]+= P[j*N+L_ind[i]]/(double)d[L_ind[i]];\t\t\t\t\n\t}\t\n\t\n\t\n\tcblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, (int)K, (int)K, (int)N, 1.0f, P, (int)N, P_temp, (int)N, 0.0f, A, (int)K);\n\t\t\n\tfree(d_inv_times_lambda);\n\tfree(P_temp);\n\treturn A;\n}\n\nstatic double* get_coef_b(sz_long N, sz_med K, sz_med L ,sz_med num_pos , sz_long* d , double* P , sz_long* L_c ){\n\n\tdouble two_over_L = -2.0f/(double) L;\n\t\n        double*\tb = (double*) malloc(K*sizeof(double));\n\n\tfor(sz_med i=0;i<K;i++) b[i]=0.0f;\n\t\n\tfor(sz_med i=0;i<K;i++){\n\t\tfor(sz_med j=0;j<num_pos;j++)\n\t\t\tb[i]+=P[i*N + L_c[j]]/(double)d[L_c[j]];\n\t\tb[i]*= two_over_L;\n\t}\n\t\n\t\n\treturn b;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "4e17f4a72751a02063ca3d4c8cbf0658192679cc", "size": 15833, "ext": "c", "lang": "C", "max_stars_repo_path": "src/comp_engine.c", "max_stars_repo_name": "DimBer/SSL_lib", "max_stars_repo_head_hexsha": "8ca9ca6f595a5da718850f3dcf3607c9ebf51c92", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-05-24T03:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-31T15:11:17.000Z", "max_issues_repo_path": "src/comp_engine.c", "max_issues_repo_name": "nikolakopoulos/Adaptive-Diffusions-for-SSL", "max_issues_repo_head_hexsha": "d2060a8875950694225611fcda7b757215cf65c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/comp_engine.c", "max_forks_repo_name": "nikolakopoulos/Adaptive-Diffusions-for-SSL", "max_forks_repo_head_hexsha": "d2060a8875950694225611fcda7b757215cf65c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T03:55:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-16T08:23:52.000Z", "avg_line_length": 29.3747680891, "max_line_length": 143, "alphanum_fraction": 0.6775721594, "num_tokens": 4576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.393373945998746}}
{"text": "#ifndef matops_h\n#define matops_h\n\n#include <ceed.h>\n#include <petsc.h>\n#include \"../include/structs.h\"\n\n// This function uses libCEED to compute the local action of an operator\nPetscErrorCode ApplyLocalCeedOp(Vec X, Vec Y, UserMult user);\n\n// This function uses libCEED to compute the non-linear residual\nPetscErrorCode FormResidual_Ceed(SNES snes, Vec X, Vec Y, void *ctx);\n\n// This function uses libCEED to apply the Jacobian for assembly via a SNES\nPetscErrorCode ApplyJacobianCoarse_Ceed(SNES snes, Vec X, Vec Y, void *ctx);\n\n// This function uses libCEED to compute the action of the Jacobian\nPetscErrorCode ApplyJacobian_Ceed(Mat A, Vec X, Vec Y);\n\n// This function uses libCEED to compute the action of the prolongation operator\nPetscErrorCode Prolong_Ceed(Mat A, Vec X, Vec Y);\n\n// This function uses libCEED to compute the action of the restriction operator\nPetscErrorCode Restrict_Ceed(Mat A, Vec X, Vec Y);\n\n// This function returns the computed diagonal of the operator\nPetscErrorCode GetDiag_Ceed(Mat A, Vec D);\n\n// This function calculates the strain energy in the final solution\nPetscErrorCode ComputeStrainEnergy(DM dm_energy, UserMult user,\n                                   CeedOperator op_energy, Vec X,\n                                   PetscReal *energy);\n\n// this function checks to see if the computed energy is close enough to reference file energy.\nPetscErrorCode RegressionTests_solids(AppCtx app_ctx, PetscReal energy);\n\n#endif // matopts_h\n", "meta": {"hexsha": "83981758bc8e5f81847f73d9bd4e601aa046bc20", "size": 1471, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/include/matops.h", "max_stars_repo_name": "AdelekeBankole/libCEED", "max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 123.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z", "max_issues_repo_path": "examples/solids/include/matops.h", "max_issues_repo_name": "AdelekeBankole/libCEED", "max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 781.0, "max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z", "max_forks_repo_path": "examples/solids/include/matops.h", "max_forks_repo_name": "AdelekeBankole/libCEED", "max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z", "avg_line_length": 38.7105263158, "max_line_length": 95, "alphanum_fraction": 0.7518694765, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3931301619572845}}
{"text": "/*\nCopyright 2017 InitialDLab\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n#pragma once\n\n//#include <gsl/gsl_rng.h>\n//#include <gsl/gsl_randist.h>\n#include <random>\n#include <cassert>\n\ninline\nsize_t \nnext_fanout(size_t size, size_t min_fanout, size_t max_fanout)\n{\n    if(size >= min_fanout + max_fanout)\n        return max_fanout;\n\n    if(size < max_fanout)\n    {\n        return size;\n    }\n\n    return size - min_fanout;\n}\n\ninline\nsize_t \ncalc_node_count(size_t size, size_t min_fanout, size_t max_fanout)\n{\n    return (size % max_fanout) \n        ? (size / max_fanout + 1)\n        : (size / max_fanout) \n        ;\n}\n\ntemplate<typename Point>\nvoid dump_point(std::ostream & out, Point const& point)\n{\n    out << boost::geometry::wkt(point);\n}\n\ntemplate<typename Box>\nvoid dump_box(std::ostream & out, Box const& box)\n{\n    out << boost::geometry::wkt(box.min_corner()) \n        << ' ' << boost::geometry::wkt(box.max_corner());\n}\n\n/*\ntemplate<typename RNG>\nsize_t alternate_binomial(size_t n, double p, RNG & rng)\n{\n    if(p > 0.5)\n        return n - alternate_binomial(n, 1.0-p, rng);\n\n    std::uniform_real_distribution<float> coin_dist(0,1);\n    double log_q = std::log(1.0 - p);\n    size_t x = 0;\n    double sum = 0;\n    for(;;) {\n        sum += std::log(coin_dist(rng)) / (n - x);\n        if(sum < log_q)\n            return x;\n        ++x;\n    }\n}\n*/\n\ntemplate<typename RNG>\ninline\nsize_t\nnext_sample_size(size_t total_sample_size, size_t cur_subtree_size, size_t total_subtree_size, RNG & rng)\n{\n    if(cur_subtree_size == 0) return 0;\n    if(cur_subtree_size == total_sample_size) return total_sample_size;\n    if(total_sample_size < 10)\n    {\n        size_t s = 0;\n        std::uniform_real_distribution<float> dist(0,1);\n        float prob = ((float)cur_subtree_size) / total_sample_size;\n        for(size_t i = 0; i < total_sample_size; ++i)\n            if(dist(rng) < prob)\n                ++s;\n        return s;\n    }\n\n    //std::binomial_distribution<int> distribution(((double)cur_subtree_size) / total_subtree_size, total_sample_size);\n    std::binomial_distribution<int> distribution(total_sample_size, ((double)cur_subtree_size) / total_subtree_size);\n    return distribution(rng);\n\n    //static gsl_rng *_gsl_rng = nullptr;\n    //if(!_gsl_rng){ _gsl_rng = gsl_rng_alloc (gsl_rng_taus); }\n    //return gsl_ran_binomial(_gsl_rng, ((double)cur_subtree_size)/total_subtree_size, total_sample_size);\n\n/*\n    return alternate_binomial(\n        total_sample_size,\n        ((double)cur_subtree_size) / total_subtree_size,\n        rng\n    );\n*/\n/*\n    return std::binomial_distribution<size_t>(\n        total_sample_size,\n        ((double)cur_subtree_size) / total_subtree_size\n    )(rng);\n*/\n}\n\ntemplate<typename RNG>\ninline\nvoid\nnext_sample_size_bulk(int trials, const std::vector<int64_t> &prefix_weights, std::vector<int> &output_counts, RNG & rng)\n{\n    assert(prefix_weights.size() == output_counts.size());\n\n    // special case\n    if (prefix_weights.size() == 1)\n    {\n        output_counts[0] = trials;\n        return;\n    }\n\n    int64_t accum = 0;\n    for (int i = 0; i < prefix_weights.size(); ++i)\n    {\n        output_counts[i] = next_sample_size(trials, prefix_weights[i] - accum, prefix_weights.back(), rng);\n        accum = prefix_weights[i];\n    }\n\n    //std::vector<int64_t> each_trial;\n    //each_trial.resize(trials);\n\n    //std::uniform_int_distribution<int64_t> dist(0, prefix_weights.back());\n\n    //std::generate(each_trial.begin(), each_trial.end(), [&rng, &dist]() {return dist(rng);});\n    //std::sort(each_trial.begin(), each_trial.end());\n    //auto last_max = each_trial.begin();\n    //auto output_itr = output_counts.begin();\n    //for (auto weight : prefix_weights)\n    //{\n    //    auto next_max = std::lower_bound(last_max, each_trial.end(), weight);\n    //    *output_itr = std::distance(last_max, next_max);\n    //    ++output_itr;\n    //    last_max = next_max;\n    //}\n\n    //if (last_max != each_trial.end())\n    //    output_counts.back() += std::distance(last_max, each_trial.end());\n\n    //for (int64_t samples_inserted = 0; samples_inserted < trials; ++samples_inserted)\n    //{\n    //    int64_t r_val = dist(rng);\n    //    auto i_itr = std::lower_bound(prefix_weights.begin(), prefix_weights.end(), r_val);\n    //    int index = i_itr - prefix_weights.begin();\n    //    ++output_counts[index];\n    //}\n\n\n    //std::uniform_int_distribution<int64_t> dist(0, prefix_weights.back());\n    //for (int64_t samples_inserted = 0; samples_inserted < trials; ++samples_inserted)\n    //{\n    //    int64_t r_val = dist(rng);\n    //    auto i_itr = std::lower_bound(prefix_weights.begin(), prefix_weights.end(), r_val);\n    //    int index = i_itr - prefix_weights.begin();\n    //    ++output_counts[index];\n    //}\n}\n", "meta": {"hexsha": "bd6a3fcea86ae5c3c1bc63ef31e72df62b9f1874", "size": 5747, "ext": "h", "lang": "C", "max_stars_repo_path": "util.h", "max_stars_repo_name": "InitialDLab/SampleIndex", "max_stars_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-09-30T22:34:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-18T21:21:35.000Z", "max_issues_repo_path": "util.h", "max_issues_repo_name": "InitialDLab/SONAR-SamplingIndex", "max_issues_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util.h", "max_forks_repo_name": "InitialDLab/SONAR-SamplingIndex", "max_forks_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7326203209, "max_line_length": 121, "alphanum_fraction": 0.6678266922, "num_tokens": 1480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.39310440365973737}}
{"text": "/***************************************************************************\nCopyright (c) 2014, The OpenBLAS Project\nAll rights reserved.\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n1. Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\nnotice, this list of conditions and the following disclaimer in\nthe documentation and/or other materials provided with the\ndistribution.\n3. Neither the name of the OpenBLAS project nor the names of\nits contributors may be used to endorse or promote products\nderived from 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\nARE DISCLAIMED. IN NO EVENT SHALL THE OPENBLAS PROJECT 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 OF\nTHE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*****************************************************************************/\n\n//#include \"bench.h\"\n#include <cblas.h>\n#include <math.h>\n#include <stdio.h>\n#include <string.h>\n#include <unistd.h>\n\n// mlir-clang dot.c -I .. -I /home/lchelini/scratch/polygeist/llvm-project/llvm/../clang/lib/Headers -o dot --emit-llvm\n\nint main(int argc, char *argv[]) {\n\n  float *x, *y;\n  float r;\n\n  int inc_x = 1, inc_y = 1;\n    \n  int size = 500;\n  x = (float *)malloc(sizeof(float) * size);\n  y = (float *)malloc(sizeof(float) * size);\n  \n\n  for (int i = 0; i < size; i++) {\n    x[i] = ((float)rand() / (float)RAND_MAX) - 0.5;\n  }\n\n  for (int i = 0; i < size; i++) {\n    y[i] = ((float)rand() / (float)RAND_MAX) - 0.5;\n  }\n\n  #pragma plugin(sdot_, \"linalg\", \"r += x(i) * y(i)\")  \n  r = sdot_(&size, x, &inc_x, y, &inc_y);\n  fprintf(stderr, \"%.6f\\n\", result);\n\n  return 0;\n}\n", "meta": {"hexsha": "f3c8d1db53be4a13a551fbaa25481017e1433c6f", "size": 2425, "ext": "c", "lang": "C", "max_stars_repo_path": "benchmark/dot.c", "max_stars_repo_name": "chelini/openBlas", "max_stars_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/dot.c", "max_issues_repo_name": "chelini/openBlas", "max_issues_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/dot.c", "max_forks_repo_name": "chelini/openBlas", "max_forks_repo_head_hexsha": "eddd31268e213b2115374b61080ec0be621f5c60", "max_forks_repo_licenses": ["BSD-3-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.4920634921, "max_line_length": 119, "alphanum_fraction": 0.6828865979, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.39306019823622323}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C header for functions manipulating waveforms.\n *\n */\n\n#ifndef _WAVEFORM_H\n#define _WAVEFORM_H\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"EOBNRv2HMROM.h\"\n\n\n#if defined(__cplusplus)\nextern \"C\" {\n#define complex _Complex\n#elif 0\n} /* so that editors will match preceding brace */\n#endif\n\n/* NOTE: uses the list of modes of EOBNRv2HMROM (listmode), to be extended when more waveform models are added */\n\n/***************** Function estimating frequency corresponding to a given time to coalescence ****************/\n\n/* Functions computing relations between chirp mass, eta, m1, m2*/\ndouble Mchirpofm1m2(\n  const double m1,   /* Mass 1 */\n  const double m2);  /* Mass 2 */\ndouble etaofm1m2(\n  const double m1,   /* Mass 1 */\n  const double m2);  /* Mass 2 */\ndouble m1ofMchirpeta(\n  const double Mchirp,   /* Chirp mass */\n  const double eta);     /* Symmetric mass ratio */\ndouble m2ofMchirpeta(\n  const double Mchirp,   /* Chirp mass */\n  const double eta);     /* Symmetric mass ratio */\n\n/* Newtonian estimate of the relation Mf(deltat/M) (for the 22 mode) - gives the starting geometric frequency for a given mass ratio and a given geometric duration of the observations */\ndouble NewtonianfoftGeom(const double q, const double t); /* t here is t/M */\n/* Newtonian estimate of the relation f(deltat) (for the 22 mode) - gives the starting frequency in Hz for a given mass ratio and a given geometric duration of the observations */\ndouble Newtonianfoft(const double m1, const double m2, const double t); /* t here is in years, m1-m2 in solar masses */\n/* Newtonian estimate of the relation f(deltat) (for the 22 mode freq) - gives the starting geometric frequency for a given time to merger and chirp mass - output in Hz */\ndouble Newtonianfoftchirp(\n  const double mchirp,                 /* Chirp mass (solar masses) */\n  const double t);                     /* Time in years */\n/* Newtonian estimate of the relation deltat(f) (for the 22 mode freq) - gives the time to merger from a starting frequency for a given chirp mass - output in years */\ndouble Newtoniantoffchirp(\n  const double mchirp,                 /* Chirp mass (solar masses) */\n  const double t);                     /* Freq in Hz */\n\n/***************** Function estimating time to coalescence and min/max frequency ****************/\n\n/* Functions reading from a list of modes the minimal and maximal frequencies */\ndouble ListmodesCAmpPhaseFrequencySeries_maxf(ListmodesCAmpPhaseFrequencySeries* listhlm);\ndouble ListmodesCAmpPhaseFrequencySeries_minf(ListmodesCAmpPhaseFrequencySeries* listhlm);\n\n/* Function estimating initial time from Psi22, according to tf_SPA = -1/(2pi)dPsi/df */\ndouble EstimateInitialTime(ListmodesCAmpPhaseFrequencySeries* listhlm, double fLow);\n\n/***************** Functions to manipulate ReImFrequencySeries structure ****************/\n\nvoid ReImFrequencySeries_AddCAmpPhaseFrequencySeries(\n  struct tagReImFrequencySeries* freqseriesReIm,              /* Output Re/Im frequency series */\n  struct tagCAmpPhaseFrequencySeries* freqseriesCAmpPhase,    /* Input CAmp/Phase frequency series, to be interpolated and added to the output */\n  double fLow,                                                /* Minimal frequency - set to 0 to ignore */\n  double fHigh,                                               /* Maximal frequency - set to 0 to ignore */\n  double fstartobsmode);                                      /* Starting frequency in case of limited duration of observations- assumed to have been scaled with the proper factor m/2 for this mode - set to 0 to ignore */\n/* Function evaluating a ReImFrequencySeries by interpolating wach mode of a ListmodesCAmpPhaseFrequencySeries and summing them, given a set of frequencies */\nvoid ReImFrequencySeries_SumListmodesCAmpPhaseFrequencySeries(\n  struct tagReImFrequencySeries* freqseriesReIm,                    /* Output Re/Im frequency series - already initialized */\n  struct tagListmodesCAmpPhaseFrequencySeries* listmodesCAmpPhase,  /* Input CAmp/Phase frequency series, to be interpolated */\n  gsl_vector* freq,                                                 /* Input set of frequencies on which evaluating */\n  double fLow,                                                      /* Minimal frequency - set to 0 to ignore */\n  double fHigh,                                                     /* Maximal frequency - set to 0 to ignore */\n  double fstartobs);                                                /* For limited duration of observation, starting frequency for the 22 mode - set to 0 to ignore */\n/* Helper function to add a mode to hplus, hcross in Fourier domain\n * - copies the function XLALSimAddMode, which was done only for TD structures */\nint FDAddMode(\n  ReImFrequencySeries* hptilde,       /* Output: frequency series for hplus */\n  ReImFrequencySeries* hctilde,       /* Output: frequency series for hcross */\n  ReImFrequencySeries* hlmtilde,      /* Input: frequency series for the mode hlm */\n  double theta,                       /* First angle for position in the sky of observer */\n  double phi,                         /* Second angle for position in the sky of observer  */\n  int l,                              /* First mode number l */\n  int m,                              /* Second mode number m */\n  int sym);                           /* If 1, assume planar symmetry and add also mode l,-m. Do not if set to 0. */\n/* Function evaluating the FD frequency series for hplus, hcross from the modes hlm */\nint GeneratehphcFDReImFrequencySeries(\n  ReImFrequencySeries** hptilde,                 /* Output: frequency series for hplus */\n  ReImFrequencySeries** hctilde,                 /* Output: frequency series for hcross */\n  ListmodesCAmpPhaseFrequencySeries* listhlm,    /* Input: frequency series for the mode hlm  */\n  double fLow,                                   /* Minimal frequency - set to 0 to ignore */\n  double fHigh,                                  /* Maximal frequency - set to 0 to ignore */\n  double fstartobs,                              /* For limited duration of observation, starting frequency for the 22 mode - set to 0 to ignore */\n  double deltaf,                                 /* Frequency step */\n  int nbpt,                                      /* Number of points of output - if 0, determined from deltaF and maximal frequency in input */\n  int nbmode,                                    /* Number of modes to add */\n  double theta,                                  /* First angle for position in the sky of observer */\n  double phi,                                    /* Second angle for position in the sky of observer */\n  int sym);                                      /* If 1, assume planar symmetry and add also mode l,-m. Do not if set to 0. */\n/* Function evaluating the FD frequency series by summing mode contributions from each hlm */\nint GenerateFDReImFrequencySeries(\n  ReImFrequencySeries** freqseries,              /* Output: frequency series */\n  ListmodesCAmpPhaseFrequencySeries* listhlm,    /* Input: FD modes hlm in the form AmpReal/AmpIm/Phase  */\n  double fLow,                                   /* Minimal frequency - set to 0 to ignore */\n  double fHigh,                                  /* Maximal frequency - set to 0 to ignore */\n  double fstartobs,                              /* For limited duration of observation, starting frequency for the 22 mode - set to 0 to ignore */\n  double deltaf,                                 /* Frequency step */\n  int nbpt);                                     /* Number of points of output - if 0, determined from deltaf and maximal frequency in input */\n/* Function evaluating the FD frequency series for a single mode contribution (l,m) */\nint GenerateFDReImFrequencySeriesSingleMode(\n  ReImFrequencySeries** freqseries,              /* Output: frequency series */\n  ListmodesCAmpPhaseFrequencySeries* listhlm,    /* Input: FD modes hlm in the form AmpReal/AmpIm/Phase  */\n  double fLow,                                   /* Minimal frequency - set to 0 to ignore */\n  double fHigh,                                  /* Maximal frequency - set to 0 to ignore */\n  double fstartobs,                              /* For limited duration of observation, starting frequency for the 22 mode - set to 0 to ignore */\n  double deltaf,                                 /* Frequency step */\n  int nbpt,                                      /* Number of points of output - if 0, determined from deltaf and maximal frequency in input */\n  int l,                                         /* Mode index l */\n  int m);                                        /* Mode index m */\n/* Function to restrict a frequency series (typically output of a FFT) to a given frequency range */\nint RestrictFDReImFrequencySeries(\n  ReImFrequencySeries** freqseriesout,           /* Output: truncated frequency series */\n  ReImFrequencySeries* freqseriesin,             /* Input: frequency series */\n  double fLow,                                   /* Minimal frequency */\n  double fHigh);                                 /* Maximal frequency */\n/* Function for getting a phase mod 2pi (between -pi and pi) */\ndouble mod2pi(double phase);\n/* Function for getting a phase mod pi (between 0 and pi, e.g. polarization) */\ndouble modpi(double phase);\n/* Function to unwrap the phase mod 2pi  - acts directly on the gsl_vector representing the phase */\nint UnwrapPhase(\n  gsl_vector*  phaseout,   /* Output: unwrapped phase vector - already allocated */\n  gsl_vector*  phasein);   /* Input: phase vector */\n/* Function to convert a time series from Re/Im form to Amp/Phase form - unwrapping the phase */\nint ReImTimeSeries_ToAmpPhase(\n  AmpPhaseTimeSeries** timeseriesout,             /* Output: Amp/Phase time series */\n  ReImTimeSeries* timeseriesin);                  /* Input: Re/Im time series */\n/* Function to convert a time series from Amp/Phase form to Re/Im form */\nint AmpPhaseTimeSeries_ToReIm(\n  ReImTimeSeries** timeseriesout,                 /* Output: Re/Im time series */\n  AmpPhaseTimeSeries* timeseriesin);              /* Input: Amp/Phase time series */\n/* Function to compute a linear resampling at high frequencies to enforce a maximal deltaf */\n/* NOTE: Assumes input frequencies are logarithmic (except maybe first interval) to evaluate when to resample */\nint SetMaxdeltafResampledFrequencies(\n  gsl_vector** freqr,              /* Output: resampled frequencies */\n  gsl_vector* freq,                /* Input: original frequencies */\n  const double maxf,               /* Input: maximal frequency - set to 0. to ignore */\n  const double deltaf);            /* Input: maximal deltaf aimed for - 0.002Hz appropriate for LISA */\n/* Function to compute a linear-in-time resampling at low frequencies to enforce a maximal deltat */\nint SetMaxdeltatResampledFrequencies(\n  gsl_vector** freqr,              /* Output: resampled frequencies */\n  gsl_vector* freq,                /* Input: original frequencies */\n  const double deltat,             /* Input: maximal deltat aimed for - fraction of a year, 1/24 (half month) appropriate for 1e-4 interpolation errors */\n  const double mchirp,             /* Input: chirp mass, used for approximate t-f correspondence */\n  const int m);                    /* Input: chirp mass, used for approximate t-f correspondence */\n/* Function to resample a CAmp/Phase frequency series on the specified frequencies */\nint CAmpPhaseFrequencySeries_Resample(\n  CAmpPhaseFrequencySeries** freqseriesout,         /* Output: CAmp/Phase freq series */\n  CAmpPhaseFrequencySeries* freqseriesin,           /* Input: CAmp/Phase freq series */\n  gsl_vector* freqr);                                 /* Input: freq vector to resample on */\n\n/***************** Spin weighted spherical harmonics ****************/\n\n/* Additional function reproducing XLALSpinWeightedSphericalHarmonic */\ndouble complex SpinWeightedSphericalHarmonic(double theta, double phi, int s, int l, int m); /* Currently only supports s=-2, l=2,3,4,5 modes */\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _WAVEFORM_H */\n", "meta": {"hexsha": "bd07a483f7deca91b139b32ce8c58af501b8d839", "size": 12677, "ext": "h", "lang": "C", "max_stars_repo_path": "tools/waveform.h", "max_stars_repo_name": "JohnGBaker/flare", "max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "tools/waveform.h", "max_issues_repo_name": "JohnGBaker/flare", "max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_issues_repo_licenses": ["Apache-2.0"], "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/waveform.h", "max_forks_repo_name": "JohnGBaker/flare", "max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 62.4482758621, "max_line_length": 221, "alphanum_fraction": 0.6380847204, "num_tokens": 2815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3928580573669613}}
{"text": "#ifndef SPN_H\n#define SPN_H\n#include \"init_cy_fde.h\"\n#include \"matrix_util.h\"\n//#include <cblas.h>\n\n\n\ntypedef struct SemiCircularNet{\n  int p;\n  int d;\n  DCOMPLEX *Pa_h_A;         // d\n  DCOMPLEX *Pa_omega;       // 2*d\n\n\n  DCOMPLEX F_A[2];         //\n  DCOMPLEX h_A[2];         //\n\n  DCOMPLEX TG_Ge_sc[4] ;   //\n  DCOMPLEX DG_sc[4];       //\n\n  DCOMPLEX temp_T_eta[4];  //\n  DCOMPLEX Dh_sc[4];       //\n\n\n  DCOMPLEX Psigma_G_sc[2]; //\n\n  DCOMPLEX Psigma_h_sc[2] ;//\n\n\n  DCOMPLEX DG_A[4];        //\n  DCOMPLEX Dh_A[4];        //\n\n  DCOMPLEX S[4];           //\n\n  DCOMPLEX temp_mat[4];    //\n\n  DCOMPLEX Psigma_omega[2];//\n\n\n}SCN;\n\nvoid\nSCN_construct(SCN* self, int p , int d);\n\nvoid\nSCN_init(SCN* self);\n\nvoid\nSCN_init_forward(SCN* self);\nvoid\nSCN_init_backward(SCN* self);\n\n\nvoid\nSCN_destroy(SCN* self);\n\n\nint\nSCN_cauchy(SCN* self);\n\nvoid\nSCN_grad(SCN* self,  int p, int d, double  *a,  double  sigma, \\\n  DCOMPLEX z,DCOMPLEX *G, DCOMPLEX *omega, DCOMPLEX *omega_sc,\\\n  DCOMPLEX *o_grad_a, DCOMPLEX *o_grad_sigma);\n\n\n\n/** Compute Cauchy transform of SemiCircular( returns total iterations)\n* @param Z : input matrix\n* @param o_G : out_put Cauchy transform\n*\n*/\nint\ncauchy_sc( int p,  int d,  double sigma, DCOMPLEX* Z, \\\n   int max_iter, double thres,\\\n   DCOMPLEX* o_G);\n\n /** Compute Cauchy transform of Signal-Plus-Noise model( returns total iterations)\n * @param Z : input matrix\n * @param o_G_sc : out_put Cauchy transform\n *\n */\nint\ncauchy_spn(int p_dim, int dim, double* a, double sigma,\\\n     DCOMPLEX* B,\\\n     int max_iter,double thres, \\\n     DCOMPLEX* o_G_sc, DCOMPLEX* o_omega, DCOMPLEX* o_omega_sc);\n\n\n/*\nOnly for debug\n*/\nvoid\ngrad_cauchy_spn(int p, int d,  double  *a, double  sigma, \\\n  DCOMPLEX z, DCOMPLEX *G, DCOMPLEX *omega, DCOMPLEX *omega_sc,\\\n  DCOMPLEX *o_grad_a, DCOMPLEX *o_grad_sigma);\n\n// transpose of derivation of Ge\n// G : 2\n// o_DGe: 2 x 2\nvoid TG_Ge( const int p, const int d, const double sigma, \\\n  const DCOMPLEX *G, DCOMPLEX *o_DGe);\n\n\n// transpose of derivation of cauchy_sc\n// G: 2\n// DG: 2 x 2\nvoid DG(const DCOMPLEX *G,  const  DCOMPLEX *DGe,  DCOMPLEX *o_DG);\n\nvoid T_eta(const int p, const int d, DCOMPLEX *o_T_eta);\n\nvoid Dh(const DCOMPLEX* DG, const DCOMPLEX *T_eta, const double sigma,DCOMPLEX *o_Dh);\n\nvoid Psigma_G(const int p,const int d, const double sigma, const DCOMPLEX *G, const DCOMPLEX *DGe, DCOMPLEX *o_Psigma_G);\n\nvoid Psigma_h(const int p, const int d, const double sigma, const DCOMPLEX * G, const DCOMPLEX* P_sigma_G, const DCOMPLEX *T_eta,\\\nDCOMPLEX* o_Psigma_h);\n\n//// Descrete\n\nvoid des_DG( int p, int d, const double *a, const DCOMPLEX *W,DCOMPLEX*o_DG);\n\n\nvoid des_Dh( const DCOMPLEX *DG, const DCOMPLEX *F,DCOMPLEX*o_Dh);\n\n\nvoid des_Pa_h( int p, int d, const double *a, const DCOMPLEX *W, DCOMPLEX *F, DCOMPLEX *Pa_h);\n\n\n\n/** compute gradient and loss of likelihood\n* return total number of forward_iter\n*\n*/\nint\ngrad_loss_cauchy_spn(  int p, int d, double  *a, double  sigma, double scale, \\\n  int  batch_size, double *batch, \\\n  double *o_grad_a, double *o_grad_sigma, double *o_loss);\n\n\n#endif\n", "meta": {"hexsha": "68709f77efbe117082f34140305f3666f1a32704", "size": 3066, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cy_fde/spn.h", "max_stars_repo_name": "ThayaFluss/cnl", "max_stars_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cy_fde/spn.h", "max_issues_repo_name": "ThayaFluss/cnl", "max_issues_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cy_fde/spn.h", "max_forks_repo_name": "ThayaFluss/cnl", "max_forks_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733", "max_forks_repo_licenses": ["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.4405594406, "max_line_length": 130, "alphanum_fraction": 0.6761252446, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.39282621149379554}}
{"text": "#pragma once\n\n#include \"schedule.h\"\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <gsl/gsl-lite.hpp>\n#include <pcg_random.hpp>\n#include <random>\n\nnamespace angonoka::stun {\nusing RandomEngine = pcg32;\n\n/**\n    Miscellaneous random number generators.\n*/\nclass RandomUtils {\npublic:\n    /**\n        Default constructor.\n    */\n    RandomUtils();\n\n    /**\n        Constructor with a fixed PRNG seed.\n\n        @param seed Random engine seed\n    */\n    RandomUtils(gsl::index seed);\n\n    /**\n        Uniformally distributed real value between 0 and 1.\n\n        @return Random number\n    */\n    float uniform_01() noexcept;\n\n    /**\n        Uniformally distributed discrete value between 0 and max.\n\n        @param max Maximum value\n\n        @return Random number\n    */\n    int16 uniform_int(int16 max) noexcept;\n\nprivate:\n    RandomEngine generator{\n        pcg_extras::seed_seq_from<std::random_device>{}};\n    boost::random::uniform_01<float> uniform_01_;\n    boost::random::uniform_int_distribution<std::int_fast16_t>\n        uniform_int_;\n};\n} // namespace angonoka::stun\n", "meta": {"hexsha": "f315cd7ba8c20b4d10e612b92c08fa84d6821e1b", "size": 1127, "ext": "h", "lang": "C", "max_stars_repo_path": "src/stun/random_utils.h", "max_stars_repo_name": "coffee-lord/angonoka", "max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z", "max_issues_repo_path": "src/stun/random_utils.h", "max_issues_repo_name": "coffee-lord/angonoka", "max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z", "max_forks_repo_path": "src/stun/random_utils.h", "max_forks_repo_name": "coffee-lord/angonoka", "max_forks_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c", "max_forks_repo_licenses": ["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.8703703704, "max_line_length": 65, "alphanum_fraction": 0.6663708962, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.39282619904300314}}
{"text": "/**\n * The driver function and some auxillaries\n * to compute the spectrum from an image and\n * information on the location and distortion of the spectra.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <limits.h>\n\n#include <gsl/gsl_roots.h>\n#include <gsl/gsl_vector.h>\n\n#include \"aXe_grism.h\"\n#include \"aXe_utils.h\"\n#include \"spce_sect.h\"\n#include \"spce_is_in.h\"\n#include \"spce_pathlength.h\"\n\n#define DEBUG_ME 0x10\n\n\n/**\n  fill in the path length field (xi in ap_pixel) from the abscissas (xs in\n  ap_pixel) (helper function for spc_extract).\n\n  @param func the spectrum trace to use for the transformation from xs to xi\n  @param table a pointer to the table of aperture pixels, terminated with\n  x=-1\n*/\nstatic int\ntransform_to_pathlen (const trace_func * const func, ap_pixel * const table)\n{\n  int i, len;\n  ap_pixel *cur_p = table;\n  gsl_vector *section_points;\n\n  while (cur_p->p_x != -1)\n    cur_p++;\n  len = cur_p - table;\n  if (len==0) return -1; // exit now if the table is empty\n\n  section_points = gsl_vector_alloc (len);\n  for (i = 0; i < len; i++)\n    {\n      gsl_vector_set (section_points, i, table[i].xs);\n    }\n\n  if (abscissa_to_pathlength (func, section_points))\n    {\n      gsl_vector_free (section_points);\n      return -1;\n    }\n\n  for (i = 0; i < len; i++)\n    {\n      table[i].xi = gsl_vector_get (section_points, i);\n    }\n\n  gsl_vector_free (section_points);\n\n  return 0;\n}\n\n\n\n/**\n   creates an ap_pixel.\n\n   @param x x coordinate of pixel relative to beam's reference point\n   @param y y coordinate of pixel relative to beam's reference point\n   @param px absolute x coordinate of the pixel\n   @param py absolute y coordinate of the pixel\n   @param ob the observation to get the pixels from\n   @param sf pointer to sectionfun structure for this beam\n   @param cur_ap a pointer to the next free aperture pixel\n   @return a pointer to the next free aperture pixel after the new pixels\n    have been added.\n\n*/\nstatic ap_pixel *\nhandle_one_pixel (const double x, const double y, const int px, const int py,\n\t\t  const observation * const obs, sectionfun * const sf,\n\t\t  const trace_func * const tracefun, ap_pixel * cur_ap)\n{\n  double res;\n  double sect_y;\n  double tmp;\n  double phi_trace;\n\n  if (find_section_point (sf, x, y, &res))\n    {\n      return cur_ap;\t/* FIXME: Issue warning here */\n    }\n  /* set the extraction weight to 1. */\n  cur_ap->weight = 1.;\n  cur_ap->xs = res;\n  phi_trace = atan (tracefun->deriv (cur_ap->xs, tracefun->data));\n  cur_ap->dxs = phi_trace;\n  cur_ap->ys = tracefun->func (cur_ap->xs, tracefun->data);\n  sect_y = tracefun->func (res, tracefun->data);\n  tmp = tracefun->func (x, tracefun->data);\n\n  cur_ap->contam = -1.0;\n  cur_ap->model = 0.0;\n  cur_ap->p_x = px;\n  cur_ap->p_y = py;\n  cur_ap->x = x;\n  cur_ap->y = y;\n  cur_ap->dist =\n    sqrt ((sect_y - y) * (sect_y - y) +\n\t  (cur_ap->xs - x) * (cur_ap->xs - x));\n\n  if ( y < tmp ) {\n    cur_ap->dist = cur_ap->dist * (-1.); /* If pixel is bwlow the trace, dist is neg. */\n  }\n  cur_ap->count = gsl_matrix_get (obs->grism, px, py);\n  cur_ap->error = gsl_matrix_get (obs->pixerrs, px, py);\n  if (obs->dq != NULL) cur_ap->dq = (long) gsl_matrix_get (obs->dq, px, py);\n  else cur_ap->dq = 0;\n\n  cur_ap++;\n  return cur_ap;\n}\n\n\n/**\n   Does some sanity checks on make_spc_table's input.\n\n   @param ob the object to check\n   @return 0 if everything is ok, -1 otherwise\n*/\nstatic int\nsanitycheck (object * const ob)\n{\n  int i;\n\n  for (i = 0; i < ob->nbeams; i++)\n    {\n      while (ob->beams[i].orient < 0)\n\t{\n\t  ob->beams[i].orient += M_PI;\n\t}\n      while (ob->beams[i].orient > M_PI)\n\t{\n\t  ob->beams[i].orient -= M_PI;\n\t}\n    }\n  return 0;\n}\n\n\n#define MIN(x,y) (((x)<(y))?(x):(y))\n#define MAX(x,y) (((x)>(y))?(x):(y))\n/**\n   computes a table of aperture pixels, i.e. of tuples containing the\n   source coordinates, the distance to the spectrum trace, the path\n   length along the trace, and the intensity.  The end of the table\n   is marked with an ap_pixel->x==-1.  This routine can do subsampling,\n   whereby each pixel is divided into n_sub*n_sub smaller pixels.\n   If n_sub==1, a special (faster) handling is enabled.\n\n   @param ob the object struct to examine\n   @param beamorder the order of the spectrum to examine\n   @param flags warning flags like in the warning field of the\n     spectrum structure.  This has to be passed in initialized.\n*/\nap_pixel *\nmake_spc_table (object * const ob, const int beamorder,\n\t\tint *const flags)\n{\n  int bb_x, bb_y, bb_w, bb_h;\n  int x, y;\n  beam *curbeam = ob->beams + beamorder;\n  double dx, dy;\n  ap_pixel *table, *cur_ap;\n  is_in_descriptor iid;\n  sectionfun sf;\n  trace_func *tracefun = curbeam->spec_trace;\n\n  quad_to_bbox (curbeam->corners, curbeam->bbox, curbeam->bbox + 1);\n  bb_x = curbeam->bbox[0].x;\n  bb_y = curbeam->bbox[0].y;\n  bb_w = curbeam->bbox[1].x - curbeam->bbox[0].x + 1;\n  bb_h = curbeam->bbox[1].y - curbeam->bbox[0].y + 1;\n\n  if (sanitycheck (ob))\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"Input data failed sanity check\");\n      return NULL;\n    }\n\n  if (fill_is_in_descriptor (&iid, curbeam->corners))\n    return NULL;\n\n  if (fill_in_sectionfun (&sf, curbeam->orient, curbeam))\n    return NULL;\n\n  if (!(table =\n\tmalloc ((bb_w * bb_h + 1) * sizeof (ap_pixel))))\n    return NULL;\n\n\n  /* We have a little coordinate confusion here.  There are three\n     systems:\n     (a) the absolute one, rooted in (0,0) of the image.\n     (b) the relative one, rooted in the reference point and used\n     when evaluating the spectrum trace.  This one is used\n     for finding the section points, etc.\n     (c) one relative to the bounding box; x and y below live in this\n     system and have to be converted into whatever system is\n     required.  dx, dy are used for the conversion to (b)\n  */\n  dx = bb_x - curbeam->refpoint.x;\n  dy = bb_y - curbeam->refpoint.y;\n  cur_ap = table;\n  for (y = 0; y <= bb_h; y++)\n    {\n      for (x = 0; x < bb_w; x++)\n\t{\n\t  if ((bb_x + x < 0) || (bb_y + y < 0)\n\t      || (bb_x + x >= (int)ob->grism_obs->grism->size1)\n\t      || (bb_y + y >= (int)ob->grism_obs->grism->size2))\n\t    {\n\t      *flags |= SPC_W_BORDER;\n\t      continue;\n\t    }\n\n\n\t  // check whether the trace description has\n\t  // an order higher than linear\n\t  if (curbeam->spec_trace->type > 1)\n\t    {\n\t      // new criteria based on the true trace distance\n\t      // which means the true distance from the section point\n\t      if (!tracedist_criteria(x + dx, y + dy, &sf, tracefun, curbeam->width+2.0))\n\t\t{\n\t\t  continue;\n\t\t}\n\t    }\n\t  else\n\t    {\n\t      // old criteria based on the box model\n\t      if (!is_in (bb_x + x, bb_y + y, &iid))\n\t\t{\n\t\t  continue;\n\t\t}\n\t    }\n\n\t  if (isnan\n\t      (gsl_matrix_get\n\t       (ob->grism_obs->grism, bb_x + x, bb_y + y)))\n\t    {\n\t      continue;\n\t    }\n\t  //\t  if (ob->ID == 11 && x + bb_x == 59)\n\t    //\t    fprintf(stdout, \"xx: %i, yy: %i: %i\\n\", x + bb_x, y + bb_y, is_in (x + bb_x, y + bb_y, &iid));\n\t  cur_ap =\n\t    handle_one_pixel (x + dx, y + dy, x + bb_x,\n\t\t\t      y + bb_y, ob->grism_obs, &sf,\n\t\t\t      tracefun, cur_ap);\n\n\t}\n    }\n\n  cur_ap->p_x = -1;\n  cur_ap->p_y = -1;\n  cur_ap->count = -1;\n\n  free_sectionfun (&sf);\n\n\n  if (transform_to_pathlen (curbeam->spec_trace, table))\n    {\n      //   free (table);\n      //   table = NULL;\n      //   return NULL;\n    }\n  return table;\n}\n\n/**\n   Similar to make_spc_table, it just works only\n   on one spot given in the parameters.\n*/\nap_pixel *\nmake_gps_table (object * const ob, const int beamorder,\n\t\tint *const flags, int xval, int yval)\n{\n  int bb_x, bb_y, bb_w, bb_h;\n  int x, y;\n  beam *curbeam = ob->beams + beamorder;\n  double dx, dy;\n  ap_pixel *table, *cur_ap;\n  is_in_descriptor iid;\n  sectionfun sf;\n  trace_func *tracefun = curbeam->spec_trace;\n\n  quad_to_bbox (curbeam->corners, curbeam->bbox, curbeam->bbox + 1);\n  bb_x = curbeam->bbox[0].x;\n  bb_y = curbeam->bbox[0].y;\n  bb_w = curbeam->bbox[1].x - curbeam->bbox[0].x + 1;\n  bb_h = curbeam->bbox[1].y - curbeam->bbox[0].y + 1;\n\n  if (sanitycheck (ob))\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"Input data failed sanity check\");\n      return NULL;\n    }\n\n  if (fill_is_in_descriptor (&iid, curbeam->corners))\n    return NULL;\n\n  if (fill_in_sectionfun (&sf, curbeam->orient, curbeam))\n    return NULL;\n\n  if (!\n      (table =\n       malloc (2 * sizeof (ap_pixel))))\n    return NULL;\n\n  /* We have a little coordinate confusion here.  There are three\n     systems:\n     (a) the absolute one, rooted in (0,0) of the image.\n     (b) the relative one, rooted in the reference point and used\n     when evaluating the spectrum trace.  This one is used\n     for finding the section points, etc.\n     (c) one relative to the bounding box; x and y below live in this\n     system and have to be converted into whatever system is\n     required.  dx, dy are used for the conversion to (b)\n  */\n  dx = bb_x - curbeam->refpoint.x;\n  dy = bb_y - curbeam->refpoint.y;\n  x  = xval - bb_x;\n  y  = yval - bb_y;\n\n  cur_ap = table;\n\n  cur_ap =\n    handle_one_pixel (x + dx, y + dy, x + bb_x,\n\t\t      y + bb_y, ob->grism_obs, &sf,\n\t\t      tracefun, cur_ap);\n\n  cur_ap->p_x = -1;\n  cur_ap->p_y = -1;\n  cur_ap->count = -1;\n\n  free_sectionfun (&sf);\n\n  transform_to_pathlen (curbeam->spec_trace, table);\n\n  return table;\n}\n\n\n\nvoid\nprint_ap_pixel_table (const ap_pixel * ap_p)\n{\n  printf (\"# x y pathlen distance lambda count error\\n\");\n  while (ap_p->p_x != -1)\n    {\n      printf (\"%d %d %f %f %f %f %f %f %f %ld\\n\", ap_p->p_x, ap_p->p_y,\n\t      ap_p->x, ap_p->y, ap_p->xi, ap_p->dist, ap_p->lambda,\n\t      ap_p->count, ap_p->error, ap_p->dq);\n      ap_p++;\n    }\n}\n\n/*\nint\ntracedist_criteria(const double x, const double y, sectionfun * const sf,\n\t\t   const trace_func *tracefun, const double width)\n{\n  double x_sect, y_sect;\n  double dist, max_dist;\n\n  int ireturn=0;\n\n\n  find_section_point (sf, x, y, &x_sect);\n  y_sect = tracefun->func (x_sect, tracefun->data);\n\n  dist =  sqrt((y_sect-y)*(y_sect-y)+(x_sect-x)*(x_sect-x));\n\n  if (dist < width)\n    ireturn=1;\n\n  return ireturn;\n}\n*/\n", "meta": {"hexsha": "acb73275af737a8699e607e4390fee8b54bb7742", "size": 10069, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/spc_extract.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spc_extract.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spc_extract.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-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.4267676768, "max_line_length": 106, "alphanum_fraction": 0.6284636012, "num_tokens": 3135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.39257984208644914}}
{"text": "/**\n * Copyright (C) 2019 Samsung Electronics Co., Ltd. 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 *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\n * @file\ttensor.h\n * @date\t04 December 2019\n * @brief\tThis is Tensor class for calculation\n * @see\t\thttps://github.com/nnstreamer/nntrainer\n * @author\tJijoong Moon <jijoong.moon@samsung.com>\n * @bug\t\tNo known bugs except for NYI items\n *\n */\n\n#ifndef __TENSOR_H__\n#define __TENSOR_H__\n#ifdef __cplusplus\n\n#ifdef USE_BLAS\nextern \"C\" {\n#include <cblas.h>\n}\n#endif\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <regex>\n#include <vector>\n\nnamespace nntrainer {\n\n#define MAXDIM 4\n\nclass TensorDim {\npublic:\n  TensorDim() {\n    for (int i = 0; i < MAXDIM; ++i) {\n      dim[i] = 1;\n    }\n  }\n  ~TensorDim(){};\n  unsigned int batch() { return dim[0]; };\n  unsigned int channel() { return dim[1]; };\n  unsigned int height() { return dim[2]; };\n  unsigned int width() { return dim[3]; };\n\n  void batch(unsigned int b) { dim[0] = b; };\n  void channel(unsigned int c) { dim[1] = c; };\n  void height(unsigned int h) { dim[2] = h; };\n  void width(unsigned int w) { dim[3] = w; };\n\n  unsigned int *getDim() { return dim; }\n\n  int setTensorDim(std::string input_shape);\n\nprivate:\n  unsigned int dim[4];\n};\n\n/**\n * @class   Tensor Class for Calculation\n * @brief   Tensor Class for Calculation\n */\nclass Tensor {\npublic:\n  /**\n   * @brief     Constructor of Tensor\n   */\n  Tensor() : height(0), width(0), batch(0), ndim(0), len(0){};\n\n  /**\n   * @brief     Constructor of Tensor with batch size one\n   * @param[in] heihgt Height of Tensor\n   * @param[in] width Width of Tensor\n   */\n  Tensor(int height, int width);\n\n  /**\n   * @brief     Constructor of Tensor\n   * @param[in] batch Batch of Tensor\n   * @param[in] heihgt Height of Tensor\n   * @param[in] width Width of Tensor\n   */\n  Tensor(int batch, int height, int width);\n\n  /**\n   * @brief   Constructor of Tensor\n   * @param[in] d data for the Tensor with batch size one\n   */\n  Tensor(std::vector<std::vector<float>> const &d);\n\n  /**\n   * @brief     Constructor of Tensor\n   * @param[in] d data for the Tensor\n   */\n  Tensor(std::vector<std::vector<std::vector<float>>> const &d);\n\n  /**\n   * @brief     return value at specific location\n   * @param[in] batch batch location\n   * @param[in] h height location\n   * @param[in] w width location\n   */\n  float getValue(int batch, int h, int w);\n\n  /**\n   * @brief     Multiply value element by element\n   * @param[in] value multiplier\n   * @retval    Calculated Tensor\n   */\n  Tensor multiply(float const &value);\n\n  /**\n   * @brief     Divide value element by element\n   * @param[in] value Divisor\n   * @retval    Calculated Tensor\n   */\n  Tensor divide(float const &value);\n\n  /**\n   * @brief     Add Tensor Element by Element\n   * @param[in] m Tensor to be added\n   * @retval    Calculated Tensor\n   */\n  Tensor add(Tensor const &m) const;\n\n  /**\n   * @brief     Add value Element by Element\n   * @param[in] value value to be added\n   * @retval    Calculated Tensor\n   */\n  Tensor add(float const &value);\n\n  /**\n   * @brief     Substract Tensor Element by Element\n   * @param[in] m Tensor to be added\n   * @retval    Calculated Tensor\n   */\n  Tensor subtract(Tensor const &m) const;\n\n  /**\n   * @brief     subtract value Element by Element\n   * @param[in] value value to be added\n   * @retval    Calculated Tensor\n   */\n  Tensor subtract(float const &value);\n\n  /**\n   * @brief     Multiply Tensor Element by Element ( Not the MxM )\n   * @param[in] m Tensor to be multiplied\n   * @retval    Calculated Tensor\n   */\n  Tensor multiply(Tensor const &m) const;\n\n  /**\n   * @brief     Divide Tensor Element by Element\n   * @param[in] m Divisor Tensor\n   * @retval    Calculated Tensor\n   */\n  Tensor divide(Tensor const &m) const;\n\n  /**\n   * @brief     Dot Product of Tensor ( equal MxM )\n   * @param[in] m Tensor\n   * @retval    Calculated Tensor\n   */\n  Tensor dot(Tensor const &m) const;\n\n  /**\n   * @brief     Transpose Tensor\n   * @retval    Calculated Tensor\n   */\n  Tensor transpose() const;\n\n  /**\n   * @brief     sum all the Tensor elements according to the batch\n   * @retval    Calculated Tensor(batch, 1, 1)\n   */\n  Tensor sum() const;\n\n  /**\n   * @brief     sum all the Tensor elements according to the axis\n   * @retval    Calculated Tensor\n   */\n  Tensor sum(int axis) const;\n\n  /**\n   * @brief     Averaging the Tensor elements according to the batch\n   * @retval    Calculated Tensor(1, height, width)\n   */\n  Tensor average() const;\n\n  /**\n   * @brief     Softmax the Tensor elements\n   * @retval    Calculated Tensor\n   */\n  Tensor softmax() const;\n\n  /**\n   * @brief     l2norm the Tensor elements\n   * @retval    Calculated l2norm\n   */\n  float l2norm() const;\n\n  /**\n   * @brief     Normalize the Tensor elements\n   * @retval    Calculated Tensor\n   */\n  Tensor normalization() const;\n\n  /**\n   * @brief     Standardize the Tensor elements\n   * @retval    Calculated Tensor\n   */\n  Tensor standardization() const;\n\n  /**\n   * @brief     Fill the Tensor elements with zero\n   */\n  void setZero();\n\n  /**\n   * @brief     Reduce Rank ( Tensor to Vector )\n   * @retval    Saved vector\n   */\n  std::vector<float> mat2vec();\n\n  /**\n   * @brief     Apply function element by element\n   * @param[in] *function function pointer applied\n   * @retval    Tensor\n   */\n  Tensor apply(float (*function)(float)) const;\n\n  /**\n   * @brief     Apply function to Tensor\n   * @param[in] *function function pointer applied\n   * @retval    Tensor\n   */\n  Tensor apply(Tensor (*function)(Tensor)) const;\n\n  /**\n   * @brief     Print element\n   * @param[in] out out stream\n   * @retval    Tensor\n   */\n  void print(std::ostream &out) const;\n\n  /**\n   * @brief     Get Width of Tensor\n   * @retval    int Width\n   */\n  int getWidth() { return width; };\n\n  /**\n   * @brief     Get Height of Tensor\n   * @retval    int Height\n   */\n  int getHeight() { return height; };\n\n  /**\n   * @brief     Get Batch of Tensor\n   * @retval    int Batch\n   */\n  int getBatch() { return batch; };\n\n  /**\n   * @brief     Set the elelemnt value\n   * @param[in] batch batch location\n   * @param[in] i height location\n   * @param[in] j width location\n   * @param[in] value value to be stored\n   */\n  void setValue(int batch, int i, int j, float value);\n\n  /**\n   * @brief     Copy the Tensor\n   * @param[in] from Tensor to be Copyed\n   * @retval    Matix\n   */\n  Tensor &copy(Tensor const &from);\n\n  /**\n   * @brief     Save the Tensor into file\n   * @param[in] file output file stream\n   */\n  void save(std::ofstream &file);\n\n  /**\n   * @brief     Read the Tensor from file\n   * @param[in] file input file stream\n   */\n  void read(std::ifstream &file);\n\n  /**\n   * @brief     return argument index which value is max\n   * @retval    int argument index\n   */\n  int argmax();\n\n  /**\n   * @brief     return Data pointer of Tensor\n   * @retval    float pointer\n   */\n  float *getData() { return data.data(); }\n\nprivate:\n  /**< handle the data as a std::vector type */\n  std::vector<float> data;\n  int height;\n  int width;\n  int batch;\n  int ndim;\n  int len;\n};\n\n/**\n * @brief   Overriding output stream\n */\nstd::ostream &operator<<(std::ostream &out, Tensor const &m);\n\n} /* namespace nntrainer */\n\n#endif /* __cplusplus */\n#endif /* __TENSOR_H__ */\n", "meta": {"hexsha": "2dfb80db126045ada6172fd82c304e945e99e62b", "size": 7782, "ext": "h", "lang": "C", "max_stars_repo_path": "nntrainer/include/tensor.h", "max_stars_repo_name": "zhoonit/nntrainer", "max_stars_repo_head_hexsha": "3fd8368ac14c1242129edb788cbc65229f61087b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nntrainer/include/tensor.h", "max_issues_repo_name": "zhoonit/nntrainer", "max_issues_repo_head_hexsha": "3fd8368ac14c1242129edb788cbc65229f61087b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nntrainer/include/tensor.h", "max_forks_repo_name": "zhoonit/nntrainer", "max_forks_repo_head_hexsha": "3fd8368ac14c1242129edb788cbc65229f61087b", "max_forks_repo_licenses": ["Apache-2.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.0919881306, "max_line_length": 75, "alphanum_fraction": 0.6202775636, "num_tokens": 2097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.392222543406466}}
{"text": "/*\n** hemodynamic modelling for single-subject LISA\n**\n** G.Lohmann, MPI-KYB,  2018\n*/\n#include <viaio/Vlib.h>\n#include <viaio/VImage.h>\n#include <viaio/mu.h>\n#include <viaio/option.h>\n\n#include <gsl/gsl_cblas.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_spline.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n#define SQR(x) ((x)*(x))\n\n#define LEN     10000   /* buffer length        */\n#define NTRIALS 10000   /* max number of trials */\n\n/* standard parameter values for gamma function, Glover 99 */\ndouble a1 = 6;\ndouble b1 = 0.9;\ndouble a2 = 12;\ndouble b2 = 0.9;\ndouble cc = 0.35;\n\n\ntypedef struct TrialStruct {\n  int   id;\n  float onset;\n  float duration;\n  float height;\n} Trial;\n\nvoid printmat(gsl_matrix *R,char *str)\n{\n  int i,j;\n  fprintf(stderr,\" %s: \\n\",str);\n  for (i=0; i<R->size1; i++) {\n    for (j=0; j<R->size2; j++) {\n      fprintf(stderr,\" %9.6f\",gsl_matrix_get(R,i,j));\n    }\n    fprintf(stderr,\"\\n\");\n  }\n  fprintf(stderr,\"\\n\");\n}\n\nvoid tprintmat(gsl_matrix *R,char *str)\n{\n  int i,j;\n  fprintf(stderr,\" %s: \\n\",str);\n  for (i=0; i<R->size2; i++) {\n    for (j=0; j<R->size1; j++) {\n      fprintf(stderr,\" %9.6f\",gsl_matrix_get(R,j,i));\n    }\n    fprintf(stderr,\"\\n\");\n  }\n  fprintf(stderr,\"\\n\");\n}\n\nvoid printvec(gsl_vector *x,char *str)\n{\n  int i;\n  fprintf(stderr,\" %s: \\n\",str);\n  for (i=0; i<x->size; i++) {\n    fprintf(stderr,\" %f\\n\",x->data[i]);\n  }\n  fprintf(stderr,\"\\n\");\n}\n\n\n/* output txt file for plotting */\nvoid PlotDesign(gsl_matrix *X,double tr,VString filename)\n{\n  int i,j;\n  double u=0;\n\n  FILE *fp = fopen(filename,\"w\");\n  if (fp == NULL) VError(\"err opening plot file\");\n  double t = 0;\n  for (i=0; i<X->size1; i++) {\n    fprintf(fp,\" %8.2f\",t);\n    for (j=0; j<X->size2; j++) {\n      u = gsl_matrix_get(X,i,j);\n      fprintf(fp,\" %10.6f\",u);\n    }\n    t += tr;\n    fprintf(fp,\"\\n\");\n  }\n  fclose(fp);\n}\n\n\n/* create design X */\ngsl_matrix *VCreateDesign(int ntimesteps,int nevents,int hemomodel,VBoolean firstcol,gsl_matrix *covariates)\n{\n  int dim = nevents;\n  if (hemomodel == 1) dim = nevents*2;\n  if (hemomodel == 2) dim = nevents*3;\n  if (firstcol == TRUE) dim++;\n  if (covariates != NULL) dim += covariates->size2;  /* nuisance covariates without task labels */\n\n  gsl_matrix *X = gsl_matrix_calloc(ntimesteps,dim);\n  return X;\n}\n\n\n/* Glover kernel, gamma function */\ndouble xgamma(double xx, double t0) \n{\n  double x, y, scale = 20;\n  double y1, y2;\n  double d1, d2;\n  x = xx - t0;\n  if(x < 0 || x > 50)\n    return 0;\n  d1 = a1 * b1;\n  d2 = a2 * b2;\n  y1 = pow(x / d1, a1) * exp(-(x - d1) / b1);\n  y2 = pow(x / d2, a2) * exp(-(x - d2) / b2);\n  y = y1 - cc * y2;\n  y /= scale;\n  return y;\n}\n\n\n/* Glover kernel, gamma function, parameters changed for block designs */\ndouble bgamma(double xx, double t0) \n{\n  double x, y, scale = 120;\n  double y1, y2;\n  double d1, d2;\n  double aa1 = 6;\n  double bb1 = 0.9;\n  double aa2 = 12;\n  double bb2 = 0.9;\n  double cx  = 0.1;\n  x = xx - t0;\n  if(x < 0 || x > 50)\n    return 0;\n  d1 = aa1 * bb1;\n  d2 = aa2 * bb2;\n  y1 = pow(x / d1, aa1) * exp(-(x - d1) / bb1);\n  y2 = pow(x / d2, aa2) * exp(-(x - d2) / bb2);\n  y = y1 - cx * y2;\n  y /= scale;\n  return y;\n}\n\n\n/* first derivative */\ndouble deriv1_gamma(double x, double t0) \n{\n  double d1, d2, y1, y2, y, xx;\n  double scale = 20.0;\n  xx = x - t0;\n  if(xx < 0 || xx > 50) return 0;\n  d1 = a1 * b1;\n  d2 = a2 * b2;\n  y1 = pow(d1, -a1) * a1 * pow(xx, (a1 - 1.0)) * exp(-(xx - d1) / b1)\n    - (pow((xx / d1), a1) * exp(-(xx - d1) / b1)) / b1;\n  y2 = pow(d2, -a2) * a2 * pow(xx, (a2 - 1.0)) * exp(-(xx - d2) / b2)\n    - (pow((xx / d2), a2) * exp(-(xx - d2) / b2)) / b2;\n  y = y1 - cc * y2;\n  y /= scale;\n  return y;\n}\n\n\n/* second derivative */\ndouble deriv2_gamma(double x, double t0) \n{\n  double d1, d2, y1, y2, y3, y4, y, xx;\n  double scale = 20.0;\n  xx = x - t0;\n  if (xx < 0 || xx > 50) return 0;\n  d1 = a1 * b1;\n  d2 = a2 * b2;\n  y1 = pow(d1, -a1) * a1 * (a1 - 1) * pow(xx, a1 - 2) * exp(-(xx - d1) / b1)\n    - pow(d1, -a1) * a1 * pow(xx, (a1 - 1)) * exp(-(xx - d1) / b1) / b1;\n  y2 = pow(d1, -a1) * a1 * pow(xx, a1 - 1) * exp(-(xx - d1) / b1) / b1\n    - pow((xx / d1), a1) * exp(-(xx - d1) / b1) / (b1 * b1);\n  y1 = y1 - y2;\n  y3 = pow(d2, -a2) * a2 * (a2 - 1) * pow(xx, a2 - 2) * exp(-(xx - d2) / b2)\n    - pow(d2, -a2) * a2 * pow(xx, (a2 - 1)) * exp(-(xx - d2) / b2) / b2;\n  y4 = pow(d2, -a2) * a2 * pow(xx, a2 - 1) * exp(-(xx - d2) / b2) / b2\n    - pow((xx / d2), a2) * exp(-(xx - d2) / b2) / (b2 * b2);\n  y2 = y3 - y4;\n  y = y1 - cc * y2;\n  y /= scale;\n  return y;\n}\n\n\n\n/* Gaussian function */\ndouble xgauss(double xx, double t0) \n{\n  double sigma=1.0;\n  double x, y, z, a = 2.506628273;\n  x = (xx - t0);\n  z = x / sigma;\n  y = exp(-0.5*z*z) / (sigma * a);\n  return y;\n}\n\n\n\nvoid XConvolve(double *src,double *dst,double *kernel,int nt,int kernelsize)\n{\n  int i,j,jj,k;\n  double sum=0;\n\n  for (i=0; i<nt; i++) {\n    sum = 0;\n    k=0;\n    for (j=i; j<i+kernelsize; j++) {\n      jj = i-k;\n      if (jj >= 0 && jj < nt) {\n\tsum += src[jj] * kernel[k];\n      }\n      k++;\n    }\n    dst[i] = sum;\n  }\n}\n\n\n/* hemodynamic modelling at high temporal resolution */\nvoid VHemoModel(Trial *trial,int ntrials,int nevents,int nt,double xtr,int hemomodel,VBoolean firstcol,\n\t\tgsl_matrix *X,gsl_matrix *covariates)\n{\n  int i,j,jj,k;\n  double t,t0,t1,h;\n\n  \n  /* set temporal resolution to 0.5 sec, reduce discretization artefacts */\n  double hfactor = floor(xtr/0.5);\n  if (hfactor < 1.0) hfactor = 1.0;\n\n  double tr = xtr/hfactor;\n  int jfactor = (int)hfactor;\n  int ntimesteps = jfactor*nt;\n\n  for(i = 0; i < nevents; i++) {\n    double xmin = VRepnMaxValue(VFloatRepn);\n    for(j = 0; j < ntrials; j++) {\n      if(trial[j].id != i) continue;\n      if(trial[j].duration < xmin) xmin = trial[j].duration;\n    }\n  }\n\n\n  /* get kernels */\n  t1 = 30.0;    /* kernel duration = 30 secs */\n  int kernelsize = t1 / tr;\n  if (tr < 0.01) VWarning(\" implausible TR (%f seconds)\",tr);\n\n  /* fprintf(stderr,\" hf= %f,  tr= %f  %f, kernelsize: %d\\n\",hfactor,xtr,tr,kernelsize); */\n  \n  double *kernel1=NULL,*kernel2=NULL;\n  double *bkernel  = (double *)VCalloc(kernelsize,sizeof(double));\n  double *kernel0  = (double *)VCalloc(kernelsize,sizeof(double));\n  if (hemomodel == 1 || hemomodel == 2) {\n    kernel1 = (double *)VCalloc(kernelsize,sizeof(double));\n  }\n  if (hemomodel == 2) {\n    kernel2 = (double *)VCalloc(kernelsize,sizeof(double));\n  }\n\n  i = 0;\n  for (t = 0; t < t1; t += tr) {\n    if (i >= kernelsize) break;\n\n    bkernel[i] = xgauss(t, 5.0*tr);\n    kernel0[i] = xgamma(t, 0.0);\n\n    if(hemomodel == 1 || hemomodel == 2)\n      kernel1[i] = deriv1_gamma(t, 0);\n    if(hemomodel == 2)\n      kernel2[i] = deriv2_gamma(t, 0);\n    i++;\n  }\n\n  \n  /* tmp storage */\n  double *x = (double *) VCalloc(ntimesteps,sizeof(double));\n  double *y = (double *) VCalloc(ntimesteps,sizeof(double));\n\n\n  /* constant in column 0 */\n  int col=0;\n  if (firstcol == TRUE) {\n    gsl_matrix_set_zero(X);\n    for (j=0; j<nt; j++) gsl_matrix_set(X,j,0,1.0);\n    col=1;\n  }\n  \n  \n  /* for each trial,event, do... */  \n  for (i = 0; i < nevents; i++) {\n    for (k=0; k<ntimesteps; k++) x[k] = y[k] = 0;\n\n    /* read design info */\n    int trialcount = 0;\n    for (j = 0; j < ntrials; j++) {\n      if(trial[j].id != i+1) continue;\n      trialcount++;\n      t0 = trial[j].onset;\n      t1 = trial[j].onset + trial[j].duration;\n      h  = trial[j].height;\n      int k0 = (int) (t0/tr + 0.5);\n      int k1 = (int) (t1/tr + 0.5);\n      \n      int klen=0;\n      for (k=k0; k<=k1; k++) {\n\tif (k < 0 || k >= ntimesteps) continue;\n\tx[k] = h;\n\tklen++;\n      }\n      if(trialcount < 1)\n\tVError(\" no trials in event %d, please re-number event-ids,  ntrials= %d\", i + 1,ntrials);\n    }\n\n    /* convolve */\n    if (hemomodel == 3)  {       /* block design, gaussian kernel */\n      XConvolve(x,y,bkernel,ntimesteps,kernelsize);\n    }\n    else {                       /* gamma function kernel */\n      XConvolve(x,y,kernel0,ntimesteps,kernelsize);\n    }\n\n    for (j=0; j<X->size1; j++) {\n      jj = j*jfactor;\n      if (jj >= ntimesteps) continue;\n      gsl_matrix_set(X,j,col,y[jj]/hfactor);\n    }\n    col++;\n\n    if (hemomodel == 1 || hemomodel == 2) {   /* gamma function kernel, first derivative */\n      XConvolve(x,y,kernel1,ntimesteps,kernelsize);\n      for (j=0; j<X->size1; j++) {\n\tjj = j*jfactor;\n\tif (jj >= ntimesteps) continue;\n\tgsl_matrix_set(X,j,col,y[jj]/hfactor);\n      }\n      col++;\n    }\n    if (hemomodel == 2) {   /* gamma function kernel, second derivative */\n      XConvolve(x,y,kernel2,ntimesteps,kernelsize);\n      for (j=0; j<X->size1; j++) {\n\tjj = j*jfactor;\n\tif (jj >= ntimesteps) continue;\n\tgsl_matrix_set(X,j,col,y[jj]/hfactor);\n      }\n      col++;\n    }\n  }\n  \n  /* add further covariates that have no task labels, will not be permuted */\n  if (covariates != NULL) {\n    for (i=0; i<covariates->size2; i++) {\n      for (j=0; j<covariates->size1; j++) {\n\tif (col >= X->size2) VError(\" VHemoModel, column= %d  %d\\n\",col,(int)X->size2);\n\tgsl_matrix_set(X,j,col,gsl_matrix_get(covariates,j,i));\n      }\n      col++;\n    }\n  }\n  \n  /* cleanup */\n  VFree(x);\n  VFree(y);\n  VFree(kernel0);\n  VFree(bkernel);\n  if (kernel1 != NULL) VFree(kernel1);\n  if (kernel2 != NULL) VFree(kernel2);\n}\n", "meta": {"hexsha": "cd7ef5c54f31639c903ba58c8d1774cd3a2db863", "size": 9402, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_prewhitening/HemoModel.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_prewhitening/HemoModel.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_prewhitening/HemoModel.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 24.1076923077, "max_line_length": 108, "alphanum_fraction": 0.5509466071, "num_tokens": 3513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3922066254281203}}
{"text": "//Causal FIR filtering of each vector in X along dim.\n//FIR impulse response is given in vector B with length Q+1.\n//(I use P for IIR filter order, since same as polynomial order.)\n\n#include <stdio.h>\n#include <math.h>\n#include <cblas.h>\n\n#ifdef __cplusplus\nnamespace codee {\nextern \"C\" {\n#endif\n\nint fir_s (float *Y, const float *X, const float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim);\nint fir_d (double *Y, const double *X, const double *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim);\nint fir_c (float *Y, const float *X, const float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim);\nint fir_z (double *Y, const double *X, const double *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim);\n\n\nint fir_s (float *Y, const float *X, const float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim)\n{\n    if (dim>3u) { fprintf(stderr,\"error in fir_s: dim must be in [0 3]\\n\"); return 1; }\n\n    const size_t N = R*C*S*H;\n    const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n\n    //Initialize Y\n    float b = *B++;\n    for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = b * *X; }\n    X -= N; Y -= N - 1u;\n\n    if (N==0u || L==1u || Q==0u) {}\n    else if (L==N)\n    {\n        if (L<30000u)\n        {\n            for (size_t q=1u; q<=Q; ++q, ++B, X-=L-q+1u, Y-=L-q)\n            {\n                b = *B;\n                for (size_t l=q; l<L; ++l, ++X, ++Y) { *Y = fmaf(b,*X,*Y); }\n            }\n        }\n        else\n        {\n            for (size_t q=1u; q<=Q; ++q, ++B, ++Y) { cblas_saxpy((int)(L-q),*B,X,1,Y,1); }\n        }\n    }\n    else\n    {\n        const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n        const size_t BS = (iscolmajor && dim==0u) ? C*S*H : K;\n        const size_t V = N/L, G = V/BS;\n\n        if (K==1u && (G==1u || BS==1u))\n        {\n            if (L<30000u)\n            {\n                for (size_t v=V; v>0u; --v, B-=Q, X+=Q, ++Y)\n                {\n                    for (size_t q=1u; q<=Q; ++q, ++B)\n                    {\n                        b = *B;\n                        for (size_t l=q; l<L; ++l, ++X, ++Y) { *Y = fmaf(b,*X,*Y); }\n                        if (q<Q) { X -= L-q; Y -= L-q-1u; }\n                    }\n                }\n            }\n            else\n            {\n                for (size_t v=V; v>0u; --v, B-=Q, X+=L, Y+=L-Q)\n                {\n                    for (size_t q=1u; q<=Q; ++q, ++B, ++Y) { cblas_saxpy((int)(L-q),*B,X,1,Y,1); }\n                }\n            }\n        }\n        else\n        {\n            Y += K - 1u;\n            for (size_t g=G; g>0u; --g, X+=BS*(L-1u), Y+=BS*(L-1u))\n            {\n                for (size_t bs=BS; bs>0u; --bs, ++X, B-=Q, Y-=K*Q-1u)\n                {\n                    for (size_t q=1u; q<=Q; ++q, ++B, Y+=K) { cblas_saxpy((int)(L-q),*B,X,(int)K,Y,(int)K); }\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n\n\nint fir_d (double *Y, const double *X, const double *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim)\n{\n    if (dim>3u) { fprintf(stderr,\"error in fir_d: dim must be in [0 3]\\n\"); return 1; }\n\n    const size_t N = R*C*S*H;\n    const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n\n    //Initialize Y\n    double b = *B++;\n    for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = b * *X; }\n    X -= N; Y -= N - 1u;\n\n    if (N==0u || L==1u || Q==0u) {}\n    else if (L==N)\n    {\n        if (L<30000u)\n        {\n            for (size_t q=1u; q<=Q; ++q, ++B, X-=L-q+1u, Y-=L-q)\n            {\n                b = *B;\n                for (size_t l=q; l<L; ++l, ++X, ++Y) { *Y = fma(b,*X,*Y); }\n            }\n        }\n        else\n        {\n            for (size_t q=1u; q<=Q; ++q, ++B, ++Y) { cblas_daxpy((int)(L-q),*B,X,1,Y,1); }\n        }\n    }\n    else\n    {\n        const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n        const size_t BS = (iscolmajor && dim==0u) ? C*S*H : K;\n        const size_t V = N/L, G = V/BS;\n\n        if (K==1u && (G==1u || BS==1u))\n        {\n            if (L<30000u)\n            {\n                for (size_t v=V; v>0u; --v, B-=Q, X+=Q, ++Y)\n                {\n                    for (size_t q=1u; q<=Q; ++q, ++B)\n                    {\n                        b = *B;\n                        for (size_t l=q; l<L; ++l, ++X, ++Y) { *Y = fma(b,*X,*Y); }\n                        if (q<Q) { X -= L-q; Y -= L-q-1u; }\n                    }\n                }\n            }\n            else\n            {\n                for (size_t v=V; v>0u; --v, B-=Q, X+=L, Y+=L-Q)\n                {\n                    for (size_t q=1u; q<=Q; ++q, ++B, ++Y) { cblas_daxpy((int)(L-q),*B,X,1,Y,1); }\n                }\n            }\n        }\n        else\n        {\n            Y += K - 1u;\n            for (size_t g=G; g>0u; --g, X+=BS*(L-1u), Y+=BS*(L-1u))\n            {\n                for (size_t bs=BS; bs>0u; --bs, ++X, B-=Q, Y-=K*Q-1u)\n                {\n                    for (size_t q=1u; q<=Q; ++q, ++B, Y+=K) { cblas_daxpy((int)(L-q),*B,X,(int)K,Y,(int)K); }\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n\n\nint fir_c (float *Y, const float *X, const float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim)\n{\n    if (dim>3u) { fprintf(stderr,\"error in fir_c: dim must be in [0 3]\\n\"); return 1; }\n\n    const size_t N = R*C*S*H;\n    const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n    float xr, xi, br, bi;\n\n    //Initialize Y\n    br = *B++; bi = *B++;\n    for (size_t n=N; n>0u; --n)\n    {\n        xr = *X++; xi = *X++;\n        *Y++ = br*xr - bi*xi;\n        *Y++ = br*xi + bi*xr;\n    }\n    X -= 2u*N; Y -= 2u*N - 2u;\n\n    if (N==0u || L==1u || Q==0u) {}\n    else if (L==N)\n    {\n        if (L<30000u)\n        {\n            for (size_t q=1u; q<=Q; ++q, X-=2u*(L-q+1u), Y-=2u*(L-q))\n            {\n                br = *B++; bi = *B++;\n                for (size_t l=q; l<L; ++l)\n                {\n                    xr = *X++; xi = *X++;\n                    *Y++ += br*xr - bi*xi;\n                    *Y++ += br*xi + bi*xr;\n                }\n            }\n        }\n        else\n        {\n            for (size_t q=1u; q<=Q; ++q, B+=2u, Y+=2u) { cblas_caxpy((int)(L-q),B,X,1,Y,1); }\n        }\n    }\n    else\n    {\n        const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n        const size_t BS = (iscolmajor && dim==0u) ? C*S*H : K;\n        const size_t V = N/L, G = V/BS;\n\n        if (K==1u && (G==1u || BS==1u))\n        {\n            if (L<30000u)\n            {\n                for (size_t v=V; v>0u; --v, B-=2u*Q, X+=2u*Q, Y+=2u)\n                {\n                    for (size_t q=1u; q<=Q; ++q)\n                    {\n                        br = *B++; bi = *B++;\n                        for (size_t l=q; l<L; ++l)\n                        {\n                            xr = *X++; xi = *X++;\n                            *Y++ += br*xr - bi*xi;\n                            *Y++ += br*xi + bi*xr;\n                        }\n                        if (q<Q) { X -= 2u*(L-q); Y -= 2u*(L-q-1u); }\n                    }\n                }\n            }\n            else\n            {\n                for (size_t v=V; v>0u; --v, X+=2u*L, B-=2u*Q, Y+=2u*(L-Q-1u))\n                {\n                    for (size_t q=0u; q<=Q; ++q, B+=2u, Y+=2u) { cblas_caxpy((int)(L-q),B,X,1,Y,1); }\n                }\n            }\n        }\n        else\n        {\n            Y += 2u*K - 2u;\n            for (size_t g=G; g>0u; --g, X+=2u*BS*(L-1u), Y+=2u*BS*(L-1u))\n            {\n                for (size_t bs=BS; bs>0u; --bs, X+=2u, B-=2u*Q, Y-=2u*K*Q-2u)\n                {\n                    for (size_t q=1u; q<=Q; ++q, B+=2u, Y+=2u*K) { cblas_caxpy((int)(L-q),B,X,(int)K,Y,(int)K); }\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n\n\nint fir_z (double *Y, const double *X, const double *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim)\n{\n    if (dim>3u) { fprintf(stderr,\"error in fir_z: dim must be in [0 3]\\n\"); return 1; }\n\n    const size_t N = R*C*S*H;\n    const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;\n    double xr, xi, br, bi;\n\n    //Initialize Y\n    br = *B++; bi = *B++;\n    for (size_t n=N; n>0u; --n)\n    {\n        xr = *X++; xi = *X++;\n        *Y++ = br*xr - bi*xi;\n        *Y++ = br*xi + bi*xr;\n    }\n    X -= 2u*N; Y -= 2u*N - 2u;\n\n    if (N==0u || L==1u || Q==0u) {}\n    else if (L==N)\n    {\n        if (L<30000u)\n        {\n            for (size_t q=1u; q<=Q; ++q, X-=2u*(L-q+1u), Y-=2u*(L-q))\n            {\n                br = *B++; bi = *B++;\n                for (size_t l=q; l<L; ++l)\n                {\n                    xr = *X++; xi = *X++;\n                    *Y++ += br*xr - bi*xi;\n                    *Y++ += br*xi + bi*xr;\n                }\n            }\n        }\n        else\n        {\n            for (size_t q=1u; q<=Q; ++q, B+=2u, Y+=2u) { cblas_zaxpy((int)(L-q),B,X,1,Y,1); }\n        }\n    }\n    else\n    {\n        const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);\n        const size_t BS = (iscolmajor && dim==0u) ? C*S*H : K;\n        const size_t V = N/L, G = V/BS;\n\n        if (K==1u && (G==1u || BS==1u))\n        {\n            if (L<30000u)\n            {\n                for (size_t v=V; v>0u; --v, B-=2u*Q, X+=2u*Q, Y+=2u)\n                {\n                    for (size_t q=1u; q<=Q; ++q)\n                    {\n                        br = *B++; bi = *B++;\n                        for (size_t l=q; l<L; ++l)\n                        {\n                            xr = *X++; xi = *X++;\n                            *Y++ += br*xr - bi*xi;\n                            *Y++ += br*xi + bi*xr;\n                        }\n                        if (q<Q) { X -= 2u*(L-q); Y -= 2u*(L-q-1u); }\n                    }\n                }\n            }\n            else\n            {\n                for (size_t v=V; v>0u; --v, X+=2u*L, B-=2u*Q, Y+=2u*(L-Q-1u))\n                {\n                    for (size_t q=0u; q<=Q; ++q, B+=2u, Y+=2u) { cblas_zaxpy((int)(L-q),B,X,1,Y,1); }\n                }\n            }\n        }\n        else\n        {\n            Y += 2u*K - 2u;\n            for (size_t g=G; g>0u; --g, X+=2u*BS*(L-1u), Y+=2u*BS*(L-1u))\n            {\n                for (size_t bs=BS; bs>0u; --bs, X+=2u, B-=2u*Q, Y-=2u*K*Q-2u)\n                {\n                    for (size_t q=1u; q<=Q; ++q, B+=2u, Y+=2u*K) { cblas_zaxpy((int)(L-q),B,X,(int)K,Y,(int)K); }\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n\n\n#ifdef __cplusplus\n}\n}\n#endif\n", "meta": {"hexsha": "7ce699d308320e9219dd92e4ecc35104e6bb5362", "size": 11329, "ext": "c", "lang": "C", "max_stars_repo_path": "c/fir.c", "max_stars_repo_name": "erikedwards4/dsp", "max_stars_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:22:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:22:40.000Z", "max_issues_repo_path": "c/fir.c", "max_issues_repo_name": "erikedwards4/dsp", "max_issues_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/fir.c", "max_forks_repo_name": "erikedwards4/dsp", "max_forks_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-05T13:50:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T13:50:32.000Z", "avg_line_length": 32.5545977011, "max_line_length": 176, "alphanum_fraction": 0.3652573043, "num_tokens": 4114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3920874904722492}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_sf_bessel.h>\n\nint\nmain (void)\n{\n  double x = 5.0;\n  double y = gsl_sf_bessel_J0 (x);\n  printf (\"J0(%g) = %.18e\\n\", x, y);\n  return 0;\n}\n", "meta": {"hexsha": "bd2848271477d2a12511abc2bebaa3897438b51e", "size": 173, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/intro.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/intro.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/intro.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 14.4166666667, "max_line_length": 36, "alphanum_fraction": 0.5953757225, "num_tokens": 69, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.3920314896779787}}
{"text": "/* statistics/test.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <string.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_test.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_sort_vector.h>\n#include <gsl/gsl_statistics.h>\n#include <gsl/gsl_ieee_utils.h>\n\nint test_nist (void);\n\n/* Test program for mean.c.  JimDavies 7.96 */\n\n#define BASE_LONG_DOUBLE\n#include \"templates_on.h\"\n#include \"test_float_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG_DOUBLE\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"test_float_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"test_float_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_FLOAT\n\n#define BASE_ULONG\n#include \"templates_on.h\"\n#include \"test_int_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_ULONG\n\n#define BASE_LONG\n#include \"templates_on.h\"\n#include \"test_int_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG\n\n#define BASE_UINT\n#include \"templates_on.h\"\n#include \"test_int_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UINT\n\n#define BASE_INT\n#include \"templates_on.h\"\n#include \"test_int_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_INT\n\n#define BASE_USHORT\n#include \"templates_on.h\"\n#include \"test_int_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_USHORT\n\n#define BASE_SHORT\n#include \"templates_on.h\"\n#include \"test_int_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_SHORT\n\n#define BASE_UCHAR\n#include \"templates_on.h\"\n#include \"test_int_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UCHAR\n\n#define BASE_CHAR\n#include \"templates_on.h\"\n#include \"test_int_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_CHAR\n\n\nint\nmain (void)\n{\n  size_t s1, s2;\n\n  gsl_ieee_env_setup ();\n\n  for (s1 = 1; s1 < 4 ; s1++) \n    {\n      s2 = (s1 < 3) ? 1 : (s1 - 1) ;\n\n      test_func (s1,s2);\n      test_float_func (s1,s2);\n      test_long_double_func (s1,s2);\n      \n      test_ulong_func (s1,s2);\n      test_long_func (s1,s2);\n      test_uint_func (s1,s2);\n      test_int_func (s1,s2);\n      test_ushort_func (s1,s2);\n      test_short_func (s1,s2);\n      test_uchar_func (s1,s2);\n      test_char_func (s1,s2);\n    }\n\n  test_nist();\n\n  exit (gsl_test_summary ());\n}\n\n", "meta": {"hexsha": "800fac4866e95dca67a60b2264ef06566e437e08", "size": 3031, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/statistics/test.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/statistics/test.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/statistics/test.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 22.7894736842, "max_line_length": 81, "alphanum_fraction": 0.7228637413, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3919418862604871}}
{"text": "/*\nBallistic: a software to benchmark ballistic models.\n\nAUTHORS: Javier Burguete Tolosa.\n\nCopyright 2018, AUTHORS.\n\nRedistribution and use in source and binary forms, with or without modification,\nare 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\n    documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\nIN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\nOF SUCH DAMAGE.\n*/\n\n/**\n * \\file utils.c\n * \\brief Source file with the useful data and functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2018.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include \"config.h\"\n#include \"equation.h\"\n\n#define DEBUG_UTILS 0           ///< macro to debug the useful functions.\n\nchar *error_message = NULL;     ///< error message string.\n\n/**\n * Function to add an error message.\n */\nvoid\nerror_add (const char *message) ///< error message.\n{\n\tchar *buffer;\n  buffer = error_message;\n  error_message = (char *) g_strconcat (message, \"\\n\", buffer, NULL);\n  g_free (buffer);\n}\n\n/**\n * Function to calculate the distance between two vectors.\n *\n * \\return vectors distance.\n */\nlong double\ndistance (long double *r1,      ///< 1st vector.\n          long double *r2)      ///< 2nd vector.\n{\n  long double d, dr[3];\n#if DEBUG_EQUATION\n  fprintf (stderr, \"distance: start\\n\");\n  fprintf (stderr, \"distance: x1=%Lg y1=%Lg z1=%Lg\\n\", r1[0], r1[1], r1[2]);\n  fprintf (stderr, \"distance: x2=%Lg y2=%Lg z2=%Lg\\n\", r2[0], r2[1], r2[2]);\n#endif\n  dr[0] = r1[0] - r2[0];\n  dr[1] = r1[1] - r2[1];\n  dr[2] = r1[2] - r2[2];\n  d = sqrtl (dr[0] * dr[0] + dr[1] * dr[1] + dr[2] * dr[2]);\n#if DEBUG_EQUATION\n  fprintf (stderr, \"distance: d=%Lg\\n\", d);\n  fprintf (stderr, \"distance: end\\n\");\n#endif\n  return d;\n}\n\n/**\n * Function to calculate the solution of a reduced 2nd order equation.\n *\n * This function calculates the solution of a reduced 2nd order equation in the\n * form:\n * \\f[x^2+a\\,x+b=0\\f]\n * in the interval \\f$x\\in\\left[x_1,\\;x_2\\right]\\f$.\n *\n * \\return solution value. If the equation can not be solved or the solution is\n * not in the interval the value is undetermined.\n */\nlong double\nsolve_quadratic_reduced (long double a, ///< a equation coefficient.\n                         long double b, ///< b equation coefficient.\n                         long double x1,        ///< lower solution limit.\n                         long double x2)        ///< higher solution limit.\n{\n  long double a2, k, x;\n#if DEBUG_EQUATION\n  fprintf (stderr, \"solve_quadratic_reduced: start\\n\");\n  fprintf (stderr, \"solve_quadratic_reduced: a=%Lg b=%Lg\\n\", a, b);\n  fprintf (stderr, \"solve_quadratic_reduced: x1=%Lg x2=%Lg\\n\", x1, x2);\n#endif\n  a2 = -0.5L * a;\n  k = sqrtl (a2 * a2 - b);\n  x = a2 + k;\n  if (x < x1 || x > x2)\n    x = a2 - k;\n#if DEBUG_EQUATION\n  fprintf (stderr, \"solve_quadratic_reduced: x=%Lg\\n\", x);\n  fprintf (stderr, \"solve_quadratic_reduced: end\\n\");\n#endif\n  return x;\n}\n\n/**\n * Function to calculate the solution of a 2nd order equation.\n *\n * This function calculates the solution of a 2nd order equation in the\n * form:\n * \\f[a\\,x^2+b\\,x+c=0\\f]\n * in the interval \\f$x\\in\\left[x_1,\\;x_2\\right]\\f$.\n *\n * \\return solution value. If the equation can not be solved or the solution is\n * not in the interval the value is undetermined.\n */\nlong double\nsolve_quadratic (long double a, ///< a equation coefficient.\n                 long double b, ///< b equation coefficient.\n                 long double c, ///< c equation coefficient.\n                 long double x1,        ///< lower solution limit.\n                 long double x2)        ///< higher solution limit.\n{\n  long double x;\n#if DEBUG_EQUATION\n  fprintf (stderr, \"solve_quadratic: start\\n\");\n  fprintf (stderr, \"solve_quadratic: a=%Lg b=%Lg c=%Lg\\n\", a, b, c);\n  fprintf (stderr, \"solve_quadratic: x1=%Lg x2=%Lg\\n\", x1, x2);\n#endif\n  if (a == 0.L)\n    x = -c / b;\n  else\n    x = solve_quadratic_reduced (b / a, c / a, x1, x2);\n#if DEBUG_EQUATION\n  fprintf (stderr, \"solve_quadratic: x=%Lg\\n\", x);\n  fprintf (stderr, \"solve_quadratic: end\\n\");\n#endif\n  return x;\n}\n\n/**\n * Function to calculate the solution of a reduced 3rd order equation.\n *\n * This function calculates the solution of a reduced 3rd order equation in the\n * form:\n * \\f[x^3+a\\,x^2+b\\,x+c=0\\f]\n * in the interval \\f$x\\in\\left[x_1,\\;x_2\\right]\\f$.\n *\n * \\return solution value. If the equation can not be solved or the solution is\n * not in the interval the value is undetermined.\n */\nlong double\nsolve_cubic_reduced (long double a,     ///< a equation coefficient.\n                     long double b,     ///< b equation coefficient.\n                     long double c,     ///< c equation coefficient.\n                     long double x1,    ///< lower solution limit.\n                     long double x2)    ///< higher solution limit.\n{\n  long double k0, k1, k2;\n#if DEBUG_EQUATION\n  fprintf (stderr, \"solve_cubic_reduced: start\\n\");\n  fprintf (stderr, \"solve_cubic_reduced: a=%Lg b=%Lg c=%Lg\\n\", a, b, c);\n  fprintf (stderr, \"solve_cubic_reduced: x1=%Lg x2=%Lg\\n\", x1, x2);\n#endif\n  a /= 3.L;\n  k0 = a * a;\n  k1 = b / 3.L - k0;\n  k0 = (b * a - c) / 2.L - a * k0;\n  k2 = k1 * k1 * k1 + k0 * k0;\n  if (k2 < 0.L)\n    {\n      k1 = sqrtl (-k1);\n      k0 = acosl (k0 / (k1 * k1 * k1)) / 3.L;\n      k1 *= 2.L;\n      k2 = k1 * cosl (k0) - a;\n      if (k2 < x1 || k2 > x2)\n        {\n          k2 = k1 * cosl (k0 + 2.L * M_PIl / 3.L) - a;\n          if (k2 < x1 || k2 > x2)\n            k2 = k1 * cosl (k0 - 2.L * M_PIl / 3.L) - a;\n        }\n    }\n  else\n    {\n      k1 = sqrtl (k2);\n      k2 = k0 + k1;\n      k2 = cbrtl (k2);\n      k0 -= k1;\n      k2 += cbrtl (k0);\n      k2 -= a;\n    }\n#if DEBUG_EQUATION\n  fprintf (stderr, \"solve_cubic_reduced: x=%Lg\\n\", k2);\n  fprintf (stderr, \"solve_cubic_reduced: end\\n\");\n#endif\n  return k2;\n}\n\n/**\n * Function to calculate the solution of a 3rd order equation.\n *\n * This function calculates the solution of a 3rd order equation in the\n * form:\n * \\f[a\\,x^3+b\\,x^2+c\\,x+d=0\\f]\n * in the interval \\f$x\\in\\left[x_1,\\;x_2\\right]\\f$.\n *\n * \\return solution value. If the equation can not be solved or the solution is\n * not in the interval the value is undetermined.\n */\nlong double\nsolve_cubic (long double a,     ///< a equation coefficient.\n             long double b,     ///< b equation coefficient.\n             long double c,     ///< c equation coefficient.\n             long double d,     ///< d equation coefficient.\n             long double x1,    ///< lower solution limit.\n             long double x2)    ///< higher solution limit.\n{\n  long double x;\n#if DEBUG_EQUATION\n  fprintf (stderr, \"solve_cubic: start\\n\");\n  fprintf (stderr, \"solve_cubic: a=%Lg b=%Lg c=%Lg d=%Lg\\n\", a, b, c, d);\n  fprintf (stderr, \"solve_cubic: x1=%Lg x2=%Lg\\n\", x1, x2);\n#endif\n  if (a == 0.L)\n    x = solve_quadratic (b, c, d, x1, x2);\n  else\n    x = solve_cubic_reduced (b / a, c / a, d / a, x1, x2);\n#if DEBUG_EQUATION\n  fprintf (stderr, \"solve_cubic: x=%Lg\\n\", x);\n  fprintf (stderr, \"solve_cubic: end\\n\");\n#endif\n  return x;\n}\n\n/**\n * Function to get an integer number of a XML node property.\n *\n * \\return Integer number value.\n */\nint\nxml_node_get_int (xmlNode * node,       ///< XML node.\n                  const xmlChar * prop, ///< XML property.\n                  int *error_code)      ///< Error code.\n{\n  int i = 0;\n  xmlChar *buffer;\n  buffer = xmlGetProp (node, prop);\n  if (!buffer)\n    *error_code = 1;\n  else\n    {\n      if (sscanf ((char *) buffer, \"%d\", &i) != 1)\n        *error_code = 2;\n      else\n        *error_code = 0;\n      xmlFree (buffer);\n    }\n  return i;\n}\n\n/**\n * Function to get an unsigned integer number of a XML node property.\n *\n * \\return Unsigned integer number value.\n */\nunsigned int\nxml_node_get_uint (xmlNode * node,      ///< XML node.\n                   const xmlChar * prop,        ///< XML property.\n                   int *error_code)     ///< Error code.\n{\n  unsigned int i = 0;\n  xmlChar *buffer;\n  buffer = xmlGetProp (node, prop);\n  if (!buffer)\n    *error_code = 1;\n  else\n    {\n      if (sscanf ((char *) buffer, \"%u\", &i) != 1)\n        *error_code = 2;\n      else\n        *error_code = 0;\n      xmlFree (buffer);\n    }\n  return i;\n}\n\n/**\n * Function to get an unsigned integer number of a XML node property with a\n *   default value.\n *\n * \\return Unsigned integer number value.\n */\nunsigned int\nxml_node_get_uint_with_default (xmlNode * node, ///< XML node.\n                                const xmlChar * prop,   ///< XML property.\n                                unsigned int default_value,\n                                ///< default value.\n                                int *error_code)        ///< Error code.\n{\n  unsigned int i;\n  if (xmlHasProp (node, prop))\n    i = xml_node_get_uint (node, prop, error_code);\n  else\n    {\n      i = default_value;\n      *error_code = 0;\n    }\n  return i;\n}\n\n/**\n * Function to get a floating point number of a XML node property.\n *\n * \\return Floating point number value.\n */\nlong double\nxml_node_get_float (xmlNode * node,     ///< XML node.\n                    const xmlChar * prop,       ///< XML property.\n                    int *error_code)    ///< Error code.\n{\n  long double x = 0.L;\n  xmlChar *buffer;\n  buffer = xmlGetProp (node, prop);\n  if (!buffer)\n    *error_code = 1;\n  else\n    {\n      if (sscanf ((char *) buffer, \"%Lf\", &x) != 1)\n        *error_code = 2;\n      else\n        *error_code = 0;\n      xmlFree (buffer);\n    }\n  return x;\n}\n\n/**\n * Function to get a floating point number of a XML node property with a \n *   default value.\n *\n * \\return Floating point number value.\n */\nlong double\nxml_node_get_float_with_default (xmlNode * node,        ///< XML node.\n                                 const xmlChar * prop,  ///< XML property.\n                                 long double default_value,\n                                 ///< default value.\n                                 int *error_code)       ///< Error code.\n{\n  long double x;\n  if (xmlHasProp (node, prop))\n    x = xml_node_get_float (node, prop, error_code);\n  else\n    {\n      x = default_value;\n      *error_code = 0;\n    }\n  return x;\n}\n", "meta": {"hexsha": "90ec7774bb2f40bedf6db0f0f2b8dbab8028b5e8", "size": 11144, "ext": "c", "lang": "C", "max_stars_repo_path": "1.1.0/utils.c", "max_stars_repo_name": "jburguete/ballistic", "max_stars_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-02T14:03:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-02T14:03:09.000Z", "max_issues_repo_path": "1.1.0/utils.c", "max_issues_repo_name": "jburguete/ballistic", "max_issues_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1.1.0/utils.c", "max_forks_repo_name": "jburguete/ballistic", "max_forks_repo_head_hexsha": "e557bce6e63bb667f1e698cff6e68013bb4e5e6f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-24T07:19:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-24T07:19:47.000Z", "avg_line_length": 29.5596816976, "max_line_length": 80, "alphanum_fraction": 0.5987975592, "num_tokens": 3198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.391829913751738}}
{"text": "//\n// Created by david on 2018-11-30.\n//\n\n#ifndef DMRG_CLASS_XDMRG_FULL_FUNCTOR_H\n#define DMRG_CLASS_XDMRG_FULL_FUNCTOR_H\n#ifdef OpenMP_AVAILABLE\n#include <omp.h>\n#endif\n\n#ifdef OpenBLAS_AVAILABLE\n#include <cblas.h>\n#endif\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/CXX11/Tensor>\n#include <general/nmspc_tensor_extra.h>\n#include <general/class_tic_toc.h>\ntemplate<typename Scalar>\nclass class_xDMRG_full_functor {\nprivate:\n    double variance;\n    double energy  ;\n    double energy_lower_bound;\n    double energy_upper_bound;\n    double energy_target;\n    double energy_window;\npublic:\n    template <typename T>\n    int sgn(const T val) const {\n        return (T(0) < val) - (val < T(0));\n    }\n\n    using MatrixType_ = Eigen::Matrix<Scalar,Eigen::Dynamic, Eigen::Dynamic>;\n    using VectorType_ = Eigen::Matrix<Scalar,Eigen::Dynamic, 1>;\n    size_t   counter = 0;\n//    const size_t shape;\n    void set_energy_bounds(double E_lower, double E_upper);\n    bool have_bounds_on_energy = false;\n    double get_variance(){return variance;}\n    double get_energy  (){return energy  ;}\n    size_t get_count   (){return counter;}\n    Eigen::Tensor<double,4> HA_MPO;\n    Eigen::Tensor<double,4> HB_MPO;\n    Eigen::Tensor<double,3> Lblock;\n    Eigen::Tensor<double,3> Rblock;\n    Eigen::Tensor<double,4> Lblock2;\n    Eigen::Tensor<double,4> Rblock2;\n\n    Eigen::Tensor<double,6> HAHB;\n    Eigen::Tensor<double,8> HAHB2;\n    Eigen::DSizes<long,4>   dsizes;\n    class_tic_toc t_lbfgs;\n    class_xDMRG_full_functor(\n            const Eigen::Tensor<Scalar,4> &HA_MPO_,\n            const Eigen::Tensor<Scalar,4> &HB_MPO_,\n            const Eigen::Tensor<Scalar,3> &Lblock_,\n            const Eigen::Tensor<Scalar,3> &Rblock_,\n            const Eigen::Tensor<Scalar,4> &Lblock2_,\n            const Eigen::Tensor<Scalar,4> &Rblock2_,\n            const Eigen::DSizes<long,4>   &dsizes_\n            );\n\n    double get_vH2v(const Eigen::Matrix<double,Eigen::Dynamic,1> &v);\n    double get_vHv(const Eigen::Matrix<double,Eigen::Dynamic,1> &v);\n    Eigen::VectorXd get_vH2 (const Eigen::Matrix<double,Eigen::Dynamic,1> &v);\n    Eigen::VectorXd get_vH (const Eigen::Matrix<double,Eigen::Dynamic,1> &v);\n    double operator()(const Eigen::Matrix<double,Eigen::Dynamic,1> &v, Eigen::Matrix<double,Eigen::Dynamic,1> &grad);\n\n\n};\n\n\n#endif //DMRG_CLASS_XDMRG_FULL_FUNCTOR_H\n", "meta": {"hexsha": "16571e13515675e2d9623457c78d9850bcc50210", "size": 2355, "ext": "h", "lang": "C", "max_stars_repo_path": "unused/class_xDMRG_full_functor.h", "max_stars_repo_name": "DavidAce/DMRG", "max_stars_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T22:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:45:27.000Z", "max_issues_repo_path": "unused/class_xDMRG_full_functor.h", "max_issues_repo_name": "DavidAce/DMRG", "max_issues_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unused/class_xDMRG_full_functor.h", "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": 31.4, "max_line_length": 117, "alphanum_fraction": 0.6840764331, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.39180789307645414}}
{"text": "/*\n    learn.c\n*/\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_multifit.h>\n#include \"learn.h\"\n#include \"feature.h\"\n#include \"imatrix.h\"\n#include \"dmatrix.h\"\n#include \"util.h\"\n#include \"likelihood.h\"\n#include \"hyper.h\"\n\nvoid mvslda_learn(document *data, double **resp, double *alpha, double beta, double nu2, double sigma2, \n    int nclass, int nlex, int dlenmax, int nresp, int maxiter, double **phi, double **theta, double **eta, \n    int **n_mz, int **n_zw, FILE *likp, FILE *hyperp, unsigned long int random_seed){\n    document *dp;\n    int ndocs;\n    int *n_m;\n    int *n_z;\n    int ***topics;\n    int word_index;\n    int word_num;\n    double sum_alpha;\n    double *left;\n    double *center;\n    double *log_right;\n    double *p_z;\n    double *log_p_z;\n    double *cum_sum_p_z;\n    double log_Z, sum_p_r, sum_empirical_z;\n    double temp_prediction;\n    double lik;\n    double **temp_phi;\n    double **temp_theta;\n    double **empirical_z;\n    int z;\n    int it;\n    int m, w, t, i, j, k;\n    const gsl_rng_type *T;\n    gsl_rng *r;\n    \n    gsl_rng_env_setup();\n    T = gsl_rng_default;\n    r = gsl_rng_alloc(T);\n    \n    // count data length\n    for(dp = data, ndocs = 0;(dp->len) != -1;dp++, ndocs++)\n        ;\n    \n    // initialize buffers\n    if((n_m = calloc(ndocs,sizeof(int))) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate n_m.\\n\");\n        return;\n    }\n    if((n_z = calloc(nclass,sizeof(int))) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate n_z.\\n\");\n        return;\n    }\n    if((left = calloc(nclass,sizeof(double))) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate left.\\n\");\n        return;\n    }\n    if((center = calloc(nclass,sizeof(double))) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate center.\\n\");\n        return;\n    }\n    if((log_right = calloc(nclass,sizeof(double))) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate log_cright.\\n\");\n        return;\n    }\n    if((p_z = calloc(nclass,sizeof(double))) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate p_z.\\n\");\n        return;\n    }\n    if((log_p_z = calloc(nclass,sizeof(double))) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate log_p_z.\\n\");\n        return;\n    }\n    if((cum_sum_p_z = calloc((nclass+1),sizeof(double))) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate cum_sum_p_z.\\n\");\n        return;\n    }\n    if((topics = calloc(ndocs,sizeof(int **))) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate topics.\\n\");\n        return;\n    }\n    if((empirical_z = dmatrix(ndocs, nclass)) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate empirical_z.\\n\");\n        return;\n    }\n    if((temp_phi = dmatrix(nlex, nclass)) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate temp_phi.\\n\");\n        exit(1);\n    }\n    if((temp_theta = dmatrix(ndocs, nclass)) == NULL){\n        fprintf(stderr,\"mvslda_learn:: cannot allocate temp_theta.\\n\");\n        exit(1);\n    }\n    \n    printf(\"Number of documents          = %d\\n\",ndocs);\n    printf(\"Number of unique words       = %d\\n\",nlex);\n    printf(\"Number of latent classes     = %d\\n\",nclass);\n    printf(\"Number of responses          = %d\\n\",nresp);\n    printf(\"Number of iteration          = %d\\n\",maxiter);\n    \n    // choose an arbitrary topic as first topic for word\n    gsl_rng_set(r, random_seed);\n    for(dp = data, m = 0;(dp->len) != -1;dp++, m++){\n        if((topics[m] = calloc((dp->len), sizeof(int *))) == NULL){\n            fprintf(stderr,\"mvslda_learn:: cannot allocate topics[m].\\n\");\n            return;\n        }\n        for(w = 0;w < (dp->len);w++){\n            if((topics[m][w] = calloc((dp->cnt[w]), sizeof(int))) == NULL){\n                fprintf(stderr,\"mvslda_learn:: cannot allocate topics[m][w].\\n\");\n                return;\n            }\n            word_index = dp->id[w];\n            word_num = dp->cnt[w];\n            for(i = 0;i < word_num;i++){\n                z = (int)gsl_rng_uniform_int(r, nclass);\n                n_mz[m][z] += 1;\n                n_m[m] += 1;\n                n_zw[z][word_index] += 1;\n                n_z[z] += 1;\n                topics[m][w][i] = z;\n            }\n        }\n    }\n    // initialize eta ([nclass, nresp])\n    for(k = 0;k < nclass;k++)\n        for(t = 0;t < nresp;t++)\n            eta[k][t] = 0.0;\n    \n    // learning main\n    for(it = 0;it < maxiter;it++){\n        printf(\"iteration %2d/%3d..\\n\", it + 1, maxiter);\n        fflush(stdout);\n        sum_alpha = 0.0;\n        for(k = 0;k < nclass;k++)\n            sum_alpha += alpha[k];\n        for (dp = data, m = 0; (dp->len) != -1; dp++, m++){\n            // for words\n            for(w = 0;w < (dp->len);w++){\n                word_index = dp->id[w];\n                word_num = dp->cnt[w];\n                for(i = 0;i < word_num;i++){\n                    z = topics[m][w][i];\n                    n_mz[m][z] -= 1;\n                    n_m[m] -= 1;\n                    n_zw[z][word_index] -= 1;\n                    n_z[z] -= 1;\n                    \n                    // compute conditional distribution log_p_z\n                    // log_p_z left ... theta term\n                    for(k = 0;k < nclass;k++){\n                        left[k] = (double)n_mz[m][k] + alpha[k];\n                        left[k] /= ((double)n_m[m] + sum_alpha);\n                    }\n                    // log_p_z center ... phi term\n                    for(k = 0;k < nclass;k++){\n                        center[k] = (double)n_zw[k][word_index] + beta;\n                        center[k] /= ((double)n_z[k] + (double)nlex * beta);\n                    }\n                    // temporal log_p_z (left and center)\n                    for(k = 0; k < nclass;k++){\n                        log_p_z[k] = log(left[k]) + log(center[k]);\n                    }\n                    // p_z right ... eta term\n                    sum_empirical_z = 0.0;\n                    for(k = 0; k < nclass;k++){\n                        empirical_z[m][k] = (double)n_mz[m][k];\n                        sum_empirical_z += (double)n_mz[m][k];\n                    }\n                    for(k = 0; k < nclass;k++){\n                        empirical_z[m][k] = empirical_z[m][k] / sum_empirical_z;\n                    }\n                    for(t = 0; t < nresp; t++){\n                        temp_prediction = 0.0;\n                        for(k = 0;k < nclass;k++){\n                            temp_prediction += eta[k][t] * empirical_z[m][k]; // dot(eta, z_d)\n                        }\n                        for(k = 0;k < nclass;k++){\n                            log_right[k] = 1.0;\n                            log_right[k] *= 1.0 / (2 * sigma2);\n                            log_right[k] *= (eta[k][t] / (double)n_m[m]);\n                            log_right[k] *= (2 * (resp[m][t] - temp_prediction) - (eta[k][t] / (double)n_m[m]));\n                            log_p_z[k] += log_right[k];\n                        }\n                    }\n                    // conditional distribution log_p_z\n                    // log_Z = logsumexp(logP_k1 + logP_k2 + ... logP_kK)\n                    log_Z = logsumexp(log_p_z, nclass);\n                    for(k = 0;k < nclass;k++){\n                        p_z[k] = exp(log_p_z[k] - log_Z); // normalize to obtain probabilities\n                    }\n                    // random sampling from p_z\n                    z = sampling_multinomial(r, p_z, cum_sum_p_z, nclass);\n                    // update buffers\n                    n_mz[m][z] += 1;\n                    n_m[m] += 1;\n                    n_zw[z][word_index] += 1;\n                    n_z[z] += 1;\n                    topics[m][w][i] = z;\n                }\n            }\n        }\n\n        // for eta update\n        //least squares for dot(Z, eta) = resp\n        for(m = 0; m < ndocs; m++){\n            sum_empirical_z = 0.0;\n            for(k = 0; k < nclass;k++){\n                empirical_z[m][k] = (double)n_mz[m][k];\n                sum_empirical_z += (double)n_mz[m][k];\n            }\n            for(k = 0; k < nclass;k++){\n                empirical_z[m][k] = empirical_z[m][k] / sum_empirical_z;\n            }\n        }\n        for(t = 0; t < nresp; t++){\n            double chisq;\n            gsl_matrix *Z, *cov;\n            gsl_vector *y, *c;\n            gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (ndocs, nclass);\n            Z = gsl_matrix_alloc(ndocs, nclass);\n            cov = gsl_matrix_alloc(nclass, nclass);\n            y = gsl_vector_alloc(ndocs);\n            c = gsl_vector_alloc(nclass);\n            for(m = 0;m < ndocs;m++){\n                gsl_vector_set(y, m, resp[m][t]);\n                for(k = 0;k < nclass;k++){\n                    gsl_matrix_set(Z, m, k, empirical_z[m][k]);\n                }\n            }\n            gsl_multifit_linear(Z, y, c, cov, &chisq, work);\n            for(k = 0;k < nclass;k++){\n                eta[k][t] = gsl_vector_get(c, k);\n            }\n            gsl_multifit_linear_free(work);\n            gsl_matrix_free(Z);\n            gsl_matrix_free(cov);\n            gsl_vector_free(y);\n            gsl_vector_free(c);\n        }\n        \n        // update hyperparameters.\n        update_alpha(alpha, n_m, n_mz, ndocs, nclass);\n        beta = update_beta(beta, n_z, n_zw, nclass, nlex);\n        \n        // compute likelihood.\n        lik = loglikelihood(n_mz, n_zw, n_m, nclass, nlex, ndocs, nresp, resp, alpha, beta, eta, empirical_z, nu2, sigma2);\n        printf(\"\\tlikelihood ... %.8f\\n\",lik);\n        printf(\"\\talpha = \\n\\t\");\n        for(k = 0;k < nclass;k++)\n            printf(\"%.8f \",alpha[k]);\n        printf(\"\\n\\tbeta ... %.2f\\n\",beta);\n        fprintf(likp,\"%.8f\\n\",lik);\n        for(k = 0;k < nclass;k++)\n            fprintf(hyperp,\"%.8f,\",alpha[k]);\n        fprintf(hyperp,\"%.8f\\n\",beta);\n    }\n    \n    // compute matrix phi ([nlex, nclass] matrix)\n    for(w = 0;w < nlex;w++)\n        for(k = 0;k < nclass;k++)\n            temp_phi[w][k] = (double)n_zw[k][w] + beta;\n    normalize_matrix_col(phi, temp_phi, nlex, nclass);\n    \n    // compute matrix theta ([ndocs, nclass])\n    for(m = 0;m < ndocs;m++)\n        for(k = 0;k < nclass;k++)\n            temp_theta[m][k] = (double)n_mz[m][k] + alpha[k];\n    normalize_matrix_row(theta, temp_theta, ndocs, nclass);\n    \n    free(n_m);\n    free(n_z);\n    free(left);\n    free(center);\n    free(log_right);\n    free(p_z);\n    free(log_p_z);\n    free(cum_sum_p_z);\n    \n    for(dp = data, m = 0;(dp->len) != -1;dp++, m++){\n        for(w = 0;w < (dp->len);w++){\n            free(topics[m][w]);\n        }\n        free(topics[m]);\n    }\n    free(topics);\n    free_dmatrix(temp_phi, nlex);\n    free_dmatrix(temp_theta, ndocs);\n    free_dmatrix(empirical_z, ndocs);\n    \n    return;\n}\n\nint sampling_multinomial(gsl_rng *r, double *p, double *cum_sum_p, int len_p){\n    int k, z;\n    double sampling;\n    \n    cum_sum_p[0] = 0.0;\n    for(k = 0;k < len_p;k++){\n        cum_sum_p[k+1] = cum_sum_p[k] + p[k];\n    }\n    sampling = gsl_rng_uniform(r);\n    for(k = 0;k < len_p;k++){\n        if((sampling >= cum_sum_p[k]) && (sampling < cum_sum_p[k+1])){\n            z = k;\n            break;\n        }\n    }\n    return z;\n}\n", "meta": {"hexsha": "2871dce7add65922b146db4426992c6b6cc23990", "size": 11286, "ext": "c", "lang": "C", "max_stars_repo_path": "src/learn.c", "max_stars_repo_name": "khigashi1987/mvsLDA", "max_stars_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/learn.c", "max_issues_repo_name": "khigashi1987/mvsLDA", "max_issues_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/learn.c", "max_forks_repo_name": "khigashi1987/mvsLDA", "max_forks_repo_head_hexsha": "b3db46a01a5561b92c64c7662571f26a6aa9eb6d", "max_forks_repo_licenses": ["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.1588785047, "max_line_length": 123, "alphanum_fraction": 0.4718234981, "num_tokens": 3051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.39166684705396687}}
{"text": "/* specfunc/poch.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include \"gsl_sf_exp.h\"\n#include \"gsl_sf_log.h\"\n#include \"gsl_sf_pow_int.h\"\n#include \"gsl_sf_psi.h\"\n#include \"gsl_sf_gamma.h\"\n\n#include \"error.h\"\n\nstatic const double bern[21] = {\n   0.0   /* no element 0 */,  \n  +0.833333333333333333333333333333333e-01,\n  -0.138888888888888888888888888888888e-02,\n  +0.330687830687830687830687830687830e-04,\n  -0.826719576719576719576719576719576e-06,\n  +0.208767569878680989792100903212014e-07,\n  -0.528419013868749318484768220217955e-09,\n  +0.133825365306846788328269809751291e-10,\n  -0.338968029632258286683019539124944e-12,\n  +0.858606205627784456413590545042562e-14,\n  -0.217486869855806187304151642386591e-15,\n  +0.550900282836022951520265260890225e-17,\n  -0.139544646858125233407076862640635e-18,\n  +0.353470703962946747169322997780379e-20,\n  -0.895351742703754685040261131811274e-22,\n  +0.226795245233768306031095073886816e-23,\n  -0.574472439520264523834847971943400e-24,\n  +0.145517247561486490186626486727132e-26,\n  -0.368599494066531017818178247990866e-28,\n  +0.933673425709504467203255515278562e-30,\n  -0.236502241570062993455963519636983e-31\n};\n\n\n/* ((a)_x - 1)/x in the \"small x\" region where\n * cancellation must be controlled.\n *\n * Based on SLATEC DPOCH1().\n */\n/*\nC When ABS(X) is so small that substantial cancellation will occur if\nC the straightforward formula is used, we use an expansion due\nC to Fields and discussed by Y. L. Luke, The Special Functions and Their\nC Approximations, Vol. 1, Academic Press, 1969, page 34.\nC\nC The ratio POCH(A,X) = GAMMA(A+X)/GAMMA(A) is written by Luke as\nC        (A+(X-1)/2)**X * polynomial in (A+(X-1)/2)**(-2) .\nC In order to maintain significance in POCH1, we write for positive a\nC        (A+(X-1)/2)**X = EXP(X*LOG(A+(X-1)/2)) = EXP(Q)\nC                       = 1.0 + Q*EXPREL(Q) .\nC Likewise the polynomial is written\nC        POLY = 1.0 + X*POLY1(A,X) .\nC Thus,\nC        POCH1(A,X) = (POCH(A,X) - 1) / X\nC                   = EXPREL(Q)*(Q/X + Q*POLY1(A,X)) + POLY1(A,X)\nC\n*/\nstatic\nint\npochrel_smallx(const double a, const double x, gsl_sf_result * result)\n{\n  /*\n   SQTBIG = 1.0D0/SQRT(24.0D0*D1MACH(1))\n   ALNEPS = LOG(D1MACH(3))\n   */\n  const double SQTBIG = 1.0/(2.0*M_SQRT2*M_SQRT3*GSL_SQRT_DBL_MIN);\n  const double ALNEPS = GSL_LOG_DBL_EPSILON - M_LN2;\n\n  if(x == 0.0) {\n    return gsl_sf_psi_e(a, result);\n  }\n  else {\n    const double bp   = (  (a < -0.5) ? 1.0-a-x : a );\n    const int\t incr = ( (bp < 10.0) ? 11.0-bp : 0 );\n    const double b    = bp + incr;\n    double dpoch1;\n    gsl_sf_result dexprl;\n    int stat_dexprl;\n    int i;\n\n    double var    = b + 0.5*(x-1.0);\n    double alnvar = log(var);\n    double q = x*alnvar;\n\n    double poly1 = 0.0;\n\n    if(var < SQTBIG) {\n      const int nterms = (int)(-0.5*ALNEPS/alnvar + 1.0);\n      const double var2 = (1.0/var)/var;\n      const double rho  = 0.5 * (x + 1.0);\n      double term = var2;\n      double gbern[24];\n      int k, j;\n\n      gbern[1] = 1.0;\n      gbern[2] = -rho/12.0;\n      poly1 = gbern[2] * term;\n\n      if(nterms > 20) {\n        /* NTERMS IS TOO BIG, MAYBE D1MACH(3) IS BAD */\n        /* nterms = 20; */\n\tresult->val = 0.0;\n\tresult->err = 0.0;\n\tGSL_ERROR (\"error\", GSL_ESANITY);\n      }\n\n      for(k=2; k<=nterms; k++) {\n        double gbk = 0.0;\n        for(j=1; j<=k; j++) {\n          gbk += bern[k-j+1]*gbern[j];\n        }\n        gbern[k+1] = -rho*gbk/k;\n\n        term  *= (2*k-2-x)*(2*k-1-x)*var2;\n        poly1 += gbern[k+1]*term;\n      }\n    }\n\n    stat_dexprl = gsl_sf_expm1_e(q, &dexprl);\n    if(stat_dexprl != GSL_SUCCESS) {\n      result->val = 0.0;\n      result->err = 0.0;\n      return stat_dexprl;\n    }\n    dexprl.val = dexprl.val/q;\n    poly1 *= (x - 1.0);\n    dpoch1 = dexprl.val * (alnvar + q * poly1) + poly1;\n\n    for(i=incr-1; i >= 0; i--) {\n      /*\n       C WE HAVE DPOCH1(B,X), BUT BP IS SMALL, SO WE USE BACKWARDS RECURSION\n       C TO OBTAIN DPOCH1(BP,X).\n       */\n      double binv = 1.0/(bp+i);\n      dpoch1 = (dpoch1 - binv) / (1.0 + x*binv);\n    }\n\n    if(bp == a) {\n      result->val = dpoch1;\n      result->err = 2.0 * GSL_DBL_EPSILON * (fabs(incr) + 1.0) * fabs(result->val);\n      return GSL_SUCCESS;\n    }\n    else {\n      /*\n       C WE HAVE DPOCH1(BP,X), BUT A IS LT -0.5.  WE THEREFORE USE A\n       C REFLECTION FORMULA TO OBTAIN DPOCH1(A,X).\n       */\n      double sinpxx = sin(M_PI*x)/x;\n      double sinpx2 = sin(0.5*M_PI*x);\n      double t1 = sinpxx/tan(M_PI*b);\n      double t2 = 2.0*sinpx2*(sinpx2/x);\n      double trig  = t1 - t2;\n      result->val  = dpoch1 * (1.0 + x*trig) + trig;\n      result->err  = (fabs(dpoch1*x) + 1.0) * GSL_DBL_EPSILON * (fabs(t1) + fabs(t2));\n      result->err += 2.0 * GSL_DBL_EPSILON * (fabs(incr) + 1.0) * fabs(result->val);\n      return GSL_SUCCESS;\n    }    \n  }\n}\n\n\n/* Assumes a>0 and a+x>0.\n */\nstatic\nint\nlnpoch_pos(const double a, const double x, gsl_sf_result * result)\n{\n  double absx = fabs(x);\n\n  if(absx > 0.1*a || absx*log(GSL_MAX_DBL(a,2.0)) > 0.1) {\n    if(a < GSL_SF_GAMMA_XMAX && a+x < GSL_SF_GAMMA_XMAX) {\n      /* If we can do it by calculating the gamma functions\n       * directly, then that will be more accurate than\n       * doing the subtraction of the logs.\n       */\n      gsl_sf_result g1;\n      gsl_sf_result g2;\n      gsl_sf_gammainv_e(a,   &g1);\n      gsl_sf_gammainv_e(a+x, &g2);\n      result->val  = -log(g2.val/g1.val);\n      result->err  = g1.err/fabs(g1.val) + g2.err/fabs(g2.val);\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      return GSL_SUCCESS;\n    }\n    else {\n      /* Otherwise we must do the subtraction.\n       */\n      gsl_sf_result lg1;\n      gsl_sf_result lg2;\n      int stat_1 = gsl_sf_lngamma_e(a,   &lg1);\n      int stat_2 = gsl_sf_lngamma_e(a+x, &lg2);\n      result->val  = lg2.val - lg1.val;\n      result->err  = lg2.err + lg1.err;\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      return GSL_ERROR_SELECT_2(stat_1, stat_2);\n    }\n  }\n  else if(absx < 0.1*a && a > 15.0) {\n    /* Be careful about the implied subtraction.\n     * Note that both a+x and and a must be\n     * large here since a is not small\n     * and x is not relatively large.\n     * So we calculate using Stirling for Log[Gamma(z)].\n     *\n     *   Log[Gamma(a+x)/Gamma(a)] = x(Log[a]-1) + (x+a-1/2)Log[1+x/a]\n     *                              + (1/(1+eps)   - 1) / (12 a)\n     *                              - (1/(1+eps)^3 - 1) / (360 a^3)\n     *                              + (1/(1+eps)^5 - 1) / (1260 a^5)\n     *                              - (1/(1+eps)^7 - 1) / (1680 a^7)\n     *                              + ...\n     */\n    const double eps = x/a;\n    const double den = 1.0 + eps;\n    const double d3 = den*den*den;\n    const double d5 = d3*den*den;\n    const double d7 = d5*den*den;\n    const double c1 = -eps/den;\n    const double c3 = -eps*(3.0+eps*(3.0+eps))/d3;\n    const double c5 = -eps*(5.0+eps*(10.0+eps*(10.0+eps*(5.0+eps))))/d5;\n    const double c7 = -eps*(7.0+eps*(21.0+eps*(35.0+eps*(35.0+eps*(21.0+eps*(7.0+eps))))))/d7;\n    const double p8 = gsl_sf_pow_int(1.0+eps,8);\n    const double c8 = 1.0/p8             - 1.0;  /* these need not   */\n    const double c9 = 1.0/(p8*(1.0+eps)) - 1.0;  /* be very accurate */\n    const double a4 = a*a*a*a;\n    const double a6 = a4*a*a;\n    const double ser_1 = c1 + c3/(30.0*a*a) + c5/(105.0*a4) + c7/(140.0*a6);\n    const double ser_2 = c8/(99.0*a6*a*a) - 691.0/360360.0 * c9/(a6*a4);\n    const double ser = (ser_1 + ser_2)/ (12.0*a);\n\n    double term1 = x * log(a/M_E);\n    double term2;\n    gsl_sf_result ln_1peps;\n    gsl_sf_log_1plusx_e(eps, &ln_1peps);  /* log(1 + x/a) */\n    term2 = (x + a - 0.5) * ln_1peps.val;\n\n    result->val  = term1 + term2 + ser;\n    result->err  = GSL_DBL_EPSILON*fabs(term1);\n    result->err += fabs((x + a - 0.5)*ln_1peps.err);\n    result->err += fabs(ln_1peps.val) * GSL_DBL_EPSILON * (fabs(x) + fabs(a) + 0.5);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    gsl_sf_result poch_rel;\n    int stat_p = pochrel_smallx(a, x, &poch_rel);\n    double eps = x*poch_rel.val;\n    int stat_e = gsl_sf_log_1plusx_e(eps, result);\n    result->err  = 2.0 * fabs(x * poch_rel.err / (1.0 + eps));\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_ERROR_SELECT_2(stat_e, stat_p);\n  }\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_lnpoch_e(const double a, const double x, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(a <= 0.0 || a+x <= 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x == 0.0) {\n    result->val = 1.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    return lnpoch_pos(a, x, result);\n  }\n}\n\n\nint\ngsl_sf_lnpoch_sgn_e(const double a, const double x,\n                       gsl_sf_result * result, double * sgn)\n{\n  if(a == 0.0 || a+x == 0.0) {\n    *sgn = 0.0;\n    DOMAIN_ERROR(result);\n  }\n  else if(x == 0.0) {\n    *sgn = 1.0;\n    result->val = 1.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(a > 0.0 && a+x > 0.0) {\n    *sgn = 1.0;\n    return lnpoch_pos(a, x, result);\n  }\n  else if(a < 0.0 && a+x < 0.0) {\n    /* Reduce to positive case using reflection.\n     */\n    double sin_1 = sin(M_PI * (1.0 - a));\n    double sin_2 = sin(M_PI * (1.0 - a - x));\n    if(sin_1 == 0.0 || sin_2 == 0.0) {\n      *sgn = 0.0;\n      DOMAIN_ERROR(result);\n    }\n    else {\n      gsl_sf_result lnp_pos;\n      int stat_pp   = lnpoch_pos(1.0-a, -x, &lnp_pos);\n      double lnterm = log(fabs(sin_1/sin_2));\n      result->val  = lnterm - lnp_pos.val;\n      result->err  = lnp_pos.err;\n      result->err += 2.0 * GSL_DBL_EPSILON * (fabs(1.0-a) + fabs(1.0-a-x)) * fabs(lnterm);\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      *sgn = GSL_SIGN(sin_1*sin_2);\n      return stat_pp;\n    }\n  }\n  else {\n    /* Evaluate gamma ratio directly.\n     */\n    gsl_sf_result lg_apn;\n    gsl_sf_result lg_a;\n    double s_apn, s_a;\n    int stat_apn = gsl_sf_lngamma_sgn_e(a+x, &lg_apn, &s_apn);\n    int stat_a   = gsl_sf_lngamma_sgn_e(a,   &lg_a,   &s_a);\n    if(stat_apn == GSL_SUCCESS && stat_a == GSL_SUCCESS) {\n      result->val  = lg_apn.val - lg_a.val;\n      result->err  = lg_apn.err + lg_a.err;\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      *sgn = s_a * s_apn;\n      return GSL_SUCCESS;\n    }\n    else if(stat_apn == GSL_EDOM || stat_a == GSL_EDOM){\n      *sgn = 0.0;\n      DOMAIN_ERROR(result);\n    }\n    else {\n      result->val = 0.0;\n      result->err = 0.0;\n      *sgn = 0.0;\n      return GSL_FAILURE;\n    }\n  }\n}\n\n\nint\ngsl_sf_poch_e(const double a, const double x, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x == 0.0) {\n    result->val = 1.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    gsl_sf_result lnpoch;\n    double sgn;\n    int stat_lnpoch = gsl_sf_lnpoch_sgn_e(a, x, &lnpoch, &sgn);\n    int stat_exp    = gsl_sf_exp_err_e(lnpoch.val, lnpoch.err, result);\n    result->val *= sgn;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_ERROR_SELECT_2(stat_exp, stat_lnpoch);\n  }\n}\n\n\nint\ngsl_sf_pochrel_e(const double a, const double x, gsl_sf_result * result)\n{\n  const double absx = fabs(x);\n  const double absa = fabs(a);\n\n  /* CHECK_POINTER(result) */\n\n  if(absx > 0.1*absa || absx*log(GSL_MAX(absa,2.0)) > 0.1) {\n    gsl_sf_result lnpoch;\n    double sgn;\n    int stat_poch = gsl_sf_lnpoch_sgn_e(a, x, &lnpoch, &sgn);\n    if(lnpoch.val > GSL_LOG_DBL_MAX) {\n      OVERFLOW_ERROR(result);\n    }\n    else {\n      const double el = exp(lnpoch.val);\n      result->val  = (sgn*el - 1.0)/x;\n      result->err  = fabs(result->val) * (lnpoch.err + 2.0 * GSL_DBL_EPSILON);\n      result->err += 2.0 * GSL_DBL_EPSILON * (fabs(sgn*el) + 1.0) / fabs(x);\n      return stat_poch;\n    }\n  }\n  else {\n    return pochrel_smallx(a, x, result);\n  }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_lnpoch(const double a, const double x)\n{\n  EVAL_RESULT(gsl_sf_lnpoch_e(a, x, &result));\n}\n\ndouble gsl_sf_poch(const double a, const double x)\n{\n  EVAL_RESULT(gsl_sf_poch_e(a, x, &result));\n}\n\ndouble gsl_sf_pochrel(const double a, const double x)\n{\n  EVAL_RESULT(gsl_sf_pochrel_e(a, x, &result));\n}\n", "meta": {"hexsha": "594f760dec025f38612a010d7f5b5f642fb12cba", "size": 13117, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/poch.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/poch.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/specfunc/poch.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 30.0848623853, "max_line_length": 94, "alphanum_fraction": 0.5883967371, "num_tokens": 4716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.39157780551789084}}
{"text": "/* ===============================================================================*/\n/*   Version 1.0.             Cullan Howlett                                      */\n/*   Copyright (c) 2017       International Centre for Radio Astronomy Research,  */\n/*   The MIT License (MIT)    University of Western Australia                     */\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 <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_integration.h>\n\n// Fisher matrix calculation for surveys with velocity and density field measurements.\n// ASSUMPTIONS:\n//  -  Uncorrelated shot-noise between the density and velocity fields\n//  -  I use the trapezium rule to integrate over r. There will be some error due to this, but this makes the most sense as \n//     we are binning the number density anyway, and it makes hella difference in the speed of the code.\n//  -  The redshift dependence of the non-linear matter and velocity divergence power spectra is captured using linear interpolation.\n//  -  The PV error scales as a fixed pecentage of H0*r.\n//  -  Flat LCDM cosmology (but not necessarily GR as gammaval can be changed).\n//  -  The damping of the velocity and density fields due to non-linear RSD is redshift independent\n\n// The parameters necessary for the calculation\nstatic int nparams = 4;           // The number of free parameters (we can use any of beta, fsigma8, r_g, sigma_g, sigma_u)\nstatic int Data[4] = {0,1,3,4};   // A vector of flags for the parameters we are interested in (0=beta, 1=fsigma8, 2=r_g, 3=sigma_g, 4=sigma_u). MAKE SURE THE LENGTH OF THIS VECTOR, NPARAMS AND THE ENTRIES AGREE/MAKE SENSE, OR YOU MIGHT GET NONSENSE RESULTS!!\nstatic int nziter = 1;            // Now many bins in redshift between zmin and zmax we are considering\nstatic double zmin = 0.0;         // The minimum redshift to consider (You must have power spectra that are within this range or GSL spline will error out)\nstatic double zmax = 0.1;         // The maximum redshift to consider (You must have power spectra that are within this range or GSL spline will error out)\nstatic double Om = 0.3121;        // The matter density at z=0\nstatic double c = 299792.458;     // The speed of light in km/s\nstatic double gammaval = 0.55;    // The value of gammaval to use in the forecasts (where f(z) = Om(z)^gammaval)\nstatic double r_g = 1.0;          // The cross correlation coefficient between the velocity and density fields\nstatic double beta0 = 0.393;      // The value of beta (at z=0, we'll modify this by the redshift dependent value of bias and f as required)\nstatic double sigma80 = 0.8150;   // The value of sigma8 at z=0\nstatic double sigma_u = 13.00;    // The value of the velocity damping parameter in Mpc/h. I use the values from Jun Koda's paper\nstatic double sigma_g = 4.24;     // The value of the density damping parameter in Mpc/h. I use the values from Jun Koda's paper\nstatic double kmax = 0.2;         // The maximum k to evaluate for dd, dv and vv correlations (Typical values are 0.1 - 0.2, on smaller scales the models are likely to break down).\nstatic double survey_area[3] = {0.0, 0.0, 1.745};   // We need to know the survey area for each survey and the overlap area between the surveys (redshift survey only first, then PV survey only, then overlap. \n                                                    // For fully overlapping we would have {0, 0, size_overlap}. For redshift larger than PV, we would have {size_red-size_overlap, 0, size_overlap}). Units are pi steradians, such that full sky is 4.0, half sky is 2.0 etc.\nstatic double error_rand = 300.0;    // The observational error due to random non-linear velocities (I normally use 300km/s as in Jun Koda's paper)\nstatic double error_dist = 0.05;     // The percentage error on the distance indicator (Typically 0.05 - 0.10 for SNe IA, 0.2 or more for Tully-Fisher or Fundamental Plane) \nstatic double verbosity = 0;         // How much output to give: 0 = only percentage errors on fsigma8, 1 = other useful info and nuisance parameters, 2 = full fisher and covariance matrices\n\n// The number of redshifts and the redshifts themselves of the input matter and velocity divergence power spectra. \n// These numbers are multiplied by 100, converted to ints and written in the form _z0p%02d which is then appended to the filename Pvel_file. See routine read_power. \nstatic double nzin = 11;\nstatic double zin[11] = {0.00, 0.05, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50};\nchar * Pvel_file = \"./example_files/example_pk\";                                                  // The file containing the velocity divergence power spectrum. Don't include .dat as we'll append the redshifts on read in\n\n// The files containing the number density of the surveys. First is the PV survey, then the redshift survey. These files MUST have the same binning and redshift range, \n// so that the sum over redshift bins works (would be fine if we used splines), i.e., if one survey is shallower then that file must contain rows with n(z)=0.\n// I also typically save nbar x 10^6 in the input file to make sure I don't lose precision when outputting small nbar values to files. This is corrected when the nbar file\n// is read in, so see the read_nz() routine!\nchar * nbar_file[300] = {\"./example_files/example_nbar_vel.dat\",\n                         \"./example_files/example_nbar_red.dat\"};      \n\n// Other global parameters and arrays\nint NK, * NRED;\ndouble pkkmin;         // The minimum kmin to integrate over, based on the input power spectrum file\ndouble pkkmax;         // The maximum k in the input power spectrum. The maximum k to integrate over is the smallest of this or kmax\ndouble * zarray;\ndouble * rarray;\ndouble * deltararray;\ndouble * growtharray;\ndouble ** nbararray;\ndouble * karray, * deltakarray;\ndouble ** pmmarray, ** pmtarray, ** pttarray;\ngsl_spline * growth_spline, * r_spline;\ngsl_interp_accel * growth_acc, * r_acc;\n\n// Prototypes\ndouble zeff_integrand(double mu, void * pin);\ndouble mu_integrand(double mu, void * pin);\ndouble ezinv(double x, void *p);\ndouble rz(double red);\ndouble growthfunc(double x, void *p);\ndouble growthz(double red);\nvoid read_nz();\nvoid read_power();\n\n// Calculates the fished matrix for a velocity survey.\nint main(int argc, char **argv) {\n    \n    FILE * fout;\n    int i, j;\n\n    // Read in the velocity divergence power spectrum output from the COPTER code (Carlson 2009)\n    read_power();\n\n    // Read in the number densities of the surveys\n    read_nz();\n\n    // Run some checks\n    if (!((survey_area[0] > 0.0) || (survey_area[2] > 0.0))) {\n        for (i=0; i<nparams; i++) {\n            if (Data[i] == 2) {\n                printf(\"ERROR: r_g is a free parameter, but there is no information in the density field (Fisher matrix will be singular)\\n\");\n                exit(0);\n            }\n            if (Data[i] == 3) {\n                printf(\"ERROR: sigma_g is a free parameter, but there is no information in the density field (Fisher matrix will be singular)\\n\");\n                exit(0);\n            }\n        }\n    }\n    if (!((survey_area[1] > 0.0) || (survey_area[2] > 0.0))) {\n        for (i=0; i<nparams; i++) {\n            if (Data[i] == 4) {\n                printf(\"ERROR: sigma_u is a free parameter, but there is no information in the velocity field (Fisher matrix will be singular)\\n\");\n                exit(0);\n            }\n        }\n    }\n    if ((sizeof(Data)/sizeof(*Data)) != nparams) {\n        printf(\"ERROR: Size of Data vector for parameters of interest must be equal to nparams\\n\");\n        exit(0);\n    }\n\n    // Calculate the Fisher matrices for all bins. \n    gsl_matrix * Fisher_Tot = gsl_matrix_alloc(nparams, nparams);\n    for (i=0; i<nparams; i++) {\n        for (j=0; j<nparams; j++) gsl_matrix_set(Fisher_Tot, i, j, 0.0);\n    }\n\n    printf(\"Evaluating the Fisher Matrix for %d bins between [z_min = %lf, z_max = %lf]\\n\", nziter, zmin, zmax);\n\n    if (verbosity == 0) printf(\"#     zmin         zmax         zeff      fsigma8(z_eff)   percentage error(z_eff)\\n\");\n\n    int ziter;\n    for (ziter = 0; ziter<nziter; ziter++) {\n\n        double zbinwidth = (zmax-zmin)/(nziter);\n        double zmin_iter = ziter*zbinwidth + zmin;\n        double zmax_iter = (ziter+1.0)*zbinwidth + zmin;\n\n        double rzmax = gsl_spline_eval(r_spline, zmax_iter, r_acc);\n        double kmin = M_PI/rzmax;\n\n        if (verbosity > 0) printf(\"Evaluating the Fisher Matrix for [k_min = %lf, k_max = %lf] and [z_min = %lf, z_max = %lf]\\n\", kmin, kmax, zmin_iter, zmax_iter);\n\n        // Calculate the effective redshift (which I base on the sum of the S/N for the density and velocity fields)\n        int numk;\n        double k_sum1 = 0.0, k_sum2 = 0.0;\n        for (numk=0; numk<NK; numk++) {\n\n            double k = karray[numk]+0.5*deltakarray[numk];\n            double deltak = deltakarray[numk];\n            if (k < kmin) continue;\n            if (k > kmax) continue;\n\n            double result, error;\n            double params[4] = {numk, k, zmin_iter, zmax_iter};\n\n            size_t nevals = 1000;\n            gsl_function F;\n            F.function = &zeff_integrand;\n            F.params = &params;\n            gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);\n\n            gsl_integration_qags(&F, 0.0, 1.0, 0, 5e-3, nevals, w, &result, &error);\n            gsl_integration_workspace_free(w);\n\n            k_sum1 += k*k*deltak*result;\n            k_sum2 += k*k*deltak;\n\n        }\n        double z_eff = k_sum1/k_sum2;\n        if (verbosity > 0) printf(\"Effective redshift z_eff = %lf\\n\", z_eff);\n\n        double growth_eff = gsl_spline_eval(growth_spline, z_eff, growth_acc);\n\n        // Calculate the fisher matrix, integrating over k, then mu, then r (r is last as it means we are effectively integrating over effective volume).\n        // As the input spectra are tabulated we'll just use the trapezium rule to integrate over k\n        gsl_matrix * Fisher = gsl_matrix_alloc(nparams, nparams);\n        for (i=0; i<nparams; i++) {\n            for (j=i; j<nparams; j++) {\n\n                double k_sum = 0.0;\n                for (numk=0; numk<NK; numk++) {\n\n                    double k = karray[numk]+0.5*deltakarray[numk];\n                    double deltak = deltakarray[numk];\n                    if (k < kmin) continue;\n                    if (k > kmax) continue;\n\n                    double result, error;\n                    double params[6] = {numk, k, Data[i], Data[j], zmin_iter, zmax_iter};\n\n                    size_t nevals = 1000;\n                    gsl_function F;\n                    F.function = &mu_integrand;\n                    F.params = &params;\n                    gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);\n\n                    gsl_integration_qags(&F, 0.0, 1.0, 0, 5e-3, nevals, w, &result, &error);\n                    gsl_integration_workspace_free(w);\n\n                    k_sum += k*k*deltak*result;\n\n                }\n                //printf(\"%d, %d, %lf\\n\", i, j, k_sum/(4.0*M_PI));\n                gsl_matrix_set(Fisher, i, j, k_sum/(4.0*M_PI));\n                gsl_matrix_set(Fisher, j, i, k_sum/(4.0*M_PI));\n\n            }\n        }\n\n        for (i=0; i<nparams; i++) {\n            for (j=0; j<nparams; j++) {\n                double val = gsl_matrix_get(Fisher_Tot, i, j) + gsl_matrix_get(Fisher, i, j);\n                gsl_matrix_set(Fisher_Tot, i, j, val);\n            }\n        }\n\n        if (verbosity == 2) {\n            printf(\"Fisher Matrix\\n======================\\n\");\n            for (i=0; i<nparams; i++) {\n                printf(\"[\");\n                for (j=0; j<nparams; j++) printf(\"%15.6lf,\\t\", gsl_matrix_get(Fisher, i, j));\n                printf(\"],\\n\");\n            }\n        }\n\n        // Now invert the Fisher matrix\n        int s;\n        gsl_permutation * p;\n        gsl_matrix * Covariance = gsl_matrix_alloc(nparams, nparams);\n        p = gsl_permutation_alloc(nparams);\n        gsl_linalg_LU_decomp(Fisher, p, &s);\n        gsl_linalg_LU_invert(Fisher, p, Covariance);\n        gsl_permutation_free(p);\n\n        double sigma8 = sigma80 * growth_eff;\n        double Omz = Om*ezinv(z_eff,NULL)*ezinv(z_eff,NULL)*(1.0+z_eff)*(1.0+z_eff)*(1.0+z_eff);\n        double f = pow(Omz, gammaval);\n        double beta = f*beta0*growth_eff/pow(Om,0.55);\n\n        if (verbosity == 0) {\n            for (i=0; i<nparams; i++) {\n                if (Data[i] == 1) printf(\"%12.6lf  %12.6lf  %12.6lf  %12.6lf  %12.6lf\\n\", zmin_iter, zmax_iter, z_eff, f*sigma8, 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8));\n            }\n        }\n\n        if (verbosity > 0) {\n            for (i=0; i<nparams; i++) {\n                if (Data[i] == 0) {\n                    printf(\"beta = %12.6lf +/- %12.6lf\\n\", beta, sqrt(gsl_matrix_get(Covariance, i, i)));\n                    printf(\"%4.2lf percent error on beta\\n\", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/beta);\n                }\n                if (Data[i] == 1) {\n                    printf(\"fsigma8 = %12.6lf +/- %12.6lf\\n\", f*sigma8, sqrt(gsl_matrix_get(Covariance, i, i)));\n                    printf(\"%4.2lf percent error on fsigma8\\n\", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8));\n                }\n                if (Data[i] == 2) {\n                    printf(\"r_g = %12.6lf +/- %12.6lf\\n\", r_g, sqrt(gsl_matrix_get(Covariance, i, i)));\n                    printf(\"%4.2lf percent error on r_g\\n\", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/r_g);\n                }\n                if (Data[i] == 3) {\n                    printf(\"sigma_g = %12.6lf +/- %12.6lf\\n\", sigma_g, sqrt(gsl_matrix_get(Covariance, i, i)));\n                    printf(\"%4.2lf percent error on sigma_g\\n\", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/sigma_g);\n                }\n                if (Data[i] == 4) {\n                    printf(\"sigma_u = %12.6lf +/- %12.6lf\\n\", sigma_u, sqrt(gsl_matrix_get(Covariance, i, i)));\n                    printf(\"%4.2lf percent error on sigma_u\\n\", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/sigma_u);\n                }\n            }\n        }\n\n        if (verbosity == 2) {\n            printf(\"Covariance Matrix\\n======================\\n\");\n            for (i=0; i<nparams; i++) {\n                printf(\"[\");\n                for (j=0; j<nparams; j++) printf(\"%15.6lf,\\t\", gsl_matrix_get(Covariance, i, j));\n                printf(\"],\\n\");\n            }\n        }\n\n        gsl_matrix_free(Fisher);\n        gsl_matrix_free(Covariance);\n    }\n\n    // Now the full Fisher matrix over all redshifts if we had more than 1 redshift bin\n    if (nziter > 1) {\n        double rzmax = gsl_spline_eval(r_spline, zmax, r_acc);\n        double kmin = M_PI/rzmax;\n\n        if (verbosity > 0) printf(\"Finally, evaluating the Fisher Matrix for [k_min = %lf, k_max = %lf] and [z_min = %lf, z_max = %lf]\\n\", kmin, kmax, zmin, zmax);\n\n        // Calculate the effective redshift\n        int numk;\n        double k_sum1 = 0.0, k_sum2 = 0.0;\n        for (numk=0; numk<NK; numk++) {\n\n            double k = karray[numk]+0.5*deltakarray[numk];\n            double deltak = deltakarray[numk];\n            if (k < kmin) continue;\n            if (k > kmax) continue;\n\n            double result, error;\n            double params[4] = {numk, k, zmin, zmax};\n\n            size_t nevals = 1000;\n            gsl_function F;\n            F.function = &zeff_integrand;\n            F.params = &params;\n            gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);\n\n            gsl_integration_qags(&F, 0.0, 1.0, 0, 5e-3, nevals, w, &result, &error);\n            gsl_integration_workspace_free(w);\n\n            k_sum1 += k*k*deltak*result;\n            k_sum2 += k*k*deltak;\n\n        }\n        double z_eff = k_sum1/k_sum2;\n        if (verbosity > 0) printf(\"Effective redshift z_eff = %lf\\n\", z_eff);\n\n        double growth_eff = gsl_spline_eval(growth_spline, z_eff, growth_acc);\n\n        if (verbosity == 2) {\n            printf(\"Fisher Matrix\\n======================\\n\");\n            for (i=0; i<nparams; i++) {\n                printf(\"[\");\n                for (j=0; j<nparams; j++) printf(\"%15.6lf,\\t\", gsl_matrix_get(Fisher_Tot, i, j));\n                printf(\"],\\n\");\n            }\n        }\n\n        // Now invert the Fisher matrix\n        int s;\n        gsl_permutation * p;\n        gsl_matrix * Covariance = gsl_matrix_alloc(nparams, nparams);\n        p = gsl_permutation_alloc(nparams);\n        gsl_linalg_LU_decomp(Fisher_Tot, p, &s);\n        gsl_linalg_LU_invert(Fisher_Tot, p, Covariance);\n        gsl_permutation_free(p);\n\n        double sigma8 = sigma80 * growth_eff;\n        double Omz = Om*ezinv(z_eff,NULL)*ezinv(z_eff,NULL)*(1.0+z_eff)*(1.0+z_eff)*(1.0+z_eff);\n        double f = pow(Omz, gammaval);\n        double beta = f*beta0*growth_eff/pow(Om,0.55);\n\n        if (verbosity == 0) {\n            printf(\"# Full redshift range:\\n\");\n            for (i=0; i<nparams; i++) {\n                if (Data[i] == 1) printf(\"%12.6lf  %12.6lf  %12.6lf  %12.6lf  %12.6lf\\n\", zmin, zmax, z_eff, f*sigma8, 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8));\n            }\n        }\n\n        if (verbosity > 0) {\n            for (i=0; i<nparams; i++) {\n                if (Data[i] == 0) {\n                    printf(\"beta = %12.6lf +/- %12.6lf\\n\", beta, sqrt(gsl_matrix_get(Covariance, i, i)));\n                    printf(\"%4.2lf percent error on beta\\n\", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/beta);\n                }\n                if (Data[i] == 1) {\n                    printf(\"fsigma8 = %12.6lf +/- %12.6lf\\n\", f*sigma8, sqrt(gsl_matrix_get(Covariance, i, i)));\n                    printf(\"%4.2lf percent error on fsigma8\\n\", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/(f*sigma8));\n                }\n                if (Data[i] == 2) {\n                    printf(\"r_g = %12.6lf +/- %12.6lf\\n\", r_g, sqrt(gsl_matrix_get(Covariance, i, i)));\n                    printf(\"%4.2lf percent error on r_g\\n\", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/r_g);\n                }\n                if (Data[i] == 3) {\n                    printf(\"sigma_g = %12.6lf +/- %12.6lf\\n\", sigma_g, sqrt(gsl_matrix_get(Covariance, i, i)));\n                    printf(\"%4.2lf percent error on sigma_g\\n\", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/sigma_g);\n                }\n                if (Data[i] == 4) {\n                    printf(\"sigma_u = %12.6lf +/- %12.6lf\\n\", sigma_u, sqrt(gsl_matrix_get(Covariance, i, i)));\n                    printf(\"%4.2lf percent error on sigma_u\\n\", 100.0*sqrt(gsl_matrix_get(Covariance, i, i))/sigma_u);\n                }\n            }\n        }\n\n        if (verbosity == 2) {\n            printf(\"Covariance Matrix\\n======================\\n\");\n            for (i=0; i<nparams; i++) {\n                printf(\"[\");\n                for (j=0; j<nparams; j++) printf(\"%15.6lf,\\t\", gsl_matrix_get(Covariance, i, j));\n                printf(\"],\\n\");\n            }\n        }\n    }\n\n    gsl_matrix_free(Fisher_Tot);\n    gsl_spline_free(growth_spline);\n    gsl_interp_accel_free(growth_acc);\n   \n    return 0;\n}\n\n// The integrand to calculate the effective redshift. I'm not actually sure how this is done in the case of \n// density and velocity field measurements, but it seems logical to base it on the sum of the integral of the density spectra and the velocity power spectra\n// weighted by their effective signal to noise. In this way the effective redshift is calculated in the same way as a redshift survey, but there is some dependence\n// on the S/N in the velocity power spectrum too. In any case, the S/N of the density field measurement is always much higher (because there are\n// no errors and the number density is higher) and so this dominates the effective redshift calculation.\ndouble zeff_integrand(double mu, void * pin) {\n\n    int i, j, m, q, u, surv;\n    double * p = (double *)pin;\n\n    int numk = (int)p[0];\n    double k = p[1];\n    double zminval = p[2];\n    double zmaxval = p[3];\n    gsl_interp_accel * Pmm_acc, * Pmt_acc, * Ptt_acc;\n    gsl_spline * Pmm_spline, * Pmt_spline, * Ptt_spline;\n    if (nzin > 1) {\n        double * Pmm_array = (double *)malloc(nzin*sizeof(double));\n        double * Pmt_array = (double *)malloc(nzin*sizeof(double));\n        double * Ptt_array = (double *)malloc(nzin*sizeof(double));\n        for (j=0; j<nzin; j++) {\n            Pmm_array[j] = pmmarray[j][numk];\n            Pmt_array[j] = pmtarray[j][numk];\n            Ptt_array[j] = pttarray[j][numk];\n        }\n        Pmm_acc    = gsl_interp_accel_alloc();\n        Pmm_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);\n        gsl_spline_init(Pmm_spline, zin, Pmm_array, nzin);\n        free(Pmm_array);\n\n        Pmt_acc    = gsl_interp_accel_alloc();\n        Pmt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);\n        gsl_spline_init(Pmt_spline, zin, Pmt_array, nzin);\n        free(Pmt_array);\n\n        Ptt_acc    = gsl_interp_accel_alloc();\n        Ptt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);\n        gsl_spline_init(Ptt_spline, zin, Ptt_array, nzin);\n        free(Ptt_array);\n    }\n\n    double dendamp = sqrt(1.0/(1.0+0.5*(k*k*mu*mu*sigma_g*sigma_g)));     // This is unitless\n    double veldamp = sin(k*sigma_u)/(k*sigma_u);                          // This is unitless\n\n    double dVeff = 0.0, zdVeff = 0.0;\n    for (i=0; i<NRED[0]; i++) {\n\n        double zval = zarray[i];\n        if (zval < zminval) continue;\n        if (zval > zmaxval) break;\n\n        double r_sum = 0.0;\n        double r = rarray[i];\n        double deltar = deltararray[i];\n\n        double dd_prefac=0.0, vv_prefac=0.0;\n        double P_gg=0.0, P_uu=0.0;\n\n        double sigma8 = sigma80 * growtharray[i];\n\n        // First lets calculate the relevant power spectra. Interpolate the power spectra linearly in redshift\n        double Pmm, Pmt, Ptt;\n        Pmm = gsl_spline_eval(Pmm_spline, zval, Pmm_acc);\n        Pmt = gsl_spline_eval(Pmt_spline, zval, Pmm_acc);\n        Ptt = gsl_spline_eval(Ptt_spline, zval, Pmm_acc);\n\n        double Omz = Om*ezinv(zval,NULL)*ezinv(zval,NULL)*(1.0+zval)*(1.0+zval)*(1.0+zval);\n        double f = pow(Omz, gammaval);\n        double beta = f*beta0*growtharray[i]/pow(Om,0.55);\n\n        vv_prefac  = 1.0e2*f*mu*veldamp/k;\n        dd_prefac = (1.0/(beta*beta) + 2.0*r_g*mu*mu/beta + mu*mu*mu*mu)*f*f*dendamp*dendamp;\n        P_gg = dd_prefac*Pmm;\n        P_uu = vv_prefac*vv_prefac*Ptt;\n\n        // We need to do the overlapping and non-overlapping parts of the redshifts and PV surveys separately\n        for (surv=0; surv<3; surv++) {\n            double surv_sum = 0.0;\n            if (survey_area[surv] > 0.0) {\n                double error_obs, error_noise, n_g = 0.0, n_u = 0.0;\n\n                // Set the nbar for each section.\n                if (surv == 0) {\n                    n_g = nbararray[1][i];\n                } else if (surv == 1) {\n                    error_obs = 100.0*error_dist*r;                              // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)\n                    error_noise = error_rand*error_rand + error_obs*error_obs;   // Error_noise is in km^{2}s^{-2}\n                    n_u = nbararray[0][i]/error_noise;                   \n                } else {\n                    error_obs = 100.0*error_dist*r;                              // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)\n                    error_noise = error_rand*error_rand + error_obs*error_obs;   // Error_noise is in km^{2}s^{-2}\n                    n_u = nbararray[0][i]/error_noise;                   \n                    n_g = nbararray[1][i];\n                }\n\n                double value1 = n_g/(1.0 + n_g*P_gg);\n                double value2 = n_u/(1.0 + n_u*P_uu);\n                surv_sum += value1*value1 + value2*value2;\n\n                surv_sum *= survey_area[surv];\n                r_sum += surv_sum;\n            }\n        }\n\n        dVeff += r*r*deltar*r_sum;\n        zdVeff += zval*r*r*deltar*r_sum;\n\n    }\n\n    gsl_spline_free(Pmm_spline);\n    gsl_spline_free(Pmt_spline);\n    gsl_spline_free(Ptt_spline);\n    gsl_interp_accel_free(Pmm_acc);\n    gsl_interp_accel_free(Pmt_acc);\n    gsl_interp_accel_free(Ptt_acc);\n\n    return zdVeff/dVeff;\n\n}\n\n// The integrand for the integral over mu in the Fisher matrix calculation.\n// For each mu we need to create a 4x4 matrix of the relevant power spectra derivatives and the inverse of the power spectrum matrix.\n// Because there are some regions where the number density goes to zero we have to work directly with the inverse as it is difficult to invert numerically\n// but if we deal with the inverse only then we can just set the relevant parts to zero when the number density is zero.\ndouble mu_integrand(double mu, void * pin) {\n\n    int i, j, m, q, u, surv;\n    double * p = (double *)pin;\n    double result, error;\n\n    int numk = (int)p[0];\n    double k = p[1];\n    double zminval = p[4];\n    double zmaxval = p[5];\n    gsl_interp_accel * Pmm_acc, * Pmt_acc, * Ptt_acc;\n    gsl_spline * Pmm_spline, * Pmt_spline, * Ptt_spline;\n    double * Pmm_array = (double *)malloc(nzin*sizeof(double));\n    double * Pmt_array = (double *)malloc(nzin*sizeof(double));\n    double * Ptt_array = (double *)malloc(nzin*sizeof(double));\n    for (j=0; j<nzin; j++) {\n        Pmm_array[j] = pmmarray[j][numk];\n        Pmt_array[j] = pmtarray[j][numk];\n        Ptt_array[j] = pttarray[j][numk];\n    }\n    Pmm_acc    = gsl_interp_accel_alloc();\n    Pmm_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);\n    gsl_spline_init(Pmm_spline, zin, Pmm_array, nzin);\n    free(Pmm_array);\n\n    Pmt_acc    = gsl_interp_accel_alloc();\n    Pmt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);\n    gsl_spline_init(Pmt_spline, zin, Pmt_array, nzin);\n    free(Pmt_array);\n\n    Ptt_acc    = gsl_interp_accel_alloc();\n    Ptt_spline = gsl_spline_alloc(gsl_interp_cspline, nzin);\n    gsl_spline_init(Ptt_spline, zin, Ptt_array, nzin);\n    free(Ptt_array);\n\n    double dendamp = sqrt(1.0/(1.0+0.5*(k*k*mu*mu*sigma_g*sigma_g)));     // This is unitless\n    double veldamp = sin(k*sigma_u)/(k*sigma_u);                          // This is unitless\n\n    double result_sum = 0.0;\n    for (i=0; i<NRED[0]; i++) {\n\n        double zval = zarray[i];\n        double r_sum = 0.0;\n        double r = rarray[i];\n        double deltar = deltararray[i];\n\n        if (zval < zminval) continue;\n        if (zval > zmaxval) break;\n\n        double dd_prefac=0.0, dv_prefac=0.0, vv_prefac=0.0;\n        double P_gg=0.0, P_ug=0.0, P_uu=0.0;\n\n        double sigma8 = sigma80 * growtharray[i];\n\n        // First lets calculate the relevant power spectra. Interpolate the power spectra linearly in redshift\n        double Pmm, Pmt, Ptt;\n        Pmm = gsl_spline_eval(Pmm_spline, zval, Pmm_acc);\n        Pmt = gsl_spline_eval(Pmt_spline, zval, Pmm_acc);\n        Ptt = gsl_spline_eval(Ptt_spline, zval, Pmm_acc);\n\n        double Omz = Om*ezinv(zval,NULL)*ezinv(zval,NULL)*(1.0+zval)*(1.0+zval)*(1.0+zval);\n        double f = pow(Omz, gammaval);\n        double beta = f*beta0*growtharray[i]/pow(Om,0.55);\n\n        vv_prefac  = 1.0e2*f*mu*veldamp/k;\n        dd_prefac = (1.0/(beta*beta) + 2.0*r_g*mu*mu/beta + mu*mu*mu*mu)*f*f*dendamp*dendamp;\n        dv_prefac = (r_g/beta + mu*mu)*f*dendamp;\n        P_gg = dd_prefac*Pmm;\n        P_ug = vv_prefac*dv_prefac*Pmt;\n        P_uu = vv_prefac*vv_prefac*Ptt;\n\n        // And now the derivatives. Need to create a matrix of derivatives for each of the two parameters of interest\n        gsl_matrix * dPdt1 = gsl_matrix_calloc(2, 2);\n        gsl_matrix * dPdt2 = gsl_matrix_calloc(2, 2);\n        double value;\n        switch((int)p[2]) {\n            // Differential w.r.t betaA\n            case 0:\n                value = -2.0*(1.0/beta + r_g*mu*mu)*f*f*dendamp*dendamp*Pmm/(beta*beta);\n                gsl_matrix_set(dPdt1, 0, 0, value);\n                value = -(vv_prefac*f*r_g*dendamp*Pmt)/(beta*beta);\n                gsl_matrix_set(dPdt1, 0, 1, value);\n                gsl_matrix_set(dPdt1, 1, 0, value);\n                break;\n            // Differential w.r.t fsigma8\n            case 1:\n                value = 2.0*(f/(beta*beta) + 2.0*f*r_g*mu*mu/beta + f*mu*mu*mu*mu)*dendamp*dendamp*Pmm/sigma8;\n                gsl_matrix_set(dPdt1, 0, 0, value);\n                value = 2.0*vv_prefac*(r_g/beta + mu*mu)*dendamp*Pmt/sigma8;\n                gsl_matrix_set(dPdt1, 0, 1, value);\n                gsl_matrix_set(dPdt1, 1, 0, value);\n                value = (2.0*P_uu)/(f*sigma8);       \n                gsl_matrix_set(dPdt1, 1, 1, value);\n                break;\n            // Differential w.r.t r_g\n            case 2:\n                value = 2.0*(1.0/beta)*mu*mu*f*f*dendamp*dendamp*Pmm;\n                gsl_matrix_set(dPdt1, 0, 0, value);\n                value = vv_prefac*(1.0/beta)*f*dendamp*Pmt;\n                gsl_matrix_set(dPdt1, 0, 1, value);\n                gsl_matrix_set(dPdt1, 1, 0, value);\n                break;\n            // Differential w.r.t sigma_g\n            case 3:\n                value = -k*k*mu*mu*dendamp*dendamp*sigma_g*P_gg;\n                gsl_matrix_set(dPdt1, 0, 0, value);\n                value = -0.5*k*k*mu*mu*dendamp*dendamp*sigma_g*P_ug;\n                gsl_matrix_set(dPdt1, 0, 1, value);\n                gsl_matrix_set(dPdt1, 1, 0, value);\n                break;\n            // Differential w.r.t sigma_u\n            case 4:\n                value = P_ug*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);\n                gsl_matrix_set(dPdt1, 0, 1, value);\n                gsl_matrix_set(dPdt1, 1, 0, value);\n                value = 2.0*P_uu*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);\n                gsl_matrix_set(dPdt1, 1, 1, value);\n                break;\n            default:\n                break;\n        }\n        switch((int)p[3]) {\n            // Differential w.r.t betaA\n            case 0:\n                value = -2.0*(1.0/beta + r_g*mu*mu)*f*f*dendamp*dendamp*Pmm/(beta*beta);\n                gsl_matrix_set(dPdt2, 0, 0, value);\n                value = -(vv_prefac*f*r_g*dendamp*Pmt)/(beta*beta);\n                gsl_matrix_set(dPdt2, 0, 1, value);\n                gsl_matrix_set(dPdt2, 1, 0, value);\n                break;\n            // Differential w.r.t fsigma8\n            case 1:\n                value = 2.0*(f/(beta*beta) + 2.0*f*r_g*mu*mu/beta + f*mu*mu*mu*mu)*dendamp*dendamp*Pmm/sigma8;\n                gsl_matrix_set(dPdt2, 0, 0, value);\n                value = 2.0*vv_prefac*(r_g/beta + mu*mu)*dendamp*Pmt/sigma8;\n                gsl_matrix_set(dPdt2, 0, 1, value);\n                gsl_matrix_set(dPdt2, 1, 0, value);\n                value = (2.0*P_uu)/(f*sigma8);       \n                gsl_matrix_set(dPdt2, 1, 1, value);\n                break;\n            // Differential w.r.t r_g\n            case 2:\n                value = 2.0*(1.0/beta)*mu*mu*f*f*dendamp*dendamp*Pmm;\n                gsl_matrix_set(dPdt2, 0, 0, value);\n                value = vv_prefac*(1.0/beta)*f*dendamp*Pmt;\n                gsl_matrix_set(dPdt2, 0, 1, value);\n                gsl_matrix_set(dPdt2, 1, 0, value);\n                break;\n            // Differential w.r.t sigma_g\n            case 3:\n                value = -k*k*mu*mu*dendamp*dendamp*sigma_g*P_gg;\n                gsl_matrix_set(dPdt2, 0, 0, value);\n                value = -0.5*k*k*mu*mu*dendamp*dendamp*sigma_g*P_ug;\n                gsl_matrix_set(dPdt2, 0, 1, value);\n                gsl_matrix_set(dPdt2, 1, 0, value);\n                break;\n            // Differential w.r.t sigma_u\n            case 4:\n                value = P_ug*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);\n                gsl_matrix_set(dPdt2, 0, 1, value);\n                gsl_matrix_set(dPdt2, 1, 0, value);\n                value = 2.0*P_uu*(k*cos(k*sigma_u)/sin(k*sigma_u) - 1.0/sigma_u);\n                gsl_matrix_set(dPdt2, 1, 1, value);\n                break;\n            default:\n                break;\n        }\n\n        // We need to do the overlapping and non-overlapping parts of the surveys separately\n        for (surv=0; surv<3; surv++) {\n            double surv_sum = 0.0;\n            if (survey_area[surv] > 0.0) {\n                double error_obs, error_noise, n_g = 0.0, n_u = 0.0;\n\n                // Set the nbar for each section.\n                if (surv == 0) {\n                    n_g = nbararray[1][i];\n                } else if (surv == 1) {\n                    error_obs = 100.0*error_dist*r;                              // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)\n                    error_noise = error_rand*error_rand + error_obs*error_obs;   // Error_noise is in km^{2}s^{-2}\n                    n_u = nbararray[0][i]/error_noise;                   \n                } else {\n                    error_obs = 100.0*error_dist*r;                              // Percentage error * distance * H0 in km/s (factor of 100.0 comes from hubble parameter)\n                    error_noise = error_rand*error_rand + error_obs*error_obs;   // Error_noise is in km^{2}s^{-2}\n                    n_u = nbararray[0][i]/error_noise;                   \n                    n_g = nbararray[1][i];\n                }\n\n                //printf(\"%lf, %lf, %lf\\n\", r, n_g, 1.0e6*n_u);\n\n                if (!((n_u > 0.0) || (n_g > 0.0))) continue;\n\n                // First we need the determinant.\n                double det = 1.0 + n_u*n_g*(P_gg*P_uu - P_ug*P_ug) + n_u*P_uu + n_g*P_gg;\n\n                // Now the inverse matrix.\n                gsl_matrix * iP = gsl_matrix_calloc(2, 2);\n                value = n_u*n_g*P_uu + n_g;\n                gsl_matrix_set(iP, 0, 0, value);\n                value = n_g*n_u*P_gg + n_u;\n                gsl_matrix_set(iP, 1, 1, value);\n                value = - n_g*n_u*P_ug;\n                gsl_matrix_set(iP, 0, 1, value);\n                gsl_matrix_set(iP, 1, 0, value);\n                \n                // Finally we need to compute the Fisher integrand by summing over the inverse and differential matrices\n                for (j=0; j<2; j++) {\n                    for (m=0; m<2; m++) {\n                        for (u=0; u<2; u++) {\n                            for (q=0; q<2; q++) {\n                                value = gsl_matrix_get(dPdt1, j, q)*gsl_matrix_get(iP, q, u)*gsl_matrix_get(dPdt2, u, m)*gsl_matrix_get(iP, m, j);\n                                surv_sum += value;\n                            }\n                        }\n                    }\n                }\n                surv_sum /= det*det;\n                surv_sum *= survey_area[surv];\n                r_sum += surv_sum;\n                gsl_matrix_free(iP);\n                //printf(\"%d, %lf, %lf, %lf, %lf\\n\", surv, k, mu, r, r_sum);\n\n            }\n        }\n        //printf(\"%lf, %lf, %lf, %lf\\n\", k, mu, r, r_sum);\n\n        result_sum += r*r*deltar*r_sum;\n\n        gsl_matrix_free(dPdt1);\n        gsl_matrix_free(dPdt2);\n    }\n\n    gsl_spline_free(Pmm_spline);\n    gsl_spline_free(Pmt_spline);\n    gsl_spline_free(Ptt_spline);\n    gsl_interp_accel_free(Pmm_acc);\n    gsl_interp_accel_free(Pmt_acc);\n    gsl_interp_accel_free(Ptt_acc);\n\n    return result_sum;\n}\n\n\n// Routine to read in the number density as a function of redshift. We need a file containing the left-most edge of each redshift bin and teh number density in that bin.\n// From this we create arrays to store the bin centre, the bin width, the comoving distance and growth factor at the bin centre and the number density.\n// The last bin width and bin centre is constructed from the last row of the input and the value of zmax at the top of the code. \n// ITS VERY IMPORTANT THAT THE NUMBER OF ROWS AND THE REDSHIFTS OF BOTH THE DENSITY AND PV NUMBER DENSITIES MATCH AS THE INTEGRATION OVER Z IS DONE USING THE TRAPEZIUM RULE.\n// ALSO MAKE NOTE OF THE FACTOR OF 1.0e-6 ON LINE 827. THIS IS BECAUSE I TYPICALLY SAVE THE VALUE OF NBAR x 10^6 IN THE INPUT FILES< SO THAT I DON'T LOSE PRECISION\n// WHEN SMALL VALUES OF THE NUMBER DENSITY ARE WRITTEN TO A FILE!\nvoid read_nz() {\n\n    FILE * fp;\n    char buf[500];\n    int i, nsamp;\n\n    NRED = (int *)calloc(2, sizeof(int));\n    nbararray = (double **)calloc(2, sizeof(double*));\n    double * zinarray;\n\n    for (nsamp = 0; nsamp < 2; nsamp++) {\n\n        if(!(fp = fopen(nbar_file[nsamp], \"r\"))) {\n            printf(\"\\nERROR: Can't open nbar file '%s'.\\n\\n\", nbar_file[nsamp]);\n            exit(0);\n        }\n\n        NRED[nsamp] = 0;\n        while(fgets(buf,500,fp)) {\n            if(strncmp(buf,\"#\",1)!=0) {\n                double tz, tnbar;\n                if(sscanf(buf, \"%lf %lf\\n\", &tz, &tnbar) != 2) {printf(\"nbar read error\\n\"); exit(0);};\n                if (tz > zmax) break;\n                NRED[nsamp]++;\n            }\n        }\n        fclose(fp);\n\n        if (nsamp == 0) zinarray = (double *)calloc(NRED[nsamp], sizeof(double));\n        nbararray[nsamp] = (double *)calloc(NRED[nsamp], sizeof(double));\n\n        NRED[nsamp] = 0;\n        fp = fopen(nbar_file[nsamp], \"r\");\n        while(fgets(buf,500,fp)) {\n            if(strncmp(buf,\"#\",1)!=0) {\n                double tz, tnbar;\n                if(sscanf(buf, \"%lf %lf\\n\", &tz, &tnbar) != 2) {printf(\"nbar read error\\n\"); exit(0);};\n                if (tz > zmax) break;\n                if (nsamp == 0) zinarray[NRED[nsamp]] = tz;\n                nbararray[nsamp][NRED[nsamp]] = 1.0e-6*tnbar;\n                NRED[nsamp]++;\n            }\n        }\n        fclose(fp);\n    }\n\n    if (NRED[1] != NRED[0]) {\n        printf(\"ERROR: The number of redshift bins for each sample must match\\n\");\n        exit(0);\n    }   \n\n    zarray = (double *)calloc(NRED[0], sizeof(double));\n    rarray = (double *)calloc(NRED[0], sizeof(double));\n    deltararray = (double *)calloc(NRED[0], sizeof(double));\n    growtharray = (double *)calloc(NRED[0], sizeof(double));\n\n    for (i=0; i<NRED[0]-1; i++) {\n        zarray[i] = (zinarray[i+1]+zinarray[i])/2.0;\n        rarray[i] = rz(zarray[i]);\n        deltararray[i] = rz(zinarray[i+1]) - rz(zinarray[i]);\n        growtharray[i] = growthz(zarray[i])/growthz(0.0);\n        //printf(\"%12.6lf %12.6lf %12.6lf %12.6lf %12.6lf %12.6lf\\n\", zarray[i], rarray[i], deltararray[i], growtharray[i], nbararray[0][i], nbararray[1][i]);\n    }\n    zarray[NRED[0]-1] = (zmax+zinarray[NRED[0]-1])/2.0;\n    rarray[NRED[0]-1] = rz(zarray[NRED[0]-1]);\n    deltararray[NRED[0]-1] = rz(zmax) - rz(zinarray[NRED[0]-1]);\n    growtharray[NRED[0]-1] = growthz(zarray[NRED[0]-1])/growthz(0.0);\n    //printf(\"%12.6lf %12.6lf %12.6lf %12.6lf %12.6lf %12.6lf\\n\", zarray[NRED[0]-1], rarray[NRED[0]-1], deltararray[NRED[0]-1], growtharray[NRED[0]-1], nbararray[0][NRED[0]-1], nbararray[1][NRED[0]-1]);\n\n    growth_acc    = gsl_interp_accel_alloc();\n    growth_spline = gsl_spline_alloc(gsl_interp_cspline, NRED[0]);\n    gsl_spline_init(growth_spline, zarray, growtharray, NRED[0]);\n\n    free(zinarray);\n\n    // Also create a simple redshift-distance spline\n    int nbins = 400;\n    double REDMIN = 0.0;\n    double REDMAX = 2.0;\n    double redbinwidth = (REDMAX-REDMIN)/(double)(nbins-1);\n    double RMIN = rz(REDMIN);\n    double RMAX = rz(REDMAX);\n    double * ztemp = (double *)malloc(nbins*sizeof(double));\n    double * rtemp = (double *)malloc(nbins*sizeof(double));\n    for (i=0;i<nbins;i++) {\n        ztemp[i] = i*redbinwidth+REDMIN;\n        rtemp[i] = rz(ztemp[i]);\n    }\n    r_acc = gsl_interp_accel_alloc();\n    r_spline = gsl_spline_alloc(gsl_interp_cspline, nbins);\n    gsl_spline_init(r_spline, ztemp, rtemp, nbins);\n\n    free(ztemp);\n    free(rtemp);\n\n    return;\n}\n\n// Routine to read in the velocity power spectrum.\nvoid read_power() {\n    \n    FILE * fp;\n    char buf[500];\n    int i, j;\n\n    pmmarray = (double**)malloc(nzin*sizeof(double*));\n    pmtarray = (double**)malloc(nzin*sizeof(double*));\n    pttarray = (double**)malloc(nzin*sizeof(double*));\n\n    for (i = 0; i<nzin; i++) {\n\n        char Pvel_file_in[500];\n        sprintf(Pvel_file_in, \"%s_z0p%02d.dat\", Pvel_file, (int)(100.0*zin[i]));\n\n        if(!(fp = fopen(Pvel_file_in, \"r\"))) {\n            printf(\"\\nERROR: Can't open power file '%s'.\\n\\n\", Pvel_file_in);\n            exit(0);\n        }\n\n        NK = 0;\n        while(fgets(buf,500,fp)) {\n            if(strncmp(buf,\"#\",1)!=0) {\n                double tk, pkdelta, pkdeltavel, pkvel;\n                if(sscanf(buf, \"%lf %lf %lf %lf\\n\", &tk, &pkdelta, &pkdeltavel, &pkvel) != 4) {printf(\"Pvel read error\\n\"); exit(0);};\n                NK++;\n            }\n        }\n        fclose(fp);\n\n        if (i == 0) {\n            karray = (double *)calloc(NK, sizeof(double));\n            deltakarray = (double *)calloc(NK-1, sizeof(double));\n        }\n        pmmarray[i] = (double *)calloc(NK, sizeof(double));\n        pmtarray[i] = (double *)calloc(NK, sizeof(double));\n        pttarray[i] = (double *)calloc(NK, sizeof(double));\n\n        NK = 0;\n        fp = fopen(Pvel_file_in, \"r\");\n        while(fgets(buf,500,fp)) {\n            if(strncmp(buf,\"#\",1)!=0) {\n                double tk, pkdelta, pkdeltavel, pkvel;\n                if(sscanf(buf, \"%lf %lf %lf %lf\\n\", &tk, &pkdelta, &pkdeltavel, &pkvel) != 4) {printf(\"Pvel read error\\n\"); exit(0);};\n                if (i == 0) karray[NK] = tk;\n                pttarray[i][NK] = pkvel;\n                pmmarray[i][NK] = pkdelta;\n                pmtarray[i][NK] = pkdeltavel;\n                NK++;\n            }\n        }\n        fclose(fp);\n    }\n\n    for (i=0; i<NK-1; i++) deltakarray[i] = karray[i+1]-karray[i];\n\n    pkkmin = karray[0];\n    pkkmax = karray[NK-1];\n\n    if (pkkmax < kmax) {\n        printf(\"ERROR: The maximum k in the input power spectra id less than k_max\\n\");\n        exit(0);\n    }\n\n    return;\n}\n\n// Integrand for the comoving distance\ndouble ezinv(double x, void *p) {\n  return 1.0/sqrt(Om*(1.0+x)*(1.0+x)*(1.0+x)+(1.0-Om));\n}\n\n// Calculates the comoving distance from the redshift\ndouble rz(double red) {\n  double result, error;\n  gsl_function F;\n  gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);\n  F.function = &ezinv;\n  gsl_integration_qags(&F, 0.0, red, 0, 1e-7, 1000, w, &result, &error);\n  gsl_integration_workspace_free(w);\n  return c*result/100.0;\n}\n\n// The integrand for the normalised growth factor\ndouble growthfunc(double x, void *p) {\n    double red = 1.0/x - 1.0;\n    double Omz = Om*ezinv(red,NULL)*ezinv(red,NULL)/(x*x*x);\n    double f = pow(Omz, gammaval);\n    return f/x;\n}\n\n// Calculates the normalised growth factor as a function of redshift given a value of gammaval\ndouble growthz(double red) {\n  double result, error;\n  gsl_function F;\n  gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);\n  F.function = &growthfunc;\n  double a = 1.0/(1.0+red);\n  gsl_integration_qags(&F, a, 1.0, 0, 1e-7, 1000, w, &result, &error);\n  gsl_integration_workspace_free(w);\n  return exp(-result);\n}\n\n\n\n", "meta": {"hexsha": "b8a6c4ff530a6603181965c09b58f198d3e99134", "size": 44585, "ext": "c", "lang": "C", "max_stars_repo_path": "PV_fisher.c", "max_stars_repo_name": "LBJ-Wade/PV_fisher", "max_stars_repo_head_hexsha": "88c519a758a56a0dac2cde207da6cc19af777e15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-01T15:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T11:39:16.000Z", "max_issues_repo_path": "PV_fisher.c", "max_issues_repo_name": "LBJ-Wade/PV_fisher", "max_issues_repo_head_hexsha": "88c519a758a56a0dac2cde207da6cc19af777e15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-30T17:39:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-05T08:34:03.000Z", "max_forks_repo_path": "PV_fisher.c", "max_forks_repo_name": "LBJ-Wade/PV_fisher", "max_forks_repo_head_hexsha": "88c519a758a56a0dac2cde207da6cc19af777e15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-20T11:31:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-20T11:31:54.000Z", "avg_line_length": 44.9445564516, "max_line_length": 271, "alphanum_fraction": 0.5630368958, "num_tokens": 12833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3913312344070363}}
{"text": "#pragma once\n\n/***************************************************\n *************** Auto-Generated File ***************\n ***************************************************/\n\n#include <cstring>\n#include <string>\n\n#include <gsl/gsl_const_mksa.h>\n#include <gsl/gsl_const_num.h>\n\n#include \"../../Utils/BinarySearch.h\"\n\nenum UnitType {\n\tNONE,\n\tDISTANCE,\n\tTIME,\n\tTIMESQUARED,\n\tSPEED,\n\tACCELERATION,\n\tAREA,\n\tVOLUME,\n\tMASS,\n\tFORCE,\n\tMASSDISTANCE,\n\tMASSPERTIMESQUARED,\n\tENERGY,\n\tMASSAREA\n};\n\nconstexpr const int numUnits = 161;\nconstexpr const char* unitNames[numUnits] = {\n\t\"acre\", \"astronomical_unit\", \"attogram\", \"attometer\", \"attometerscubed\",\n\t\"attometerssquared\", \"attosecond\", \"barn\", \"btu\", \"calorie\", \"canadian_gallon\", \"carat\",\n\t\"centimeter\", \"century\", \"cup\", \"decade\", \"decameter\", \"decimeter\", \"dyne\",\n\t\"electron_volt\", \"erg\", \"exagram\", \"exameter\", \"exameterscubed\", \"exameterssquared\",\n\t\"exasecond\", \"fathom\", \"femtogram\", \"femtometer\", \"femtometerscubed\",\n\t\"femtometerssquared\", \"femtosecond\", \"fluid_ounce\", \"foot\", \"gigagram\", \"gigameter\",\n\t\"gigameterscubed\", \"gigameterssquared\", \"gigasecond\", \"gram\", \"gram_force\", \"grammeter\",\n\t\"grammeterspersecondsquared\", \"grammeterssquared\", \"grammeterssquaredpersecondsquared\",\n\t\"grampersecondsquared\", \"grav_accel\", \"hectare\", \"hectometer\", \"hour\", \"inch\", \"joule\",\n\t\"kilogram\", \"kilometer\", \"kilometers_per_hour\", \"kilometerscubed\", \"kilometerssquared\",\n\t\"kilopound_force\", \"kilosecond\", \"knot\", \"light_year\", \"liter\", \"mass_electron\",\n\t\"mass_muon\", \"mass_neutron\", \"mass_proton\", \"megagram\", \"megameter\", \"megameterscubed\",\n\t\"megameterssquared\", \"megasecond\", \"meter\", \"meterscubed\", \"meterspersecond\",\n\t\"meterspersecondsquared\", \"meterssquared\", \"metric_ton\", \"microgram\", \"microliter\",\n\t\"micrometer\", \"micrometerscubed\", \"micrometerssquared\", \"microsecond\", \"mil\", \"mile\",\n\t\"miles_per_hour\", \"millenium\", \"milligram\", \"milliliter\", \"millimeter\",\n\t\"millimeterscubed\", \"millimeterssquared\", \"millisecond\", \"minute\", \"month\", \"nanogram\",\n\t\"nanometer\", \"nanometerscubed\", \"nanometerssquared\", \"nanosecond\", \"nautical_mile\",\n\t\"newton\", \"newton_meter\", \"ounce_mass\", \"petagram\", \"petameter\", \"petameterscubed\",\n\t\"petameterssquared\", \"petasecond\", \"picogram\", \"picometer\", \"picometerscubed\",\n\t\"picometerssquared\", \"picosecond\", \"pint\", \"pound_force\", \"pound_mass\", \"poundal\",\n\t\"quart\", \"rydberg\", \"second\", \"secondsquared\", \"solar_mass\", \"speed_of_light\",\n\t\"tablespoon\", \"teaspoon\", \"teragram\", \"terameter\", \"terameterscubed\",\n\t\"terameterssquared\", \"terasecond\", \"therm\", \"ton\", \"troy_ounce\", \"uk_gallon\", \"uk_ton\",\n\t\"unified_atomic_mass\", \"us_gallon\", \"week\", \"yard\", \"year\", \"yoctogram\", \"yoctometer\",\n\t\"yoctometerscubed\", \"yoctometerssquared\", \"yoctosecond\", \"yottagram\", \"yottameter\",\n\t\"yottameterscubed\", \"yottameterssquared\", \"yottasecond\", \"zeptogram\", \"zeptometer\",\n\t\"zeptometerscubed\", \"zeptometerssquared\", \"zeptosecond\", \"zettagram\", \"zettameter\",\n\t\"zettameterscubed\", \"zettameterssquared\", \"zettasecond\"\n};\nconstexpr const int unitIndices[numUnits] = {\n\t52, 0, 53, 54, 56, 55, 57, 58, 59, 61, 2, 1, 63, 62, 64, 66, 65, 67, 3, 4, 68, 5, 6, 8,\n\t7, 9, 76, 69, 71, 73, 72, 74, 70, 75, 11, 12, 14, 13, 15, 77, 83, 78, 79, 80, 81, 82,\n\t10, 85, 86, 84, 87, 16, 88, 90, 94, 92, 91, 89, 95, 93, 98, 17, 102, 103, 104, 105, 19,\n\t20, 22, 21, 23, 99, 107, 100, 101, 106, 118, 142, 143, 144, 146, 145, 147, 110, 109,\n\t116, 112, 108, 111, 113, 115, 114, 117, 18, 119, 120, 121, 123, 122, 125, 124, 24, 25,\n\t126, 26, 27, 29, 28, 30, 128, 129, 131, 130, 132, 133, 97, 96, 127, 134, 31, 135, 136,\n\t32, 60, 138, 141, 33, 34, 36, 35, 37, 139, 137, 140, 39, 40, 38, 41, 148, 149, 154, 150,\n\t151, 153, 152, 155, 42, 43, 45, 44, 46, 156, 157, 159, 158, 160, 47, 48, 50, 49, 51\n};\nconstexpr const char * unitAbbreviations[numUnits] = {\n\t\"AU\", \"CD\", \"CG\", \"Dy\", \"EV\", \"Eg\", \"Em\", \"Em^2\", \"Em^3\", \"Es\", \"G\", \"Gg\", \"Gm\", \"Gm^2\",\n\t\"Gm^3\", \"Gs\", \"J\", \"L\", \"M\", \"Mg\", \"Mm\", \"Mm^2\", \"Mm^3\", \"Ms\", \"N\", \"Nm\", \"Pg\", \"Pm\",\n\t\"Pm^2\", \"Pm^3\", \"Ps\", \"Ry\", \"SM\", \"Tg\", \"Tm\", \"Tm^2\", \"Tm^3\", \"Ts\", \"UAM\", \"UKG\", \"UKT\",\n\t\"USG\", \"Yg\", \"Ym\", \"Ym^2\", \"Ym^3\", \"Ys\", \"Zg\", \"Zm\", \"Zm^2\", \"Zm^3\", \"Zs\", \"ac\", \"ag\",\n\t\"am\", \"am^2\", \"am^3\", \"as\", \"bn\", \"btu\", \"c\", \"cal\", \"cen\", \"cm\", \"cp\", \"dcm\", \"dec\",\n\t\"dm\", \"erg\", \"fg\", \"floz\", \"fm\", \"fm^2\", \"fm^3\", \"fs\", \"ft\", \"fth\", \"g\", \"g*m\",\n\t\"g*m/s^2\", \"g*m^2\", \"g*m^2/s^2\", \"g/s^2\", \"gF\", \"h\", \"hec\", \"hm\", \"in\", \"kg\", \"klbF\",\n\t\"km\", \"km^2\", \"km^3\", \"knt\", \"kph\", \"ks\", \"lb\", \"lbF\", \"ly\", \"m\", \"m/s\", \"m/s^2\", \"mE\",\n\t\"mMu\", \"mNt\", \"mPt\", \"m^2\", \"m^3\", \"mg\", \"mi\", \"mil\", \"ml\", \"mln\", \"mm\", \"mm^2\", \"mm^3\",\n\t\"mph\", \"ms\", \"mt\", \"mth\", \"ng\", \"nm\", \"nm^2\", \"nm^3\", \"nmi\", \"ns\", \"oz\", \"pdl\", \"pg\",\n\t\"pm\", \"pm^2\", \"pm^3\", \"ps\", \"pt\", \"qt\", \"s\", \"s^2\", \"t\", \"tbsp\", \"thm\", \"toz\", \"tsp\",\n\t\"ug\", \"ul\", \"um\", \"um^2\", \"um^3\", \"us\", \"wk\", \"yd\", \"yg\", \"ym\", \"ym^2\", \"ym^3\", \"yr\",\n\t\"ys\", \"zg\", \"zm\", \"zm^2\", \"zm^3\", \"zs\"\n};\nconstexpr const UnitType unitTypes[numUnits] = {\n\tDISTANCE, MASS, VOLUME, FORCE, ENERGY, MASS, DISTANCE, AREA, VOLUME, TIME, ACCELERATION,\n\tMASS, DISTANCE, AREA, VOLUME, TIME, ENERGY, VOLUME, TIME, MASS, DISTANCE, AREA, VOLUME,\n\tTIME, FORCE, ENERGY, MASS, DISTANCE, AREA, VOLUME, TIME, ENERGY, MASS, MASS, DISTANCE,\n\tAREA, VOLUME, TIME, MASS, VOLUME, MASS, VOLUME, MASS, DISTANCE, AREA, VOLUME, TIME,\n\tMASS, DISTANCE, AREA, VOLUME, TIME, AREA, MASS, DISTANCE, AREA, VOLUME, TIME, AREA,\n\tENERGY, SPEED, ENERGY, TIME, DISTANCE, VOLUME, DISTANCE, TIME, DISTANCE, ENERGY, MASS,\n\tVOLUME, DISTANCE, AREA, VOLUME, TIME, DISTANCE, DISTANCE, MASS, MASSDISTANCE, FORCE,\n\tMASSAREA, ENERGY, MASSPERTIMESQUARED, FORCE, TIME, AREA, DISTANCE, DISTANCE, MASS,\n\tFORCE, DISTANCE, AREA, VOLUME, SPEED, SPEED, TIME, MASS, FORCE, DISTANCE, DISTANCE,\n\tSPEED, ACCELERATION, MASS, MASS, MASS, MASS, AREA, VOLUME, MASS, DISTANCE, DISTANCE,\n\tVOLUME, TIME, DISTANCE, AREA, VOLUME, SPEED, TIME, MASS, TIME, MASS, DISTANCE, AREA,\n\tVOLUME, DISTANCE, TIME, MASS, FORCE, MASS, DISTANCE, AREA, VOLUME, TIME, VOLUME, VOLUME,\n\tTIME, TIMESQUARED, MASS, VOLUME, ENERGY, MASS, VOLUME, MASS, VOLUME, DISTANCE, AREA,\n\tVOLUME, TIME, TIME, DISTANCE, MASS, DISTANCE, AREA, VOLUME, TIME, TIME, MASS, DISTANCE,\n\tAREA, VOLUME, TIME\n};\nconstexpr const double unitConversions[numUnits] = {\n\tGSL_CONST_MKSA_ASTRONOMICAL_UNIT, GSL_CONST_MKSA_CARAT*1000.0,\n\tGSL_CONST_MKSA_CANADIAN_GALLON, GSL_CONST_MKSA_DYNE*1000.0,\n\tGSL_CONST_MKSA_ELECTRON_VOLT*1000.0, GSL_CONST_NUM_EXA, GSL_CONST_NUM_EXA,\n\tGSL_CONST_NUM_EXA, GSL_CONST_NUM_EXA, GSL_CONST_NUM_EXA, GSL_CONST_MKSA_GRAV_ACCEL,\n\tGSL_CONST_NUM_GIGA, GSL_CONST_NUM_GIGA, GSL_CONST_NUM_GIGA, GSL_CONST_NUM_GIGA,\n\tGSL_CONST_NUM_GIGA, GSL_CONST_MKSA_JOULE*1000.0, GSL_CONST_MKSA_LITER,\n\tGSL_CONST_MKSA_MINUTE, GSL_CONST_NUM_MEGA, GSL_CONST_NUM_MEGA, GSL_CONST_NUM_MEGA,\n\tGSL_CONST_NUM_MEGA, GSL_CONST_NUM_MEGA, GSL_CONST_MKSA_NEWTON*1000.0, 1000,\n\tGSL_CONST_NUM_PETA, GSL_CONST_NUM_PETA, GSL_CONST_NUM_PETA, GSL_CONST_NUM_PETA,\n\tGSL_CONST_NUM_PETA, GSL_CONST_MKSA_RYDBERG*1000.0, GSL_CONST_MKSA_SOLAR_MASS*1000.0,\n\tGSL_CONST_NUM_TERA, GSL_CONST_NUM_TERA, GSL_CONST_NUM_TERA, GSL_CONST_NUM_TERA,\n\tGSL_CONST_NUM_TERA, GSL_CONST_MKSA_UNIFIED_ATOMIC_MASS*1000.0, GSL_CONST_MKSA_UK_GALLON,\n\tGSL_CONST_MKSA_UK_TON*1000.0, GSL_CONST_MKSA_US_GALLON, GSL_CONST_NUM_YOTTA,\n\tGSL_CONST_NUM_YOTTA, GSL_CONST_NUM_YOTTA, GSL_CONST_NUM_YOTTA, GSL_CONST_NUM_YOTTA,\n\tGSL_CONST_NUM_ZETTA, GSL_CONST_NUM_ZETTA, GSL_CONST_NUM_ZETTA, GSL_CONST_NUM_ZETTA,\n\tGSL_CONST_NUM_ZETTA, GSL_CONST_MKSA_ACRE, GSL_CONST_NUM_ATTO, GSL_CONST_NUM_ATTO,\n\tGSL_CONST_NUM_ATTO, GSL_CONST_NUM_ATTO, GSL_CONST_NUM_ATTO, GSL_CONST_MKSA_BARN,\n\tGSL_CONST_MKSA_BTU*1000.0, GSL_CONST_MKSA_SPEED_OF_LIGHT, GSL_CONST_MKSA_CALORIE*1000.0,\n\t3153600000, 1e-2, GSL_CONST_MKSA_CUP, 1e1, 315360000, 1e-1, GSL_CONST_MKSA_ERG*1000.0,\n\tGSL_CONST_NUM_FEMTO, GSL_CONST_MKSA_FLUID_OUNCE, GSL_CONST_NUM_FEMTO,\n\tGSL_CONST_NUM_FEMTO, GSL_CONST_NUM_FEMTO, GSL_CONST_NUM_FEMTO, GSL_CONST_MKSA_FOOT,\n\tGSL_CONST_MKSA_FATHOM, 1, 1, 1, 1, 1, 1, GSL_CONST_MKSA_GRAM_FORCE*1000.0,\n\tGSL_CONST_MKSA_HOUR, GSL_CONST_MKSA_HECTARE, 1e2, GSL_CONST_MKSA_INCH,\n\tGSL_CONST_NUM_KILO, GSL_CONST_MKSA_KILOPOUND_FORCE*1000.0, GSL_CONST_NUM_KILO,\n\tGSL_CONST_NUM_KILO, GSL_CONST_NUM_KILO, GSL_CONST_MKSA_KNOT,\n\tGSL_CONST_MKSA_KILOMETERS_PER_HOUR, GSL_CONST_NUM_KILO,\n\tGSL_CONST_MKSA_POUND_MASS*1000.0, GSL_CONST_MKSA_POUND_FORCE*1000.0,\n\tGSL_CONST_MKSA_LIGHT_YEAR, 1, 1, 1, GSL_CONST_MKSA_MASS_ELECTRON*1000.0,\n\tGSL_CONST_MKSA_MASS_MUON*1000.0, GSL_CONST_MKSA_MASS_NEUTRON*1000.0,\n\tGSL_CONST_MKSA_MASS_PROTON*1000.0, 1, 1, GSL_CONST_NUM_MILLI, GSL_CONST_MKSA_MILE,\n\tGSL_CONST_MKSA_MIL, 1e-6, 31536000000, GSL_CONST_NUM_MILLI, GSL_CONST_NUM_MILLI,\n\tGSL_CONST_NUM_MILLI, GSL_CONST_MKSA_MILES_PER_HOUR, GSL_CONST_NUM_MILLI,\n\tGSL_CONST_MKSA_METRIC_TON*1000.0, 2628288, GSL_CONST_NUM_NANO, GSL_CONST_NUM_NANO,\n\tGSL_CONST_NUM_NANO, GSL_CONST_NUM_NANO, GSL_CONST_MKSA_NAUTICAL_MILE,\n\tGSL_CONST_NUM_NANO, GSL_CONST_MKSA_OUNCE_MASS*1000.0, GSL_CONST_MKSA_POUNDAL*1000.0,\n\tGSL_CONST_NUM_PICO, GSL_CONST_NUM_PICO, GSL_CONST_NUM_PICO, GSL_CONST_NUM_PICO,\n\tGSL_CONST_NUM_PICO, GSL_CONST_MKSA_PINT, GSL_CONST_MKSA_QUART, 1, 1,\n\tGSL_CONST_MKSA_TON*1000.0, GSL_CONST_MKSA_TABLESPOON, GSL_CONST_MKSA_THERM*1000.0,\n\tGSL_CONST_MKSA_TROY_OUNCE*1000.0, GSL_CONST_MKSA_TEASPOON, GSL_CONST_NUM_MICRO, 1e-9,\n\tGSL_CONST_NUM_MICRO, GSL_CONST_NUM_MICRO, GSL_CONST_NUM_MICRO, GSL_CONST_NUM_MICRO,\n\tGSL_CONST_MKSA_WEEK, GSL_CONST_MKSA_YARD, GSL_CONST_NUM_YOCTO, GSL_CONST_NUM_YOCTO,\n\tGSL_CONST_NUM_YOCTO, GSL_CONST_NUM_YOCTO, 31536000, GSL_CONST_NUM_YOCTO,\n\tGSL_CONST_NUM_ZEPTO, GSL_CONST_NUM_ZEPTO, GSL_CONST_NUM_ZEPTO, GSL_CONST_NUM_ZEPTO,\n\tGSL_CONST_NUM_ZEPTO\n};\n\n/*\nReturns index of the unit in the unitNames array.\n\nUses binary search under the hood to search for the index.\n\nParameters\n----------\nname: The name of the unit\n\nReturns\n-------\nThe index or -1 if the provided name is not a unit.\n*/\nCONSTEXPR_BINARY_SEARCH(getUnitIndex, unitNames, numUnits)\n\nCONSTEXPR_BINARY_SEARCH(getAbbrIndex, unitAbbreviations, numUnits)\n\n\nconstexpr UnitType getUnitType(const char* name){\n    int index = getUnitIndex(name);\n    if (index != -1){\n\t\treturn NONE;\n\t}\n\treturn unitTypes[index];\n}\ninline UnitType getUnitType(const std::string& name){\n    int index = getUnitIndex(name.c_str());\n    if (index != -1){\n\t\treturn NONE;\n\t}\n\treturn unitTypes[index];\n}\ninline UnitType getUnitType(int index){\n    if (index < 0 || index >= numUnits){\n\t\treturn NONE;\n\t}\n\treturn unitTypes[index];\n}\n\nconstexpr double getUnitConversion(const char* name){\n    int index = getUnitIndex(name);\n    if (index != -1){\n\t\treturn NONE;\n\t}\n\treturn unitConversions[index];\n}\ninline double getUnitConversion(const std::string& name){\n    int index = getUnitIndex(name.c_str());\n    if (index != -1){\n\t\treturn NONE;\n\t}\n\treturn unitConversions[index];\n}\ninline double getUnitConversion(int index){\n    if (index < 0 || index >= numUnits){\n\t\treturn NONE;\n\t}\n\treturn unitConversions[index];\n}\n", "meta": {"hexsha": "c9ab21ebaeac616bd049152213105fa3198ce11e", "size": 10901, "ext": "h", "lang": "C", "max_stars_repo_path": "MathEngine/Expressions/UnitConversionExpression/Units.h", "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathEngine/Expressions/UnitConversionExpression/Units.h", "max_issues_repo_name": "antoniojkim/CalcPlusPlus", "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathEngine/Expressions/UnitConversionExpression/Units.h", "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.4198113208, "max_line_length": 89, "alphanum_fraction": 0.7092927254, "num_tokens": 4237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.39125142302002114}}
{"text": "/**\n *\n * @file core_scasum.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated c Tue Jan  7 11:44:46 2014\n *\n **/\n#include <cblas.h>\n#include <math.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex32_t\n *\n *  CORE_scasum - Computes the sums of the absolute values of elements in a same\n *  row or column.\n *  This function is an auxiliary function to norm computations.\n *\n *******************************************************************************\n *\n * @param[in] storev\n *          Specifies whether the sums are made per column or row.\n *          = PlasmaColumnwise: Computes the sum on each column\n *          = PlasmaRowwise:    Computes the sum on each row\n *\n * @param[in] uplo\n *          Specifies whether the matrix A is upper triangular or lower triangular or general\n *          = PlasmaUpperLower: All matrix A is referenced;\n *          = PlasmaUpper: Upper triangle of A is referenced;\n *          = PlasmaLower: Lower triangle of A is referenced.\n *\n * @param[in] M\n *          M specifies the number of rows of the matrix A. M >= 0.\n *\n * @param[in] N\n *          N specifies the number of columns of the matrix A. N >= 0.\n *\n * @param[in] A\n *          A is a M-by-N matrix.\n *\n * @param[in] lda\n *          The leading dimension of the array A. lda >= max(1,M).\n *\n * @param[out] work\n *          Array of dimension M if storev = PlasmaRowwise; N otherwise.\n *          On exit, contains the sums of the absolute values per column or row.\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_scasum = PCORE_scasum\n#define CORE_scasum PCORE_scasum\n#endif\nvoid CORE_scasum(PLASMA_enum storev, PLASMA_enum uplo, int M, int N,\n                 const PLASMA_Complex32_t *A, int lda, float *work)\n{\n    const PLASMA_Complex32_t *tmpA;\n    float *tmpW, sum, abs;\n    int i,j;\n\n    switch (uplo) {\n    case PlasmaUpper:\n        for (j = 0; j < N; j++) {\n            tmpA = A+(j*lda);\n            sum = 0.0;\n            for (i = 0; i < j; i++) {\n                abs      = cabsf(*tmpA);\n                sum     += abs;\n                work[i] += abs;\n                tmpA++;\n            }\n            work[j] += sum + cabsf(*tmpA);\n        }\n        break;\n    case PlasmaLower:\n        for (j = 0; j < N; j++) {\n            tmpA = A+(j*lda)+j;\n\n            sum = 0.0;\n            work[j] += cabsf(*tmpA);\n\n            tmpA++;\n            for (i = j+1; i < M; i++) {\n                abs      = cabsf(*tmpA);\n                sum     += abs;\n                work[i] += abs;\n                tmpA++;\n            }\n            work[j] += sum;\n        }\n        break;\n    case PlasmaUpperLower:\n    default:\n        if (storev == PlasmaColumnwise) {\n            for (j = 0; j < N; j++) {\n                /* work[j] += cblas_scasum(M, &(A[j*lda]), 1); */\n                tmpA = A+(j*lda);\n                for (i = 0; i < M; i++) {\n                    work[j] +=  cabsf(*tmpA);\n                    tmpA++;\n                }\n            }\n        }\n        else {\n            for (j = 0; j < N; j++) {\n                tmpA = A+(j*lda);\n                tmpW = work;\n                for (i = 0; i < M; i++) {\n                    /* work[i] += cabsf( A[j*lda+i] );*/\n                    *tmpW += cabsf( *tmpA );\n                    tmpA++; tmpW++;\n                }\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "65dd0bd9db8878c0f6f5405cc8bf8c80323e6f1f", "size": 3664, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_scasum.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_scasum.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_scasum.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.5483870968, "max_line_length": 93, "alphanum_fraction": 0.4495087336, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.39125142302002114}}
{"text": "#include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h\"\n#include <gsl/gsl_statistics.h>\nint main(int argc, const char * argv[]) {\nunsigned long int hexdouble;\nint a;\na = atoi(argv[1]);\nint argv_cnt = 2;\ndouble b[5];\nfor(int i = 0; i < a; i++) {\nsscanf(argv[argv_cnt++], \"%lX\", &hexdouble);\nb[i] = *(double*)(&hexdouble);\n}\nunsigned long c = 1;\ndouble d[5];\nfor(int i = 0; i < a; i++) {\nsscanf(argv[argv_cnt++], \"%lX\", &hexdouble);\nd[i] = *(double*)(&hexdouble);\n}\nunsigned long e = 1;\ndouble g;\nsscanf(argv[argv_cnt++], \"%lX\", &hexdouble);\ng = *(double*)(&hexdouble);\ndouble h;\nsscanf(argv[argv_cnt++], \"%lX\", &hexdouble);\nh = *(double*)(&hexdouble);\ndouble result = gsl_stats_wkurtosis_m_sd(b, c, d, e, a, g, h);\n//printf(\"%.15f\\n\", result);\nVALGRIND_PRINT_VALUES(\"result\", 1, &result);\nreturn 0;\n}", "meta": {"hexsha": "b100ffff08ce88daa68dd87a74bbc70add700ebf", "size": 861, "ext": "c", "lang": "C", "max_stars_repo_path": "others/stats/gsl_stats_wkurtosis_m_sd.c", "max_stars_repo_name": "floatfeather/FpGenetic", "max_stars_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "others/stats/gsl_stats_wkurtosis_m_sd.c", "max_issues_repo_name": "floatfeather/FpGenetic", "max_issues_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/stats/gsl_stats_wkurtosis_m_sd.c", "max_forks_repo_name": "floatfeather/FpGenetic", "max_forks_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_forks_repo_licenses": ["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.90625, "max_line_length": 78, "alphanum_fraction": 0.643437863, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.39122596565222606}}
{"text": "#include <cblas.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <papi.h>\n\n#ifndef MATLEN\n#define MATLEN 128\n#endif\n\n#ifndef QUIET\n#define PRINT( exp ) exp\n#else\n#define PRINT( exp )\n#endif\n\n\nint main( ) {\n  int EventSet = PAPI_NULL;\n  long long values[ 4 ], s, e;\n  int retval;\n  double *a, *b, *c;\n\n  /* INICIALIZA\u00c7\u00c3O */\n\n  PRINT( printf( \"Inicializando Matriz: %dx%d\\n\", MATLEN, MATLEN ) );\n\n  a = ( double* ) malloc( MATLEN * MATLEN * sizeof( double ) );\n  b = ( double* ) malloc( MATLEN * MATLEN * sizeof( double ) );\n  c = ( double* ) malloc( MATLEN * MATLEN * sizeof( double ) );\n\n  /*\n   * CONFIGURA\u00c7\u00c3O DO PAPI\n   * Init PAPI library\n   */\n  retval = PAPI_library_init( PAPI_VER_CURRENT );\n  if( retval != PAPI_VER_CURRENT ) {\n    printf( \"Erro em PAPI_library_init : retval = %d\\n\", retval );\n    exit( 1 );\n  }\n  if( ( retval = PAPI_create_eventset( &EventSet ) ) != PAPI_OK ) {\n    printf( \"Erro em PAPI_create_eventset : retval = %d\\n\", retval );\n    exit( 1 );\n  }\n  if( PAPI_add_event( EventSet, PAPI_L2_DCM ) != PAPI_OK ) {\n    printf( \"Erro em PAPI_L2_DCM\\n\" );\n    exit( 1 );\n  }\n  if( PAPI_add_event( EventSet, PAPI_DP_OPS ) != PAPI_OK ) {\n    printf( \"Erro em PAPI_DP_OPS\\n\" );\n    exit( 1 );\n  }\n  if( PAPI_add_event( EventSet, PAPI_TOT_CYC ) != PAPI_OK ) {\n    printf( \"Erro em PAPI_TOT_CYC\\n\" );\n    exit( 1 );\n  }\n  if( PAPI_add_event( EventSet, PAPI_TOT_INS ) != PAPI_OK ) {\n    printf( \"Erro em PAPI_TOT_INS\\n\" );\n    exit( 1 );\n  }\n  if( ( retval = PAPI_start( EventSet ) ) != PAPI_OK ) {\n    printf( \"Erro em PAPI_start\" );\n    exit( 1 );\n  }\n  s = PAPI_get_real_usec( );\n  /* FUN\u00c7\u00c3O A SER AVALIADA */\n\n  cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,\n               MATLEN, MATLEN, MATLEN, 1.0, a, MATLEN,\n               b, MATLEN, 0.0, c, MATLEN );\n\n  /* FIM DA FUN\u00c7\u00c3O A SER AVALIADA */\n  e = PAPI_get_real_usec( );\n  if( ( retval = PAPI_read( EventSet, &values[ 0 ] ) ) != PAPI_OK ) {\n    printf( \"Erro em PAPI_read\" );\n    exit( 1 );\n  }\n  if( ( retval = PAPI_stop( EventSet, NULL ) ) != PAPI_OK ) {\n    printf( \"Erro em PAPI_stop\" );\n    exit( 1 );\n  }\n  double cpi = ( double ) values[ 2 ] / ( double ) values[ 3 ];\n  double icp = ( double ) values[ 3 ] / ( double ) values[ 2 ];\n  double mflops = ( double ) values[ 1 ];\n  // double mflops = ( double ) 2 * MATLEN * MATLEN * MATLEN;\n  mflops = ( mflops / ( ( double ) ( e - s ) ) );\n  /* EXIBINDO INFORMA\u00c7\u00d5ES */\n  PRINT(\n    printf( \"PAPI_L2_DCM = %lld\\n\", values[ 0 ] );\n    printf( \"PAPI_DP_OPS = %lld\\n\", values[ 1 ] );\n\n    /* CPI */\n    printf( \"PAPI_TOT_CYC = %lld\\n\", values[ 2 ] );\n    printf( \"PAPI_TOT_INS = %lld\\n\", values[ 3 ] );\n    printf( \"CPI: %.2f\\n\", cpi );\n    printf( \"ICP: %.2f\\n\", icp );\n\n    printf( \"Wallclock time: %lld ms\\n\", e - s );\n    printf( \"MFLOPS: %g\\n\", mflops );\n    printf( \"Fim\\n\" );\n    );\n  /*       MAT BLk Time  DCM   MFLOPS CPI */\n  printf( \"%d, %lld, %lld, %.2f, %.2f\\n\", MATLEN, e - s, values[ 0 ], mflops, cpi );\n  free( a );\n  free( b );\n  free( c );\n  return( 0 );\n}\n", "meta": {"hexsha": "6c5235fd137bea3d24578d9e2e599545c8df1ae5", "size": 3010, "ext": "c", "lang": "C", "max_stars_repo_path": "at02-cache/ex04/ex04.c", "max_stars_repo_name": "lellisls/PAD", "max_stars_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "at02-cache/ex04/ex04.c", "max_issues_repo_name": "lellisls/PAD", "max_issues_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "at02-cache/ex04/ex04.c", "max_forks_repo_name": "lellisls/PAD", "max_forks_repo_head_hexsha": "eb4fcb9c19ca4fc2cba2a392928957efe4bd5198", "max_forks_repo_licenses": ["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.8703703704, "max_line_length": 84, "alphanum_fraction": 0.5700996678, "num_tokens": 1071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3908901156725145}}
{"text": "/* specfunc/bessel.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author:  G. Jungman */\n/* Miscellaneous support functions for Bessel function evaluations.\n */\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include \"gsl_sf_airy.h\"\n#include \"gsl_sf_elementary.h\"\n#include \"gsl_sf_exp.h\"\n#include \"gsl_sf_gamma.h\"\n#include \"gsl_sf_trig.h\"\n\n#include \"error.h\"\n\n#include \"bessel_amp_phase.h\"\n#include \"bessel_temme.h\"\n#include \"bessel.h\"\n\n#define CubeRoot2_  1.25992104989487316476721060728\n\n\n\n/* Debye functions [Abramowitz+Stegun, 9.3.9-10] */\n\ninline static double \ndebye_u1(const double * tpow)\n{\n  return (3.0*tpow[1] - 5.0*tpow[3])/24.0;\n}\n\ninline static double \ndebye_u2(const double * tpow)\n{\n  return (81.0*tpow[2] - 462.0*tpow[4] + 385.0*tpow[6])/1152.0;\n}\n\ninline\nstatic double debye_u3(const double * tpow)\n{\n  return (30375.0*tpow[3] - 369603.0*tpow[5] + 765765.0*tpow[7] - 425425.0*tpow[9])/414720.0;\n}\n\ninline\nstatic double debye_u4(const double * tpow)\n{\n  return (4465125.0*tpow[4] - 94121676.0*tpow[6] + 349922430.0*tpow[8] - \n          446185740.0*tpow[10] + 185910725.0*tpow[12])/39813120.0;\n}\n\ninline\nstatic double debye_u5(const double * tpow)\n{\n  return (1519035525.0*tpow[5]     - 49286948607.0*tpow[7] + \n          284499769554.0*tpow[9]   - 614135872350.0*tpow[11] + \n          566098157625.0*tpow[13]  - 188699385875.0*tpow[15])/6688604160.0;\n}\n\n#if 0\ninline\nstatic double debye_u6(const double * tpow)\n{\n  return (2757049477875.0*tpow[6] - 127577298354750.0*tpow[8] + \n          1050760774457901.0*tpow[10] - 3369032068261860.0*tpow[12] + \n          5104696716244125.0*tpow[14] - 3685299006138750.0*tpow[16] + \n          1023694168371875.0*tpow[18])/4815794995200.0;\n}\n#endif\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_bessel_IJ_taylor_e(const double nu, const double x,\n                             const int sign,\n                             const int kmax,\n                             const double threshold,\n                             gsl_sf_result * result\n                             )\n{\n  /* CHECK_POINTER(result) */\n\n  if(nu < 0.0 || x < 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x == 0.0) {\n    if(nu == 0.0) {\n      result->val = 1.0;\n      result->err = 0.0;\n    }\n    else {\n      result->val = 0.0;\n      result->err = 0.0;\n    }\n    return GSL_SUCCESS;\n  }\n  else {\n    gsl_sf_result prefactor;   /* (x/2)^nu / Gamma(nu+1) */\n    gsl_sf_result sum;\n\n    int stat_pre;\n    int stat_sum;\n    int stat_mul;\n\n    if(nu == 0.0) {\n      prefactor.val = 1.0;\n      prefactor.err = 0.0;\n      stat_pre = GSL_SUCCESS;\n    }\n    else if(nu < INT_MAX-1) {\n      /* Separate the integer part and use\n       * y^nu / Gamma(nu+1) = y^N /N! y^f / (N+1)_f,\n       * to control the error.\n       */\n      const int    N = (int)floor(nu + 0.5);\n      const double f = nu - N;\n      gsl_sf_result poch_factor;\n      gsl_sf_result tc_factor;\n      const int stat_poch = gsl_sf_poch_e(N+1.0, f, &poch_factor);\n      const int stat_tc   = gsl_sf_taylorcoeff_e(N, 0.5*x, &tc_factor);\n      const double p = pow(0.5*x,f);\n      prefactor.val  = tc_factor.val * p / poch_factor.val;\n      prefactor.err  = tc_factor.err * p / poch_factor.val;\n      prefactor.err += fabs(prefactor.val) / poch_factor.val * poch_factor.err;\n      prefactor.err += 2.0 * GSL_DBL_EPSILON * fabs(prefactor.val);\n      stat_pre = GSL_ERROR_SELECT_2(stat_tc, stat_poch);\n    }\n    else {\n      gsl_sf_result lg;\n      const int stat_lg = gsl_sf_lngamma_e(nu+1.0, &lg);\n      const double term1  = nu*log(0.5*x);\n      const double term2  = lg.val;\n      const double ln_pre = term1 - term2;\n      const double ln_pre_err = GSL_DBL_EPSILON * (fabs(term1)+fabs(term2)) + lg.err;\n      const int stat_ex = gsl_sf_exp_err_e(ln_pre, ln_pre_err, &prefactor);\n      stat_pre = GSL_ERROR_SELECT_2(stat_ex, stat_lg);\n    }\n\n    /* Evaluate the sum.\n     * [Abramowitz+Stegun, 9.1.10]\n     * [Abramowitz+Stegun, 9.6.7]\n     */\n    {\n      const double y = sign * 0.25 * x*x;\n      double sumk = 1.0;\n      double term = 1.0;\n      int k;\n\n      for(k=1; k<=kmax; k++) {\n        term *= y/((nu+k)*k);\n        sumk += term;\n        if(fabs(term/sumk) < threshold) break;\n      }\n\n      sum.val = sumk;\n      sum.err = threshold * fabs(sumk);\n\n      stat_sum = ( k >= kmax ? GSL_EMAXITER : GSL_SUCCESS );\n    }\n\n    stat_mul = gsl_sf_multiply_err_e(prefactor.val, prefactor.err,\n                                        sum.val, sum.err,\n                                        result);\n\n    return GSL_ERROR_SELECT_3(stat_mul, stat_pre, stat_sum);\n  }\n}\n\n\n/* x >> nu*nu+1\n * error ~ O( ((nu*nu+1)/x)^3 )\n *\n * empirical error analysis:\n *   choose  GSL_ROOT3_MACH_EPS * x > (nu*nu + 1)\n *\n * This is not especially useful. When the argument gets\n * large enough for this to apply, the cos() and sin()\n * start loosing digits. However, this seems inevitable\n * for this particular method.\n */\nint\ngsl_sf_bessel_Jnu_asympx_e(const double nu, const double x, gsl_sf_result * result)\n{\n  double mu   = 4.0*nu*nu;\n  double mum1 = mu-1.0;\n  double mum9 = mu-9.0;\n  double chi = x - (0.5*nu + 0.25)*M_PI;\n  double P   = 1.0 - mum1*mum9/(128.0*x*x);\n  double Q   = mum1/(8.0*x);\n  double pre = sqrt(2.0/(M_PI*x));\n  double c   = cos(chi);\n  double s   = sin(chi);\n  double r   = mu/x;\n  result->val  = pre * (c*P - s*Q);\n  result->err  = pre * GSL_DBL_EPSILON * (fabs(c*P) + fabs(s*Q));\n  result->err += pre * fabs(0.1*r*r*r);\n  return GSL_SUCCESS;\n}\n\n\n/* x >> nu*nu+1\n */\nint\ngsl_sf_bessel_Ynu_asympx_e(const double nu, const double x, gsl_sf_result * result)\n{\n  double ampl;\n  double theta;\n  double alpha = x;\n  double beta  = -0.5*nu*M_PI;\n  int stat_a = gsl_sf_bessel_asymp_Mnu_e(nu, x, &ampl);\n  int stat_t = gsl_sf_bessel_asymp_thetanu_corr_e(nu, x, &theta);\n  double sin_alpha = sin(alpha);\n  double cos_alpha = cos(alpha);\n  double sin_chi   = sin(beta + theta);\n  double cos_chi   = cos(beta + theta);\n  double sin_term     = sin_alpha * cos_chi + sin_chi * cos_alpha;\n  double sin_term_mag = fabs(sin_alpha * cos_chi) + fabs(sin_chi * cos_alpha);\n  result->val  = ampl * sin_term;\n  result->err  = fabs(ampl) * GSL_DBL_EPSILON * sin_term_mag;\n  result->err += fabs(result->val) * 2.0 * GSL_DBL_EPSILON;\n\n  if(fabs(alpha) > 1.0/GSL_DBL_EPSILON) {\n    result->err *= 0.5 * fabs(alpha);\n  }\n  else if(fabs(alpha) > 1.0/GSL_SQRT_DBL_EPSILON) {\n    result->err *= 256.0 * fabs(alpha) * GSL_SQRT_DBL_EPSILON;\n  }\n\n  return GSL_ERROR_SELECT_2(stat_t, stat_a);\n}\n\n\n/* x >> nu*nu+1\n */\nint\ngsl_sf_bessel_Inu_scaled_asympx_e(const double nu, const double x, gsl_sf_result * result)\n{\n  double mu   = 4.0*nu*nu;\n  double mum1 = mu-1.0;\n  double mum9 = mu-9.0;\n  double pre  = 1.0/sqrt(2.0*M_PI*x);\n  double r    = mu/x;\n  result->val = pre * (1.0 - mum1/(8.0*x) + mum1*mum9/(128.0*x*x));\n  result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val) + pre * fabs(0.1*r*r*r);\n  return GSL_SUCCESS;\n}\n\n/* x >> nu*nu+1\n */\nint\ngsl_sf_bessel_Knu_scaled_asympx_e(const double nu, const double x, gsl_sf_result * result)\n{\n  double mu   = 4.0*nu*nu;\n  double mum1 = mu-1.0;\n  double mum9 = mu-9.0;\n  double pre  = sqrt(M_PI/(2.0*x));\n  double r    = nu/x;\n  result->val = pre * (1.0 + mum1/(8.0*x) + mum1*mum9/(128.0*x*x));\n  result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val) + pre * fabs(0.1*r*r*r);\n  return GSL_SUCCESS;\n}\n\n\n/* nu -> Inf; uniform in x > 0  [Abramowitz+Stegun, 9.7.7]\n *\n * error:\n *   The error has the form u_N(t)/nu^N  where  0 <= t <= 1.\n *   It is not hard to show that |u_N(t)| is small for such t.\n *   We have N=6 here, and |u_6(t)| < 0.025, so the error is clearly\n *   bounded by 0.025/nu^6. This gives the asymptotic bound on nu\n *   seen below as nu ~ 100. For general MACH_EPS it will be \n *                     nu > 0.5 / MACH_EPS^(1/6)\n *   When t is small, the bound is even better because |u_N(t)| vanishes\n *   as t->0. In fact u_N(t) ~ C t^N as t->0, with C ~= 0.1.\n *   We write\n *                     err_N <= min(0.025, C(1/(1+(x/nu)^2))^3) / nu^6\n *   therefore\n *                     min(0.29/nu^2, 0.5/(nu^2+x^2)) < MACH_EPS^{1/3}\n *   and this is the general form.\n *\n * empirical error analysis, assuming 14 digit requirement:\n *   choose   x > 50.000 nu   ==>  nu >   3\n *   choose   x > 10.000 nu   ==>  nu >  15\n *   choose   x >  2.000 nu   ==>  nu >  50\n *   choose   x >  1.000 nu   ==>  nu >  75\n *   choose   x >  0.500 nu   ==>  nu >  80\n *   choose   x >  0.100 nu   ==>  nu >  83\n *\n * This makes sense. For x << nu, the error will be of the form u_N(1)/nu^N,\n * since the polynomial term will be evaluated near t=1, so the bound\n * on nu will become constant for small x. Furthermore, increasing x with\n * nu fixed will decrease the error.\n */\nint\ngsl_sf_bessel_Inu_scaled_asymp_unif_e(const double nu, const double x, gsl_sf_result * result)\n{\n  int i;\n  double z = x/nu;\n  double root_term = sqrt(1.0 + z*z);\n  double pre = 1.0/sqrt(2.0*M_PI*nu * root_term);\n  double eta = root_term + log(z/(1.0+root_term));\n  double ex_arg = ( z < 1.0/GSL_ROOT3_DBL_EPSILON ? nu*(-z + eta) : -0.5*nu/z*(1.0 - 1.0/(12.0*z*z)) );\n  gsl_sf_result ex_result;\n  int stat_ex = gsl_sf_exp_e(ex_arg, &ex_result);\n  if(stat_ex == GSL_SUCCESS) {\n    double t = 1.0/root_term;\n    double sum;\n    double tpow[16];\n    tpow[0] = 1.0;\n    for(i=1; i<16; i++) tpow[i] = t * tpow[i-1];\n    sum = 1.0 + debye_u1(tpow)/nu + debye_u2(tpow)/(nu*nu) + debye_u3(tpow)/(nu*nu*nu)\n          + debye_u4(tpow)/(nu*nu*nu*nu) + debye_u5(tpow)/(nu*nu*nu*nu*nu);\n    result->val  = pre * ex_result.val * sum;\n    result->err  = pre * ex_result.val / (nu*nu*nu*nu*nu*nu);\n    result->err += pre * ex_result.err * fabs(sum);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    result->val = 0.0;\n    result->err = 0.0;\n    return stat_ex;\n  }\n}\n\n\n/* nu -> Inf; uniform in x > 0  [Abramowitz+Stegun, 9.7.8]\n *\n * error:\n *   identical to that above for Inu_scaled\n */\nint\ngsl_sf_bessel_Knu_scaled_asymp_unif_e(const double nu, const double x, gsl_sf_result * result)\n{\n  int i;\n  double z = x/nu;\n  double root_term = sqrt(1.0 + z*z);\n  double pre = sqrt(M_PI/(2.0*nu*root_term));\n  double eta = root_term + log(z/(1.0+root_term));\n  double ex_arg = ( z < 1.0/GSL_ROOT3_DBL_EPSILON ? nu*(z - eta) : 0.5*nu/z*(1.0 + 1.0/(12.0*z*z)) );\n  gsl_sf_result ex_result;\n  int stat_ex = gsl_sf_exp_e(ex_arg, &ex_result);\n  if(stat_ex == GSL_SUCCESS) {\n    double t = 1.0/root_term;\n    double sum;\n    double tpow[16];\n    tpow[0] = 1.0;\n    for(i=1; i<16; i++) tpow[i] = t * tpow[i-1];\n    sum = 1.0 - debye_u1(tpow)/nu + debye_u2(tpow)/(nu*nu) - debye_u3(tpow)/(nu*nu*nu)\n          + debye_u4(tpow)/(nu*nu*nu*nu) - debye_u5(tpow)/(nu*nu*nu*nu*nu);\n    result->val  = pre * ex_result.val * sum;\n    result->err  = pre * ex_result.err * fabs(sum);\n    result->err += pre * ex_result.val / (nu*nu*nu*nu*nu*nu);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    result->val = 0.0;\n    result->err = 0.0;\n    return stat_ex;\n  }\n}\n\n\n/* Evaluate J_mu(x),J_{mu+1}(x) and Y_mu(x),Y_{mu+1}(x)  for |mu| < 1/2\n */\nint\ngsl_sf_bessel_JY_mu_restricted(const double mu, const double x,\n                               gsl_sf_result * Jmu, gsl_sf_result * Jmup1,\n                               gsl_sf_result * Ymu, gsl_sf_result * Ymup1)\n{\n  /* CHECK_POINTER(Jmu) */\n  /* CHECK_POINTER(Jmup1) */\n  /* CHECK_POINTER(Ymu) */\n  /* CHECK_POINTER(Ymup1) */\n\n  if(x < 0.0 || fabs(mu) > 0.5) {\n    Jmu->val   = 0.0;\n    Jmu->err   = 0.0;\n    Jmup1->val = 0.0;\n    Jmup1->err = 0.0;\n    Ymu->val   = 0.0;\n    Ymu->err   = 0.0;\n    Ymup1->val = 0.0;\n    Ymup1->err = 0.0;\n    GSL_ERROR (\"error\", GSL_EDOM);\n  }\n  else if(x == 0.0) {\n    if(mu == 0.0) {\n      Jmu->val   = 1.0;\n      Jmu->err   = 0.0;\n    }\n    else {\n      Jmu->val   = 0.0;\n      Jmu->err   = 0.0;\n    }\n    Jmup1->val = 0.0;\n    Jmup1->err = 0.0;\n    Ymu->val   = 0.0;\n    Ymu->err   = 0.0;\n    Ymup1->val = 0.0;\n    Ymup1->err = 0.0;\n    GSL_ERROR (\"error\", GSL_EDOM);\n  }\n  else {\n    int stat_Y;\n    int stat_J;\n\n    if(x < 2.0) {\n      /* Use Taylor series for J and the Temme series for Y.\n       * The Taylor series for J requires nu > 0, so we shift\n       * up one and use the recursion relation to get Jmu, in\n       * case mu < 0.\n       */\n      gsl_sf_result Jmup2;\n      int stat_J1 = gsl_sf_bessel_IJ_taylor_e(mu+1.0, x, -1, 100, GSL_DBL_EPSILON,  Jmup1);\n      int stat_J2 = gsl_sf_bessel_IJ_taylor_e(mu+2.0, x, -1, 100, GSL_DBL_EPSILON, &Jmup2);\n      double c = 2.0*(mu+1.0)/x;\n      Jmu->val  = c * Jmup1->val - Jmup2.val;\n      Jmu->err  = c * Jmup1->err + Jmup2.err;\n      Jmu->err += 2.0 * GSL_DBL_EPSILON * fabs(Jmu->val);\n      stat_J = GSL_ERROR_SELECT_2(stat_J1, stat_J2);\n      stat_Y = gsl_sf_bessel_Y_temme(mu, x, Ymu, Ymup1);\n      return GSL_ERROR_SELECT_2(stat_J, stat_Y);\n    }\n    else if(x < 1000.0) {\n      double P, Q;\n      double J_ratio;\n      double J_sgn;\n      const int stat_CF1 = gsl_sf_bessel_J_CF1(mu, x, &J_ratio, &J_sgn);\n      const int stat_CF2 = gsl_sf_bessel_JY_steed_CF2(mu, x, &P, &Q);\n      double Jprime_J_ratio = mu/x - J_ratio;\n      double gamma = (P - Jprime_J_ratio)/Q;\n      Jmu->val = J_sgn * sqrt(2.0/(M_PI*x) / (Q + gamma*(P-Jprime_J_ratio)));\n      Jmu->err = 4.0 * GSL_DBL_EPSILON * fabs(Jmu->val);\n      Jmup1->val = J_ratio * Jmu->val;\n      Jmup1->err = fabs(J_ratio) * Jmu->err;\n      Ymu->val = gamma * Jmu->val;\n      Ymu->err = fabs(gamma) * Jmu->err;\n      Ymup1->val = Ymu->val * (mu/x - P - Q/gamma);\n      Ymup1->err = Ymu->err * fabs(mu/x - P - Q/gamma) + 4.0*GSL_DBL_EPSILON*fabs(Ymup1->val);\n      return GSL_ERROR_SELECT_2(stat_CF1, stat_CF2);\n    }\n    else {\n      /* Use asymptotics for large argument.\n       */\n      const int stat_J0 = gsl_sf_bessel_Jnu_asympx_e(mu,     x, Jmu);\n      const int stat_J1 = gsl_sf_bessel_Jnu_asympx_e(mu+1.0, x, Jmup1);\n      const int stat_Y0 = gsl_sf_bessel_Ynu_asympx_e(mu,     x, Ymu);\n      const int stat_Y1 = gsl_sf_bessel_Ynu_asympx_e(mu+1.0, x, Ymup1);\n      stat_J = GSL_ERROR_SELECT_2(stat_J0, stat_J1);\n      stat_Y = GSL_ERROR_SELECT_2(stat_Y0, stat_Y1);\n      return GSL_ERROR_SELECT_2(stat_J, stat_Y);\n    }\n  }\n}\n\n\nint\ngsl_sf_bessel_J_CF1(const double nu, const double x,\n                    double * ratio, double * sgn)\n{\n  const double RECUR_BIG = GSL_SQRT_DBL_MAX;\n  const int maxiter = 10000;\n  int n = 1;\n  double Anm2 = 1.0;\n  double Bnm2 = 0.0;\n  double Anm1 = 0.0;\n  double Bnm1 = 1.0;\n  double a1 = x/(2.0*(nu+1.0));\n  double An = Anm1 + a1*Anm2;\n  double Bn = Bnm1 + a1*Bnm2;\n  double an;\n  double fn = An/Bn;\n  double dn = a1;\n  double s  = 1.0;\n\n  while(n < maxiter) {\n    double old_fn;\n    double del;\n    n++;\n    Anm2 = Anm1;\n    Bnm2 = Bnm1;\n    Anm1 = An;\n    Bnm1 = Bn;\n    an = -x*x/(4.0*(nu+n-1.0)*(nu+n));\n    An = Anm1 + an*Anm2;\n    Bn = Bnm1 + an*Bnm2;\n\n    if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) {\n      An /= RECUR_BIG;\n      Bn /= RECUR_BIG;\n      Anm1 /= RECUR_BIG;\n      Bnm1 /= RECUR_BIG;\n      Anm2 /= RECUR_BIG;\n      Bnm2 /= RECUR_BIG;\n    }\n\n    old_fn = fn;\n    fn = An/Bn;\n    del = old_fn/fn;\n\n    dn = 1.0 / (2.0*(nu+n)/x - dn);\n    if(dn < 0.0) s = -s;\n\n    if(fabs(del - 1.0) < 2.0*GSL_DBL_EPSILON) break;\n  }\n\n  *ratio = fn;\n  *sgn   = s;\n\n  if(n >= maxiter)\n    GSL_ERROR (\"error\", GSL_EMAXITER);\n  else\n    return GSL_SUCCESS;\n}\n\n\n\n/* Evaluate the continued fraction CF1 for J_{nu+1}/J_nu\n * using Gautschi (Euler) equivalent series.\n * This exhibits an annoying problem because the\n * a_k are not positive definite (in fact they are all negative).\n * There are cases when rho_k blows up. Example: nu=1,x=4.\n */\n#if 0\nint\ngsl_sf_bessel_J_CF1_ser(const double nu, const double x,\n                        double * ratio, double * sgn)\n{\n  const int maxk = 20000;\n  double tk   = 1.0;\n  double sum  = 1.0;\n  double rhok = 0.0;\n  double dk = 0.0;\n  double s  = 1.0;\n  int k;\n\n  for(k=1; k<maxk; k++) {\n    double ak = -0.25 * (x/(nu+k)) * x/(nu+k+1.0);\n    rhok = -ak*(1.0 + rhok)/(1.0 + ak*(1.0 + rhok));\n    tk  *= rhok;\n    sum += tk;\n\n    dk = 1.0 / (2.0/x - (nu+k-1.0)/(nu+k) * dk);\n    if(dk < 0.0) s = -s;\n\n    if(fabs(tk/sum) < GSL_DBL_EPSILON) break;\n  }\n\n  *ratio = x/(2.0*(nu+1.0)) * sum;\n  *sgn   = s;\n\n  if(k == maxk)\n    GSL_ERROR (\"error\", GSL_EMAXITER);\n  else\n    return GSL_SUCCESS;\n}\n#endif\n\n\n/* Evaluate the continued fraction CF1 for I_{nu+1}/I_nu\n * using Gautschi (Euler) equivalent series.\n */\nint\ngsl_sf_bessel_I_CF1_ser(const double nu, const double x, double * ratio)\n{\n  const int maxk = 20000;\n  double tk   = 1.0;\n  double sum  = 1.0;\n  double rhok = 0.0;\n  int k;\n\n  for(k=1; k<maxk; k++) {\n    double ak = 0.25 * (x/(nu+k)) * x/(nu+k+1.0);\n    rhok = -ak*(1.0 + rhok)/(1.0 + ak*(1.0 + rhok));\n    tk  *= rhok;\n    sum += tk;\n    if(fabs(tk/sum) < GSL_DBL_EPSILON) break;\n  }\n\n  *ratio = x/(2.0*(nu+1.0)) * sum;\n\n  if(k == maxk)\n    GSL_ERROR (\"error\", GSL_EMAXITER);\n  else\n    return GSL_SUCCESS;\n}\n\n\nint\ngsl_sf_bessel_JY_steed_CF2(const double nu, const double x,\n                           double * P, double * Q)\n{\n  const int max_iter = 10000;\n  const double SMALL = 1.0e-100;\n\n  int i = 1;\n\n  double x_inv = 1.0/x;\n  double a = 0.25 - nu*nu;\n  double p = -0.5*x_inv;\n  double q = 1.0;\n  double br = 2.0*x;\n  double bi = 2.0;\n  double fact = a*x_inv/(p*p + q*q);\n  double cr = br + q*fact;\n  double ci = bi + p*fact;\n  double den = br*br + bi*bi;\n  double dr = br/den;\n  double di = -bi/den;\n  double dlr = cr*dr - ci*di;\n  double dli = cr*di + ci*dr;\n  double temp = p*dlr - q*dli;\n  q = p*dli + q*dlr;\n  p = temp;\n  for (i=2; i<=max_iter; i++) {\n    a  += 2*(i-1);\n    bi += 2.0;\n    dr = a*dr + br;\n    di = a*di + bi;\n    if(fabs(dr)+fabs(di) < SMALL) dr = SMALL;\n    fact = a/(cr*cr+ci*ci);\n    cr = br + cr*fact;\n    ci = bi - ci*fact;\n    if(fabs(cr)+fabs(ci) < SMALL) cr = SMALL;\n    den = dr*dr + di*di;\n    dr /= den;\n    di /= -den;\n    dlr = cr*dr - ci*di;\n    dli = cr*di + ci*dr;\n    temp = p*dlr - q*dli;\n    q = p*dli + q*dlr;\n    p = temp;\n    if(fabs(dlr-1.0)+fabs(dli) < GSL_DBL_EPSILON) break;\n  }\n\n  *P = p;\n  *Q = q;\n\n  if(i == max_iter)\n    GSL_ERROR (\"error\", GSL_EMAXITER);\n  else\n    return GSL_SUCCESS;\n}\n\n\n/* Evaluate continued fraction CF2, using Thompson-Barnett-Temme method,\n * to obtain values of exp(x)*K_nu and exp(x)*K_{nu+1}.\n *\n * This is unstable for small x; x > 2 is a good cutoff.\n * Also requires |nu| < 1/2.\n */\nint\ngsl_sf_bessel_K_scaled_steed_temme_CF2(const double nu, const double x,\n                                       double * K_nu, double * K_nup1,\n                                       double * Kp_nu)\n{\n  const int maxiter = 10000;\n\n  int i = 1;\n  double bi = 2.0*(1.0 + x);\n  double di = 1.0/bi;\n  double delhi = di;\n  double hi    = di;\n\n  double qi   = 0.0;\n  double qip1 = 1.0;\n\n  double ai = -(0.25 - nu*nu);\n  double a1 = ai;\n  double ci = -ai;\n  double Qi = -ai;\n\n  double s = 1.0 + Qi*delhi;\n\n  for(i=2; i<=maxiter; i++) {\n    double dels;\n    double tmp;\n    ai -= 2.0*(i-1);\n    ci  = -ai*ci/i;\n    tmp  = (qi - bi*qip1)/ai;\n    qi   = qip1;\n    qip1 = tmp;\n    Qi += ci*qip1;\n    bi += 2.0;\n    di  = 1.0/(bi + ai*di);\n    delhi = (bi*di - 1.0) * delhi;\n    hi += delhi;\n    dels = Qi*delhi;\n    s += dels;\n    if(fabs(dels/s) < GSL_DBL_EPSILON) break;\n  }\n  \n  hi *= -a1;\n  \n  *K_nu   = sqrt(M_PI/(2.0*x)) / s;\n  *K_nup1 = *K_nu * (nu + x + 0.5 - hi)/x;\n  *Kp_nu  = - *K_nup1 + nu/x * *K_nu;\n  if(i == maxiter)\n    GSL_ERROR (\"error\", GSL_EMAXITER);\n  else\n    return GSL_SUCCESS;\n}\n\n\nint gsl_sf_bessel_cos_pi4_e(double y, double eps, gsl_sf_result * result)\n{\n  const double sy = sin(y);\n  const double cy = cos(y);\n  const double s = sy + cy;\n  const double d = sy - cy;\n  const double abs_sum = fabs(cy) + fabs(sy);\n  double seps;\n  double ceps;\n  if(fabs(eps) < GSL_ROOT5_DBL_EPSILON) {\n    const double e2 = eps*eps;\n    seps = eps * (1.0 - e2/6.0 * (1.0 - e2/20.0));\n    ceps = 1.0 - e2/2.0 * (1.0 - e2/12.0);\n  }\n  else {\n    seps = sin(eps);\n    ceps = cos(eps);\n  }\n  result->val = (ceps * s - seps * d)/ M_SQRT2;\n  result->err = 2.0 * GSL_DBL_EPSILON * (fabs(ceps) + fabs(seps)) * abs_sum / M_SQRT2;\n\n  /* Try to account for error in evaluation of sin(y), cos(y).\n   * This is a little sticky because we don't really know\n   * how the library routines are doing their argument reduction.\n   * However, we will make a reasonable guess.\n   * FIXME ?\n   */\n  if(y > 1.0/GSL_DBL_EPSILON) {\n    result->err *= 0.5 * y;\n  }\n  else if(y > 1.0/GSL_SQRT_DBL_EPSILON) {\n    result->err *= 256.0 * y * GSL_SQRT_DBL_EPSILON;\n  }\n\n  return GSL_SUCCESS;\n}\n\n\nint gsl_sf_bessel_sin_pi4_e(double y, double eps, gsl_sf_result * result)\n{\n  const double sy = sin(y);\n  const double cy = cos(y);\n  const double s = sy + cy;\n  const double d = sy - cy;\n  const double abs_sum = fabs(cy) + fabs(sy);\n  double seps;\n  double ceps;\n  if(fabs(eps) < GSL_ROOT5_DBL_EPSILON) {\n    const double e2 = eps*eps;\n    seps = eps * (1.0 - e2/6.0 * (1.0 - e2/20.0));\n    ceps = 1.0 - e2/2.0 * (1.0 - e2/12.0);\n  }\n  else {\n    seps = sin(eps);\n    ceps = cos(eps);\n  }\n  result->val = (ceps * d + seps * s)/ M_SQRT2;\n  result->err = 2.0 * GSL_DBL_EPSILON * (fabs(ceps) + fabs(seps)) * abs_sum / M_SQRT2;\n\n  /* Try to account for error in evaluation of sin(y), cos(y).\n   * See above.\n   * FIXME ?\n   */\n  if(y > 1.0/GSL_DBL_EPSILON) {\n    result->err *= 0.5 * y;\n  }\n  else if(y > 1.0/GSL_SQRT_DBL_EPSILON) {\n    result->err *= 256.0 * y * GSL_SQRT_DBL_EPSILON;\n  }\n\n  return GSL_SUCCESS;\n}\n\n\n/************************************************************************\n *                                                                      *\n  Asymptotic approximations 8.11.5, 8.12.5, and 8.42.7 from\n  G.N.Watson, A Treatise on the Theory of Bessel Functions,\n  2nd Edition (Cambridge University Press, 1944).\n  Higher terms in expansion for x near l given by\n  Airey in Phil. Mag. 31, 520 (1916).\n\n  This approximation is accurate to near 0.1% at the boundaries\n  between the asymptotic regions; well away from the boundaries\n  the accuracy is better than 10^{-5}.\n *                                                                      *\n ************************************************************************/\n#if 0\ndouble besselJ_meissel(double nu, double x)\n{\n  double beta = pow(nu, 0.325);\n  double result;\n\n  /* Fitted matching points.   */\n  double llimit = 1.1 * beta;\n  double ulimit = 1.3 * beta;\n\n  double nu2 = nu * nu;\n\n  if (nu < 5. && x < 1.)\n    {\n      /* Small argument and order. Use a Taylor expansion. */\n      int k;\n      double xo2 = 0.5 * x;\n      double gamfactor = pow(nu,nu) * exp(-nu) * sqrt(nu * 2. * M_PI)\n\t* (1. + 1./(12.*nu) + 1./(288.*nu*nu));\n      double prefactor = pow(xo2, nu) / gamfactor;\n      double C[5];\n\n      C[0] = 1.;\n      C[1] = -C[0] / (nu+1.);\n      C[2] = -C[1] / (2.*(nu+2.));\n      C[3] = -C[2] / (3.*(nu+3.));\n      C[4] = -C[3] / (4.*(nu+4.));\n      \n      result = 0.;\n      for(k=0; k<5; k++)\n\tresult += C[k] * pow(xo2, 2.*k);\n\n      result *= prefactor;\n    }\n  else if(x < nu - llimit)\n    {\n      /* Small x region: x << l.    */\n      double z = x / nu;\n      double z2 = z*z;\n      double rtomz2 = sqrt(1.-z2);\n      double omz2_2 = (1.-z2)*(1.-z2);\n\n      /* Calculate Meissel exponent. */\n      double term1 = 1./(24.*nu) * ((2.+3.*z2)/((1.-z2)*rtomz2) -2.);\n      double term2 = - z2*(4. + z2)/(16.*nu2*(1.-z2)*omz2_2);\n      double V_nu = term1 + term2;\n      \n      /* Calculate the harmless prefactor. */\n      double sterlingsum = 1. + 1./(12.*nu) + 1./(288*nu2);\n      double harmless = 1. / (sqrt(rtomz2*2.*M_PI*nu) * sterlingsum);\n\n      /* Calculate the logarithm of the nu dependent prefactor. */\n      double ln_nupre = rtomz2 + log(z) - log(1. + rtomz2);\n\n      result = harmless * exp(nu*ln_nupre - V_nu);\n    } \n  else if(x < nu + ulimit)\n    {         \n      /* Intermediate region 1: x near nu. */\n      double eps = 1.-nu/x;\n      double eps_x = eps * x;\n      double eps_x_2 = eps_x * eps_x;\n      double xo6 = x/6.;\n      double B[6];\n      static double gam[6] = {2.67894, 1.35412, 1., 0.89298, 0.902745, 1.};\n      static double sf[6] = {0.866025, 0.866025, 0., -0.866025, -0.866025, 0.};\n      \n      /* Some terms are identically zero, because sf[] can be zero.\n       * Some terms do not appear in the result.\n       */\n      B[0] = 1.;\n      B[1] = eps_x;\n      /* B[2] = 0.5 * eps_x_2 - 1./20.; */\n      B[3] = eps_x * (eps_x_2/6. - 1./15.);\n      B[4] = eps_x_2 * (eps_x_2 - 1.)/24. + 1./280.;\n      /* B[5] = eps_x * (eps_x_2*(0.5*eps_x_2 - 1.)/60. + 43./8400.); */\n\n      result  = B[0] * gam[0] * sf[0] / pow(xo6, 1./3.);\n      result += B[1] * gam[1] * sf[1] / pow(xo6, 2./3.);\n      result += B[3] * gam[3] * sf[3] / pow(xo6, 4./3.);\n      result += B[4] * gam[4] * sf[4] / pow(xo6, 5./3.);\n\n      result /= (3.*M_PI);\n    }\n  else \n    {\n      /* Region of very large argument. Use expansion\n       * for x>>l, and we need not be very exacting.\n       */\n      double secb = x/nu;\n      double sec2b= secb*secb;\n      \n      double cotb = 1./sqrt(sec2b-1.);      /* cotb=cot(beta) */\n\n      double beta = acos(nu/x);\n      double trigarg = nu/cotb - nu*beta - 0.25 * M_PI;\n      \n      double cot3b = cotb * cotb * cotb;\n      double cot6b = cot3b * cot3b;\n\n      double sum1, sum2, expterm, prefactor, trigcos;\n\n      sum1  = 2.0 + 3.0 * sec2b;\n      trigarg -= sum1 * cot3b / (24.0 * nu);\n\n      trigcos = cos(trigarg);\n\n      sum2 = 4.0 + sec2b;\n      expterm = sum2 * sec2b * cot6b / (16.0 * nu2);\n\n      expterm = exp(-expterm);\n      prefactor = sqrt(2. * cotb / (nu * M_PI));\n      \n      result = prefactor * expterm * trigcos;\n    }\n\n  return  result;\n}\n#endif\n", "meta": {"hexsha": "c46f5630923a8144ca9138d87a1933bb0663e501", "size": 26478, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/specfunc/bessel.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 28.440386681, "max_line_length": 103, "alphanum_fraction": 0.5676032933, "num_tokens": 9694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3908285023041581}}
{"text": "#ifndef LIBGAD\n#define LIBGAD\n#ifndef NOPOT\n#define POTENTIAL\n#endif\n#include <stdio.h>\n#include <math.h>\n\n#ifndef NOGSL\n#ifndef GSL\n#define GSL\n#endif\n#endif\n\n#ifdef GSL\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_linalg.h>\n#endif\n\n#define\tMIN(a, b)   ((a)<(b)?(a):(b))\n#define\tMAX(a, b)   ((a)>(b)?(a):(b))\n#define ABS(a) ((a) >= 0 ? (a) : -(a))\n#define SQR(x) ((x)*(x))\n#define OMEGA_M 0.26\n#define OMEGA_L 0.74\n#define HUB 0.72\n#define GRAV 6.6742e-11\n#define MSUN 1.989e30\n#define KPC 3.085678e19  //meters\n#define sec_per_yr 3.155e7\n#define GALAGE(a) galage(a, OMEGA_M, OMEGA_L, HUB)\n#define TIMEDIFF(a,b) timediff(a, b, OMEGA_M, OMEGA_L, HUB)\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n#ifdef LONGIDS\ntypedef unsigned long long IDtype;\n#else \ntypedef unsigned int IDtype;\n#endif\n\n\ntypedef float fltarr[3];\nstruct header\n  {\n    int npart[6];\n    double massarr[6];\n    double time;\n    double redsh;\n    int flg_sfr;\n    int flg_fdbck;\n    int nall[6];\n    int flag_cool;\n    int numfiles;\n    double boxsize;\n    double omega0;\n    double omegal;\n    double hubparam;\n    int flg_age;\n    int flg_mtl;\n    int bytesleft[22];\n};\n\ntypedef struct sphdata\n{\n  float u;\n  float rho;\n  float nelec;\n  float nh;\n  float hsml;\n  float sfr;\n#ifdef WINDS\n  float dtime;\n  float metals[4];\n  float tmax;\n  float n_spawn;\n#endif //WINDS\n#ifdef METALS\n  float temp;\n#endif\n} sphdata;\n\n#if defined(WINDS) || defined(METALS)\ntypedef struct stardata\n{\n#ifdef WINDS\n  float metals[4];\n  float tmax;\n  float n_spawn;\n#else\n  int let;\n  float initialmass;\n#endif\n} stardata;\n#endif //WINDS || METALS\n\ntypedef struct gadpart\n{\n  fltarr pos;\n#ifndef NOVEL\n  fltarr vel;\n#endif //NOVEL\n  float mass;\n  IDtype id;\n  short type;\n#ifndef NOGAS\n  sphdata *sph;\n  float stellarage;\n#endif\n#ifdef POTENTIAL\n  float pot;\n#endif\n\n#if defined(WINDS) || defined(METALS)\n  stardata *sd;\n#endif //WINDS\n\n#ifdef METALS\n  float* metals;\n#endif\n} gadpart;\n\ntypedef struct gadpart_dist\n{\n  gadpart part;\n  double dist;\n} gadpart_dist;\n\nint cmp_id (const void *first, const void *second);\nint cmp_pointer_id(const void *a, const void *b);\nint cmp_type (const void *first, const void *second);\nint cmp_pos (const void *first, const void *second);\nint cmp_x (const void *first, const void *second);\nint cmp_y (const void *first, const void *second);\nint cmp_z (const void *first, const void *second);\nint cmp_dist (const void *first, const void *second);\nint cmp_int (const void *first, const void *second);\nint cmp_float (const void *first, const void *second);\nunsigned int readgadget(char *filename, struct header *h, fltarr **p, fltarr **v, int **n, float **m);\nunsigned int readgadget_part(char *filename, struct header *h,struct gadpart **part);\n#ifdef LONGIDS\nunsigned int writegadget(char *filename, struct header h, fltarr *p, fltarr *v, long *n, float *m);\n#else\nunsigned int writegadget(char *filename, struct header h, fltarr *p, fltarr *v, int *n, float *m);\n#endif\nunsigned int writegadget_part(char *filename, struct header h, struct gadpart *part);\nunsigned int readgadget_novel(char *filename, struct header *h, fltarr **p, int **n, float **m);\nunsigned int readgadget_sph(char *filename, struct header *h, fltarr **p, fltarr **v, int **n, float **m, float **u, float **rho, float **d1, float **d2, float **d3, float **d4 , float **sa);\nint convertunits(struct header *head, struct gadpart *part, double convert_mass, double convert_distance);\ndouble distance(fltarr a, fltarr b);\ndouble distance_nopb(fltarr a, fltarr b);\ndouble distbox(fltarr a, fltarr min, fltarr max);\ndouble distbox_nopb(fltarr a, fltarr min, fltarr max);\nvoid cpygadpart(gadpart * to, gadpart * from);\nint gadsearch(gadpart_dist *data, double toFind, int start, int end);\ndouble nfwfit(double *par, gadpart_dist *part, int cnt, double rv, double soft, double *rcs);\ndouble densproffit(double *par, gadpart_dist *part, int cnt, double re, double soft, double *rcs, int type);\nvoid calcdist(gadpart_dist *gd, int cnt, float *center);\nvoid simplecenter(gadpart *part, int cnt, double* cm, int use);\nvoid pcenter(gadpart_dist *part, int cnt, double, float*, int);\nvoid findcenter(gadpart *part, int cnt, double maxdist, int use);\nvoid simplecm(gadpart ** part, int cnt, float * cm);\ndouble r200(gadpart_dist* pd, int cnt, double denscontrast, struct header h, int *vcnt, double *mvir);\ndouble xoffset(gadpart_dist* pd, int cnt, float rvir, float* center);\n#ifndef NOGAS\ndouble temperature(const gadpart part);\n#endif //NOGAS\nvoid dummyfunction();\ndouble galage(double z, double omegam, double omegal, double h);\ndouble timediff(double z1, double z2, double omegam, double omegal, double h);\ndouble a2z(double a);\ndouble z2a(double z);\ndouble angle(fltarr a, fltarr b);\ndouble radvel(fltarr vel, fltarr rad);\nstruct header cphead(struct header head, gadpart* part, int cnt);\n\n#ifdef GSL\nvoid rotatepart(gadpart *part, int numpart, const gsl_matrix *rotmat);\nvoid xrotate(double angle, gadpart *part, int numpart);\nvoid yrotate(double angle, gadpart *part, int numpart);\nvoid zrotate(double angle, gadpart *part, int numpart);\nvoid rotategalaxy(gadpart *part, int numpart, double rad, int use, double *res, gsl_matrix **rotation);\n#endif\n\n#endif //LIBGAD\n", "meta": {"hexsha": "6fd4a442db59520e5cb3f4fb4916aadbff71e511", "size": 5363, "ext": "h", "lang": "C", "max_stars_repo_path": "libgad.h", "max_stars_repo_name": "Fette3lke/GadTools", "max_stars_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libgad.h", "max_issues_repo_name": "Fette3lke/GadTools", "max_issues_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-01-12T14:40:32.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-12T14:40:32.000Z", "max_forks_repo_path": "libgad.h", "max_forks_repo_name": "lgo33/GadTools", "max_forks_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1", "max_forks_repo_licenses": ["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.7875647668, "max_line_length": 191, "alphanum_fraction": 0.7188140966, "num_tokens": 1679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8198933403143929, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3907444820364651}}
{"text": "#ifndef __MATH_GSL_MATRIX__\n#define __MATH_GSL_MATRIX__\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_cblas.h>\n\nclass GslMatrixItem {\n public:\n  GslMatrixItem(gsl_matrix* ptr, size_t index1, size_t index2) :\n    ptr_(ptr),\n    index1_(index1),\n    index2_(index2) { }\n\n  operator const double() {\n    return gsl_matrix_get(ptr_, index1_, index2_);\n  }\n\n  double operator =(const double v) {\n    gsl_matrix_set(ptr_, index1_, index2_, v);\n    return v;\n  }\n\n  double operator +=(const double v) {\n    double old_v = gsl_matrix_get(ptr_, index1_, index2_);\n    gsl_matrix_set(ptr_, index1_, index2_, v + old_v);\n    return v + old_v;\n  }\n private:\n  gsl_matrix* ptr_;\n  size_t index1_;\n  size_t index2_;\n};\n\nclass GslMatrixBase {\n public:\n  GslMatrixBase& operator=(const double v) {\n    if (v == 0.0) {\n      SetZero();\n    } else {\n      SetAll(v);\n    }\n    return *this;\n  }\n\n  GslMatrixItem operator()(const size_t index1, const size_t index2) const {\n    assert(ptr_ != NULL);\n    return GslMatrixItem(ptr_, index1, index2);\n  }\n\n  void SetZero() {\n    assert(ptr_ != NULL);\n    gsl_matrix_set_zero(ptr_);\n  }\n\n  void SetAll(const double v) {\n    assert(ptr_ != NULL);\n    gsl_matrix_set_all(ptr_, v);\n  }\n  \n  void Reset(gsl_matrix* val) {\n    if(ptr_ != NULL) {\n      gsl_matrix_free(ptr_);\n    }\n    ptr_ = val;\n  }\n\n  int Fprintf(FILE* stream, const char* format) const {\n    assert(ptr_ != NULL);\n    return gsl_matrix_fprintf(stream, ptr_, format);\n  }\n\n  int Fscanf(FILE* stream) {\n    assert(ptr_ != NULL);\n    return gsl_matrix_fscanf(stream, ptr_);\n  }\n\n  void Set(const int i, const int j, double val) {\n    gsl_matrix_set(ptr_, i, j, val);\n  }\n\n  /*\n    double operator()(const int nCol, const int nRow) {\n    return gsl_matrix_get(ptr_, nCol, nRow);\n    }\n  */\n\n  int size1() const {\n    return ptr_->size1;\n  }\n\n  int size2() const {\n    return ptr_->size2;\n  }\n\n  double Trace() const {\n    double val = 0;\n    assert(ptr_ != NULL);\n    assert(ptr_->size1 == ptr_->size2);\n    for (size_t ii = 0; ii < ptr_->size1; ++ii) {\n      val += gsl_matrix_get(ptr_, ii, ii);\n    }\n    return val;\n  }\n\n  double Sum() const {\n    double val = 0;\n    assert(ptr_ != NULL);\n    for (size_t ii = 0; ii < ptr_->size1; ++ii) {\n      for (size_t jj = 0; jj < ptr_->size2; ++jj) {\n\tval += gsl_matrix_get(ptr_, ii, jj);\n      }\n    }\n    return val;\n  }\n\n  /*\n   * Apply the transpose of this matrix to a vector x and store the result.\n\n   int TransMul(const GslVector& x, GslVector& res, double scale = 0.0) {\n   return gsl_blas_dgemv(CblasTrans, 1.0, ptr_, x.ptr(), scale, res.ptr());\n   }\n   \n   int Mul(const GslVector& x, GslVector& res, double scale = 0.0) {\n   return gsl_blas_dgemv(CblasNoTrans, 1.0, ptr_, x.ptr(), scale, res.ptr());\n   }\n  */\n\n  const gsl_matrix* ptr() const { return ptr_; }\n  gsl_matrix* mutable_ptr() { return ptr_; }\n\n protected:\n  GslMatrixBase() : ptr_(NULL) {\n  }  \n  gsl_matrix* ptr_;\n\n private:\n  GslMatrixBase(const GslMatrixBase&) { }\n};\n\nclass GslMatrix : public GslMatrixBase {\n public:\n  GslMatrix(const size_t size1, const size_t size2) : GslMatrixBase() {\n    Allocate(size1, size2);\n  }\n\n  void Allocate(const size_t size1, const size_t size2) {\n    assert(ptr_ == NULL);\n    ptr_ = gsl_matrix_alloc(size1, size2);\n  }\n\n  GslMatrix() : GslMatrixBase() {\n  }\n\n  GslMatrix(gsl_matrix* val) : GslMatrixBase() {\n    ptr_ = val;\n  }\n\n  ~GslMatrix() {\n    if(ptr_ != NULL) {\n      gsl_matrix_free(ptr_);\n    }\n  }\n\n  GslMatrixBase& operator=(const double v) {\n    GslMatrixBase::operator=(v);\n    return *this;\n  }\n private:\n  GslMatrix(const GslMatrix&) { }\n};\n\n\nclass GslSubmatrix : public GslMatrixBase {\n public:\n GslSubmatrix(GslMatrixBase& matrix, size_t k1, size_t k2, size_t n1, size_t n2) :\n  view_(gsl_matrix_submatrix(matrix.mutable_ptr(), k1, k2, n1, n2)) {    \n     ptr_ = &view_.matrix;\n  }\n\n GslSubmatrix(gsl_matrix* matrix, size_t k1, size_t k2, size_t n1, size_t n2) :\n  view_(gsl_matrix_submatrix(matrix, k1, k2, n1, n2)) {    \n     ptr_ = &view_.matrix;\n  }\n\n  GslMatrixBase& operator=(const double v) {\n    GslMatrixBase::operator=(v);\n    return *this;\n  }\n private:\n  gsl_matrix_view view_;\n  GslSubmatrix(const GslSubmatrix&) { }\n};\n\n#endif  // __MATH_GSL_MATRIX__\n", "meta": {"hexsha": "2563f949559df5dadaf678b171a9dd38ef0f485d", "size": 4256, "ext": "h", "lang": "C", "max_stars_repo_path": "DTM/dtm-master/lib/math/gsl_matrix.h", "max_stars_repo_name": "boomsbloom/dtm-fmri", "max_stars_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z", "max_issues_repo_path": "DTM/dtm-master/lib/math/gsl_matrix.h", "max_issues_repo_name": "boomsbloom/dtm-fmri", "max_issues_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DTM/dtm-master/lib/math/gsl_matrix.h", "max_forks_repo_name": "boomsbloom/dtm-fmri", "max_forks_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z", "avg_line_length": 21.7142857143, "max_line_length": 82, "alphanum_fraction": 0.6315789474, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.390412619185459}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"compearth.h\"\n/*\n#ifdef COMPEARTH_USE_MKL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n*/\n\n/*!\n * @brief Converts a moment tensor, M, from input system defined by i1in\n *        to moment tensor, Mout, to output system defind by i2in.\n *\n * @param[in] nmt      Number of moment tensors.\n * @param[in] i1in     Coordinate system for M: \\n\n *                       = CE_USE (1) -> up, south, east \\n\n *                       = CE_NED (2) -> north, east, down \\n\n *                       = CE_NWU (3) -> north west, up \\n\n *                       = CE_ENU (4) -> east, north, up \\n\n *                       = CE_SEU (5) -> south, east, up \\n\n * @param[in] i2in     Coordinate system for Mout: \\n\n *                       = CE_USE (1) -> up, south, east \\n\n *                       = CE_NED (2) -> north, east, down \\n\n *                       = CE_NWU (3) -> north west, up \\n\n *                       = CE_ENU (4) -> east, north, up \\n\n *                       = CE_SEU (5) -> south, east, up \\n\n * @param[in] M        Input moment tensor in system i1in.  This is an\n *                     an array of dimension [6 x nmt].\n *                     The C indices {0,1,2,3,4,5} correspond to matrix\n *                     indices: {11, 22, 33, 12, 13, 23}.\n *\n * @param[out] Mout    Corresponding moment tensor now in system i2in.\n *                     This is an array of dimension [6 x nmt].\n *                     the C indices {0,1,2,3,4,5} correspond to matrix\n *                     indices: {11, 22, 33, 12, 13, 23}\n * \n * @result 0 indicates success.\n *\n * @date 2016 - Ben Baker converted Carl Tape's convert_MT.m to C\n *\n * @copyright MIT\n *\n */\nint compearth_convertMT(const int nmt,\n                        const enum compearthCoordSystem_enum i1in,\n                        const enum compearthCoordSystem_enum i2in,\n                        const double *__restrict__ M,\n                        double *__restrict__ Mout)\n{\n    int i, i1, i2;\n    // Check the inputs to avoid seg faults\n    if (nmt < 1 || M == NULL || Mout == NULL)\n    {\n        if (nmt < 1){fprintf(stderr, \"%s: No moment tensors\\n\", __func__);}\n        if (M == NULL){fprintf(stderr, \"%s: Error M is NULL\\n\", __func__);}\n        if (Mout == NULL)\n        {\n            fprintf(stderr, \"%s: Error Mout is NULL\\n\", __func__);\n        }\n        return -1;\n    }\n    for (i=0; i<6*nmt; i++){Mout[i] = 0.0;}\n    // Quick checks\n    i1 = (int) i1in;\n    i2 = (int) i2in;\n    if (i1 < 1 || i1 > 5)\n    {\n        fprintf(stderr, \"%s: Error unknown input coordinate system %d\\n\",\n                __func__, i1);\n        return -1;\n    }\n    if (i2 < 1 || i2 > 5)\n    {\n        fprintf(stderr, \"%s: Error unkonwn output coordinate system %d\\n\",\n                __func__, i2);\n        return -1;\n    }\n    // Base case\n    if (i1 == i2)\n    {\n        memcpy(Mout, M, (size_t) nmt*6*sizeof(double));\n        //cblas_dcopy(6*nmt, M, 1, Mout, 1);\n        return 0;\n    }\n    // Convert\n    if (i1 == 1)\n    {\n        // up-south-east (GCMT) to north-east-down (AkiRichards)\n        // (AR, 1980, p. 118)\n        if (i2 == 2)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+1]; //  tt -> xx\n                Mout[6*i+1] = M[6*i+2]; //  pp -> yy\n                Mout[6*i+2] = M[6*i+0]; //  rr -> zz\n                Mout[6*i+3] =-M[6*i+5]; // -tp -> xy\n                Mout[6*i+4] = M[6*i+3]; //  rt -> xz\n                Mout[6*i+5] =-M[6*i+4]; // -rp -> yz\n            }\n       }\n       // up-south-east (GCMT) to north-west-up\n       else if (i2 == 3)\n       {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+1];\n                Mout[6*i+1] = M[6*i+2];\n                Mout[6*i+2] = M[6*i+0];\n                Mout[6*i+3] = M[6*i+5];\n                Mout[6*i+4] =-M[6*i+3];\n                Mout[6*i+5] =-M[6*i+4];\n            }\n       }\n       // up-south-east (GCMT) to east-north-up\n       else if (i2 == 4)\n       {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+2];\n                Mout[6*i+1] = M[6*i+1];\n                Mout[6*i+2] = M[6*i+0];\n                Mout[6*i+3] =-M[6*i+5];\n                Mout[6*i+4] = M[6*i+4];\n                Mout[6*i+5] =-M[6*i+3];\n            }\n       }\n       // up-south-east (GCMT) to south-east-up\n       else if (i2 == 5)\n       {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+1];\n                Mout[6*i+1] = M[6*i+2];\n                Mout[6*i+2] = M[6*i+0];\n                Mout[6*i+3] = M[6*i+5];\n                Mout[6*i+4] = M[6*i+3];\n                Mout[6*i+5] = M[6*i+4];\n            }\n        }\n    }\n    else if (i1 == 2)\n    {\n        // north-east-down (AkiRichards) to up-south-east (GCMT) \n        // (AR, 1980, p. 118)\n        if (i2 == 1)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+2]; //  zz -> rr\n                Mout[6*i+1] = M[6*i+0]; //  xx -> tt\n                Mout[6*i+2] = M[6*i+1]; //  yy -> pp \n                Mout[6*i+3] = M[6*i+4]; //  xz -> rt \n                Mout[6*i+4] =-M[6*i+5]; // -yz -> rp\n                Mout[6*i+5] =-M[6*i+3]; // -xy -> tp\n            }\n        }\n        // north-east-down (AkiRichards) to north-west-up\n        else if (i2 == 3)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+0];\n                Mout[6*i+1] = M[6*i+1];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] =-M[6*i+3];\n                Mout[6*i+4] =-M[6*i+4];\n                Mout[6*i+5] = M[6*i+5];\n            }\n        }\n        // north-east-down (AkiRichards) to east-north-up\n        else if (i2 == 4)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+1];\n                Mout[6*i+1] = M[6*i+0];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] = M[6*i+3];\n                Mout[6*i+4] =-M[6*i+5];\n                Mout[6*i+5] =-M[6*i+4];\n            }\n        }\n        // north-east-down (AkiRichards) to south-east-up\n        else if (i2 == 5)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+0];\n                Mout[6*i+1] = M[6*i+1];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] =-M[6*i+3];\n                Mout[6*i+4] = M[6*i+4];\n                Mout[6*i+5] =-M[6*i+5];\n            }\n        }\n    }\n    else if (i1 == 3)\n    {\n        // north-west-up to up-south-east (GCMT)\n        if (i2 == 1)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+2];\n                Mout[6*i+1] = M[6*i+0];\n                Mout[6*i+2] = M[6*i+1];\n                Mout[6*i+3] =-M[6*i+4];\n                Mout[6*i+4] =-M[6*i+5];\n                Mout[6*i+5] = M[6*i+3];\n            }\n        }\n        // north-west-up to north-east-down (AkiRichards)\n        else if (i2 == 2)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+0];\n                Mout[6*i+1] = M[6*i+1];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] =-M[6*i+3];\n                Mout[6*i+4] =-M[6*i+4];\n                Mout[6*i+5] = M[6*i+5];\n            }\n        }\n        // north-west-up to east-north-up\n        else if (i2 == 4)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+1];\n                Mout[6*i+1] = M[6*i+0];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] =-M[6*i+3];\n                Mout[6*i+4] =-M[6*i+5];\n                Mout[6*i+5] = M[6*i+4];\n            }\n        }\n        // north-west-up to south-east-up\n        else if (i2 == 5)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+0];\n                Mout[6*i+1] = M[6*i+1];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] = M[6*i+3];\n                Mout[6*i+4] =-M[6*i+4];\n                Mout[6*i+5] =-M[6*i+5];\n            }\n        }\n    }\n    else if (i1 == 4)\n    {\n        // east-north-up to up-south-east (GCMT)\n        if (i2 == 1)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+2];\n                Mout[6*i+1] = M[6*i+1];\n                Mout[6*i+2] = M[6*i+0];\n                Mout[6*i+3] =-M[6*i+5];\n                Mout[6*i+4] = M[6*i+4];\n                Mout[6*i+5] =-M[6*i+3];\n            }\n        }\n        // east-north-up to north-east-down (AkiRichards)\n        else if (i2 == 2)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+1];\n                Mout[6*i+1] = M[6*i+0];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] = M[6*i+3];\n                Mout[6*i+4] =-M[6*i+5];\n                Mout[6*i+5] =-M[6*i+4];\n            }\n        }\n        // east-north-up to north-west-up\n        else if (i2 == 3)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+1];\n                Mout[6*i+1] = M[6*i+0];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] =-M[6*i+3];\n                Mout[6*i+4] = M[6*i+5];\n                Mout[6*i+5] =-M[6*i+4];\n            }\n        }\n        // east-north-up to south-east-up\n        else if (i2 == 5)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+1];\n                Mout[6*i+1] = M[6*i+0];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] =-M[6*i+3];\n                Mout[6*i+4] =-M[6*i+5];\n                Mout[6*i+5] = M[6*i+4];\n            }\n        }\n    }\n    else if (i1 == 5)\n    {\n        // south-east-up to up-south-east (GCMT)\n        if (i2 == 1)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+2];\n                Mout[6*i+1] = M[6*i+0];\n                Mout[6*i+2] = M[6*i+1];\n                Mout[6*i+3] = M[6*i+4];\n                Mout[6*i+4] = M[6*i+5];\n                Mout[6*i+5] = M[6*i+3];\n            }\n        }\n        // south-east-up to north-east-down (AkiRichards)\n        else if (i2 == 2)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+0];\n                Mout[6*i+1] = M[6*i+1];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] =-M[6*i+3];\n                Mout[6*i+4] = M[6*i+4];\n                Mout[6*i+5] =-M[6*i+5];\n            }\n        }\n        // south-east-up to north-west-up\n        else if (i2 == 3)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+0];\n                Mout[6*i+1] = M[6*i+1];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] = M[6*i+3];\n                Mout[6*i+4] =-M[6*i+4];\n                Mout[6*i+5] =-M[6*i+5];\n            }\n        }\n        // south-east-up to east-north-up\n        else if (i2 == 4)\n        {\n            for (i=0; i<nmt; i++)\n            {\n                Mout[6*i+0] = M[6*i+1];\n                Mout[6*i+1] = M[6*i+0];\n                Mout[6*i+2] = M[6*i+2];\n                Mout[6*i+3] =-M[6*i+3];\n                Mout[6*i+4] = M[6*i+5];\n                Mout[6*i+5] =-M[6*i+4];\n            }\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "506fc89de15df26755ed819545994301bd3a5f4d", "size": 11373, "ext": "c", "lang": "C", "max_stars_repo_path": "c_src/convertMT.c", "max_stars_repo_name": "OUCyf/mtbeach", "max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z", "max_issues_repo_path": "c_src/convertMT.c", "max_issues_repo_name": "carltape/mtbeach", "max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c_src/convertMT.c", "max_forks_repo_name": "carltape/mtbeach", "max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z", "avg_line_length": 30.9048913043, "max_line_length": 75, "alphanum_fraction": 0.3423898707, "num_tokens": 4059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587586, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.390412619185459}}
{"text": "/* eigen/nonsymmv.c\n * \n * Copyright (C) 2006 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_vector_complex.h>\n#include <gsl/gsl_matrix.h>\n\n/*\n * This module computes the eigenvalues and eigenvectors of a real\n * nonsymmetric matrix.\n * \n * This file contains routines based on original code from LAPACK\n * which is distributed under the modified BSD license. The LAPACK\n * routines used are DTREVC and DLALN2.\n */\n\n#define GSL_NONSYMMV_SMLNUM (2.0 * GSL_DBL_MIN)\n#define GSL_NONSYMMV_BIGNUM ((1.0 - GSL_DBL_EPSILON) / GSL_NONSYMMV_SMLNUM)\n\nstatic void nonsymmv_get_right_eigenvectors(gsl_matrix *T, gsl_matrix *Z,\n                                            gsl_vector_complex *eval,\n                                            gsl_matrix_complex *evec,\n                                            gsl_eigen_nonsymmv_workspace *w);\nstatic inline void nonsymmv_solve_equation(gsl_matrix *A, double z,\n                                           gsl_vector *b, gsl_vector *x,\n                                           double *s, double *xnorm,\n                                           double smin);\nstatic inline void nonsymmv_solve_equation_z(gsl_matrix *A, gsl_complex *z,\n                                             gsl_vector_complex *b,\n                                             gsl_vector_complex *x,\n                                             double *s, double *xnorm,\n                                             double smin);\nstatic void nonsymmv_normalize_eigenvectors(gsl_vector_complex *eval,\n                                            gsl_matrix_complex *evec);\n\n/*\ngsl_eigen_nonsymmv_alloc()\n\nAllocate a workspace for solving the nonsymmetric eigenvalue problem.\nThe size of this workspace is O(5n).\n\nInputs: n - size of matrices\n\nReturn: pointer to workspace\n*/\n\ngsl_eigen_nonsymmv_workspace *\ngsl_eigen_nonsymmv_alloc(const size_t n)\n{\n  gsl_eigen_nonsymmv_workspace *w;\n\n  if (n == 0)\n    {\n      GSL_ERROR_NULL (\"matrix dimension must be positive integer\",\n                      GSL_EINVAL);\n    }\n\n  w = (gsl_eigen_nonsymmv_workspace *)\n      malloc (sizeof (gsl_eigen_nonsymmv_workspace));\n\n  if (w == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for workspace\", GSL_ENOMEM);\n    }\n\n  w->size = n;\n  w->Z = NULL;\n  w->nonsymm_workspace_p = gsl_eigen_nonsymm_alloc(n);\n\n  if (w->nonsymm_workspace_p == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for nonsymm workspace\", GSL_ENOMEM);\n    }\n\n  /*\n   * set parameters to compute the full Schur form T and balance\n   * the matrices\n   */\n  gsl_eigen_nonsymm_params(1, 1, w->nonsymm_workspace_p);\n\n  w->work = gsl_vector_alloc(n);\n  w->work2 = gsl_vector_alloc(n);\n  w->work3 = gsl_vector_alloc(n);\n  if (w->work == 0 || w->work2 == 0 || w->work3 == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for nonsymmv additional workspace\", GSL_ENOMEM);\n    }\n\n  return (w);\n} /* gsl_eigen_nonsymmv_alloc() */\n\n/*\ngsl_eigen_nonsymmv_free()\n  Free workspace w\n*/\n\nvoid\ngsl_eigen_nonsymmv_free (gsl_eigen_nonsymmv_workspace * w)\n{\n  gsl_eigen_nonsymm_free(w->nonsymm_workspace_p);\n  gsl_vector_free(w->work);\n  gsl_vector_free(w->work2);\n  gsl_vector_free(w->work3);\n\n  free(w);\n} /* gsl_eigen_nonsymmv_free() */\n\n/*\ngsl_eigen_nonsymmv()\n\nSolve the nonsymmetric eigensystem problem\n\nA x = \\lambda x\n\nfor the eigenvalues \\lambda and right eigenvectors x\n\nInputs: A    - general real matrix\n        eval - where to store eigenvalues\n        evec - where to store eigenvectors\n        w    - workspace\n\nReturn: success or error\n*/\n\nint\ngsl_eigen_nonsymmv (gsl_matrix * A, gsl_vector_complex * eval,\n                    gsl_matrix_complex * evec,\n                    gsl_eigen_nonsymmv_workspace * w)\n{\n  const size_t N = A->size1;\n\n  /* check matrix and vector sizes */\n\n  if (N != A->size2)\n    {\n      GSL_ERROR (\"matrix must be square to compute eigenvalues\", GSL_ENOTSQR);\n    }\n  else if (eval->size != N)\n    {\n      GSL_ERROR (\"eigenvalue vector must match matrix size\", GSL_EBADLEN);\n    }\n  else if (evec->size1 != evec->size2)\n    {\n      GSL_ERROR (\"eigenvector matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (evec->size1 != N)\n    {\n      GSL_ERROR (\"eigenvector matrix has wrong size\", GSL_EBADLEN);\n    }\n  else\n    {\n      int s;\n      gsl_matrix Z;\n\n      /*\n       * We need a place to store the Schur vectors, so we will\n       * treat evec as a real matrix and store them in the left\n       * half - the factor of 2 in the tda corresponds to the\n       * complex multiplicity\n       */\n      Z.size1 = N;\n      Z.size2 = N;\n      Z.tda = 2 * N;\n      Z.data = evec->data;\n      Z.block = 0;\n      Z.owner = 0;\n\n      /* compute eigenvalues, Schur form, and Schur vectors */\n      s = gsl_eigen_nonsymm_Z(A, eval, &Z, w->nonsymm_workspace_p);\n\n      if (w->Z)\n        {\n          /*\n           * save the Schur vectors in user supplied matrix, since\n           * they will be destroyed when computing eigenvectors\n           */\n          gsl_matrix_memcpy(w->Z, &Z);\n        }\n\n      /* only compute eigenvectors if we found all eigenvalues */\n      if (s == GSL_SUCCESS)\n        {\n          /* compute eigenvectors */\n          nonsymmv_get_right_eigenvectors(A, &Z, eval, evec, w);\n\n          /* normalize so that Euclidean norm is 1 */\n          nonsymmv_normalize_eigenvectors(eval, evec);\n        }\n\n      return s;\n    }\n} /* gsl_eigen_nonsymmv() */\n\n/*\ngsl_eigen_nonsymmv_Z()\n  Compute eigenvalues and eigenvectors of a real nonsymmetric matrix\nand also save the Schur vectors. See comments in gsl_eigen_nonsymm_Z\nfor more information.\n\nInputs: A    - real nonsymmetric matrix\n        eval - where to store eigenvalues\n        evec - where to store eigenvectors\n        Z    - where to store Schur vectors\n        w    - nonsymmv workspace\n\nReturn: success or error\n*/\n\nint\ngsl_eigen_nonsymmv_Z (gsl_matrix * A, gsl_vector_complex * eval,\n                      gsl_matrix_complex * evec, gsl_matrix * Z,\n                      gsl_eigen_nonsymmv_workspace * w)\n{\n  /* check matrix and vector sizes */\n\n  if (A->size1 != A->size2)\n    {\n      GSL_ERROR (\"matrix must be square to compute eigenvalues/eigenvectors\", GSL_ENOTSQR);\n    }\n  else if (eval->size != A->size1)\n    {\n      GSL_ERROR (\"eigenvalue vector must match matrix size\", GSL_EBADLEN);\n    }\n  else if (evec->size1 != evec->size2)\n    {\n      GSL_ERROR (\"eigenvector matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (evec->size1 != A->size1)\n    {\n      GSL_ERROR (\"eigenvector matrix has wrong size\", GSL_EBADLEN);\n    }\n  else if ((Z->size1 != Z->size2) || (Z->size1 != A->size1))\n    {\n      GSL_ERROR (\"Z matrix has wrong dimensions\", GSL_EBADLEN);\n    }\n  else\n    {\n      int s;\n\n      w->Z = Z;\n\n      s = gsl_eigen_nonsymmv(A, eval, evec, w);\n\n      w->Z = NULL;\n\n      return s;\n    }\n} /* gsl_eigen_nonsymmv_Z() */\n\n/********************************************\n *           INTERNAL ROUTINES              *\n ********************************************/\n\n/*\nnonsymmv_get_right_eigenvectors()\n  Compute the right eigenvectors of the Schur form T and then\nbacktransform them using the Schur vectors to get right eigenvectors of\nthe original matrix.\n\nInputs: T    - Schur form\n        Z    - Schur vectors\n        eval - where to store eigenvalues (to ensure that the\n               correct eigenvalue is stored in the same position\n               as the eigenvectors)\n        evec - where to store eigenvectors\n        w    - nonsymmv workspace\n\nReturn: none\n\nNotes: 1) based on LAPACK routine DTREVC - the algorithm used is\n          backsubstitution on the upper quasi triangular system T\n          followed by backtransformation by Z to get vectors of the\n          original matrix.\n\n       2) The Schur vectors in Z are destroyed and replaced with\n          eigenvectors stored with the same storage scheme as DTREVC.\n          The eigenvectors are also stored in 'evec'\n\n       3) The matrix T is unchanged on output\n\n       4) Each eigenvector is normalized so that the element of\n          largest magnitude has magnitude 1; here the magnitude of\n          a complex number (x,y) is taken to be |x| + |y|\n*/\n\nstatic void\nnonsymmv_get_right_eigenvectors(gsl_matrix *T, gsl_matrix *Z,\n                                gsl_vector_complex *eval,\n                                gsl_matrix_complex *evec,\n                                gsl_eigen_nonsymmv_workspace *w)\n{\n  const size_t N = T->size1;\n  const double smlnum = GSL_DBL_MIN * N / GSL_DBL_EPSILON;\n  const double bignum = (1.0 - GSL_DBL_EPSILON) / smlnum;\n  int i;              /* looping */\n  size_t iu,          /* looping */\n         ju,\n         ii;\n  gsl_complex lambda; /* current eigenvalue */\n  double lambda_re,   /* Re(lambda) */\n         lambda_im;   /* Im(lambda) */\n  gsl_matrix_view Tv, /* temporary views */\n                  Zv;\n  gsl_vector_view y,  /* temporary views */\n                  y2,\n                  ev,\n                  ev2;\n  double dat[4],      /* scratch arrays */\n         dat_X[4];\n  double scale;       /* scale factor */\n  double xnorm;       /* |X| */\n  gsl_vector_complex_view ecol, /* column of evec */\n                          ecol2;\n  int complex_pair;   /* complex eigenvalue pair? */\n  double smin;\n\n  /*\n   * Compute 1-norm of each column of upper triangular part of T\n   * to control overflow in triangular solver\n   */\n\n  gsl_vector_set(w->work3, 0, 0.0);\n  for (ju = 1; ju < N; ++ju)\n    {\n      gsl_vector_set(w->work3, ju, 0.0);\n      for (iu = 0; iu < ju; ++iu)\n        {\n          gsl_vector_set(w->work3, ju,\n                         gsl_vector_get(w->work3, ju) +\n                         fabs(gsl_matrix_get(T, iu, ju)));\n        }\n    }\n\n  for (i = (int) N - 1; i >= 0; --i)\n    {\n      iu = (size_t) i;\n\n      /* get current eigenvalue and store it in lambda */\n      lambda_re = gsl_matrix_get(T, iu, iu);\n\n      if (iu != 0 && gsl_matrix_get(T, iu, iu - 1) != 0.0)\n        {\n          lambda_im = sqrt(fabs(gsl_matrix_get(T, iu, iu - 1))) *\n                      sqrt(fabs(gsl_matrix_get(T, iu - 1, iu)));\n        }\n      else\n        {\n          lambda_im = 0.0;\n        }\n\n      GSL_SET_COMPLEX(&lambda, lambda_re, lambda_im);\n\n      smin = GSL_MAX(GSL_DBL_EPSILON * (fabs(lambda_re) + fabs(lambda_im)),\n                     smlnum);\n      smin = GSL_MAX(smin, GSL_NONSYMMV_SMLNUM);\n\n      if (lambda_im == 0.0)\n        {\n          int k, l;\n          gsl_vector_view bv, xv;\n\n          /* real eigenvector */\n\n          /*\n           * The ordering of eigenvalues in 'eval' is arbitrary and\n           * does not necessarily follow the Schur form T, so store\n           * lambda in the right slot in eval to ensure it corresponds\n           * to the eigenvector we are about to compute\n           */\n          gsl_vector_complex_set(eval, iu, lambda);\n\n          /*\n           * We need to solve the system:\n           *\n           * (T(1:iu-1, 1:iu-1) - lambda*I)*X = -T(1:iu-1,iu)\n           */\n\n          /* construct right hand side */\n          for (k = 0; k < i; ++k)\n            {\n              gsl_vector_set(w->work,\n                             (size_t) k,\n                             -gsl_matrix_get(T, (size_t) k, iu));\n            }\n\n          gsl_vector_set(w->work, iu, 1.0);\n\n          for (l = i - 1; l >= 0; --l)\n            {\n              size_t lu = (size_t) l;\n\n              if (lu == 0)\n                complex_pair = 0;\n              else\n                complex_pair = gsl_matrix_get(T, lu, lu - 1) != 0.0;\n\n              if (!complex_pair)\n                {\n                  double x;\n\n                  /*\n                   * 1-by-1 diagonal block - solve the system:\n                   *\n                   * (T_{ll} - lambda)*x = -T_{l(iu)}\n                   */\n\n                  Tv = gsl_matrix_submatrix(T, lu, lu, 1, 1);\n                  bv = gsl_vector_view_array(dat, 1);\n                  gsl_vector_set(&bv.vector, 0,\n                                 gsl_vector_get(w->work, lu));\n                  xv = gsl_vector_view_array(dat_X, 1);\n\n                  nonsymmv_solve_equation(&Tv.matrix,\n                                          lambda_re,\n                                          &bv.vector,\n                                          &xv.vector,\n                                          &scale,\n                                          &xnorm,\n                                          smin);\n\n                  /* scale x to avoid overflow */\n                  x = gsl_vector_get(&xv.vector, 0);\n                  if (xnorm > 1.0)\n                    {\n                      if (gsl_vector_get(w->work3, lu) > bignum / xnorm)\n                        {\n                          x /= xnorm;\n                          scale /= xnorm;\n                        }\n                    }\n\n                  if (scale != 1.0)\n                    {\n                      gsl_vector_view wv;\n\n                      wv = gsl_vector_subvector(w->work, 0, iu + 1);\n                      gsl_blas_dscal(scale, &wv.vector);\n                    }\n\n                  gsl_vector_set(w->work, lu, x);\n\n                  if (lu > 0)\n                    {\n                      gsl_vector_view v1, v2;\n\n                      /* update right hand side */\n\n                      v1 = gsl_matrix_column(T, lu);\n                      v1 = gsl_vector_subvector(&v1.vector, 0, lu);\n\n                      v2 = gsl_vector_subvector(w->work, 0, lu);\n\n                      gsl_blas_daxpy(-x, &v1.vector, &v2.vector);\n                    } /* if (l > 0) */\n                } /* if (!complex_pair) */\n              else\n                {\n                  double x11, x21;\n\n                  /*\n                   * 2-by-2 diagonal block\n                   */\n\n                  Tv = gsl_matrix_submatrix(T, lu - 1, lu - 1, 2, 2);\n                  bv = gsl_vector_view_array(dat, 2);\n                  gsl_vector_set(&bv.vector, 0,\n                                 gsl_vector_get(w->work, lu - 1));\n                  gsl_vector_set(&bv.vector, 1,\n                                 gsl_vector_get(w->work, lu));\n                  xv = gsl_vector_view_array(dat_X, 2);\n\n                  nonsymmv_solve_equation(&Tv.matrix,\n                                          lambda_re,\n                                          &bv.vector,\n                                          &xv.vector,\n                                          &scale,\n                                          &xnorm,\n                                          smin);\n\n                  /* scale X(1,1) and X(2,1) to avoid overflow */\n                  x11 = gsl_vector_get(&xv.vector, 0);\n                  x21 = gsl_vector_get(&xv.vector, 1);\n\n                  if (xnorm > 1.0)\n                    {\n                      double beta;\n\n                      beta = GSL_MAX(gsl_vector_get(w->work3, lu - 1),\n                                     gsl_vector_get(w->work3, lu));\n                      if (beta > bignum / xnorm)\n                        {\n                          x11 /= xnorm;\n                          x21 /= xnorm;\n                          scale /= xnorm;\n                        }\n                    }\n\n                  /* scale if necessary */\n                  if (scale != 1.0)\n                    {\n                      gsl_vector_view wv;\n\n                      wv = gsl_vector_subvector(w->work, 0, iu + 1);\n                      gsl_blas_dscal(scale, &wv.vector);\n                    }\n\n                  gsl_vector_set(w->work, lu - 1, x11);\n                  gsl_vector_set(w->work, lu, x21);\n\n                  /* update right hand side */\n                  if (lu > 1)\n                    {\n                      gsl_vector_view v1, v2;\n\n                      v1 = gsl_matrix_column(T, lu - 1);\n                      v1 = gsl_vector_subvector(&v1.vector, 0, lu - 1);\n                      v2 = gsl_vector_subvector(w->work, 0, lu - 1);\n                      gsl_blas_daxpy(-x11, &v1.vector, &v2.vector);\n\n                      v1 = gsl_matrix_column(T, lu);\n                      v1 = gsl_vector_subvector(&v1.vector, 0, lu - 1);\n                      gsl_blas_daxpy(-x21, &v1.vector, &v2.vector);\n                    }\n\n                  --l;\n                } /* if (complex_pair) */\n            } /* for (l = i - 1; l >= 0; --l) */\n\n          /*\n           * At this point, w->work is an eigenvector of the\n           * Schur form T. To get an eigenvector of the original\n           * matrix, we multiply on the left by Z, the matrix of\n           * Schur vectors\n           */\n\n          ecol = gsl_matrix_complex_column(evec, iu);\n          y = gsl_matrix_column(Z, iu);\n\n          if (iu > 0)\n            {\n              gsl_vector_view x;\n\n              Zv = gsl_matrix_submatrix(Z, 0, 0, N, iu);\n\n              x = gsl_vector_subvector(w->work, 0, iu);\n\n              /* compute Z * w->work and store it in Z(:,iu) */\n              gsl_blas_dgemv(CblasNoTrans,\n                             1.0,\n                             &Zv.matrix,\n                             &x.vector,\n                             gsl_vector_get(w->work, iu),\n                             &y.vector);\n            } /* if (iu > 0) */\n\n          /* store eigenvector into evec */\n\n          ev = gsl_vector_complex_real(&ecol.vector);\n          ev2 = gsl_vector_complex_imag(&ecol.vector);\n\n          scale = 0.0;\n          for (ii = 0; ii < N; ++ii)\n            {\n              double a = gsl_vector_get(&y.vector, ii);\n\n              /* store real part of eigenvector */\n              gsl_vector_set(&ev.vector, ii, a);\n\n              /* set imaginary part to 0 */\n              gsl_vector_set(&ev2.vector, ii, 0.0);\n\n              if (fabs(a) > scale)\n                scale = fabs(a);\n            }\n\n          if (scale != 0.0)\n            scale = 1.0 / scale;\n\n          /* scale by magnitude of largest element */\n          gsl_blas_dscal(scale, &ev.vector);\n        } /* if (GSL_IMAG(lambda) == 0.0) */\n      else\n        {\n          gsl_vector_complex_view bv, xv;\n          size_t k;\n          int l;\n          gsl_complex lambda2;\n\n          /* complex eigenvector */\n\n          /*\n           * Store the complex conjugate eigenvalues in the right\n           * slots in eval\n           */\n          GSL_SET_REAL(&lambda2, GSL_REAL(lambda));\n          GSL_SET_IMAG(&lambda2, -GSL_IMAG(lambda));\n          gsl_vector_complex_set(eval, iu - 1, lambda);\n          gsl_vector_complex_set(eval, iu, lambda2);\n\n          /*\n           * First solve:\n           *\n           * [ T(i:i+1,i:i+1) - lambda*I ] * X = 0\n           */\n\n          if (fabs(gsl_matrix_get(T, iu - 1, iu)) >=\n              fabs(gsl_matrix_get(T, iu, iu - 1)))\n            {\n              gsl_vector_set(w->work, iu - 1, 1.0);\n              gsl_vector_set(w->work2, iu,\n                             lambda_im / gsl_matrix_get(T, iu - 1, iu));\n            }\n          else\n            {\n              gsl_vector_set(w->work, iu - 1,\n                             -lambda_im / gsl_matrix_get(T, iu, iu - 1));\n              gsl_vector_set(w->work2, iu, 1.0);\n            }\n          gsl_vector_set(w->work, iu, 0.0);\n          gsl_vector_set(w->work2, iu - 1, 0.0);\n\n          /* construct right hand side */\n          for (k = 0; k < iu - 1; ++k)\n            {\n              gsl_vector_set(w->work, k,\n                             -gsl_vector_get(w->work, iu - 1) *\n                             gsl_matrix_get(T, k, iu - 1));\n              gsl_vector_set(w->work2, k,\n                             -gsl_vector_get(w->work2, iu) *\n                             gsl_matrix_get(T, k, iu));\n            }\n\n          /*\n           * We must solve the upper quasi-triangular system:\n           *\n           * [ T(1:i-2,1:i-2) - lambda*I ] * X = s*(work + i*work2)\n           */\n\n          for (l = i - 2; l >= 0; --l)\n            {\n              size_t lu = (size_t) l;\n\n              if (lu == 0)\n                complex_pair = 0;\n              else\n                complex_pair = gsl_matrix_get(T, lu, lu - 1) != 0.0;\n\n              if (!complex_pair)\n                {\n                  gsl_complex bval;\n                  gsl_complex x;\n\n                  /*\n                   * 1-by-1 diagonal block - solve the system:\n                   *\n                   * (T_{ll} - lambda)*x = work + i*work2\n                   */\n\n                  Tv = gsl_matrix_submatrix(T, lu, lu, 1, 1);\n                  bv = gsl_vector_complex_view_array(dat, 1);\n                  xv = gsl_vector_complex_view_array(dat_X, 1);\n\n                  GSL_SET_COMPLEX(&bval,\n                                  gsl_vector_get(w->work, lu),\n                                  gsl_vector_get(w->work2, lu));\n                  gsl_vector_complex_set(&bv.vector, 0, bval);\n\n                  nonsymmv_solve_equation_z(&Tv.matrix,\n                                            &lambda,\n                                            &bv.vector,\n                                            &xv.vector,\n                                            &scale,\n                                            &xnorm,\n                                            smin);\n\n                  if (xnorm > 1.0)\n                    {\n                      if (gsl_vector_get(w->work3, lu) > bignum / xnorm)\n                        {\n                          gsl_blas_zdscal(1.0/xnorm, &xv.vector);\n                          scale /= xnorm;\n                        }\n                    }\n\n                  /* scale if necessary */\n                  if (scale != 1.0)\n                    {\n                      gsl_vector_view wv;\n\n                      wv = gsl_vector_subvector(w->work, 0, iu + 1);\n                      gsl_blas_dscal(scale, &wv.vector);\n                      wv = gsl_vector_subvector(w->work2, 0, iu + 1);\n                      gsl_blas_dscal(scale, &wv.vector);\n                    }\n\n                  x = gsl_vector_complex_get(&xv.vector, 0);\n                  gsl_vector_set(w->work, lu, GSL_REAL(x));\n                  gsl_vector_set(w->work2, lu, GSL_IMAG(x));\n\n                  /* update the right hand side */\n                  if (lu > 0)\n                    {\n                      gsl_vector_view v1, v2;\n\n                      v1 = gsl_matrix_column(T, lu);\n                      v1 = gsl_vector_subvector(&v1.vector, 0, lu);\n                      v2 = gsl_vector_subvector(w->work, 0, lu);\n                      gsl_blas_daxpy(-GSL_REAL(x), &v1.vector, &v2.vector);\n\n                      v2 = gsl_vector_subvector(w->work2, 0, lu);\n                      gsl_blas_daxpy(-GSL_IMAG(x), &v1.vector, &v2.vector);\n                    } /* if (lu > 0) */\n                } /* if (!complex_pair) */\n              else\n                {\n                  gsl_complex b1, b2, x1, x2;\n\n                  /*\n                   * 2-by-2 diagonal block - solve the system\n                   */\n\n                  Tv = gsl_matrix_submatrix(T, lu - 1, lu - 1, 2, 2);\n                  bv = gsl_vector_complex_view_array(dat, 2);\n                  xv = gsl_vector_complex_view_array(dat_X, 2);\n\n                  GSL_SET_COMPLEX(&b1,\n                                  gsl_vector_get(w->work, lu - 1),\n                                  gsl_vector_get(w->work2, lu - 1));\n                  GSL_SET_COMPLEX(&b2,\n                                  gsl_vector_get(w->work, lu),\n                                  gsl_vector_get(w->work2, lu));\n                  gsl_vector_complex_set(&bv.vector, 0, b1);\n                  gsl_vector_complex_set(&bv.vector, 1, b2);\n\n                  nonsymmv_solve_equation_z(&Tv.matrix,\n                                            &lambda,\n                                            &bv.vector,\n                                            &xv.vector,\n                                            &scale,\n                                            &xnorm,\n                                            smin);\n\n                  x1 = gsl_vector_complex_get(&xv.vector, 0);\n                  x2 = gsl_vector_complex_get(&xv.vector, 1);\n\n                  if (xnorm > 1.0)\n                    {\n                      double beta;\n\n                      beta = GSL_MAX(gsl_vector_get(w->work3, lu - 1),\n                                     gsl_vector_get(w->work3, lu));\n                      if (beta > bignum / xnorm)\n                        {\n                          gsl_blas_zdscal(1.0/xnorm, &xv.vector);\n                          scale /= xnorm;\n                        }\n                    }\n\n                  /* scale if necessary */\n                  if (scale != 1.0)\n                    {\n                      gsl_vector_view wv;\n\n                      wv = gsl_vector_subvector(w->work, 0, iu + 1);\n                      gsl_blas_dscal(scale, &wv.vector);\n                      wv = gsl_vector_subvector(w->work2, 0, iu + 1);\n                      gsl_blas_dscal(scale, &wv.vector);\n                    }\n                  gsl_vector_set(w->work, lu - 1, GSL_REAL(x1));\n                  gsl_vector_set(w->work, lu, GSL_REAL(x2));\n                  gsl_vector_set(w->work2, lu - 1, GSL_IMAG(x1));\n                  gsl_vector_set(w->work2, lu, GSL_IMAG(x2));\n\n                  /* update right hand side */\n                  if (lu > 1)\n                    {\n                      gsl_vector_view v1, v2, v3, v4;\n\n                      v1 = gsl_matrix_column(T, lu - 1);\n                      v1 = gsl_vector_subvector(&v1.vector, 0, lu - 1);\n                      v4 = gsl_matrix_column(T, lu);\n                      v4 = gsl_vector_subvector(&v4.vector, 0, lu - 1);\n                      v2 = gsl_vector_subvector(w->work, 0, lu - 1);\n                      v3 = gsl_vector_subvector(w->work2, 0, lu - 1);\n\n                      gsl_blas_daxpy(-GSL_REAL(x1), &v1.vector, &v2.vector);\n                      gsl_blas_daxpy(-GSL_REAL(x2), &v4.vector, &v2.vector);\n                      gsl_blas_daxpy(-GSL_IMAG(x1), &v1.vector, &v3.vector);\n                      gsl_blas_daxpy(-GSL_IMAG(x2), &v4.vector, &v3.vector);\n                    } /* if (lu > 1) */\n\n                  --l;\n                } /* if (complex_pair) */\n            } /* for (l = i - 2; l >= 0; --l) */\n\n          /*\n           * At this point, work + i*work2 is an eigenvector\n           * of T - backtransform to get an eigenvector of the\n           * original matrix\n           */\n\n          y = gsl_matrix_column(Z, iu - 1);\n          y2 = gsl_matrix_column(Z, iu);\n\n          if (iu > 1)\n            {\n              gsl_vector_view x;\n\n              /* compute real part of eigenvectors */\n\n              Zv = gsl_matrix_submatrix(Z, 0, 0, N, iu - 1);\n              x = gsl_vector_subvector(w->work, 0, iu - 1);\n\n              gsl_blas_dgemv(CblasNoTrans,\n                             1.0,\n                             &Zv.matrix,\n                             &x.vector,\n                             gsl_vector_get(w->work, iu - 1),\n                             &y.vector);\n\n\n              /* now compute the imaginary part */\n              x = gsl_vector_subvector(w->work2, 0, iu - 1);\n\n              gsl_blas_dgemv(CblasNoTrans,\n                             1.0,\n                             &Zv.matrix,\n                             &x.vector,\n                             gsl_vector_get(w->work2, iu),\n                             &y2.vector);\n            }\n          else\n            {\n              gsl_blas_dscal(gsl_vector_get(w->work, iu - 1), &y.vector);\n              gsl_blas_dscal(gsl_vector_get(w->work2, iu), &y2.vector);\n            }\n\n          /*\n           * Now store the eigenvectors into evec - the real parts\n           * are Z(:,iu - 1) and the imaginary parts are\n           * +/- Z(:,iu)\n           */\n\n          /* get views of the two eigenvector slots */\n          ecol = gsl_matrix_complex_column(evec, iu - 1);\n          ecol2 = gsl_matrix_complex_column(evec, iu);\n\n          /*\n           * save imaginary part first as it may get overwritten\n           * when copying the real part due to our storage scheme\n           * in Z/evec\n           */\n          ev = gsl_vector_complex_imag(&ecol.vector);\n          ev2 = gsl_vector_complex_imag(&ecol2.vector);\n          scale = 0.0;\n          for (ii = 0; ii < N; ++ii)\n            {\n              double a = gsl_vector_get(&y2.vector, ii);\n\n              scale = GSL_MAX(scale,\n                              fabs(a) + fabs(gsl_vector_get(&y.vector, ii)));\n\n              gsl_vector_set(&ev.vector, ii, a);\n              gsl_vector_set(&ev2.vector, ii, -a);\n            }\n\n          /* now save the real part */\n          ev = gsl_vector_complex_real(&ecol.vector);\n          ev2 = gsl_vector_complex_real(&ecol2.vector);\n          for (ii = 0; ii < N; ++ii)\n            {\n              double a = gsl_vector_get(&y.vector, ii);\n\n              gsl_vector_set(&ev.vector, ii, a);\n              gsl_vector_set(&ev2.vector, ii, a);\n            }\n\n          if (scale != 0.0)\n            scale = 1.0 / scale;\n\n          /* scale by largest element magnitude */\n\n          gsl_blas_zdscal(scale, &ecol.vector);\n          gsl_blas_zdscal(scale, &ecol2.vector);\n\n          /*\n           * decrement i since we took care of two eigenvalues at\n           * the same time\n           */\n          --i;\n        } /* if (GSL_IMAG(lambda) != 0.0) */\n    } /* for (i = (int) N - 1; i >= 0; --i) */\n} /* nonsymmv_get_right_eigenvectors() */\n\n/*\nnonsymmv_solve_equation()\n\n  Solve the equation which comes up in the back substitution\nwhen computing eigenvectors corresponding to real eigenvalues.\nThe equation that is solved is:\n\n(A - z*I)*x = s*b\n\nwhere\n\nA is n-by-n with n = 1 or 2\nb and x are n-by-1 real vectors\ns is a scaling factor set by this function to prevent overflow in x\n\nInputs: A     - square matrix (n-by-n)\n        z     - real scalar (eigenvalue)\n        b     - right hand side vector\n        x     - (output) where to store solution\n        s     - (output) scale factor\n        xnorm - (output) infinity norm of X\n        smin  - lower bound on singular values of A - if A - z*I\n                is less than this value, we'll use smin*I instead.\n                This value should be a safe distance above underflow.\n\nNotes: 1) A and b are not changed on output\n       2) Based on lapack routine DLALN2\n*/\n\nstatic inline void\nnonsymmv_solve_equation(gsl_matrix *A, double z, gsl_vector *b,\n                        gsl_vector *x, double *s, double *xnorm,\n                        double smin)\n{\n  size_t N = A->size1;\n  double bnorm;\n  double scale = 1.0;\n  \n  if (N == 1)\n    {\n      double c,     /* denominator */\n             cnorm; /* |c| */\n\n      /*\n       * we have a 1-by-1 (real) scalar system to solve:\n       *\n       * (a - z)*x = b\n       * with z real\n       */\n\n      /* c = a - z */\n      c = gsl_matrix_get(A, 0, 0) - z;\n      cnorm = fabs(c);\n\n      if (cnorm < smin)\n        {\n          /* set c = smin*I */\n          c = smin;\n          cnorm = smin;\n        }\n\n      /* check scaling for x = b / c */\n      bnorm = fabs(gsl_vector_get(b, 0));\n      if (cnorm < 1.0 && bnorm > 1.0)\n        {\n          if (bnorm > GSL_NONSYMMV_BIGNUM*cnorm)\n            scale = 1.0 / bnorm;\n        }\n\n      /* compute x */\n      gsl_vector_set(x, 0, gsl_vector_get(b, 0) * scale / c);\n      *xnorm = fabs(gsl_vector_get(x, 0));\n    } /* if (N == 1) */\n  else\n    {\n      double cr[2][2];\n      double *crv;\n      double cmax;\n      size_t icmax, j;\n      double bval1, bval2;\n      double ur11, ur12, ur22, ur11r;\n      double cr21, cr22;\n      double lr21;\n      double b1, b2, bbnd;\n      double x1, x2;\n      double temp;\n      size_t ipivot[4][4] = { { 0, 1, 2, 3 },\n                              { 1, 0, 3, 2 },\n                              { 2, 3, 0, 1 },\n                              { 3, 2, 1, 0 } };\n      int rswap[4] = { 0, 1, 0, 1 };\n      int zswap[4] = { 0, 0, 1, 1 };\n\n      /*\n       * we have a 2-by-2 real system to solve:\n       *\n       * [ A11 - z   A12   ] [ x1 ] = [ b1 ]\n       * [   A21   A22 - z ] [ x2 ]   [ b2 ]\n       *\n       * (z real)\n       */\n\n      crv = (double *) cr;\n\n      /*\n       * compute the real part of C = A - z*I - use column ordering\n       * here since porting from lapack\n       */\n      cr[0][0] = gsl_matrix_get(A, 0, 0) - z;\n      cr[1][1] = gsl_matrix_get(A, 1, 1) - z;\n      cr[0][1] = gsl_matrix_get(A, 1, 0);\n      cr[1][0] = gsl_matrix_get(A, 0, 1);\n\n      /* find the largest element in C */\n      cmax = 0.0;\n      icmax = 0;\n      for (j = 0; j < 4; ++j)\n        {\n          if (fabs(crv[j]) > cmax)\n            {\n              cmax = fabs(crv[j]);\n              icmax = j;\n            }\n        }\n\n      bval1 = gsl_vector_get(b, 0);\n      bval2 = gsl_vector_get(b, 1);\n\n      /* if norm(C) < smin, use smin*I */\n\n      if (cmax < smin)\n        {\n          bnorm = GSL_MAX(fabs(bval1), fabs(bval2));\n          if (smin < 1.0 && bnorm > 1.0)\n            {\n              if (bnorm > GSL_NONSYMMV_BIGNUM*smin)\n                scale = 1.0 / bnorm;\n            }\n          temp = scale / smin;\n          gsl_vector_set(x, 0, temp * bval1);\n          gsl_vector_set(x, 1, temp * bval2);\n          *xnorm = temp * bnorm;\n          *s = scale;\n          return;\n        }\n\n      /* gaussian elimination with complete pivoting */\n      ur11 = crv[icmax];\n      cr21 = crv[ipivot[1][icmax]];\n      ur12 = crv[ipivot[2][icmax]];\n      cr22 = crv[ipivot[3][icmax]];\n      ur11r = 1.0 / ur11;\n      lr21 = ur11r * cr21;\n      ur22 = cr22 - ur12 * lr21;\n\n      /* if smaller pivot < smin, use smin */\n      if (fabs(ur22) < smin)\n        ur22 = smin;\n\n      if (rswap[icmax])\n        {\n          b1 = bval2;\n          b2 = bval1;\n        }\n      else\n        {\n          b1 = bval1;\n          b2 = bval2;\n        }\n\n      b2 -= lr21 * b1;\n      bbnd = GSL_MAX(fabs(b1 * (ur22 * ur11r)), fabs(b2));\n      if (bbnd > 1.0 && fabs(ur22) < 1.0)\n        {\n          if (bbnd >= GSL_NONSYMMV_BIGNUM * fabs(ur22))\n            scale = 1.0 / bbnd;\n        }\n\n      x2 = (b2 * scale) / ur22;\n      x1 = (scale * b1) * ur11r - x2 * (ur11r * ur12);\n      if (zswap[icmax])\n        {\n          gsl_vector_set(x, 0, x2);\n          gsl_vector_set(x, 1, x1);\n        }\n      else\n        {\n          gsl_vector_set(x, 0, x1);\n          gsl_vector_set(x, 1, x2);\n        }\n\n      *xnorm = GSL_MAX(fabs(x1), fabs(x2));\n\n      /* further scaling if norm(A) norm(X) > overflow */\n      if (*xnorm > 1.0 && cmax > 1.0)\n        {\n          if (*xnorm > GSL_NONSYMMV_BIGNUM / cmax)\n            {\n              temp = cmax / GSL_NONSYMMV_BIGNUM;\n              gsl_blas_dscal(temp, x);\n              *xnorm *= temp;\n              scale *= temp;\n            }\n        }\n    } /* if (N == 2) */\n\n  *s = scale;\n} /* nonsymmv_solve_equation() */\n\n/*\nnonsymmv_solve_equation_z()\n\n  Solve the equation which comes up in the back substitution\nwhen computing eigenvectors corresponding to complex eigenvalues.\nThe equation that is solved is:\n\n(A - z*I)*x = s*b\n\nwhere\n\nA is n-by-n with n = 1 or 2\nb and x are n-by-1 complex vectors\ns is a scaling factor set by this function to prevent overflow in x\n\nInputs: A     - square matrix (n-by-n)\n        z     - complex scalar (eigenvalue)\n        b     - right hand side vector\n        x     - (output) where to store solution\n        s     - (output) scale factor\n        xnorm - (output) infinity norm of X\n        smin  - lower bound on singular values of A - if A - z*I\n                is less than this value, we'll use smin*I instead.\n                This value should be a safe distance above underflow.\n\nNotes: 1) A and b are not changed on output\n       2) Based on lapack routine DLALN2\n*/\n\nstatic inline void\nnonsymmv_solve_equation_z(gsl_matrix *A, gsl_complex *z,\n                          gsl_vector_complex *b, gsl_vector_complex *x,\n                          double *s, double *xnorm, double smin)\n{\n  size_t N = A->size1;\n  double scale = 1.0;\n  double bnorm;\n\n  if (N == 1)\n    {\n      double cr,    /* denominator */\n             ci,\n             cnorm; /* |c| */\n      gsl_complex bval, c, xval, tmp;\n\n      /*\n       * we have a 1-by-1 (complex) scalar system to solve:\n       *\n       * (a - z)*x = b\n       * (z is complex, a is real)\n       */\n\n      /* c = a - z */\n      cr = gsl_matrix_get(A, 0, 0) - GSL_REAL(*z);\n      ci = -GSL_IMAG(*z);\n      cnorm = fabs(cr) + fabs(ci);\n\n      if (cnorm < smin)\n        {\n          /* set c = smin*I */\n          cr = smin;\n          ci = 0.0;\n          cnorm = smin;\n        }\n\n      /* check scaling for x = b / c */\n      bval = gsl_vector_complex_get(b, 0);\n      bnorm = fabs(GSL_REAL(bval)) + fabs(GSL_IMAG(bval));\n      if (cnorm < 1.0 && bnorm > 1.0)\n        {\n          if (bnorm > GSL_NONSYMMV_BIGNUM*cnorm)\n            scale = 1.0 / bnorm;\n        }\n\n      /* compute x */\n      GSL_SET_COMPLEX(&tmp, scale*GSL_REAL(bval), scale*GSL_IMAG(bval));\n      GSL_SET_COMPLEX(&c, cr, ci);\n      xval = gsl_complex_div(tmp, c);\n\n      gsl_vector_complex_set(x, 0, xval);\n\n      *xnorm = fabs(GSL_REAL(xval)) + fabs(GSL_IMAG(xval));\n    } /* if (N == 1) */\n  else\n    {\n      double cr[2][2], ci[2][2];\n      double *civ, *crv;\n      double cmax;\n      gsl_complex bval1, bval2;\n      gsl_complex xval1, xval2;\n      double xr1, xi1;\n      size_t icmax;\n      size_t j;\n      double temp;\n      double ur11, ur12, ur22, ui11, ui12, ui22, ur11r, ui11r;\n      double ur12s, ui12s;\n      double u22abs;\n      double lr21, li21;\n      double cr21, cr22, ci21, ci22;\n      double br1, bi1, br2, bi2, bbnd;\n      gsl_complex b1, b2;\n      size_t ipivot[4][4] = { { 0, 1, 2, 3 },\n                              { 1, 0, 3, 2 },\n                              { 2, 3, 0, 1 },\n                              { 3, 2, 1, 0 } };\n      int rswap[4] = { 0, 1, 0, 1 };\n      int zswap[4] = { 0, 0, 1, 1 };\n\n      /*\n       * complex 2-by-2 system:\n       *\n       * [ A11 - z   A12   ] [ X1 ] = [ B1 ]\n       * [   A21   A22 - z ] [ X2 ]   [ B2 ]\n       *\n       * (z complex)\n       *\n       * where the X and B values are complex.\n       */\n\n      civ = (double *) ci;\n      crv = (double *) cr;\n\n      /*\n       * compute the real part of C = A - z*I - use column ordering\n       * here since porting from lapack\n       */\n      cr[0][0] = gsl_matrix_get(A, 0, 0) - GSL_REAL(*z);\n      cr[1][1] = gsl_matrix_get(A, 1, 1) - GSL_REAL(*z);\n      cr[0][1] = gsl_matrix_get(A, 1, 0);\n      cr[1][0] = gsl_matrix_get(A, 0, 1);\n\n      /* compute the imaginary part */\n      ci[0][0] = -GSL_IMAG(*z);\n      ci[0][1] = 0.0;\n      ci[1][0] = 0.0;\n      ci[1][1] = -GSL_IMAG(*z);\n\n      cmax = 0.0;\n      icmax = 0;\n\n      for (j = 0; j < 4; ++j)\n        {\n          if (fabs(crv[j]) + fabs(civ[j]) > cmax)\n            {\n              cmax = fabs(crv[j]) + fabs(civ[j]);\n              icmax = j;\n            }\n        }\n\n      bval1 = gsl_vector_complex_get(b, 0);\n      bval2 = gsl_vector_complex_get(b, 1);\n\n      /* if norm(C) < smin, use smin*I */\n      if (cmax < smin)\n        {\n          bnorm = GSL_MAX(fabs(GSL_REAL(bval1)) + fabs(GSL_IMAG(bval1)),\n                          fabs(GSL_REAL(bval2)) + fabs(GSL_IMAG(bval2)));\n          if (smin < 1.0 && bnorm > 1.0)\n            {\n              if (bnorm > GSL_NONSYMMV_BIGNUM*smin)\n                scale = 1.0 / bnorm;\n            }\n\n          temp = scale / smin;\n          xval1 = gsl_complex_mul_real(bval1, temp);\n          xval2 = gsl_complex_mul_real(bval2, temp);\n          gsl_vector_complex_set(x, 0, xval1);\n          gsl_vector_complex_set(x, 1, xval2);\n          *xnorm = temp * bnorm;\n          *s = scale;\n          return;\n        }\n\n      /* gaussian elimination with complete pivoting */\n      ur11 = crv[icmax];\n      ui11 = civ[icmax];\n      cr21 = crv[ipivot[1][icmax]];\n      ci21 = civ[ipivot[1][icmax]];\n      ur12 = crv[ipivot[2][icmax]];\n      ui12 = civ[ipivot[2][icmax]];\n      cr22 = crv[ipivot[3][icmax]];\n      ci22 = civ[ipivot[3][icmax]];\n\n      if (icmax == 0 || icmax == 3)\n        {\n          /* off diagonals of pivoted C are real */\n          if (fabs(ur11) > fabs(ui11))\n            {\n              temp = ui11 / ur11;\n              ur11r = 1.0 / (ur11 * (1.0 + temp*temp));\n              ui11r = -temp * ur11r;\n            }\n          else\n            {\n              temp = ur11 / ui11;\n              ui11r = -1.0 / (ui11 * (1.0 + temp*temp));\n              ur11r = -temp*ui11r;\n            }\n          lr21 = cr21 * ur11r;\n          li21 = cr21 * ui11r;\n          ur12s = ur12 * ur11r;\n          ui12s = ur12 * ui11r;\n          ur22 = cr22 - ur12 * lr21;\n          ui22 = ci22 - ur12 * li21;\n        }\n      else\n        {\n          /* diagonals of pivoted C are real */\n          ur11r = 1.0 / ur11;\n          ui11r = 0.0;\n          lr21 = cr21 * ur11r;\n          li21 = ci21 * ur11r;\n          ur12s = ur12 * ur11r;\n          ui12s = ui12 * ur11r;\n          ur22 = cr22 - ur12 * lr21 + ui12 * li21;\n          ui22 = -ur12 * li21 - ui12 * lr21;\n        }\n\n      u22abs = fabs(ur22) + fabs(ui22);\n\n      /* if smaller pivot < smin, use smin */\n      if (u22abs < smin)\n        {\n          ur22 = smin;\n          ui22 = 0.0;\n        }\n\n      if (rswap[icmax])\n        {\n          br2 = GSL_REAL(bval1);\n          bi2 = GSL_IMAG(bval1);\n          br1 = GSL_REAL(bval2);\n          bi1 = GSL_IMAG(bval2);\n        }\n      else\n        {\n          br1 = GSL_REAL(bval1);\n          bi1 = GSL_IMAG(bval1);\n          br2 = GSL_REAL(bval2);\n          bi2 = GSL_IMAG(bval2);\n        }\n\n      br2 += li21*bi1 - lr21*br1;\n      bi2 -= li21*br1 + lr21*bi1;\n      bbnd = GSL_MAX((fabs(br1) + fabs(bi1)) *\n                     (u22abs * (fabs(ur11r) + fabs(ui11r))),\n                     fabs(br2) + fabs(bi2));\n      if (bbnd > 1.0 && u22abs < 1.0)\n        {\n          if (bbnd >= GSL_NONSYMMV_BIGNUM*u22abs)\n            {\n              scale = 1.0 / bbnd;\n              br1 *= scale;\n              bi1 *= scale;\n              br2 *= scale;\n              bi2 *= scale;\n            }\n        }\n\n      GSL_SET_COMPLEX(&b1, br2, bi2);\n      GSL_SET_COMPLEX(&b2, ur22, ui22);\n      xval2 = gsl_complex_div(b1, b2);\n\n      xr1 = ur11r*br1 - ui11r*bi1 - ur12s*GSL_REAL(xval2) + ui12s*GSL_IMAG(xval2);\n      xi1 = ui11r*br1 + ur11r*bi1 - ui12s*GSL_REAL(xval2) - ur12s*GSL_IMAG(xval2);\n      GSL_SET_COMPLEX(&xval1, xr1, xi1);\n\n      if (zswap[icmax])\n        {\n          gsl_vector_complex_set(x, 0, xval2);\n          gsl_vector_complex_set(x, 1, xval1);\n        }\n      else\n        {\n          gsl_vector_complex_set(x, 0, xval1);\n          gsl_vector_complex_set(x, 1, xval2);\n        }\n\n      *xnorm = GSL_MAX(fabs(GSL_REAL(xval1)) + fabs(GSL_IMAG(xval1)),\n                       fabs(GSL_REAL(xval2)) + fabs(GSL_IMAG(xval2)));\n\n      /* further scaling if norm(A) norm(X) > overflow */\n      if (*xnorm > 1.0 && cmax > 1.0)\n        {\n          if (*xnorm > GSL_NONSYMMV_BIGNUM / cmax)\n            {\n              temp = cmax / GSL_NONSYMMV_BIGNUM;\n              gsl_blas_zdscal(temp, x);\n              *xnorm *= temp;\n              scale *= temp;\n            }\n        }\n    } /* if (N == 2) */\n\n  *s = scale;\n} /* nonsymmv_solve_equation_z() */\n\n/*\nnonsymmv_normalize_eigenvectors()\n  Normalize eigenvectors so that their Euclidean norm is 1\n\nInputs: eval - eigenvalues\n        evec - eigenvectors\n*/\n\nstatic void\nnonsymmv_normalize_eigenvectors(gsl_vector_complex *eval,\n                                gsl_matrix_complex *evec)\n{\n  const size_t N = evec->size1;\n  size_t i;     /* looping */\n  gsl_complex ei;\n  gsl_vector_complex_view vi;\n  gsl_vector_view re, im;\n  double scale; /* scaling factor */\n\n  for (i = 0; i < N; ++i)\n    {\n      ei = gsl_vector_complex_get(eval, i);\n      vi = gsl_matrix_complex_column(evec, i);\n\n      re = gsl_vector_complex_real(&vi.vector);\n\n      if (GSL_IMAG(ei) == 0.0)\n        {\n          scale = 1.0 / gsl_blas_dnrm2(&re.vector);\n          gsl_blas_dscal(scale, &re.vector);\n        }\n      else if (GSL_IMAG(ei) > 0.0)\n        {\n          im = gsl_vector_complex_imag(&vi.vector);\n\n          scale = 1.0 / gsl_hypot(gsl_blas_dnrm2(&re.vector),\n                                  gsl_blas_dnrm2(&im.vector));\n          gsl_blas_zdscal(scale, &vi.vector);\n\n          vi = gsl_matrix_complex_column(evec, i + 1);\n          gsl_blas_zdscal(scale, &vi.vector);\n        }\n    }\n} /* nonsymmv_normalize_eigenvectors() */\n", "meta": {"hexsha": "bcd258916f556dc3407693e716a828d71e99cdaa", "size": 45275, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/eigen/nonsymmv.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/eigen/nonsymmv.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/eigen/nonsymmv.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 30.778382053, "max_line_length": 96, "alphanum_fraction": 0.4682937604, "num_tokens": 12148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3903911505966178}}
{"text": "/* integration/gsl_integration.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_INTEGRATION_H__\n#define __GSL_INTEGRATION_H__\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/* Workspace for adaptive integrators */\n\ntypedef struct\n  {\n    size_t limit;\n    size_t size;\n    size_t nrmax;\n    size_t i;\n    size_t maximum_level;\n    double *alist;\n    double *blist;\n    double *rlist;\n    double *elist;\n    size_t *order;\n    size_t *level;\n  }\ngsl_integration_workspace;\n\ngsl_integration_workspace *\n  gsl_integration_workspace_alloc (const size_t n);\n\nvoid\n  gsl_integration_workspace_free (gsl_integration_workspace * w);\n\n\n/* Workspace for QAWS integrator */\n\ntypedef struct\n{\n  double alpha;\n  double beta;\n  int mu;\n  int nu;\n  double ri[25];\n  double rj[25];\n  double rg[25];\n  double rh[25];\n}\ngsl_integration_qaws_table;\n\ngsl_integration_qaws_table * \ngsl_integration_qaws_table_alloc (double alpha, double beta, int mu, int nu);\n\nint\ngsl_integration_qaws_table_set (gsl_integration_qaws_table * t,\n                                double alpha, double beta, int mu, int nu);\n\nvoid\ngsl_integration_qaws_table_free (gsl_integration_qaws_table * t);\n\n/* Workspace for QAWO integrator */\n\nenum gsl_integration_qawo_enum { GSL_INTEG_COSINE, GSL_INTEG_SINE };\n\ntypedef struct\n{\n  size_t n;\n  double omega;\n  double L;\n  double par;\n  enum gsl_integration_qawo_enum sine;\n  double *chebmo;\n}\ngsl_integration_qawo_table;\n\ngsl_integration_qawo_table * \ngsl_integration_qawo_table_alloc (double omega, double L, \n                                  enum gsl_integration_qawo_enum sine,\n                                  size_t n);\n\nint\ngsl_integration_qawo_table_set (gsl_integration_qawo_table * t,\n                                double omega, double L,\n                                enum gsl_integration_qawo_enum sine);\n\nint\ngsl_integration_qawo_table_set_length (gsl_integration_qawo_table * t,\n                                       double L);\n\nvoid\ngsl_integration_qawo_table_free (gsl_integration_qawo_table * t);\n\n\n/* Definition of an integration rule */\n\ntypedef void gsl_integration_rule (const gsl_function * f,\n                                   double a, double b,\n                                   double *result, double *abserr,\n                                   double *defabs, double *resabs);\n\nvoid gsl_integration_qk15 (const gsl_function * f, double a, double b,\n                           double *result, double *abserr,\n                           double *resabs, double *resasc);\n\nvoid gsl_integration_qk21 (const gsl_function * f, double a, double b,\n                           double *result, double *abserr,\n                           double *resabs, double *resasc);\n\nvoid gsl_integration_qk31 (const gsl_function * f, double a, double b,\n                           double *result, double *abserr,\n                           double *resabs, double *resasc);\n\nvoid gsl_integration_qk41 (const gsl_function * f, double a, double b,\n                           double *result, double *abserr,\n                           double *resabs, double *resasc);\n\nvoid gsl_integration_qk51 (const gsl_function * f, double a, double b,\n                           double *result, double *abserr,\n                           double *resabs, double *resasc);\n\nvoid gsl_integration_qk61 (const gsl_function * f, double a, double b,\n                           double *result, double *abserr,\n                           double *resabs, double *resasc);\n\nvoid gsl_integration_qcheb (gsl_function * f, double a, double b, \n                            double *cheb12, double *cheb24);\n\n/* The low-level integration rules in QUADPACK are identified by small\n   integers (1-6). We'll use symbolic constants to refer to them.  */\n\nenum\n  {\n    GSL_INTEG_GAUSS15 = 1,      /* 15 point Gauss-Kronrod rule */\n    GSL_INTEG_GAUSS21 = 2,      /* 21 point Gauss-Kronrod rule */\n    GSL_INTEG_GAUSS31 = 3,      /* 31 point Gauss-Kronrod rule */\n    GSL_INTEG_GAUSS41 = 4,      /* 41 point Gauss-Kronrod rule */\n    GSL_INTEG_GAUSS51 = 5,      /* 51 point Gauss-Kronrod rule */\n    GSL_INTEG_GAUSS61 = 6       /* 61 point Gauss-Kronrod rule */\n  };\n\nvoid \ngsl_integration_qk (const int n, const double xgk[], \n                    const double wg[], const double wgk[],\n                    double fv1[], double fv2[],\n                    const gsl_function *f, double a, double b,\n                    double * result, double * abserr, \n                    double * resabs, double * resasc);\n\n\nint gsl_integration_qng (const gsl_function * f,\n                         double a, double b,\n                         double epsabs, double epsrel,\n                         double *result, double *abserr,\n                         size_t * neval);\n\nint gsl_integration_qag (const gsl_function * f,\n                         double a, double b,\n                         double epsabs, double epsrel, size_t limit,\n                         int key,\n                         gsl_integration_workspace * workspace,\n                         double *result, double *abserr);\n\nint gsl_integration_qagi (gsl_function * f,\n                          double epsabs, double epsrel, size_t limit,\n                          gsl_integration_workspace * workspace,\n                          double *result, double *abserr);\n\nint gsl_integration_qagiu (gsl_function * f,\n                           double a,\n                           double epsabs, double epsrel, size_t limit,\n                           gsl_integration_workspace * workspace,\n                           double *result, double *abserr);\n\nint gsl_integration_qagil (gsl_function * f,\n                           double b,\n                           double epsabs, double epsrel, size_t limit,\n                           gsl_integration_workspace * workspace,\n                           double *result, double *abserr);\n\n\nint gsl_integration_qags (const gsl_function * f,\n                          double a, double b,\n                          double epsabs, double epsrel, size_t limit,\n                          gsl_integration_workspace * workspace,\n                          double *result, double *abserr);\n\nint gsl_integration_qagp (const gsl_function * f,\n                          double *pts, size_t npts,\n                          double epsabs, double epsrel, size_t limit,\n                          gsl_integration_workspace * workspace,\n                          double *result, double *abserr);\n\nint gsl_integration_qawc (gsl_function *f,\n                          const double a, const double b, const double c,\n                          const double epsabs, const double epsrel, const size_t limit,\n                          gsl_integration_workspace * workspace,\n                          double * result, double * abserr);\n\nint gsl_integration_qaws (gsl_function * f,\n                          const double a, const double b,\n                          gsl_integration_qaws_table * t,\n                          const double epsabs, const double epsrel,\n                          const size_t limit,\n                          gsl_integration_workspace * workspace,\n                          double *result, double *abserr);\n\nint gsl_integration_qawo (gsl_function * f,\n                          const double a,\n                          const double epsabs, const double epsrel,\n                          const size_t limit,\n                          gsl_integration_workspace * workspace,\n                          gsl_integration_qawo_table * wf,\n                          double *result, double *abserr);\n\nint gsl_integration_qawf (gsl_function * f,\n                          const double a,\n                          const double epsabs,\n                          const size_t limit,\n                          gsl_integration_workspace * workspace,\n                          gsl_integration_workspace * cycle_workspace,\n                          gsl_integration_qawo_table * wf,\n                          double *result, double *abserr);\n\n/* Workspace for fixed-order Gauss-Legendre integration */\n\ntypedef struct\n  {\n    size_t n;         /* number of points */\n    double *x;        /* Gauss abscissae/points */\n    double *w;        /* Gauss weights for each abscissae */\n    int precomputed;  /* high precision abscissae/weights precomputed? */\n  }\ngsl_integration_glfixed_table;\n\n\ngsl_integration_glfixed_table * gsl_integration_glfixed_table_alloc (size_t n);\n\nvoid gsl_integration_glfixed_table_free (gsl_integration_glfixed_table * t);\n\n/* Routine for fixed-order Gauss-Legendre integration */\n\ndouble gsl_integration_glfixed (const gsl_function *f,\n                                double a,\n                                double b,\n                                const gsl_integration_glfixed_table * t);\n\n/* Routine to retrieve the i-th Gauss-Legendre point and weight from t */\n\nint gsl_integration_glfixed_point (double a,\n                                   double b,\n                                   size_t i,\n                                   double *xi,\n                                   double *wi,\n                                   const gsl_integration_glfixed_table * t);\n\n\n/* Cquad integration - Pedro Gonnet */\n\n/* Data of a single interval */\ntypedef struct\n{\n  double a, b;\n  double c[64];\n  double fx[33];\n  double igral, err;\n  int depth, rdepth, ndiv;\n} gsl_integration_cquad_ival;\n\n\n/* The workspace is just a collection of intervals */\ntypedef struct\n{\n  size_t size;\n  gsl_integration_cquad_ival *ivals;\n  size_t *heap;\n} gsl_integration_cquad_workspace;\n\ngsl_integration_cquad_workspace *\ngsl_integration_cquad_workspace_alloc (const size_t n);\n\nvoid\ngsl_integration_cquad_workspace_free (gsl_integration_cquad_workspace * w);\n\nint\ngsl_integration_cquad (const gsl_function * f, double a, double b,\n\t\t                   double epsabs, double epsrel,\n\t\t                   gsl_integration_cquad_workspace * ws,\n\t\t                   double *result, double *abserr, size_t * nevals);\n\n/* Romberg integration workspace and routines */\n\ntypedef struct\n{\n  size_t n;       /* maximum number of steps */\n  double *work1;  /* workspace for a row of R matrix, size n */\n  double *work2;  /* workspace for a row of R matrix, size n */\n} gsl_integration_romberg_workspace;\n\ngsl_integration_romberg_workspace *gsl_integration_romberg_alloc(const size_t n);\nvoid gsl_integration_romberg_free(gsl_integration_romberg_workspace * w);\nint gsl_integration_romberg(const gsl_function * f, const double a, const double b,\n                            const double epsabs, const double epsrel, double * result,\n                            size_t * neval, gsl_integration_romberg_workspace * w);\n\n/* IQPACK related structures and routines */\n\ntypedef struct\n{\n  double alpha;\n  double beta;\n  double a;\n  double b;\n  double zemu;\n  double shft;\n  double slp;\n  double al;\n  double be;\n} gsl_integration_fixed_params;\n\ntypedef struct\n{\n  int (*check)(const size_t n, const gsl_integration_fixed_params * params);\n  int (*init)(const size_t n, double * diag, double * subdiag, gsl_integration_fixed_params * params);\n} gsl_integration_fixed_type;\n\ntypedef struct\n{\n  size_t n;        /* number of nodes/weights */\n  double *weights; /* quadrature weights */\n  double *x;       /* quadrature nodes */\n  double *diag;    /* diagonal of Jacobi matrix */\n  double *subdiag; /* subdiagonal of Jacobi matrix */\n  const gsl_integration_fixed_type * type;\n} gsl_integration_fixed_workspace;\n\n/* IQPACK integral types */\nGSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_legendre;\nGSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_chebyshev;\nGSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_gegenbauer;\nGSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_jacobi;\nGSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_laguerre;\nGSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_hermite;\nGSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_exponential;\nGSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_rational;\nGSL_VAR const gsl_integration_fixed_type * gsl_integration_fixed_chebyshev2;\n\ngsl_integration_fixed_workspace *\ngsl_integration_fixed_alloc(const gsl_integration_fixed_type * type, const size_t n,\n                            const double a, const double b, const double alpha, const double beta);\n\nvoid gsl_integration_fixed_free(gsl_integration_fixed_workspace * w);\n\nsize_t gsl_integration_fixed_n(const gsl_integration_fixed_workspace * w);\n\ndouble *gsl_integration_fixed_nodes(const gsl_integration_fixed_workspace * w);\n\ndouble *gsl_integration_fixed_weights(const gsl_integration_fixed_workspace * w);\n\nint gsl_integration_fixed(const gsl_function * func, double * result,\n                          const gsl_integration_fixed_workspace * w);\n\n__END_DECLS\n\n#endif /* __GSL_INTEGRATION_H__ */\n", "meta": {"hexsha": "1e8b38ac4cb3826cc627917637f5a9b101902574", "size": 13855, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_integration.h", "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_integration.h", "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_integration.h", "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "avg_line_length": 35.4347826087, "max_line_length": 102, "alphanum_fraction": 0.6292313244, "num_tokens": 2970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175005616831, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3902220614081496}}
{"text": "/** @file */\n\n#ifndef __CCL_F2D_H_INCLUDED__\n#define __CCL_F2D_H_INCLUDED__\n\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_interp2d.h>\n#include <gsl/gsl_spline2d.h>\n\nCCL_BEGIN_DECLS\n\n//f2d extrapolation types for early times\ntypedef enum ccl_f2d_extrap_growth_t\n{\n  ccl_f2d_cclgrowth = 401, //Use CCL's linear growth\n  ccl_f2d_customgrowth = 402, //Use a custom growth function\n  ccl_f2d_constantgrowth = 403, //Use a constant growth factor\n  ccl_f2d_no_extrapol = 404, //Do not extrapolate, just throw an exception\n} ccl_f2d_extrap_growth_t;\n\n//f2d interpolation types\ntypedef enum ccl_f2d_interp_t\n{\n  ccl_f2d_3 = 303, //Bicubic interpolation\n} ccl_f2d_interp_t;\n\n/**\n * Struct containing a 2D power spectrum\n */\ntypedef struct {\n  double lkmin,lkmax; /**< Edges in log(k)*/\n  double amin,amax; /**< Edges in a*/\n  int is_factorizable; /**< Is this factorizable into k- and a-dependent functions? */\n  int is_k_constant; /**< no k-dependence, just return 1*/\n  int is_a_constant; /**< no a-dependence, just return 1*/\n  int extrap_order_lok; /**< Order of extrapolating polynomial in log(k) for low k (0, 1 or 2)*/\n  int extrap_order_hik; /**< Order of extrapolating polynomial in log(k) for high k (0, 1 or 2)*/\n  ccl_f2d_extrap_growth_t extrap_linear_growth;  /**< Extrapolation type at high redshifts*/\n  int is_log; /**< Do I hold the values of log(f(k,a))?*/\n  double (*growth)(double); /**< Custom extrapolating growth function*/\n  double growth_factor_0; /**< Constant extrapolating growth factor*/\n  int growth_exponent; /**< Power to which growth should be exponentiated*/\n  gsl_spline *fk; /**< Spline holding the values of the k-dependent factor*/\n  gsl_spline *fa; /**< Spline holding the values of the a-dependent factor*/\n  gsl_spline2d *fka; /**< Spline holding the values of f(k,a)*/\n} ccl_f2d_t;\n\n/**\n * Create a ccl_f2d_t structure.\n * @param na number of elements in a_arr.\n * @param a_arr array of scale factor values at which the function is defined. The array should be ordered.\n * @param nk number of elements of lk_arr.\n * @param lk_arr array of logarithmic wavenumbers at which the function is defined (i.e. this array contains ln(k), NOT k). The array should be ordered.\n * @param fka_arr array of size na * nk containing the 2D function. The 2D ordering is such that fka_arr[ia*nk+ik] = f(k=exp(lk_arr[ik]),a=a_arr[ia]).\n * @param fk_arr array of size nk containing the k-dependent part of the function. Only relevant if is_factorizable is true.\n * @param fa_arr array of size na containing the a-dependent part of the function. Only relevant if is_factorizable is true.\n * @param is_factorizable if not 0, fk_arr and fa_arr will be used as 1-D arrays to construct a factorizable 2D function.\n * @param extrap_order_lok Order of the polynomial that extrapolates on wavenumbers smaller than the minimum of lk_arr. Allowed values: 0 (constant), 1 (linear extrapolation) and 2 (quadratic extrapolation). Extrapolation happens in ln(k).\n * @param extrap_order_hik Order of the polynomial that extrapolates on wavenumbers larger than the maximum of lk_arr. Allowed values: 0 (constant), 1 (linear extrapolation) and 2 (quadratic extrapolation). Extrapolation happens in ln(k).\n * @param extrap_linear_growth: ccl_f2d_extrap_growth_t value defining how the function with scale factors below the interpolation range. Allowed values: ccl_f2d_cclgrowth (scale with the CCL linear growth factor), ccl_f2d_customgrowth (scale with a custom function of redshift passed through `growth`), ccl_f2d_constantgrowth (scale by multiplying the function at the earliest available scale factor by a constant number, defined by `growth_factor_0`), ccl_f2d_no_extrapol (throw an error if the function is ever evaluated outside the interpolation range in a). Note that, above the interpolation range (i.e. for low redshifts), the function will be assumed constant.\n * @param is_fka_log: if not zero, `fka_arr` contains ln(f(k,a)) instead of f(k,a). If the function is factorizable, then `fk_arr` holds ln(K(k)) and `fa_arr` holds ln(A(a)), where f(k,a)=K(k)*A(a).\n * @param growth: custom growth function. Irrelevant if extrap_linear_growth!=ccl_f2d_customgrowth.\n * @param growth_factor_0: custom growth function. Irrelevant if extrap_linear_growth!=ccl_f2d_constantgrowth.\n * @param growth_exponent: power to which the extrapolating growth factor should be exponentiated when extrapolating (e.g. usually 2 for linear power spectra).\n * @param interp_type: 2D interpolation method. Currently only ccl_f2d_3 is implemented (bicubic interpolation).\n * @param status Status flag. 0 if there are no errors, nonzero otherwise.\n */\nccl_f2d_t *ccl_f2d_t_new(int na,double *a_arr,\n\t\t\t int nk,double *lk_arr,\n\t\t\t double *fka_arr,\n\t\t\t double *fk_arr,\n\t\t\t double *fa_arr,\n\t\t\t int is_factorizable,\n\t\t\t int extrap_order_lok,\n\t\t\t int extrap_order_hik,\n\t\t\t ccl_f2d_extrap_growth_t extrap_linear_growth,\n\t\t\t int is_fka_log,\n\t\t\t double (*growth)(double),\n\t\t\t double growth_factor_0,\n\t\t\t int growth_exponent,\n\t\t\t ccl_f2d_interp_t interp_type,\n\t\t\t int *status);\n\n/**\n * Evaluate 2D function of k and a defined by ccl_f2d_t structure.\n * @param fka ccl_f2d_t structure defining f(k,a).\n * @param lk Natural logarithm of the wavenumber.\n * @param a Scale factor.\n * @param cosmo ccl_cosmology structure, only needed if evaluating f(k,a) at small scale factors outside the interpolation range, and if fka was initialized with extrap_linear_growth = ccl_f2d_cclgrowth.\n * @param status Status flag. 0 if there are no errors, nonzero otherwise.\n */\ndouble ccl_f2d_t_eval(ccl_f2d_t *fka,double lk,double a,void *cosmo,\n\t\t      int *status);\n\n/**\n * F2D structure destructor.\n * Frees up all memory associated with a f2d structure.\n * @param fka Structure to be freed.\n */\nvoid ccl_f2d_t_free(ccl_f2d_t *fka);\n\nCCL_END_DECLS\n\n#endif\n", "meta": {"hexsha": "a51892ae3b3ce048473fff6fe7376bb6b76d6343", "size": 5813, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ccl_f2d.h", "max_stars_repo_name": "benediktdiemer/CCL", "max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ccl_f2d.h", "max_issues_repo_name": "benediktdiemer/CCL", "max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ccl_f2d.h", "max_forks_repo_name": "benediktdiemer/CCL", "max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z", "avg_line_length": 55.3619047619, "max_line_length": 668, "alphanum_fraction": 0.7567521073, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.3902220614081494}}
{"text": "#include \"mpi.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <math.h>\n#include <libiomp/omp.h>\n#include <string.h>\n#include <stdbool.h>\n\n#ifdef __APPLE__\n\n#include <cblas.h>\n\n#define set_num_threads(x) openblas_set_num_threads(x)\n#define get_num_threads() openblas_get_num_threads()\n#else\n#include <mkl.h>\n#define set_num_threads(x) mkl_set_num_threads(x)\n#define get_num_threads() mkl_get_num_threads()\n#endif\n\n\nint main(int argc, char **argv) {\n\n    char *filename = NULL;\n    int option = 0, omp_threads = 1;\n    while ((option = getopt(argc, argv, \"f:t:\")) != -1) {\n        switch (option) {\n            case 'f':\n                filename = optarg;\n                break;\n            case 't':\n                omp_threads = atoi(optarg);\n                break;\n            default:\n                printf(\"Usage: mpi_cg -f string -t num_threads \\n\");\n                return 0;\n        }\n    }\n    if (filename == NULL) {\n        printf(\"Usage: mpi_cg -f string -t num_threads \\n\");\n        return 0;\n    }\n\n    set_num_threads(omp_threads);\n    omp_set_num_threads(omp_threads);\n\n    int numTasks, rank;\n    MPI_Init(&argc, &argv);\n    MPI_Comm_size(MPI_COMM_WORLD, &numTasks);\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n    int qProcs = (int) sqrt(numTasks);\n    if (qProcs - sqrt(numTasks) != 0) {\n        if (rank == 0)\n            printf(\"np must be a square number\\n\");\n        MPI_Finalize();\n        return 0;\n    }\n\n    int n, dims[2] = {qProcs, qProcs}, periods[2] = {0, 0}, reorder = 0, coords[2], rc;\n    MPI_Comm cartComm;\n    MPI_Cart_create(MPI_COMM_WORLD, 2, dims, periods, reorder, &cartComm);\n    MPI_Comm_rank(cartComm, &rank);\n    MPI_Cart_coords(cartComm, rank, 2, coords);\n\n    MPI_File matFile;\n    rc = MPI_File_open(cartComm, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &matFile);\n    if (rc && (rank == 0)) {\n        printf(\"Unable to open file %s\\n\", filename);\n        fflush(stdout);\n    }\n\n    MPI_Status status;\n    MPI_File_read(matFile, &n, 1, MPI_INT, &status);\n    int blockSize = (n + qProcs - 1) / qProcs;  /* number of rows in _block_ */\n    int lastBlock = n - (qProcs - 1) * blockSize;\n\n    double *LocalA = (double *) malloc(blockSize * blockSize * sizeof(double));\n\n    MPI_Datatype readFileType;\n    MPI_Type_vector(blockSize, blockSize, n, MPI_DOUBLE, &readFileType);\n    MPI_Type_commit(&readFileType);\n    MPI_Offset offset = (MPI_Offset) (1 * sizeof(int) +\n                                      sizeof(double) * (blockSize * coords[1] + blockSize * n * coords[0]));\n    MPI_File_set_view(matFile, offset, MPI_DOUBLE, readFileType,\n                      \"native\", MPI_INFO_NULL);\n\n    MPI_File_read_at(matFile, 0, LocalA, blockSize * blockSize, MPI_DOUBLE, &status);\n    MPI_Type_free(&readFileType);\n    if (coords[0] == qProcs - 1) {\n        memset(LocalA + lastBlock * blockSize, 0, (blockSize - lastBlock) * blockSize * sizeof(double));\n    }\n    if (coords[1] == qProcs - 1) {\n        int kk = 0;\n        for (kk = 0; kk < blockSize; ++kk) {\n            memset(LocalA + kk * blockSize + lastBlock, 0, (blockSize - lastBlock) * sizeof(double));\n        }\n    }\n\n    double *LocalB = (double *) malloc(blockSize * sizeof(double));\n    memset(LocalB, 0, blockSize * sizeof(double));\n    offset = (MPI_Offset) (1 * sizeof(int) + sizeof(double) * n * n);\n    MPI_File_set_view(matFile, offset, MPI_DOUBLE, MPI_DOUBLE,\n                      \"native\", MPI_INFO_NULL);\n    offset = coords[1] * blockSize;\n    MPI_File_read_at_all(matFile, offset, LocalB, coords[1] == qProcs - 1 ? lastBlock : blockSize, MPI_DOUBLE, &status);\n\n    MPI_File_close(&matFile);\n    double mpi_start = MPI_Wtime();\n    MPI_Comm rowComm, colComm;\n    MPI_Comm_split(MPI_COMM_WORLD, coords[0], rank, &rowComm);\n    MPI_Comm_split(MPI_COMM_WORLD, coords[1], rank, &colComm);\n\n    double tolerance = 1e-8;\n    double alpha, beta, rho_new = 0.0, rho_old = 0.0;\n    int iteration = 0;\n    int world_root = numTasks - 1;\n    double *loc_Vr = (double *) malloc(blockSize * sizeof(double));\n    double *loc_Vp = (double *) malloc(blockSize * sizeof(double));\n    double *loc_Vw = (double *) malloc(blockSize * sizeof(double));\n    double *loc_Vx = (double *) malloc(blockSize * sizeof(double));\n\n    int row_rank, col_rank;\n    MPI_Comm_rank(colComm, &col_rank);\n    MPI_Comm_rank(rowComm, &row_rank);\n\n    //localr <- localB\n    memset(loc_Vx, 0, blockSize * sizeof(double));\n    cblas_dcopy(blockSize, LocalB, 1, loc_Vr, 1);\n    double b_norm2 = 0;\n    if (col_rank == qProcs - 1) {\n        double loc_b_dot = cblas_ddot((row_rank == qProcs - 1 ? lastBlock : blockSize), loc_Vr, 1, loc_Vr, 1);\n        MPI_Reduce(&loc_b_dot, &rho_new, 1, MPI_DOUBLE, MPI_SUM, qProcs - 1, rowComm);\n        b_norm2 = sqrt(rho_new);\n    }\n\n    int loopBreak = 0;\n    while (true) {\n        if (rank == world_root) {\n            loopBreak = (sqrt(rho_new) / b_norm2 < tolerance) ? 1 : 0;\n        }\n        MPI_Bcast(&loopBreak, 1, MPI_INT, world_root, MPI_COMM_WORLD);\n        if (loopBreak > 0)\n            break;\n\n        iteration++;\n        if (iteration == 1) {\n            cblas_dcopy(blockSize, loc_Vr, 1, loc_Vp, 1);\n        } else {\n            if (rank == world_root) {\n                beta = rho_new / rho_old;\n            }\n            MPI_Bcast(&beta, 1, MPI_DOUBLE, world_root, MPI_COMM_WORLD);\n            cblas_dscal((row_rank == qProcs - 1 ? lastBlock : blockSize), beta, loc_Vp, 1);\n            cblas_daxpy((row_rank == qProcs - 1 ? lastBlock : blockSize), 1.0, loc_Vr, 1, loc_Vp, 1);\n        }\n\n        cblas_dgemv(CblasRowMajor, CblasNoTrans, (col_rank == qProcs - 1 ? lastBlock : blockSize),\n                    (row_rank == qProcs - 1 ? lastBlock : blockSize),\n                    1.0, LocalA, blockSize, loc_Vp, 1, 0.0, loc_Vw, 1);\n\n        if (col_rank == row_rank) {\n            MPI_Reduce(MPI_IN_PLACE, loc_Vw, blockSize, MPI_DOUBLE, MPI_SUM, col_rank, rowComm);\n        } else {\n            MPI_Reduce(loc_Vw, loc_Vw, blockSize, MPI_DOUBLE, MPI_SUM, col_rank, rowComm);\n        }\n\n        MPI_Bcast(loc_Vw, (row_rank == qProcs - 1 ? lastBlock : blockSize), MPI_DOUBLE, row_rank, colComm);\n\n        if (col_rank == qProcs - 1) {\n            double loc_pw_dot = cblas_ddot((row_rank == qProcs - 1 ? lastBlock : blockSize), loc_Vp, 1, loc_Vw,\n                                           1), glo_pw_dot;\n            MPI_Reduce(&loc_pw_dot, &glo_pw_dot, 1, MPI_DOUBLE, MPI_SUM, qProcs - 1, rowComm);\n            if (rank == world_root) {\n                alpha = rho_new / glo_pw_dot;\n            }\n        }\n        MPI_Bcast(&alpha, 1, MPI_DOUBLE, world_root, MPI_COMM_WORLD);\n\n        cblas_daxpy((row_rank == qProcs - 1 ? lastBlock : blockSize), -alpha, loc_Vw, 1, loc_Vr, 1);\n\n        if (coords[0] == qProcs - 1) {\n            rho_old = rho_new;\n            cblas_daxpy((row_rank == qProcs - 1 ? lastBlock : blockSize), alpha, loc_Vp, 1, loc_Vx, 1);\n            double loc_r_dot = cblas_ddot(blockSize, loc_Vr, 1, loc_Vr, 1);\n\n            MPI_Reduce(&loc_r_dot, &rho_new, 1, MPI_DOUBLE, MPI_SUM, qProcs - 1, rowComm);\n        }\n    }\n\n    if (rank == world_root) {\n        printf(\"mpi_cg_it: %d\\t\", iteration);\n        printf(\"mpi_cg_time: %f\\n\", MPI_Wtime() - mpi_start);\n\n    }\n    MPI_Comm_free(&cartComm);\n    MPI_Comm_free(&colComm);\n    MPI_Comm_free(&rowComm);\n\n    if (col_rank == qProcs - 1) {\n        for (rc = 0; rc < (row_rank == qProcs - 1 ? lastBlock : blockSize); ++rc) {\n            if (fabs(loc_Vx[rc] - 1) > 1e-3) {\n                printf(\"MPI_CG_ERR %f \\n\", loc_Vx[rc]);\n                break;\n            }\n        }\n    }\n    MPI_Finalize();\n}\n", "meta": {"hexsha": "33e50246d91f6dd81a7ebcb05ea7e30040f051fc", "size": 7610, "ext": "c", "lang": "C", "max_stars_repo_path": "mpi/mpi_cg.c", "max_stars_repo_name": "baishuai/MEXP", "max_stars_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mpi/mpi_cg.c", "max_issues_repo_name": "baishuai/MEXP", "max_issues_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mpi/mpi_cg.c", "max_forks_repo_name": "baishuai/MEXP", "max_forks_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599", "max_forks_repo_licenses": ["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.0663507109, "max_line_length": 120, "alphanum_fraction": 0.5872536137, "num_tokens": 2215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3897991791398161}}
{"text": "/* multifit/test.c\n * \n * Copyright (C) 2007 Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* These tests are based on the NIST Statistical Reference Datasets\n   See http://www.nist.gov/itl/div898/strd/index.html for more\n   information. */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_test.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_multifit_nlin.h>\n#include <gsl/gsl_blas.h>\n\n#include <gsl/gsl_ieee_utils.h>\n\n#include \"test_longley.c\"\n#include \"test_filip.c\"\n#include \"test_pontius.c\"\n#include \"test_brown.c\"\n#include \"test_enso.c\"\n#include \"test_kirby2.c\"\n#include \"test_hahn1.c\"\n#include \"test_nelson.c\"\n#include \"test_fn.c\"\n#include \"test_estimator.c\"\n\nvoid\ntest_lmder (gsl_multifit_function_fdf * f, double x0[], \n            double * X, double F[], double * cov);\n\nvoid\ntest_fdf (const char * name, gsl_multifit_function_fdf * f, \n          double x0[], double x[], double sumsq,\n          double sigma[]);\n\nint\nmain (void)\n{\n  gsl_ieee_env_setup();\n\n  test_longley();\n  test_filip();\n  test_pontius();\n  test_estimator();\n\n  {\n    gsl_multifit_function_fdf f = make_fdf (&brown_f, &brown_df, &brown_fdf,\n                                            brown_N, brown_P, 0);\n    \n    test_lmder(&f, brown_x0, &brown_X[0][0], brown_F, &brown_cov[0][0]);\n  }\n\n  {\n    gsl_multifit_function_fdf f = make_fdf (&enso_f, &enso_df, &enso_fdf,\n                                            enso_N, enso_P, 0);\n\n    test_fdf(\"nist-ENSO\", &f, enso_x0, enso_x, enso_sumsq, enso_sigma);\n  }\n\n  {\n    gsl_multifit_function_fdf f = make_fdf (&kirby2_f, &kirby2_df, &kirby2_fdf,\n                                            kirby2_N, kirby2_P, 0);\n\n    test_fdf(\"nist-kirby2\", &f, kirby2_x0, kirby2_x, kirby2_sumsq, kirby2_sigma);\n  }\n\n  {\n    gsl_multifit_function_fdf f = make_fdf (&hahn1_f, &hahn1_df, &hahn1_fdf,\n                                            hahn1_N, hahn1_P, 0);\n\n    test_fdf(\"nist-hahn1\", &f, hahn1_x0, hahn1_x, hahn1_sumsq, hahn1_sigma);\n  }\n\n#ifdef JUNK\n  {\n    gsl_multifit_function_fdf f = make_fdf (&nelson_f, &nelson_df, &nelson_fdf,\n                                            nelson_N, nelson_P, 0);\n\n    test_fdf(\"nist-nelson\", &f, nelson_x0, nelson_x, nelson_sumsq, nelson_sigma);\n  }\n#endif\n\n  /* now summarize the results */\n\n  exit (gsl_test_summary ());\n}\n\n\nvoid\ntest_lmder (gsl_multifit_function_fdf * f, double x0[], \n            double * X, double F[], double * cov)\n{\n  const gsl_multifit_fdfsolver_type *T;\n  gsl_multifit_fdfsolver *s;\n\n  const size_t n = f->n;\n  const size_t p = f->p;\n\n  int status;\n  size_t iter = 0, i;\n  \n  gsl_vector_view x = gsl_vector_view_array (x0, p);\n\n  T = gsl_multifit_fdfsolver_lmsder;\n  s = gsl_multifit_fdfsolver_alloc (T, n, p);\n  gsl_multifit_fdfsolver_set (s, f, &x.vector);\n\n  do\n    {\n      status = gsl_multifit_fdfsolver_iterate (s);\n\n      for (i = 0 ; i < p; i++)\n        {\n          gsl_test_rel (gsl_vector_get (s->x, i), X[p*iter+i], 1e-5, \n                        \"lmsder, iter=%u, x%u\", iter, i);\n        }\n\n      gsl_test_rel (gsl_blas_dnrm2 (s->f), F[iter], 1e-5, \n                    \"lmsder, iter=%u, f\", iter);\n\n      iter++;\n    }\n  while (iter < 20);\n  \n  {\n    size_t i, j;\n    gsl_matrix * covar = gsl_matrix_alloc (4, 4);\n    gsl_multifit_covar (s->J, 0.0, covar);\n\n    for (i = 0; i < 4; i++) \n      {\n        for (j = 0; j < 4; j++)\n          {\n            gsl_test_rel (gsl_matrix_get(covar,i,j), cov[i*p + j], 1e-7, \n                          \"gsl_multifit_covar cov(%d,%d)\", i, j) ;\n          }\n      }\n\n    gsl_matrix_free (covar);\n  }\n\n  gsl_multifit_fdfsolver_free (s);\n\n}\n\nvoid\ntest_fdf (const char * name, gsl_multifit_function_fdf * f, \n          double x0[], double x_final[], \n          double f_sumsq, double sigma[])\n{\n  const gsl_multifit_fdfsolver_type *T;\n  gsl_multifit_fdfsolver *s;\n  \n  const size_t n = f->n;\n  const size_t p = f->p;\n\n  int status;\n  size_t iter = 0;\n\n  gsl_vector_view x = gsl_vector_view_array (x0, p);\n\n  T = gsl_multifit_fdfsolver_lmsder;\n  s = gsl_multifit_fdfsolver_alloc (T, n, p);\n  gsl_multifit_fdfsolver_set (s, f, &x.vector);\n\n  do\n    {\n      status = gsl_multifit_fdfsolver_iterate (s);\n\n#ifdef DEBUG\n       printf(\"iter = %d  status = %d  |f| = %.18e x = \\n\", \n         iter, status, gsl_blas_dnrm2 (s->f));\n         \n         gsl_vector_fprintf(stdout, s->x, \"%.8e\");\n#endif       \n      status = gsl_multifit_test_delta (s->dx, s->x, 0.0, 1e-7);\n\n      iter++;\n    }\n  while (status == GSL_CONTINUE && iter < 1000);\n  \n  {\n    size_t i;\n    gsl_matrix * covar = gsl_matrix_alloc (p, p);\n    gsl_multifit_covar (s->J, 0.0, covar);\n\n    for (i = 0 ; i < p; i++)\n      {\n        gsl_test_rel (gsl_vector_get (s->x, i), x_final[i], 1e-5, \n                      \"%s, lmsder, x%u\", name, i);\n      }\n\n\n    {\n      double s2 = pow(gsl_blas_dnrm2 (s->f), 2.0);\n\n      gsl_test_rel (s2, f_sumsq, 1e-5, \"%s, lmsder, |f|^2\", name);\n\n      for (i = 0; i < p; i++) \n        {\n          double ei = sqrt(s2/(n-p))*sqrt(gsl_matrix_get(covar,i,i));\n          gsl_test_rel (ei, sigma[i], 1e-4, \n                        \"%s, sigma(%d)\", name, i) ;\n        }\n    }\n\n    gsl_matrix_free (covar);\n  }\n\n  /* Check that there is no hidden state, restarting should \n     produce identical results. */\n\n  {\n    int status0, status1;\n    size_t i;\n    gsl_multifit_fdfsolver *t = gsl_multifit_fdfsolver_alloc (T, n, p);\n    gsl_multifit_fdfsolver_set (t, f, &x.vector);\n\n    /* do a few extra iterations to stir things up */\n\n    gsl_multifit_fdfsolver_set (s, f, &x.vector);\n\n    for (i = 0; i < 3; i++) \n      {\n        gsl_multifit_fdfsolver_iterate (s);\n      }\n\n    gsl_multifit_fdfsolver_set (s, f, &x.vector);\n\n    do\n      {\n        status0 = gsl_multifit_fdfsolver_iterate (s);\n        status1 = gsl_multifit_fdfsolver_iterate (t);\n\n        gsl_test_int(status0, status1, \"%s, lmsder status after set iter=%u\", name, iter);\n        \n        for (i = 0; i < p; i++) {\n          double sxi = gsl_vector_get(s->x,i);\n          double txi = gsl_vector_get(t->x,i);\n#ifdef DEBUG\n          printf(\"%d %g %g\\n\", i, sxi, txi);\n#endif\n          gsl_test_rel(sxi, txi, 1e-15, \"%s, lmsder after set, %u/%u\", name, iter, i);\n        }\n        \n#ifdef DEBUG\n        printf(\"iter = %d  status = %d  |f| = %.18e x = \\n\", \n               iter, status, gsl_blas_dnrm2 (s->f));\n        \n        gsl_vector_fprintf(stdout, s->x, \"%.8e\");\n#endif       \n        status0 = gsl_multifit_test_delta (s->dx, s->x, 0.0, 1e-7);\n        status1 = gsl_multifit_test_delta (t->dx, s->x, 0.0, 1e-7);\n        \n        gsl_test_int(status0, status1, \"%s, lmsder test delta status after set iter=%u\", name, iter);\n\n        iter++;\n      }\n    while (status1 == GSL_CONTINUE && iter < 1000);\n\n    gsl_multifit_fdfsolver_free (t);\n  }\n\n  gsl_multifit_fdfsolver_free (s);\n}\n", "meta": {"hexsha": "309efcf5835be820cc66b8cf110840180493117a", "size": 7502, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/multifit/test.c", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/test.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/test.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 26.4154929577, "max_line_length": 101, "alphanum_fraction": 0.5910423887, "num_tokens": 2419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.38973682783652397}}
{"text": "/* poly.c - Polynomial (de)compression routines\n *\n * Copyright (c) 2015 Maurizio Tomasi\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, copy,\n * modify, merge, publish, distribute, sublicense, and/or sell copies\n * 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\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 OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * 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\n * SOFTWARE.\n */\n\n#include \"libpolycomp.h\"\n#include <assert.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <gsl/gsl_block_double.h>\n#include <gsl/gsl_vector_double.h>\n#include <gsl/gsl_matrix_double.h>\n#include <gsl/gsl_multifit.h>\n\n#include <fftw3.h>\n\n#ifdef WITH_OPENMP\n\n#include <omp.h>\n\n#else\n\nstatic int omp_get_thread_num(void) { return 0; }\nstatic int omp_get_max_threads(void) { return 1; }\n\n#endif\n\n/**********************************************************************/\n\n/** \\defgroup poly Polynomial compression functions\n *\n * Polynomial compression relies on a simple idea, that is to divide\n * the input data stream into subsets of consecutive samples (called\n * \"chunks\"), and to approximate each chunk by means of a polynomial.\n * Such compression is inherently lossy, as the residuals of the\n * fitting procedure are usually discarded. If the polynomial used for\n * the fitting produces residuals that are too large, usually the\n * samples in the chunk are saved in uncompressed form.\n *\n * This idea has been widely applied in the literature. Libpolycomp\n * implements an improvement over it, because if the fit residuals are\n * too large, the library saves a chopped sequence of the Chebyshev\n * transform of the residuals. This allows to achieve better\n * compression ratios in those cases where polynomial fitting is not\n * always enough to keep compression errors below the desired\n * threshold. This kind of compression works quite well for smooth\n * data series, where changes between consecutive samples are well\n * described by slowly varying continuous functions. It is not\n * suitable if the signal contains noise, unless this noise is\n * significantly smaller than the signal and than the error threshold.\n *\n * Libpolycomp allows to avoid the usage of Chebyshev transforms. In\n * this case, if no polynomial of the desired degree are able to fit\n * the data with the given error threshold, the data for that chunk is\n * saved uncompressed.\n *\n * The typical workflow for applying polynomial compression is the\n * following:\n *\n * 1. Allocate a new \\ref pcomp_polycomp_t object via a call to \\ref\n *    pcomp_init_polycomp. Such object contains the parameters to be\n *    used for the compression, e.g., the size of each chunk, the\n *    degree of the fitting polynomial, whether to apply or not the\n *    Chebyshev transform to the residuals, etc.\n *\n * 2. Split the data into chunks and compress each of them using the\n *    function \\ref pcomp_compress_polycomp.\n *\n * 3. Convert the list of chunks into a byte sequence using \\ref\n *    pcomp_encode_chunks, typically with the purpose of saving it\n *    into a file or sending it through a pipe/socket/etc.\n *\n * The decompression workflow is specular:\n *\n * 1. Process the byte sequence containing the compressed data using\n *    \\ref pcomp_decode_chunks. This will produce a list of chunks\n *    that are still compressed.\n *\n * 2. Decompress the chunks using the function \\ref\n *    pcomp_decompress_polycomp.\n *\n * The compression functions described in this page use the \\ref\n * pcomp_polycomp_t structure to determine which parameters to use for\n * the compression. The functions that allow to allocate/free/manage\n * this structure are the following:\n *\n * - \\ref pcomp_init_polycomp and \\ref pcomp_free_polycomp\n * - \\ref pcomp_polycomp_samples_per_chunk\n * - \\ref pcomp_polycomp_num_of_poly_coeffs\n * - \\ref pcomp_polycomp_max_error\n * - \\ref pcomp_polycomp_algorithm\n * - \\ref pcomp_polycomp_period and \\ref pcomp_polycomp_set_period\n *\n * It is possible to use a set of more low-level functions to use\n * polynomial compression. Refer to \\ref poly_lowlevel for further\n * information.\n */\n\n/** \\defgroup poly_lowlevel Polynomial compression (low-level functions)\n */\n\n/**********************************************************************/\n\nstatic double integer_power(int x, int y)\n{\n    double dbl_x = (double)x;\n\n    if (y < 0)\n        abort();\n\n    if (y == 0)\n        return 1.0;\n    else if (y == 1)\n        return dbl_x;\n    else {\n        double result = dbl_x * dbl_x;\n        int cur_power = 2;\n        while (2 * cur_power < y) {\n            result *= result;\n            cur_power *= 2;\n        }\n\n        if (y > cur_power)\n            result *= integer_power(x, y - cur_power);\n\n        return result;\n    }\n}\n\n/***********************************************************************\n * Types and functions used for polynomial least-square fitting\n */\n\nstruct __pcomp_poly_fit_data_t {\n    size_t num_of_samples;\n    size_t num_of_coeffs;\n    gsl_multifit_linear_workspace* workspace;\n    gsl_matrix* matrix;\n    gsl_vector* y;\n    gsl_vector* c;\n    gsl_matrix* cov_matrix;\n};\n\n/** \\ingroup polyfit\n *\n * \\brief Allocate a new instance of the \\ref pcomp_poly_fit_data_t\n * structure on the heap\n *\n * \\param[in] num_of_samples Number of floating-point numbers that\n * must fit the polynomial\n *\n * \\param[in] num_of_coeffs Number of coefficients of the\n * least-squares fitting polynomial \\f$p(x)\\f$. This is equal to\n * \\f$\\deg p(x) + 1\\f$, where \\f$\\deg p(x)\\f$ is the degree of the\n * polynomial. Thus, for a parabolic polynomial of the form \\f$p(x) =\n * a x^2 + b x + c\\f$, \\a num_of_coeffs = 3.\n *\n * \\returns A newly created instance of \\ref pcomp_poly_fit_data_t\n * structure. This must be freed using \\ref pcomp_free_poly_fit, once\n * it is no longer used.\n */\npcomp_poly_fit_data_t* pcomp_init_poly_fit(size_t num_of_samples,\n                                           size_t num_of_coeffs)\n{\n    size_t i, j;\n\n    pcomp_poly_fit_data_t* poly_fit\n        = malloc(sizeof(pcomp_poly_fit_data_t));\n    if (poly_fit == NULL)\n        abort();\n\n    poly_fit->num_of_samples = num_of_samples;\n    poly_fit->num_of_coeffs = num_of_coeffs;\n    poly_fit->workspace\n        = gsl_multifit_linear_alloc(num_of_samples, num_of_coeffs);\n    poly_fit->matrix = gsl_matrix_alloc(num_of_samples, num_of_coeffs);\n    poly_fit->y = gsl_vector_alloc(num_of_samples);\n    poly_fit->c = gsl_vector_alloc(num_of_coeffs);\n    poly_fit->cov_matrix\n        = gsl_matrix_alloc(num_of_coeffs, num_of_coeffs);\n\n    for (i = 0; i < num_of_samples; ++i) {\n        for (j = 0; j < num_of_coeffs; ++j) {\n            gsl_matrix_set(poly_fit->matrix, i, j,\n                           integer_power(i + 1, j));\n        }\n    }\n\n    return poly_fit;\n}\n\n/** \\ingroup polyfit\n *\n * \\brief Free an instance of the \\ref pcomp_poly_fit_data_t that has\n * been allocated via a call to \\ref pcomp_init_poly_fit.\n *\n * \\param[in] poly_fit Pointer to the structure to be freed\n */\nvoid pcomp_free_poly_fit(pcomp_poly_fit_data_t* poly_fit)\n{\n    if (poly_fit == NULL)\n        return;\n\n    gsl_matrix_free(poly_fit->matrix);\n    gsl_vector_free(poly_fit->y);\n    gsl_vector_free(poly_fit->c);\n    gsl_matrix_free(poly_fit->cov_matrix);\n    gsl_multifit_linear_free(poly_fit->workspace);\n\n    free(poly_fit);\n}\n\n/** \\ingroup polyfit\n *\n * \\brief Return the number of samples to be used in a polynomial fit\n *\n * \\param[in] poly_fit Pointer to the structure detailing the fit\n *\n * \\returns The number of samples that should be passed to a call to\n * \\ref pcomp_run_poly_fit.\n */\nsize_t\npcomp_poly_fit_num_of_samples(const pcomp_poly_fit_data_t* poly_fit)\n{\n    if (poly_fit == NULL)\n        abort();\n\n    return poly_fit->num_of_samples;\n}\n\n/** \\ingroup polyfit\n *\n * \\brief Return the number of coefficients of the least-squares\n * fitting polynomial\n *\n * \\param[in] poly_fit Pointer to the structure detailing the fit\n *\n * \\returns The number of coefficients for the fitting polynomial (one\n * plus the polynomial degree)\n */\nsize_t\npcomp_poly_fit_num_of_coeffs(const pcomp_poly_fit_data_t* poly_fit)\n{\n    if (poly_fit == NULL)\n        abort();\n\n    return poly_fit->num_of_coeffs;\n}\n\n/** \\ingroup polyfit\n *\n * \\brief Calculates a polynomial least-squares fit.\n *\n * Compute a least-squares fit between the numbers \\f$x_i\\f$ (with\n * \\f$i = 1 \\ldots N\\f$) and the polynomial \\f$p(x)\\f$ through the\n * points \\f$(i, x_i)_{i=1}^N\\f$. The coefficients of \\f$p(x)\\f$ are\n * saved in \\a coeffs, from the least to the greatest degree.\n *\n * Here is an example of the usage of this function:\n *\n * \\code{.c}\n * double points[] = { 1.0, 3.0, 5.0 };\n * double coeffs[2];\n * const size_t num_of_points = sizeof(points) / sizeof(points[0]);\n * const size_t num_of_coeffs = sizeof(coeffs) / sizeof(coeffs[0]);\n * pcomp_poly_fit_data_t* poly_fit;\n *\n * poly_fit = pcomp_init_poly_fit(num_of_points, num_of_coeffs);\n * pcomp_run_poly_fit(poly_fit, coeffs, points);\n * printf(\"The data are fitted by the polynomial y = %f + %f x\\n\",\n *        coeffs[0], coeffs[1]);\n * \\endcode\n *\n * \\param[in] poly_fit Pointer to a \\ref pcomp_poly_fit_data_t\n * structure, created using the \\ref pcomp_init_poly_fit function.\n *\n * \\param[out] coeffs Pointer to an array where the coefficients of\n * the polynomial will be stored on exit. The array must have room for\n * a number of elements greater or equal than the value returned by\n * \\ref pcomp_poly_fit_num_of_coeffs.\n *\n * \\param[in] points Array of numbers \\f$x_i\\f$ to use in the fit. The\n * number of elements considered in the fit is equal to the return\n * value of \\ref pcomp_poly_fit_num_of_samples.\n *\n * \\returns \\ref PCOMP_STAT_SUCCESS if the fit was computed\n * successfully, \\ref PCOMP_STAT_INVALID_FIT if the data are incorrect\n * (e.g., there are fewer samples than unknowns).\n */\nint pcomp_run_poly_fit(pcomp_poly_fit_data_t* poly_fit, double* coeffs,\n                       const double* points)\n{\n    size_t idx;\n    double chisq;\n\n    if (poly_fit == NULL || coeffs == NULL || points == NULL)\n        abort();\n\n    for (idx = 0; idx < poly_fit->num_of_samples; ++idx) {\n        gsl_vector_set(poly_fit->y, idx, points[idx]);\n    }\n\n    if (gsl_multifit_linear(poly_fit->matrix, poly_fit->y, poly_fit->c,\n                            poly_fit->cov_matrix, &chisq,\n                            poly_fit->workspace) != 0) {\n        return PCOMP_STAT_INVALID_FIT;\n    }\n\n    for (idx = 0; idx < poly_fit->num_of_coeffs; ++idx) {\n        coeffs[idx] = gsl_vector_get(poly_fit->c, idx);\n    }\n\n    return PCOMP_STAT_SUCCESS;\n}\n\n/***********************************************************************\n * Types and functions used for computing Chebyshev transforms\n */\n\nstruct __pcomp_chebyshev_t {\n    double* input;\n    double* output;\n    size_t num_of_samples;\n    fftw_plan fftw_plan_ptr;\n    pcomp_transform_direction_t dir;\n};\n\n/** \\ingroup cheby\n *\n * \\brief Allocate a new instance of the \\ref pcomp_chebyshev_t\n * structure on the heap\n *\n * Despite the fact that this function takes the parameter \\a dir, the\n * function which actually computes the Chebyshev transform (\\ref\n * pcomp_run_chebyshev) allow to specify the desired direction. The\n * purpose of having \\a dir encoded in \\ref pcomp_chebyshev_t is that\n * sometimes it is useful to keep it memorized in the structure\n * itself.\n *\n * \\param[in] num_of_samples Number of floating-point numbers that\n * will be transformed\n *\n * \\param[in] dir Direction of the transform (either forward or\n * backward). This is used to determine the normalization constant of\n * the transform:\n * - If computing a forward transform, the normalization is \\f$1 / (N\n *   - 1)\\f$, with \\f$N\\f$ the number of samples.\n * - If computing a backward transform, the normalization is 1.\n *\n * \\returns A newly created instance of \\ref pcomp_poly_fit_data_t\n * structure. This must be freed using \\ref pcomp_free_poly_fit, once\n * it is no longer used.\n */\npcomp_chebyshev_t* pcomp_init_chebyshev(size_t num_of_samples,\n                                        pcomp_transform_direction_t dir)\n{\n    pcomp_chebyshev_t* chebyshev = malloc(sizeof(pcomp_chebyshev_t));\n    if (chebyshev == NULL)\n        abort();\n\n    chebyshev->input = fftw_alloc_real(num_of_samples);\n    chebyshev->output = fftw_alloc_real(num_of_samples);\n    chebyshev->num_of_samples = num_of_samples;\n    chebyshev->fftw_plan_ptr = fftw_plan_r2r_1d(\n        num_of_samples, chebyshev->input, chebyshev->output,\n        FFTW_REDFT00, FFTW_ESTIMATE);\n    chebyshev->dir = dir;\n\n    return chebyshev;\n}\n\n/** \\ingroup cheby\n *\n * \\brief Free the memory allocated by a previous call to \\ref\n * pcomp_init_chebyshev.\n *\n * \\param[in] plan Pointer to the structure to be freed.\n */\nvoid pcomp_free_chebyshev(pcomp_chebyshev_t* plan)\n{\n    if (plan == NULL)\n        return;\n\n    if (plan->input != NULL)\n        fftw_free(plan->input);\n\n    if (plan->output != NULL)\n        fftw_free(plan->output);\n\n    if (plan->fftw_plan_ptr != NULL)\n        fftw_destroy_plan(plan->fftw_plan_ptr);\n\n    free(plan);\n}\n\n/** \\ingroup cheby\n *\n * \\brief Return the number of samples in a Chebyshev transform\n *\n * \\param[in] plan Pointer to the Chebyshev plan.\n *\n * \\returns The number of elements that are used in the Chebyshev\n * transform specified by \\a plan.\n */\nsize_t pcomp_chebyshev_num_of_samples(const pcomp_chebyshev_t* plan)\n{\n    if (plan == NULL)\n        abort();\n\n    return plan->num_of_samples;\n}\n\n/** \\ingroup cheby\n *\n * \\brief Return the direction of a Chebyshev transform\n *\n * \\param[in] plan Pointer to the Chebyshev plan.\n *\n * \\returns A \\ref pcomp_transform_direction_t value specifying the\n * normalization used for the Chebyshev transform specified by \\a\n * plan.\n */\npcomp_transform_direction_t\npcomp_chebyshev_direction(const pcomp_chebyshev_t* plan)\n{\n    if (plan == NULL)\n        abort();\n\n    return plan->dir;\n}\n\nstatic double chebyshev_normalization(pcomp_transform_direction_t dir,\n                                      size_t num_of_samples)\n{\n    if (dir == PCOMP_TD_DIRECT)\n        return 1.0 / (((double)num_of_samples) - 1.0);\n    else\n        return 0.5;\n}\n\n/** \\ingroup cheby\n *\n * \\brief Compute a forward/backward Chebyshev discrete transform\n *\n * \\code{.c}\n * #define NUM_OF_POINTS 3\n * double points[NUM_OF_POINTS] = { 0.0, 1.0, 3.0 };\n * double transform[NUM_OF_POINTS];\n * pcomp_chebyshev_t* chebyshev;\n * size_t idx;\n *\n * chebyshev = pcomp_init_chebyshev(NUM_OF_POINTS, PCOMP_TD_DIRECT);\n * pcomp_run_chebyshev(chebyshev, PCOMP_TD_DIRECT, transform, points);\n *\n * puts(\"Transform:\");\n * for (idx = 0; idx < NUM_OF_POINTS; ++idx) {\n *     printf(\"%f\\t\", transform[idx]);\n * }\n * puts(\"\");\n * \\endcode\n *\n * \\param[in] plan Pointer to a Chebyshev plan created by \\ref\n * pcomp_init_chebyshev\n *\n * \\param[in] dir Direction of the transform. This parameter overrides\n * the internal direction of \\a plan (returned by \\ref\n * pcomp_chebyshev_direction).\n *\n * \\param[out] output Pointer to an array of \\c double values that will\n * contain the Chebyshev transform of \\a input. It must have room for\n * a number of elements at least equal to the return value of \\ref\n * pcomp_num_of_samples.\n *\n * \\param[in] input Array of \\c double values to be transformed. The\n * function will use the first N elements, where N is the return value\n * of \\ref pcomp_num_of_samples.\n *\n * \\returns \\ref PCOMP_STAT_SUCCESS when successful.\n */\nint pcomp_run_chebyshev(pcomp_chebyshev_t* plan,\n                        pcomp_transform_direction_t dir, double* output,\n                        const double* input)\n{\n    double norm;\n    size_t idx;\n\n    if (plan == NULL)\n        abort();\n\n    if (input != NULL) {\n        for (idx = 0; idx < plan->num_of_samples; ++idx) {\n            plan->input[idx] = input[idx];\n        }\n    }\n\n    fftw_execute(plan->fftw_plan_ptr);\n    norm = chebyshev_normalization(dir, plan->num_of_samples);\n\n    for (idx = 0; idx < plan->num_of_samples; ++idx) {\n        plan->output[idx] *= norm;\n    }\n\n    if (output != NULL && output != plan->output) {\n        for (idx = 0; idx < plan->num_of_samples; ++idx) {\n            output[idx] = plan->output[idx];\n        }\n    }\n\n    return PCOMP_STAT_SUCCESS;\n}\n\n/** \\ingroup cheby\n *\n * \\brief Return the input data used in the last call to \\ref\n *pcomp_run_chebyshev\n *\n * If \\ref pcomp_run_chebyshev was never called, the array returned by\n * this function contains garbage.\n *\n * \\param[in] plan Pointer to a Chebyshev plan created by \\ref\n * pcomp_init_chebyshev\n *\n * \\return A pointer to the first element of the array of elements\n * used as input by the last call to \\ref pcomp_run_chebyshev.\n */\nconst double* pcomp_chebyshev_input(const pcomp_chebyshev_t* plan)\n{\n    if (plan == NULL)\n        abort();\n    return plan->input;\n}\n\n/** \\ingroup cheby\n *\n * \\brief Return the output (Chebyshev transform) of the last call to\n *\\ref pcomp_run_chebyshev\n *\n * If \\ref pcomp_run_chebyshev was never called, the array returned by\n * this function contains garbage.\n *\n * \\param[in] plan Pointer to a Chebyshev plan created by \\ref\n * pcomp_init_chebyshev\n *\n * \\return A pointer to the first element of the array of elements\n * containing the output of the last call to \\ref pcomp_run_chebyshev.\n */\nconst double* pcomp_chebyshev_output(const pcomp_chebyshev_t* plan)\n{\n    if (plan == NULL)\n        abort();\n    return plan->output;\n}\n\n/***********************************************************************\n * Types and functions used for applying the combined\n * fitting/Chebyshev transforms\n */\n\nstruct __pcomp_polycomp_t {\n    size_t samples_per_chunk;\n    pcomp_poly_fit_data_t* poly_fit;\n    pcomp_chebyshev_t* chebyshev;\n    pcomp_chebyshev_t* inv_chebyshev;\n    double max_allowable_error;\n    pcomp_polycomp_algorithm_t algorithm;\n    double period;\n};\n\n/** \\ingroup poly\n *\n * \\brief Allocate space for a \\ref pcomp_polycomp_t structure\n *\n * \\param[in] samples_per_chunk Number of samples in each chunk\n *\n * \\param[in] num_of_coeffs Number of polynomial coefficients to use\n *\n * \\param[in] max_allowable_error Upper bound for the compression\n * error (positive value)\n *\n * \\param[in] algorithm Kind of compression algorithm to use\n *\n * \\returns A pointer to the newly allocate \\ref pcomp_polycomp_t\n * structure. This must be freed using \\ref pcomp_free_polycomp, once\n * it is no longer used.\n */\npcomp_polycomp_t*\npcomp_init_polycomp(pcomp_chunk_size_t samples_per_chunk,\n                    pcomp_poly_size_t num_of_coeffs,\n                    double max_allowable_error,\n                    pcomp_polycomp_algorithm_t algorithm)\n{\n    pcomp_polycomp_t* params = malloc(sizeof(pcomp_polycomp_t));\n    if (params == NULL)\n        abort();\n\n    params->samples_per_chunk = samples_per_chunk;\n    params->poly_fit\n        = pcomp_init_poly_fit(samples_per_chunk, num_of_coeffs);\n    params->chebyshev\n        = pcomp_init_chebyshev(samples_per_chunk, PCOMP_TD_DIRECT);\n    params->inv_chebyshev\n        = pcomp_init_chebyshev(samples_per_chunk, PCOMP_TD_INVERSE);\n    params->max_allowable_error = max_allowable_error;\n    params->algorithm = algorithm;\n    params->period = 0.0;\n\n    return params;\n}\n\n/** \\ingroup poly\n *\n * \\brief Free the memory allocated by \\ref pcomp_init_polycomp for a\n * \\ref pcomp_polycomp_t structure.\n *\n * \\param[in] params Pointer to the structure to be freed\n */\nvoid pcomp_free_polycomp(pcomp_polycomp_t* params)\n{\n    if (params == NULL)\n        return;\n\n    pcomp_free_poly_fit(params->poly_fit);\n    pcomp_free_chebyshev(params->chebyshev);\n    pcomp_free_chebyshev(params->inv_chebyshev);\n\n    free(params);\n}\n\n/** \\ingroup poly\n *\n * \\brief Return the number of samples per chunk\n *\n * This function returns the size of each chunk but the last one in\n * the input data for a polynomial compression. Such chunks contain a\n * set of consecutive values in the input array passed to routines as\n * \\ref pcomp_compress_polycomp.\n *\n * \\param[in] params Pointer to a \\ref pcomp_polycomp_t structure\n * containing the compression parameters\n *\n * \\returns The number of samples in each chunk.\n */\npcomp_chunk_size_t\npcomp_polycomp_samples_per_chunk(const pcomp_polycomp_t* params)\n{\n    if (params == NULL)\n        abort();\n\n    return params->samples_per_chunk;\n}\n\n/** \\ingroup poly\n *\n * \\brief Return the number of coefficients for the fitting polynomial\n * used in the polynomial compression.\n *\n * The return value has the same meaning as the value returned by the\n * \\ref pcomp_poly_fit_num_of_coeffs.\n *\n * \\param[in] params Pointer to a \\ref pcomp_polycomp_t structure\n * containing the compression parameters\n *\n * \\returns The number of coefficients of the fitting polynomial.\n */\npcomp_poly_size_t\npcomp_polycomp_num_of_poly_coeffs(const pcomp_polycomp_t* params)\n{\n    if (params == NULL || params->poly_fit == NULL)\n        abort();\n\n    return params->poly_fit->num_of_coeffs;\n}\n\n/** \\ingroup poly\n *\n * \\brief Return the upper bound on the error of the polynomial\n *compression.\n *\n * \\param[in] params Pointer to a \\ref pcomp_polycomp_t structure\n * containing the compression parameters\n *\n * \\returns The maximum allowable error for the polynomial compression.\n */\ndouble pcomp_polycomp_max_error(const pcomp_polycomp_t* params)\n{\n    if (params == NULL)\n        abort();\n\n    return params->max_allowable_error;\n}\n\n/** \\ingroup poly\n *\n * \\brief Return the kind of algorithm used for a polynomial\n *compression.\n *\n * \\param[in] params Pointer to a \\ref pcomp_polycomp_t structure\n * containing the compression parameters\n *\n * \\returns The algorithm to be used by the compressor.\n */\npcomp_polycomp_algorithm_t\npcomp_polycomp_algorithm(const pcomp_polycomp_t* params)\n{\n    if (params == NULL)\n        abort();\n\n    return params->algorithm;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Return a pointer to a \\ref pcomp_chebyshev_t structure\n * representing the forward Chebyshev transform.\n *\n * \\param[in] params Pointer to a \\ref pcomp_polycomp_t structure\n * containing the compression parameters\n *\n * \\returns The algorithm to be used by the compressor.\n */\npcomp_chebyshev_t*\npcomp_polycomp_forward_cheby(const pcomp_polycomp_t* params)\n{\n    if (params == NULL)\n        abort();\n\n    return params->chebyshev;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Return a pointer to a \\ref pcomp_chebyshev_t structure\n * representing the forward Chebyshev transform.\n *\n * \\param[in] params Pointer to a \\ref pcomp_polycomp_t structure\n * containing the compression parameters\n *\n * \\returns The algorithm to be used by the compressor.\n */\npcomp_chebyshev_t*\npcomp_polycomp_backward_cheby(const pcomp_polycomp_t* params)\n{\n    if (params == NULL)\n        abort();\n\n    return params->inv_chebyshev;\n}\n\n/** \\ingroup poly\n *\n * \\brief Return the period of the input data, or a number\n * less than or equal to 0 if the data have no periodicity.\n *\n * See also \\ref pcomp_polycomp_set_period.\n *\n * \\param[in] params Pointer to a \\ref pcomp_polycomp_t structure\n * containing the compression parameters\n *\n * \\returns The periodicity. If zero or negative, no periodicity is\n * assumed in the data to be compressed.\n */\ndouble pcomp_polycomp_period(const pcomp_polycomp_t* params)\n{\n    if (params == NULL)\n        abort();\n\n    return params->period;\n}\n\n/** \\ingroup poly\n *\n * \\brief Set the periodicity of the data to be compressed\n *\n * If \\a period is a value greater than zero, this is assumed to be\n * the periodicity of the input data: the value \\a x is therefore\n * assumed equivalent to \\a x + \\a period and to \\a x - \\a period. It\n * is typically a multiple of Pi = 3.14159...\n *\n * The polynomial compressor can improve the compression ratio for\n * data if they have some form of periodicity.\n *\n * \\param[in] params Pointer to a \\ref pcomp_polycomp_t structure\n * containing the compression parameters\n *\n * \\param[in] period The periodicity of the data, or a zero/negative\n * value if no periodicity should be assumed by the compressor.\n */\nvoid pcomp_polycomp_set_period(pcomp_polycomp_t* params, double period)\n{\n    if (params == NULL)\n        abort();\n\n    params->period = period;\n}\n\n/***********************************************************************\n * Evaluate the value of a polynomial at a point using Horner's formula\n */\n\nstatic double eval_poly(double* coeffs, size_t num_of_coeffs, double x)\n{\n    if (coeffs == NULL)\n        abort();\n\n    if (num_of_coeffs >= 1) {\n        int idx = num_of_coeffs - 1;\n        double result = coeffs[idx];\n\n        if (num_of_coeffs == 1)\n            return result;\n\n        for (idx = num_of_coeffs - 2; idx >= 0; --idx)\n            result = result * x + coeffs[idx];\n\n        return result;\n    }\n    else\n        return 0.0;\n}\n\n/***********************************************************************/\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Remove sudden jumps from \\a input\n *\n * Assuming that the data in the array \\a input have a periodicity\n * equal to \\a period, the function copies them to \\a output while\n * applying a positive/negative offset equal to a multiple of \\a\n * period.\n *\n * It is ok for \\a input and \\a output to point to the same memory\n * location.\n *\n * \\param[out] output Pointer to the array that will contain the\n * result. It must have room for at least \\a num_of_samples values.\n *\n * \\param[in] input Array of \\a num_of_samples values to process.\n *\n * \\param[in] num_of_samples Number of samples to process in \\a input\n *\n * \\param[in] period Periodicity of the data. If less or equal to\n * zero, \\a input is copied verbatim to \\a output.\n */\n\nvoid pcomp_straighten(double* output, const double* input,\n                      size_t num_of_samples, double period)\n{\n    size_t idx;\n\n    if (input == NULL || output == NULL)\n        abort();\n\n    if (period > 0) {\n        double half_period = period * 0.5;\n        double offset = 0.0;\n\n        output[0] = input[0];\n\n        for (idx = 1; idx < num_of_samples; ++idx) {\n            double diff_with_previous = input[idx] - input[idx - 1];\n            if (diff_with_previous > half_period)\n                offset -= period;\n            else if (diff_with_previous < -half_period)\n                offset += period;\n\n            output[idx] = input[idx] + offset;\n        }\n    }\n    else {\n        for (idx = 0; idx < num_of_samples; ++idx)\n            output[idx] = input[idx];\n    }\n}\n\n/***********************************************************************\n * Chunk initialization/destruction\n */\n\n/* Information about a chunk of data compressed using the polynomial\n * compression */\nstruct __pcomp_polycomp_chunk_t {\n    /* Number of samples in this chunk */\n    size_t num_of_samples;\n\n    /* Is this chunk compressed using polynomial/Chebyshev\n     * coefficients? */\n    int is_compressed;\n    /* If the chunk is not compressed (is_compressed == 0), this\n     * points to a buffer which holds \"num_of_samples\" uncompressed\n     * samples */\n    double* uncompressed;\n\n    /* Polynomial coefficients, from the lowest-order to the\n     * highest-order */\n    size_t num_of_poly_coeffs;\n    double* poly_coeffs;\n\n    /* Chebyshev coefficients */\n    uint8_t* cheby_mask;\n    size_t num_of_cheby_coeffs; /* This is always less than\n                                 * num_of_samples, as the Chebyshev\n                                 * series is chopped. */\n    double* cheby_coeffs;\n};\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Allocate memory for a \\ref pcomp_polycomp_chunk_t object\n *\n * \\param[in] num_of_samples Number of samples that the chunk will be\n * capable to hold.\n *\n * \\return A pointer to the newly allocated object. Use \\ref\n * pcomp_free_chunk to free the memory once is no longer needed.\n */\npcomp_polycomp_chunk_t*\npcomp_init_chunk(pcomp_chunk_size_t num_of_samples)\n{\n    pcomp_polycomp_chunk_t* chunk\n        = malloc(sizeof(pcomp_polycomp_chunk_t));\n    if (chunk == NULL)\n        abort();\n\n    chunk->num_of_samples = num_of_samples;\n\n    chunk->is_compressed = 0;\n    chunk->uncompressed\n        = malloc(sizeof(double) * sizeof(chunk->num_of_samples));\n\n    chunk->num_of_poly_coeffs = 0;\n    chunk->poly_coeffs = NULL;\n\n    chunk->num_of_cheby_coeffs = 0;\n    chunk->cheby_coeffs = NULL;\n    chunk->cheby_mask = NULL;\n\n    return chunk;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Allocate memory for a \\ref pcomp_polycomp_chunk_t object and\n * fill it with data in uncompressed form.\n *\n * \\param[in] num_of_samples Number of samples that the chunk will be\n * capable to hold.\n *\n * \\param[in] samples The (uncompressed) samples to copy into the\n * chunk. After the call, \\a input is no longer needed and can be\n * freed without invalidating the pointer returned by the function.\n *\n * \\return A pointer to the newly allocated object. Use \\ref\n * pcomp_free_chunk to free the memory once is no longer needed.\n */\npcomp_polycomp_chunk_t*\npcomp_init_uncompressed_chunk(pcomp_chunk_size_t num_of_samples,\n                              const double* samples)\n{\n    pcomp_polycomp_chunk_t* chunk\n        = malloc(sizeof(pcomp_polycomp_chunk_t));\n    const size_t num_of_bytes = sizeof(double) * num_of_samples;\n    if (chunk == NULL)\n        abort();\n\n    chunk->num_of_samples = num_of_samples;\n\n    chunk->is_compressed = 0;\n    chunk->uncompressed = malloc(num_of_bytes);\n    if (chunk->uncompressed == NULL)\n        abort();\n    memcpy(chunk->uncompressed, samples, num_of_bytes);\n\n    chunk->num_of_poly_coeffs = 0;\n    chunk->poly_coeffs = NULL;\n\n    chunk->num_of_cheby_coeffs = 0;\n    chunk->cheby_coeffs = NULL;\n    chunk->cheby_mask = NULL;\n\n    return chunk;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Allocate memory for a \\ref pcomp_polycomp_chunk_t object and\n * fill it with data compressed using the polynomial compression\n * algorithm.\n *\n * \\param[in] num_of_samples Number of samples that the chunk will be\n * capable to hold.\n *\n * \\param[in] num_of_poly_coeffs Number of coefficients of the\n * interpolating polynomial.\n *\n * \\param[in] poly_coeffs Pointer to the coefficients of the\n * interpolating polynomial. Their number must be equal to the\n * parameter \\a num_of_poly_coeffs.\n *\n * \\param[in] num_of_cheby_coeffs Number of nonzero Chebyshev\n * coefficients associated with the polynomial fit. This number is\n * always less than \\a num_of_samples. Zero is allowed.\n *\n * \\param[in] cheby_mask Bitmask representing the position of the\n * nonzero coefficients in \\a cheby_coeffs within the full sequence.\n * (Use \\ref pcomp_mask_get_bit and \\ref pcomp_mask_set_bit to\n * read/write bits in the sequence.)\n *\n * \\param[in] cheby_coeffs Array of nonzero Chebyshev coefficients.\n * Their number must be equal to \\a num_of_cheby_coeffs.\n *\n * \\return A pointer to the newly allocated object. Use \\ref\n * pcomp_free_chunk to free the memory once is no longer needed.\n */\npcomp_polycomp_chunk_t* pcomp_init_compressed_chunk(\n    pcomp_chunk_size_t num_of_samples,\n    pcomp_poly_size_t num_of_poly_coeffs, const double* poly_coeffs,\n    pcomp_chunk_size_t num_of_cheby_coeffs, const uint8_t* cheby_mask,\n    const double* cheby_coeffs)\n{\n    size_t size;\n    pcomp_polycomp_chunk_t* chunk;\n\n    if (num_of_samples == 0 || poly_coeffs == NULL)\n        abort();\n\n    chunk = malloc(sizeof(pcomp_polycomp_chunk_t));\n    if (chunk == NULL)\n        abort();\n\n    chunk->num_of_samples = num_of_samples;\n    chunk->is_compressed = 1;\n    chunk->uncompressed = NULL;\n\n    chunk->num_of_poly_coeffs = num_of_poly_coeffs;\n    size = num_of_poly_coeffs * sizeof(double);\n    chunk->poly_coeffs = malloc(size);\n    if (chunk->poly_coeffs == NULL)\n        abort();\n    memcpy(chunk->poly_coeffs, poly_coeffs, size);\n\n    chunk->num_of_cheby_coeffs = num_of_cheby_coeffs;\n    if (num_of_cheby_coeffs > 0) {\n        size = num_of_cheby_coeffs * sizeof(double);\n        chunk->cheby_coeffs = malloc(size);\n        if (chunk->cheby_coeffs == NULL)\n            abort();\n        memcpy(chunk->cheby_coeffs, cheby_coeffs, size);\n\n        size = pcomp_chunk_cheby_mask_size(num_of_samples)\n               * sizeof(uint8_t);\n        chunk->cheby_mask = malloc(size);\n        if (chunk->cheby_mask == NULL)\n            abort();\n        memcpy(chunk->cheby_mask, cheby_mask, size);\n    }\n    else {\n        chunk->cheby_mask = NULL;\n        chunk->cheby_coeffs = NULL;\n    }\n\n    return chunk;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Free memory associated with a \\ref pcomp_poly_chunk_t\n *\n * This function releases the memory allocated by one of the following\n * functions:\n * - \\ref pcomp_init_chunk\n * - \\ref pcomp_init_uncompressed_chunk\n * - \\ref pcomp_init_compressed_chunk\n *\n * \\param[in] chunk Pointer to the object to be freed.\n */\nvoid pcomp_free_chunk(pcomp_polycomp_chunk_t* chunk)\n{\n    if (chunk == NULL)\n        return;\n\n    if (chunk->uncompressed != NULL)\n        free(chunk->uncompressed);\n\n    if (chunk->poly_coeffs != NULL)\n        free(chunk->poly_coeffs);\n\n    if (chunk->cheby_coeffs != NULL)\n        free(chunk->cheby_coeffs);\n\n    if (chunk->cheby_mask != NULL)\n        free(chunk->cheby_mask);\n\n    free(chunk);\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Return the number of samples in a chunk\n *\n * \\param[in] chunk Pointer to the chunk data\n *\n * \\returns The number of samples\n */\npcomp_chunk_size_t\npcomp_chunk_num_of_samples(const pcomp_polycomp_chunk_t* chunk)\n{\n    if (chunk == NULL)\n        abort();\n\n    return chunk->num_of_samples;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Return the number of bytes necessary to encode a chunk\n *\n * Refer to \\ref pcomp_encode_chunks and \\ref pcomp_decode_chunks for\n * further details.\n *\n * \\param[in] chunk Pointer to the chunk data\n *\n * \\returns The number of bytes\n */\nsize_t pcomp_chunk_num_of_bytes(const pcomp_polycomp_chunk_t* chunk)\n{\n    if (chunk == NULL)\n        abort();\n\n    if (chunk->is_compressed) {\n        /* The size is calculated as follows:\n         * - the \"compressed\" flag (int8_t)\n         * - the number of samples (pcomp_chunk_size_t)\n         * - the number N of polynomial coefficients (pcomp_poly_size_t)\n         * - the size of the Chebyshev mask\n         * - the number M of Chebyshev coefficients (pcomp_chunk_size_t)\n         * - Nx8 bytes for the polynomial (only if M > 0)\n         * - Mx8 bytes for the Chebyshev coefficients (only if M > 0)\n         */\n        size_t result = sizeof(int8_t) + sizeof(pcomp_chunk_size_t)\n                        + sizeof(pcomp_poly_size_t)\n                        + (chunk->num_of_poly_coeffs) * sizeof(double)\n                        + sizeof(pcomp_chunk_size_t);\n\n        if (chunk->num_of_cheby_coeffs > 0) {\n            result += pcomp_chunk_cheby_mask_size(chunk->num_of_samples)\n                      + chunk->num_of_cheby_coeffs * sizeof(double);\n        }\n\n        return result;\n    }\n    else {\n        /* The size is calculated as follows:\n         * - 1 byte for the \"uncompressed\" flag\n         * - 4 bytes for the number of samples\n         * - Nx8 bytes for the samples\n         */\n        return sizeof(int8_t) + sizeof(pcomp_chunk_size_t)\n               + chunk->num_of_samples * sizeof(double);\n    }\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Return nonzero if the chunk holds data in uncompressed form.\n */\nint pcomp_chunk_is_compressed(const pcomp_polycomp_chunk_t* chunk)\n{\n    if (chunk == NULL)\n        abort();\n\n    return chunk->is_compressed;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief If the chunks contain uncompressed data, returns a pointer\n * to the first element. Otherwise, return \\c NULL.\n */\nconst double*\npcomp_chunk_uncompressed_data(const pcomp_polycomp_chunk_t* chunk)\n{\n    if (chunk == NULL)\n        abort();\n\n    if (chunk->is_compressed)\n        return NULL;\n\n    return chunk->uncompressed;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief If the chunks contain compressed data, returns the number of\n * polynomial coefficients used in the compression. Otherwise, return\n * zero.\n */\npcomp_poly_size_t\npcomp_chunk_num_of_poly_coeffs(const pcomp_polycomp_chunk_t* chunk)\n{\n    if (chunk == NULL)\n        abort();\n\n    if (!chunk->is_compressed)\n        return 0;\n\n    return chunk->num_of_poly_coeffs;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief If the chunks contain compressed data, returns a pointer to\n * the first element of the array of coefficients of the interpolating\n * polynomial. Otherwise, return \\c NULL.\n */\nconst double*\npcomp_chunk_poly_coeffs(const pcomp_polycomp_chunk_t* chunk)\n{\n    if (chunk == NULL)\n        abort();\n\n    if (!chunk->is_compressed || chunk->num_of_poly_coeffs == 0)\n        return NULL;\n\n    return chunk->poly_coeffs;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief If the chunks contain compressed data, returns the number of\n * nonzero Chebyshev coefficients held in the chunk. Otherwise, return\n * zero.\n */\npcomp_chunk_size_t\npcomp_chunk_num_of_cheby_coeffs(const pcomp_polycomp_chunk_t* chunk)\n{\n    if (chunk == NULL)\n        abort();\n\n    if (!chunk->is_compressed)\n        return 0;\n\n    return chunk->num_of_cheby_coeffs;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief If the chunks contain compressed data, returns a pointer to\n * the first element of the Chebyshev transform of the fit residuals.\n * Otherwise, return \\c NULL.\n */\nconst double*\npcomp_chunk_cheby_coeffs(const pcomp_polycomp_chunk_t* chunk)\n{\n    if (chunk == NULL)\n        abort();\n\n    if (!chunk->is_compressed || chunk->num_of_cheby_coeffs == 0)\n        return NULL;\n\n    return chunk->cheby_coeffs;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Return the number of bytes required for the bitmask of\n * nonzero Chebyshev coefficients.\n *\n * The polynomial compression compresses Chebyshev transforms by\n * saving only those coefficients that are significantly different\n * from zero. In order to keep track of the position of such\n * coefficients in the full array, a bit mask is used. This function\n * determines how many bytes are required for such mask, which is\n * internally represented by Libpolycomp as an array of \\c uint8_t\n * values.\n *\n * \\param[in] chunk_size Number of samples in the chunk\n *\n * \\returns The number of bytes (\\c uint8_t values) required for the\n * mask.\n */\nsize_t pcomp_chunk_cheby_mask_size(pcomp_chunk_size_t chunk_size)\n{\n    return chunk_size / CHAR_BIT\n           + ((chunk_size % CHAR_BIT) > 0 ? 1 : 0);\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Return a pointer to the bitmask of nonzero Chebyshev\n * coefficients for a chunk\n *\n * \\param[in] chunk Pointer to the chunk\n *\n * \\returns A pointer to the array of bytes which make up the mask.\n * Use \\ref pcomp_mask_get_bit to access the values of each bit.\n */\nconst uint8_t*\npcomp_chunk_cheby_mask(const pcomp_polycomp_chunk_t* chunk)\n{\n    if (chunk == NULL)\n        abort();\n\n    return chunk->cheby_mask;\n}\n\n/**********************************************************************/\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Compute a polynomial fit of the data in \\a input and a\n * Chebyshev transform of the residuals\n *\n * Note that this function *always* computes the Chebyshev transform\n * of the data, even if there is a perfect fit between the polynomial\n * and the input data.\n *\n * \\param[in] params Pointer to a \\ref pcomp_polycomp_t structure\n * initialized by \\ref pcomp_init_polycomp.\n *\n * \\param[out] coeffs Pointer to the array that on exit will hold the\n * coefficients of the best-fit polynomial. It must have enough room\n * for a number of elements equal to the return value of \\ref\n * pcomp_polycomp_num_of_poly_coeffs.\n *\n * \\param[out] cheby_residuals Pointer to an array that on exit will\n * contain the Chebyshev transform of the residuals of the fit. It can\n * be \\c NULL; in any case, these numbers can be obtained by the use\n * of a call to \\ref pcomp_polycomp_forward_cheby and \\ref\n * pcomp_chebyshev_output.\n *\n * \\param[in] input Pointer to the array of values to be transformed.\n * The number of values used is equal to the return value of the\n * function \\ref pcomp_polycomp_samples_per_chunk.\n *\n * \\param[out] max_residual Pointer to a variable that will hold the\n * maximum absolute value of the discrepancy between each sample in \\a\n * input and the polynomial fit. It can be \\c NULL.\n *\n * \\returns If no errors occurred, \\ref PCOMP_STAT_SUCCESS. Otherwise,\n * the function returns the code of the error.\n */\n\nint pcomp_polyfit_and_chebyshev(pcomp_polycomp_t* params,\n                                double* coeffs, double* cheby_residuals,\n                                const double* input,\n                                double* max_residual)\n{\n    size_t idx;\n    int status;\n    double running_max = -1.0; /* Negative stands for \"uninitialized\" */\n\n    status = pcomp_run_poly_fit(params->poly_fit, coeffs, input);\n    if (status != PCOMP_STAT_SUCCESS)\n        return status;\n\n    for (idx = 0; idx < params->samples_per_chunk; ++idx) {\n        double abs_residual;\n\n        params->chebyshev->input[idx]\n            = input[idx]\n              - eval_poly(coeffs, params->poly_fit->num_of_coeffs,\n                          idx + 1.0);\n\n        abs_residual = fabs(params->chebyshev->input[idx]);\n        if (abs_residual > running_max || running_max < 0.0)\n            running_max = abs_residual;\n    }\n\n    if (max_residual != NULL)\n        *max_residual = running_max;\n\n    if (params->algorithm != PCOMP_ALG_NO_CHEBYSHEV) {\n        status = pcomp_run_chebyshev(\n            params->chebyshev, params->chebyshev->dir, NULL, NULL);\n\n        if (cheby_residuals != NULL\n            && cheby_residuals != params->chebyshev->output) {\n            memcpy(cheby_residuals, params->chebyshev->output,\n                   sizeof(params->chebyshev->output[0])\n                       * params->chebyshev->num_of_samples);\n        }\n    }\n\n    return status;\n}\n\n/***********************************************************************\n * Sort the array \"positions\" according to the absolute values of\n * \"coeffs\", in *descending* order. The function uses the merge sort\n * algorithm. */\n\nstatic void sort_positions(pcomp_chunk_size_t positions[],\n                           const double coeffs[], size_t num)\n{\n    size_t front, back;\n    double pivot;\n    pcomp_chunk_size_t temp;\n\n    if (num < 2)\n        return;\n\n    pivot = fabs(coeffs[positions[num / 2]]);\n    for (front = 0, back = num - 1;; front++, back--) {\n        while (fabs(coeffs[positions[front]]) > pivot) {\n            front++;\n        }\n\n        while (pivot > fabs(coeffs[positions[back]])) {\n            if (back == 0)\n                break;\n            back--;\n        }\n\n        if (front >= back)\n            break;\n\n        temp = positions[front];\n        positions[front] = positions[back];\n        positions[back] = temp;\n    }\n    sort_positions(positions, coeffs, front);\n    sort_positions(positions + front, coeffs, num - front);\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Return the value of the bit at the position \\a pos in the\n * bitmask \\a mask.\n *\n * \\param[in] mask Pointer to the first byte of the mask\n *\n * \\param[in] pos Zero-based index of the bit in the mask\n *\n * \\returns Either 0 or 1, depending on the value of the bit.\n */\nint pcomp_mask_get_bit(const uint8_t* mask, size_t pos)\n{\n    return (mask[pos / CHAR_BIT] & (1 << (pos % CHAR_BIT))) != 0;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Set the value of the bit at position \\a pos in the bitmask \\a\n *\n * \\param[inout] mask The bitmask to modify\n *\n * \\param[in] pos Zero-based index of the byte to set\n *\n * \\param[in] value Value of the bit (either 0 or 1; any value\n * different from zero is treated as equal to 1)\n */\nvoid pcomp_mask_set_bit(uint8_t* mask, size_t pos, int value)\n{\n    if (value != 0) {\n        mask[pos / CHAR_BIT] |= (1 << (pos % CHAR_BIT));\n    }\n    else {\n        mask[pos / CHAR_BIT] &= ~(((uint8_t)1) << (pos % CHAR_BIT));\n    }\n}\n\nstatic double compute_discrepancy(double a[], double b[], size_t num)\n{\n    size_t idx;\n    double err = 0.0;\n    for (idx = 0; idx < num; ++idx) {\n        double cur_err = fabs(a[idx] - b[idx]);\n        if (cur_err > err)\n            err = cur_err;\n    }\n\n    return err;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Find the smallest subset of Chebyshev coefficients that can\n * approximate a Chebyshev transform with an error less than \\a\n * max_allowable_error.\n *\n * On exit, the bits in \\a bitmask will be set to 1 in correspondence\n * of every Chebyshev coefficient that must be retained. The function\n * returns the number of Chebyshev coefficients to retain (i.e., the\n * number of bits in \\a mask that have been set to 1).\n *\n * \\param[in] chebyshev Pointer to a \\ref pcomp_chebyshev_t structure\n * used to compute the forward Chebyshev transform (from the space of\n * the fit residuals to the Chebyshev space)\n *\n * \\param[in] inv_chebyshev Pointer to a \\ref pcomp_chebyshev_t\n * structure representing the inverse transform of \\a chebyshev.\n *\n * \\param[in] max_allowable_error The maximum allowed discrepancy for\n * the chopped Chebyshev, as measured in the space of the fit\n * residuals.\n *\n * \\param[out] mask Bitmask that will contain the position of the\n * unchopped Chebyshev terms of the transform of the fit residuals.\n * Use \\ref pcomp_mask_get_bit to access each element.\n *\n * \\param[out] max_error If not \\c NULL, it will be set to the maximum\n * error due to the chopping of the Chebyshev transform represented by\n * \\a mask.\n *\n * \\returns The number of bits equal to one in \\a mask, i.e., the\n * number of unchopped Chebyshev coefficients.\n */\nsize_t pcomp_find_chebyshev_mask(pcomp_chebyshev_t* chebyshev,\n                                 pcomp_chebyshev_t* inv_chebyshev,\n                                 double max_allowable_error,\n                                 uint8_t* mask, double* max_error)\n{\n    size_t idx;\n    size_t cur_coeff = 0;\n    pcomp_chunk_size_t* positions;\n    double err;\n\n    if (chebyshev == NULL || inv_chebyshev == NULL || mask == NULL\n        || chebyshev->num_of_samples != inv_chebyshev->num_of_samples)\n        abort();\n\n    if (max_allowable_error <= 0.0)\n        return 0;\n\n    /* The \"positions\" array contains the indexes to the\n     * chebyshev->output array, i.e., the list of Chebyshev\n     * coefficients to sort in decreasing order. At the beginning each\n     * entry is set to its own index:\n     *\n     *            +---+---+---+-----+\n     * positions: | 0 | 1 | 2 | ... |\n     *            +---+---+---+-----+\n     *\n     * After the call to \"sort_positions\", the \"positions\" array\n     * contains the indexes to \"chebyshev->output\" ordered according\n     * to the decreasing absolute value of the latters, e.g.:\n     *\n     *            +---+---+---+-----+\n     * positions: | 7 | 2 | 5 | ... |\n     *            +---+---+---+-----+\n     */\n    positions = malloc(chebyshev->num_of_samples\n                       * sizeof(pcomp_chunk_size_t));\n    if (positions == NULL)\n        abort();\n    for (idx = 0; idx < chebyshev->num_of_samples; ++idx) {\n        positions[idx] = idx;\n    }\n    sort_positions(positions, chebyshev->output,\n                   chebyshev->num_of_samples);\n\n    /* Start by setting all the coefficients to zero */\n    memset(&inv_chebyshev->input[0], 0,\n           chebyshev->num_of_samples * sizeof(inv_chebyshev->input[0]));\n    memset(&mask[0], 0,\n           pcomp_chunk_cheby_mask_size(chebyshev->num_of_samples));\n\n    /* Add the coefficients one by one until the error is below\n     * \"max_allowable_error\" */\n    cur_coeff = 0;\n    while (cur_coeff < chebyshev->num_of_samples) {\n\n        inv_chebyshev->input[positions[cur_coeff]]\n            = chebyshev->output[positions[cur_coeff]];\n        pcomp_mask_set_bit(mask, positions[cur_coeff], 1);\n        ++cur_coeff;\n\n        pcomp_run_chebyshev(inv_chebyshev, inv_chebyshev->dir, NULL,\n                            NULL);\n        err = compute_discrepancy(chebyshev->input,\n                                  inv_chebyshev->output,\n                                  chebyshev->num_of_samples);\n\n        if (err < max_allowable_error)\n            break;\n    }\n\n    free(positions);\n    if (max_error != NULL)\n        *max_error = err;\n\n    return cur_coeff;\n}\n\n/* This function is used internally by \"pcomp_run_polycomp_on_chunk\"\n * and \"pcomp_decompress_poly_chunk\" to make sure there is no memory\n * leak on the chunk passed as argument. */\nstatic void clear_chunk(pcomp_polycomp_chunk_t* chunk)\n{\n    /* Leave chunk->uncompressed as it is, as it never changes\n     */\n\n    chunk->num_of_poly_coeffs = 0;\n    if (chunk->poly_coeffs != NULL)\n        free(chunk->poly_coeffs);\n\n    chunk->num_of_cheby_coeffs = 0;\n    if (chunk->cheby_coeffs != NULL)\n        free(chunk->cheby_coeffs);\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Compress the first \\a num_of_samples elements in \\a input\n * and store them in \\a chunk.\n *\n * The function determines if the data in \\a input can be efficiently\n * compressed using polynomial compression with the parameters\n * described by \\a params. If it is so, it stores the compressed data\n * in \\a chunk. If the compression ratio is small or equal to one, or\n * if the compression error is too large, the function copies the data\n * in \\a input into \\a chunk in uncompressed format.\n *\n * The following example shows how to use this function together with\n * \\ref pcomp_init_chunk:\n *\n * \\code{.c}\n * double input[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0,\n *                    7.0, 8.0, 9.0, 11.0 };\n * size_t input_size = sizeof(input) / sizeof(input[0]);\n * pcomp_polycomp_chunk_t* chunk;\n * pcomp_polycomp_t* polycomp;\n * double max_error;\n * size_t idx;\n *\n * polycomp = pcomp_init_polycomp(input_size, 2, 1.0e-5,\n *                                PCOMP_ALG_USE_CHEBYSHEV);\n * chunk = pcomp_init_chunk(input_size);\n *\n * pcomp_run_polycomp_on_chunk(polycomp, input, input_size, chunk,\n *                             &max_error);\n * \\endcode\n *\n * \\param[in] params Pointer to a \\a pcomp_polycomp_t structure\n * (created using \\ref pcomp_init_polycomp) which provides the\n * parameters of the compression.\n *\n * \\param[in] input The sequence of numbers to compress. Their number\n * is equal to the parameter \\a num_of_samples\n *\n * \\param[in] num_of_samples Number of values in \\a input to compress\n *\n * \\param[inout] chunk The chunk that will contain the data, either in\n * compressed or uncompressed format. It must have already been\n * initialized via a call to \\ref pcomp_init_chunk.\n *\n * \\param[out] max_error On exit, the function writes the compression\n * error here. It can be \\c NULL.\n *\n * \\returns Either \\ref PCOMP_STAT_SUCCESS (if no errors occurred), or\n * the error code.\n */\nint pcomp_run_polycomp_on_chunk(pcomp_polycomp_t* params,\n                                const double* input,\n                                pcomp_chunk_size_t num_of_samples,\n                                pcomp_polycomp_chunk_t* chunk,\n                                double* max_error)\n{\n    uint8_t* mask = NULL;\n    double* coeffs = NULL;\n    size_t cheby_coeffs_to_retain = 0;\n    int apply_chebyshev = 1;\n    double* buf = NULL;\n    const double* straightened_input;\n\n    if (chunk == NULL || input == NULL || params == NULL\n        || params->poly_fit == NULL || params->chebyshev == NULL\n        || params->inv_chebyshev == NULL)\n        abort();\n\n    clear_chunk(chunk);\n\n    if (num_of_samples != params->samples_per_chunk)\n        return PCOMP_STAT_INVALID_BUFFER;\n\n    if (params->period > 0.0) {\n        buf = malloc(num_of_samples * sizeof(input[0]));\n        if (buf == NULL)\n            abort();\n        pcomp_straighten(buf, input, num_of_samples, params->period);\n        straightened_input = buf; /* This preserve const-correctness */\n    }\n    else {\n        straightened_input = input;\n    }\n\n    if (num_of_samples <= params->poly_fit->num_of_coeffs) {\n        /* The number of element is so small that is better to store\n         * them uncompressed */\n        chunk->is_compressed = 0;\n    }\n    else {\n        double max_residual;\n\n        /* Compute the polynomial fit and the full Chebyshev\n         * transform */\n        coeffs\n            = malloc(sizeof(double) * params->poly_fit->num_of_coeffs);\n        if (coeffs == NULL)\n            abort();\n        pcomp_polyfit_and_chebyshev(params, coeffs, NULL,\n                                    straightened_input, &max_residual);\n        apply_chebyshev\n            = (max_residual >= params->max_allowable_error)\n              && (params->algorithm != PCOMP_ALG_NO_CHEBYSHEV);\n\n        /* If the Chebyshev transform is needed, chop it as much as\n         * possible */\n        if (apply_chebyshev) {\n            mask = malloc(pcomp_chunk_cheby_mask_size(num_of_samples));\n            if (mask == NULL)\n                abort();\n            cheby_coeffs_to_retain = pcomp_find_chebyshev_mask(\n                params->chebyshev, params->inv_chebyshev,\n                params->max_allowable_error, mask, max_error);\n\n            chunk->is_compressed = (cheby_coeffs_to_retain\n                                    + params->poly_fit->num_of_coeffs)\n                                   < num_of_samples;\n            if (!chunk->is_compressed) {\n                free(mask);\n                mask = NULL;\n            }\n        }\n        else {\n            /* Assume that num_of_samples > deg(p) + 1 */\n            chunk->is_compressed\n                = (max_residual <= params->max_allowable_error);\n        }\n    }\n\n    chunk->num_of_samples = num_of_samples;\n    if (chunk->is_compressed) {\n        size_t idx;\n\n        chunk->num_of_poly_coeffs = params->poly_fit->num_of_coeffs;\n        chunk->poly_coeffs = coeffs;\n        if (apply_chebyshev) {\n            size_t cheby_idx;\n\n            chunk->num_of_cheby_coeffs = cheby_coeffs_to_retain;\n            chunk->cheby_mask = mask;\n            chunk->cheby_coeffs\n                = malloc(sizeof(double) * cheby_coeffs_to_retain);\n            if (chunk->cheby_coeffs == NULL)\n                abort();\n            cheby_idx = 0;\n            for (idx = 0; idx < params->chebyshev->num_of_samples;\n                 ++idx) {\n                if (pcomp_mask_get_bit(mask, idx)) {\n                    chunk->cheby_coeffs[cheby_idx++]\n                        = params->chebyshev->output[idx];\n                }\n            }\n        }\n        else {\n            chunk->num_of_cheby_coeffs = 0;\n            chunk->cheby_mask = NULL;\n            chunk->cheby_coeffs = NULL;\n        }\n    }\n    else {\n        size_t idx;\n\n        if (coeffs != NULL)\n            free(coeffs);\n\n        chunk->uncompressed = malloc(sizeof(double) * num_of_samples);\n        if (chunk->uncompressed == NULL)\n            abort();\n        for (idx = 0; idx < num_of_samples; ++idx)\n            chunk->uncompressed[idx] = input[idx];\n\n        if (max_error != NULL)\n            *max_error = 0.0;\n    }\n\n    if (buf != NULL) {\n        free(buf);\n    }\n\n    return PCOMP_STAT_SUCCESS;\n}\n\n/** \\ingroup poly_lowlevel\n *\n * \\brief Decompress the data in a chunk\n *\n * This function performs the decompression of a chunk, and it is the\n * counterpart of \\ref pcomp_run_polycomp_on_chunk. Here is an\n * example:\n *\n * \\code{.c}\n * double* decompr;\n * pcomp_chebyshev_t* inv_chebyshev;\n *\n * // We assume that \"chunk\" has already been initialized somewhere\n * decompr = malloc(sizeof(double) *\n *                  pcomp_chunk_num_of_samples(chunk));\n *\n * inv_chebyshev = pcomp_init_chebyshev(input_size,\n *                                      PCOMP_TD_INVERSE);\n * pcomp_decompress_polycomp_chunk(decompr, chunk, inv_chebyshev);\n * \\endcode\n *\n * \\param[out] output Pointer to the array that will contain the\n * uncompressed data\n *\n * \\param[in] chunk The chunk to decompress\n *\n * \\param[in] inv_chebyshev Pointer to a \\ref pcomp_chebyshev_t object\n * that performs the inverse Chebyshev transform. The function does\n * not allocate an object of this kind because in this way such\n * objects can be reused on subsequent calls to \\ref\n * pcomp_decompress_polycomp_chunk.\n *\n * \\returns Either \\ref PCOMP_STAT_SUCCESS if no error occurred, or\n * the error code.\n */\nint pcomp_decompress_polycomp_chunk(double* output,\n                                    const pcomp_polycomp_chunk_t* chunk,\n                                    pcomp_chebyshev_t* inv_chebyshev)\n{\n    if (output == NULL || chunk == NULL || inv_chebyshev == NULL)\n        abort();\n\n    if (chunk->is_compressed) {\n        size_t idx;\n\n        /* Compute the values of the polynomial at the points 1,\n         * 2, ...\n         */\n        for (idx = 0; idx < chunk->num_of_samples; ++idx) {\n            output[idx] = eval_poly(chunk->poly_coeffs,\n                                    chunk->num_of_poly_coeffs, idx + 1);\n        }\n\n        /* If present, add the contribution of the Chebyshev\n         * transform\n         */\n        if (chunk->num_of_cheby_coeffs > 0) {\n            size_t cur_cheby_idx = 0;\n            if (chunk->cheby_coeffs == NULL)\n                abort();\n\n            for (idx = 0; idx < chunk->num_of_samples; ++idx) {\n                if (pcomp_mask_get_bit(chunk->cheby_mask, idx)) {\n                    if (cur_cheby_idx >= chunk->num_of_cheby_coeffs) {\n                        abort();\n                    }\n\n                    inv_chebyshev->input[idx]\n                        = chunk->cheby_coeffs[cur_cheby_idx++];\n                }\n                else {\n                    inv_chebyshev->input[idx] = 0.0;\n                }\n            }\n            pcomp_run_chebyshev(inv_chebyshev, inv_chebyshev->dir, NULL,\n                                NULL);\n\n            for (idx = 0; idx < chunk->num_of_samples; ++idx) {\n                output[idx] += inv_chebyshev->output[idx];\n            }\n        }\n    }\n    else {\n        memcpy(output, chunk->uncompressed,\n               sizeof(chunk->uncompressed[0]) * chunk->num_of_samples);\n    }\n\n    return PCOMP_STAT_SUCCESS;\n}\n\n/** \\ingroup poly\n *\n * \\brief Compress the array \\a input_buf using polynomial compression\n *\n * This function compresses the first \\a input_size elements of the\n * array \\a input_buf using the polynomial compression scheme. The\n * output is an array of chunks saved in \\a output_buf (the number of\n * elements of this array is saved in \\a num_of_chunks). The \\a params\n * variable specifies the parameters used by the compression\n * algorithm.\n *\n * Here is an example showing how to compress a sequence of numbers in\n * the variable \\a input:\n *\n * \\code{.c}\n * double input[] = { 1.0, 2.0, 3.0, 4.0, 3.0, 2.0,\n *                    1.0, 2.0, 6.0, 7.0, 9.0 };\n * size_t input_size = sizeof(input) / sizeof(input[0]);\n * double* decompr;\n * size_t decompr_size;\n * pcomp_polycomp_chunk_t** chunks;\n * size_t num_of_chunks;\n * pcomp_polycomp_t* params;\n * size_t idx;\n *\n * params = pcomp_init_polycomp(4, 2, 1.0e-5, PCOMP_ALG_USE_CHEBYSHEV);\n * pcomp_compress_polycomp(&chunks, &num_of_chunks, input, input_size,\n *                         params);\n *\n * // Print some information for each chunk\n * for(idx = 0; idx < num_of_chunks; ++idx) {\n *     printf(\"Chunk %lu of %lu: %s\\n\", idx + 1, num_of_chunks,\n *            pcomp_chunk_is_compressed(chunks[idx]) ?\n *                \"compressed\" : \"uncompressed\");\n * }\n * \\endcode\n *\n * Once the sequence \\a input_buf is compressed, the array of chunks\n * can either be analyzed (e.g., using a \\c for loop as in the example\n * above) or encoded using the \\ref pcomp_encode_chunks. Once the\n * variable \\a output_buf is no longer used, it should be freed via a\n * call to \\ref pcomp_free_chunks.\n *\n * \\param[out] output_buf Pointer to a variable that will receive the\n * address of an array of \\ref pcomp_polycomp_chunk_t variables\n * created by the function. Such array contains the whole set of data\n * in \\a input in compressed format. The array can be freed via a call\n * to \\ref pcomp_free_chunks.\n *\n * \\param[out] num_of_chunks On output, the variable will contain the\n * number of chunks saved in \\a output_buf.\n *\n * \\param[in] input_buf Pointer to the array of numbers to compress.\n *\n * \\param[in] input_size Number of elements in \\a input_buf to\n * compress.\n *\n * \\param[in] params Parameters used for the compression. The variable\n * must have been created via a call to \\ref pcomp_init_polycomp.\n *\n * \\returns Either \\ref PCOMP_STAT_SUCCESS if no error occurred, or\n * the error code.\n */\nint pcomp_compress_polycomp(pcomp_polycomp_chunk_t** output_buf[],\n                            size_t* num_of_chunks,\n                            const double* input_buf, size_t input_size,\n                            const pcomp_polycomp_t* params)\n{\n    size_t idx;\n    pcomp_polycomp_t** chunk_params;\n    pcomp_polycomp_t* last_chunk_params;\n    size_t samples_in_last_chunk = 0;\n\n    if (output_buf == NULL || num_of_chunks == NULL || input_buf == NULL\n        || params == NULL || params->poly_fit == NULL)\n        abort();\n\n    /* Calculate how many chunks we'll create */\n    *num_of_chunks = input_size / params->samples_per_chunk;\n    samples_in_last_chunk = input_size % params->samples_per_chunk;\n    if (samples_in_last_chunk != 0)\n        ++(*num_of_chunks);\n\n    *output_buf\n        = malloc(sizeof(pcomp_polycomp_chunk_t*) * (*num_of_chunks));\n    if (*output_buf == NULL)\n        abort();\n\n    /* Allocate a pcomp_polycomp_t structure for each of the OpenMP\n     * threads */\n    chunk_params\n        = malloc(sizeof(pcomp_polycomp_t*) * omp_get_max_threads());\n    for (idx = 0; idx < omp_get_max_threads(); ++idx) {\n        chunk_params[idx] = pcomp_init_polycomp(\n            params->samples_per_chunk, params->poly_fit->num_of_coeffs,\n            params->max_allowable_error, params->algorithm);\n    }\n\n    if (samples_in_last_chunk != 0) {\n        /* This is going to be used by just *one* OpenMP process */\n        last_chunk_params = pcomp_init_polycomp(\n            samples_in_last_chunk, params->poly_fit->num_of_coeffs,\n            params->max_allowable_error, params->algorithm);\n    }\n    else {\n        last_chunk_params = NULL;\n    }\n\n#pragma omp parallel for\n    for (idx = 0; idx < *num_of_chunks; ++idx) {\n        const double* cur_input = input_buf\n                                  + params->samples_per_chunk * idx;\n        pcomp_polycomp_t* cur_params;\n        size_t cur_chunk_size;\n\n        if (idx + 1 < *num_of_chunks || last_chunk_params == NULL) {\n            cur_params = chunk_params[omp_get_thread_num()];\n            cur_chunk_size = params->samples_per_chunk;\n        }\n        else {\n            cur_params = last_chunk_params;\n            cur_chunk_size = samples_in_last_chunk;\n        }\n\n        if (cur_params == NULL)\n            abort();\n\n        (*output_buf)[idx] = pcomp_init_chunk(cur_chunk_size);\n        pcomp_run_polycomp_on_chunk(cur_params, cur_input,\n                                    cur_chunk_size, (*output_buf)[idx],\n                                    NULL);\n    }\n\n    for (idx = 0; idx < omp_get_max_threads(); ++idx)\n        pcomp_free_polycomp(chunk_params[idx]);\n    free(chunk_params);\n\n    pcomp_free_polycomp(last_chunk_params);\n\n    return PCOMP_STAT_SUCCESS;\n}\n\n/** \\ingroup poly\n *\n * \\brief Compute the sum of the number of samples encoded in \\a\n *chunk_array\n *\n * \\param[in] chunk_array Array of \\ref pcomp_polycomp_chunk_t\n * variables. Typically, such array is created via a call to \\ref\n * pcomp_compress_polycomp.\n *\n * \\param[in] num_of_chunks Number of elements in \\a chunk_array\n *\n * \\returns The overall number of samples encoded in the sequence of\n * chunks\n */\nsize_t\npcomp_total_num_of_samples(pcomp_polycomp_chunk_t* const chunk_array[],\n                           size_t num_of_chunks)\n{\n    size_t total = 0;\n    size_t idx;\n    if (chunk_array == NULL)\n        abort();\n\n    for (idx = 0; idx < num_of_chunks; ++idx) {\n        if (chunk_array[idx] == NULL)\n            abort();\n\n        total += chunk_array[idx]->num_of_samples;\n    }\n\n    return total;\n}\n\n/** \\ingroup poly\n *\n * \\brief Decompress a sequence of chunks\n *\n * This function is the counterpart for \\ref pcomp_compress_polycomp.\n *\n * \\param[out] output_buf Pointer to the variable that will hold the\n * uncompressed data. It must have room for a number of elements at\n * least equal to the return value of \\ref pcomp_total_num_of_samples.\n *\n * \\param[in] chunk_array Array of chunks holding the data in\n * compressed format.\n *\n * \\param[in] num_of_chunks Number of elements in the array \\a\n * chunk_array.\n *\n * \\returns Either \\ref PCOMP_STAT_SUCCESS if no error occurred, or\n * the error code.\n */\nint pcomp_decompress_polycomp(\n    double* output_buf, pcomp_polycomp_chunk_t* const chunk_array[],\n    size_t num_of_chunks)\n{\n    size_t idx;\n    size_t* start_pos_list;\n    pcomp_chebyshev_t** inv_cheby_list = NULL;\n    pcomp_chebyshev_t* last_inv_cheby = NULL;\n\n    if (output_buf == NULL || chunk_array == NULL || num_of_chunks == 0)\n        abort();\n\n    /* Precompute the position in the output buffer where the\n     * decompressed data from each chunk will be written: in this way,\n     * we prevent data races in the parallel for loop below. */\n    start_pos_list = malloc(sizeof(size_t) * num_of_chunks);\n    if (start_pos_list == NULL)\n        abort();\n\n    start_pos_list[0] = 0;\n    for (idx = 0; idx < num_of_chunks - 1; ++idx) {\n        /* The algorithm heavy relies on the fact that *all the\n         * chunks* but the last one have the same number of\n         * elements! */\n        if (chunk_array[idx]->num_of_samples\n            != chunk_array[0]->num_of_samples)\n            abort();\n\n        start_pos_list[idx + 1] = start_pos_list[idx]\n                                  + chunk_array[idx]->num_of_samples;\n    }\n\n    /* Since FFTW's plan allocation functions are not reentrant, we\n     * must initialize them outside the parallel loop. */\n    inv_cheby_list\n        = malloc(sizeof(pcomp_chebyshev_t*) * omp_get_max_threads());\n    if (inv_cheby_list == NULL)\n        abort();\n    for (idx = 0; idx < omp_get_max_threads(); ++idx) {\n        if (idx < num_of_chunks) {\n            inv_cheby_list[idx] = pcomp_init_chebyshev(\n                chunk_array[idx]->num_of_samples, PCOMP_TD_INVERSE);\n        }\n        else {\n            inv_cheby_list[idx] = NULL;\n        }\n    }\n    if (chunk_array[num_of_chunks - 1]->num_of_samples\n        != chunk_array[0]->num_of_samples) {\n        last_inv_cheby = pcomp_init_chebyshev(\n            chunk_array[num_of_chunks - 1]->num_of_samples,\n            PCOMP_TD_INVERSE);\n    }\n    else\n        last_inv_cheby = NULL;\n\n#pragma omp parallel for\n    for (idx = 0; idx < num_of_chunks; ++idx) {\n        pcomp_chebyshev_t* cur_inv_cheby;\n        if (chunk_array[idx] == NULL)\n            abort();\n\n        if (idx + 1 < num_of_chunks || last_inv_cheby == NULL) {\n            cur_inv_cheby = inv_cheby_list[omp_get_thread_num()];\n        }\n        else {\n            cur_inv_cheby = last_inv_cheby;\n        }\n\n        pcomp_decompress_polycomp_chunk(\n            output_buf + start_pos_list[idx], chunk_array[idx],\n            cur_inv_cheby);\n    }\n\n    free(start_pos_list);\n\n    for (idx = 0; idx < omp_get_max_threads(); ++idx) {\n        pcomp_free_chebyshev(inv_cheby_list[idx]);\n    }\n    free(inv_cheby_list);\n    pcomp_free_chebyshev(last_inv_cheby);\n\n    return PCOMP_STAT_SUCCESS;\n}\n\n/** \\ingroup poly\n *\n * \\brief Free an array of chunks\n *\n * \\param[in] chunk_array An array of chunks. This variable must have\n * been allocated by a call to \\ref pcomp_compress_polycomp.\n *\n * \\param[in] num_of_chunks Number of elements in the array \\a\n * chunk_array\n */\nvoid pcomp_free_chunks(pcomp_polycomp_chunk_t* chunk_array[],\n                       size_t num_of_chunks)\n{\n    size_t idx;\n\n    if (chunk_array == NULL)\n        return;\n\n    for (idx = 0; idx < num_of_chunks; ++idx) {\n        pcomp_free_chunk(chunk_array[idx]);\n    }\n\n    free(chunk_array);\n}\n\n/** \\ingroup poly\n *\n * \\brief Number of bytes required by \\ref pcomp_encode_chunks\n *\n * This function computes the number of bytes required to encode the\n * array of chunks in the variable \\a chunks. Unlike functions like\n * \\ref pcomp_rle_bufsize, this function provides an exact estimate,\n * not an upper bound.\n *\n * \\param[in] chunks Array of chunks to encode. This should have been\n * initialized via a call to \\ref pcomp_compress_polycomp.\n *\n * \\param[in] num_of_chunks Number of elements in \\a chunks.\n *\n * \\returns The number of bytes required for the output buffer used by\n * \\ref pcomp_encode_chunks.\n */\nsize_t pcomp_chunks_num_of_bytes(pcomp_polycomp_chunk_t* const chunks[],\n                                 size_t num_of_chunks)\n{\n    size_t result = sizeof(size_t); /* Room for the number of chunks */\n    size_t idx;\n\n    for (idx = 0; idx < num_of_chunks; ++idx) {\n        result += pcomp_chunk_num_of_bytes(chunks[idx]);\n    }\n\n    return result;\n}\n\n/***********************************************************************\n * Encode/decode a list of chunks into a raw stream of bytes (suitable\n * for I/O).\n */\n\n#define SAVE_TO_PTR_AND_INCREMENT(buf, value, type)                    \\\n    {                                                                  \\\n        *((type*)buf) = value;                                         \\\n        buf = ((type*)buf) + 1;                                        \\\n    }\n\n/** \\ingroup poly\n *\n * \\brief Encode a list of chunks into a sequence of raw bytes\n *\n * This function transforms an array of instances to \\ref\n * pcomp_polycomp_chunk_t variables into a sequence of raw bytes,\n * suitable for I/O. It can be used together with \\ref\n * pcomp_compress_polycomp to compress a dataset and save it into a\n * binary file.\n *\n * To decode byte sequences produced by this function, use \\ref\n * pcomp_decode_chunks.\n *\n * \\param[out] buf Pointer to a memory buffer that will receive the\n * result of the encoding. It must have room for a number of bytes (\\c\n * uint8_t) at least equal to the return value of \\ref\n * pcomp_chunks_num_of_bytes.\n *\n * \\param[out] buf_size On exit, it will contain the number of bytes\n * actually written in \\a buf. The latter number is equal to the value\n * returned by \\ref pcomp_chunks_num_of_bytes.\n *\n * \\param[in] chunk_array Array of chunks to encode\n *\n * \\param[in] num_of_chunks Number of elements in the array \\a\n * chunk_array.\n *\n * \\returns Either \\ref PCOMP_STAT_SUCCESS if no error occurred, or\n * the error code.\n */\nint pcomp_encode_chunks(void* buf, size_t* buf_size,\n                        pcomp_polycomp_chunk_t* const chunk_array[],\n                        size_t num_of_chunks)\n{\n    void* buf_ptr = buf;\n    size_t chunk_idx;\n    uint64_t num_of_chunks_uint64 = (uint64_t)num_of_chunks;\n\n    if (chunk_array == NULL || num_of_chunks == 0)\n        abort();\n\n    SAVE_TO_PTR_AND_INCREMENT(buf_ptr, num_of_chunks_uint64, uint64_t);\n    num_of_chunks = num_of_chunks_uint64;\n\n    for (chunk_idx = 0; chunk_idx < num_of_chunks; ++chunk_idx) {\n        const pcomp_polycomp_chunk_t* cur_chunk\n            = chunk_array[chunk_idx];\n        size_t idx; /* Used for inner loops */\n\n        SAVE_TO_PTR_AND_INCREMENT(buf_ptr, cur_chunk->is_compressed,\n                                  uint8_t);\n        SAVE_TO_PTR_AND_INCREMENT(buf_ptr, cur_chunk->num_of_samples,\n                                  pcomp_chunk_size_t);\n\n        if (cur_chunk->is_compressed) {\n            size_t cheby_mask_size = pcomp_chunk_cheby_mask_size(\n                cur_chunk->num_of_samples);\n\n            SAVE_TO_PTR_AND_INCREMENT(buf_ptr,\n                                      cur_chunk->num_of_poly_coeffs,\n                                      pcomp_poly_size_t);\n            for (idx = 0; idx < cur_chunk->num_of_poly_coeffs; idx++) {\n                SAVE_TO_PTR_AND_INCREMENT(\n                    buf_ptr, cur_chunk->poly_coeffs[idx], double);\n            }\n\n            SAVE_TO_PTR_AND_INCREMENT(buf_ptr,\n                                      cur_chunk->num_of_cheby_coeffs,\n                                      pcomp_chunk_size_t);\n            if (cur_chunk->num_of_cheby_coeffs > 0) {\n                /* Mask */\n                for (idx = 0; idx < cheby_mask_size; ++idx) {\n                    SAVE_TO_PTR_AND_INCREMENT(\n                        buf_ptr, cur_chunk->cheby_mask[idx], uint8_t);\n                }\n                /* Chebyshev coefficients */\n                for (idx = 0; idx < cur_chunk->num_of_cheby_coeffs;\n                     idx++) {\n                    SAVE_TO_PTR_AND_INCREMENT(\n                        buf_ptr, cur_chunk->cheby_coeffs[idx], double);\n                }\n            }\n        }\n        else {\n            for (idx = 0; idx < cur_chunk->num_of_samples; idx++) {\n                SAVE_TO_PTR_AND_INCREMENT(\n                    buf_ptr, cur_chunk->uncompressed[idx], double);\n            }\n        }\n    }\n\n    *buf_size = ((uint8_t*)buf_ptr) - ((uint8_t*)buf);\n    return PCOMP_STAT_SUCCESS;\n}\n\n#define READ_FROM_PTR_AND_INCREMENT(var, pointer, type)                \\\n    {                                                                  \\\n        var = *((type*)(pointer));                                     \\\n        pointer = ((type*)(pointer)) + 1;                              \\\n    }\n\n/** \\ingroup poly\n *\n * \\brief Decode a byte sequence created by \\ref pcomp_encode_chunks\n * into an array of chunks.\n *\n * This function can be used to read from a binary file or a socket a\n * sequence of chunks encoded by \\ref pcomp_encode_chunks. The\n * function allocates memory for an array of \\ref\n * pcomp_polycomp_chunk_t structures and returns it in the variable \\a\n * chunk_array. The latter variable must be freed using \\ref\n * pcomp_free_chunks once it is no longer needed.\n *\n * This function is the counterpart for \\ref pcomp_encode_chunks.\n *\n * \\param[out] chunk_array Pointer to an array that will contain the\n * chunks decoded from \\a buf.\n *\n * \\param[out] num_of_chunks On exit, this variable will hold the\n * number of chunks saved in \\a chunk_array.\n *\n * \\param[in] Pointer to the byte sequence to decode.\n *\n * \\returns Either \\ref PCOMP_STAT_SUCCESS if no error occurred, or\n * the error code.\n */\nint pcomp_decode_chunks(pcomp_polycomp_chunk_t** chunk_array[],\n                        size_t* num_of_chunks, const void* buf)\n{\n    const void* cur_ptr = buf;\n    size_t chunk_idx;\n    double* poly_buf = NULL;\n    size_t poly_buf_size = 0;\n    double* cheby_buf = NULL;\n    size_t cheby_buf_size = 0;\n    uint8_t* cheby_mask_buf = NULL;\n    size_t cheby_mask_buf_size = 0;\n    double* uncompr_buf = NULL;\n    size_t uncompr_buf_size = 0;\n    uint64_t num_of_chunks_uint64;\n\n    if (buf == NULL || chunk_array == NULL || num_of_chunks == NULL)\n        abort();\n\n    READ_FROM_PTR_AND_INCREMENT(num_of_chunks_uint64, cur_ptr,\n                                uint64_t);\n    *num_of_chunks = num_of_chunks_uint64;\n\n    *chunk_array\n        = malloc(sizeof(pcomp_polycomp_chunk_t*) * (*num_of_chunks));\n    if (*chunk_array == NULL)\n        abort();\n\n    for (chunk_idx = 0; chunk_idx < *num_of_chunks; ++chunk_idx) {\n        uint8_t is_compressed;\n        size_t num_of_samples;\n        size_t idx; /* Used for inner loops */\n\n        READ_FROM_PTR_AND_INCREMENT(is_compressed, cur_ptr, uint8_t);\n        READ_FROM_PTR_AND_INCREMENT(num_of_samples, cur_ptr,\n                                    pcomp_chunk_size_t);\n\n        if (is_compressed) {\n            size_t num_of_poly_coeffs;\n            size_t num_of_cheby_coeffs;\n            size_t cheby_mask_size\n                = pcomp_chunk_cheby_mask_size(num_of_samples);\n\n            READ_FROM_PTR_AND_INCREMENT(num_of_poly_coeffs, cur_ptr,\n                                        pcomp_poly_size_t);\n            if (num_of_poly_coeffs > poly_buf_size) {\n                poly_buf_size = num_of_poly_coeffs;\n                poly_buf\n                    = realloc(poly_buf, poly_buf_size * sizeof(double));\n            }\n            for (idx = 0; idx < num_of_poly_coeffs; ++idx) {\n                READ_FROM_PTR_AND_INCREMENT(poly_buf[idx], cur_ptr,\n                                            double);\n            }\n\n            READ_FROM_PTR_AND_INCREMENT(num_of_cheby_coeffs, cur_ptr,\n                                        pcomp_chunk_size_t);\n            if (num_of_cheby_coeffs > 0) {\n                if (cheby_mask_size > cheby_mask_buf_size) {\n                    cheby_mask_buf_size = cheby_mask_size;\n                    cheby_mask_buf = realloc(cheby_mask_buf,\n                                             cheby_mask_buf_size\n                                                 * sizeof(uint8_t));\n                }\n                for (idx = 0; idx < cheby_mask_size; ++idx) {\n                    READ_FROM_PTR_AND_INCREMENT(cheby_mask_buf[idx],\n                                                cur_ptr, uint8_t);\n                }\n\n                if (num_of_cheby_coeffs > cheby_buf_size) {\n                    cheby_buf_size = num_of_cheby_coeffs;\n                    cheby_buf = realloc(\n                        cheby_buf, cheby_buf_size * sizeof(double));\n                }\n                for (idx = 0; idx < num_of_cheby_coeffs; ++idx) {\n                    READ_FROM_PTR_AND_INCREMENT(cheby_buf[idx], cur_ptr,\n                                                double);\n                }\n            }\n\n            (*chunk_array)[chunk_idx] = pcomp_init_compressed_chunk(\n                num_of_samples, num_of_poly_coeffs, poly_buf,\n                num_of_cheby_coeffs, cheby_mask_buf, cheby_buf);\n        }\n        else {\n            if (num_of_samples > uncompr_buf_size) {\n                uncompr_buf_size = num_of_samples;\n                uncompr_buf = realloc(\n                    uncompr_buf, uncompr_buf_size * sizeof(double));\n            }\n            for (idx = 0; idx < num_of_samples; ++idx) {\n                READ_FROM_PTR_AND_INCREMENT(uncompr_buf[idx], cur_ptr,\n                                            double);\n            }\n\n            (*chunk_array)[chunk_idx] = pcomp_init_uncompressed_chunk(\n                num_of_samples, uncompr_buf);\n        }\n    }\n\n    if (poly_buf != NULL)\n        free(poly_buf);\n\n    if (cheby_buf != NULL)\n        free(cheby_buf);\n\n    if (uncompr_buf != NULL)\n        free(uncompr_buf);\n\n    return PCOMP_STAT_SUCCESS;\n}\n", "meta": {"hexsha": "f0f526dd28f3d39f7bf6bb79a5cb454407ebc67c", "size": 78827, "ext": "c", "lang": "C", "max_stars_repo_path": "poly.c", "max_stars_repo_name": "ziotom78/libpolycomp", "max_stars_repo_head_hexsha": "5b292411a7f9b692d4d5225713d7987199b5478f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-06-02T21:41:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-31T05:43:37.000Z", "max_issues_repo_path": "poly.c", "max_issues_repo_name": "ziotom78/libpolycomp", "max_issues_repo_head_hexsha": "5b292411a7f9b692d4d5225713d7987199b5478f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "poly.c", "max_forks_repo_name": "ziotom78/libpolycomp", "max_forks_repo_head_hexsha": "5b292411a7f9b692d4d5225713d7987199b5478f", "max_forks_repo_licenses": ["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.79790238, "max_line_length": 73, "alphanum_fraction": 0.6414807109, "num_tokens": 19349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.3896029607474689}}
{"text": "//\n// Created by Harold on 2020/9/21.\n//\n\n#ifndef M_MATH_M_FILTER_H\n#define M_MATH_M_FILTER_H\n\n#include <gsl/gsl_filter.h>\n#include <gsl/gsl_vector.h>\n\nnamespace M_MATH {\n    class GaussianFilter {\n    public:\n        enum EndpointType {\n            NO_PAD,\n            ZERO_PAD,\n            VALUE_PAD\n        };\n    public:\n        static bool filter(double const* x,\n                           size_t length,\n                           size_t window_size,\n                           double alpha,\n                           EndpointType type,\n                           size_t n_length,\n                           double* n_x,\n                           size_t order);\n    private:\n        static gsl_filter_end_t EndpointType2GSL(EndpointType);\n    };\n\n    gsl_filter_end_t GaussianFilter::EndpointType2GSL(GaussianFilter::EndpointType type) {\n        switch (type) {\n            case NO_PAD:\n                return GSL_FILTER_END_TRUNCATE;\n            case ZERO_PAD:\n                return GSL_FILTER_END_PADZERO;\n            case VALUE_PAD:\n                return GSL_FILTER_END_PADVALUE;\n        }\n        // default is no pad\n        // no padding is performed, and the windows are simply truncated as the end points are approached\n        return GSL_FILTER_END_TRUNCATE;\n    }\n\n    // filter with nth order Gaussian filter, default order = 0\n    bool GaussianFilter::filter(const double *x, size_t length, size_t window_size, double alpha,\n                                GaussianFilter::EndpointType type, size_t n_length, double *n_x,\n                                size_t order = 0) {\n        // workspace\n        gsl_filter_gaussian_workspace *gauss_p = gsl_filter_gaussian_alloc(window_size);\n        if (gauss_p == nullptr)\n            return false;\n        // xx, yy\n        gsl_vector *xx = gsl_vector_alloc(length);\n        gsl_vector *yy = gsl_vector_alloc(length);\n        for (auto i = 0; i < length; ++i) {\n            gsl_vector_set(xx, i, x[i]);\n        }\n\n        /* print kernel to debug\n        // kernel\n        gsl_vector *k = gsl_vector_alloc(window_size);\n        // compute kernel without normalization\n        gsl_filter_gaussian_kernel(alpha, 0, 0, k);\n        // print kernel\n        printf(\"%s\", \"kernel: \");\n        for (auto i = 0; i < window_size; ++i)\n            printf(\"%e \", gsl_vector_get(k, i));\n        printf(\"\\n\");\n        gsl_vector_free(k);\n         */\n\n        // apply filter\n        if (gsl_filter_gaussian(EndpointType2GSL(type), alpha, order, xx, yy, gauss_p) != 0) {\n            gsl_vector_free(xx);\n            gsl_vector_free(yy);\n            gsl_filter_gaussian_free(gauss_p);\n            return false;\n        }\n\n        for (auto i = 0; i < n_length; ++i) {\n            n_x[i] = gsl_vector_get(yy, i);\n        }\n\n        // clean up\n        gsl_vector_free(xx);\n        gsl_vector_free(yy);\n        gsl_filter_gaussian_free(gauss_p);\n\n        return true;\n    }\n}\n\n#endif //M_MATH_M_FILTER_H\n", "meta": {"hexsha": "224194b9c3f996351852d9e9a024fc8df0b8b442", "size": 2953, "ext": "h", "lang": "C", "max_stars_repo_path": "include/m_filter.h", "max_stars_repo_name": "Harold2017/m_math", "max_stars_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-04T12:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T08:00:15.000Z", "max_issues_repo_path": "include/m_filter.h", "max_issues_repo_name": "Harold2017/m_math", "max_issues_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-03T02:50:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T06:32:29.000Z", "max_forks_repo_path": "include/m_filter.h", "max_forks_repo_name": "Harold2017/m_math", "max_forks_repo_head_hexsha": "2815ed395b0c51a6cab2f20754a6edeee44bd495", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-04T12:26:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T12:26:12.000Z", "avg_line_length": 30.7604166667, "max_line_length": 105, "alphanum_fraction": 0.5475787335, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984445, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3894691357525287}}
{"text": "#ifndef _CODE_LIBS_EPFLLIB_INCLUDE_GUARD\n#define _CODE_LIBS_EPFLLIB_INCLUDE_GUARD\n\n//changes to version glm_popdyn_1.0_test2:\n//lookuptable for G(x)=exp(-0.5*DT*c*exp(x/deltaV)) instead of lambda and Plam\n\n\n#ifndef GLM\n#define GLM 0\n#endif\n\n\n#ifndef GLM2\n#define GLM2 2\n#endif\n\n#ifndef GLIF\n#define GLIF 10\n#endif\n\n#ifndef GLIF1\n#define GLIF1 11\n#endif\n\n#ifndef GLIF2\n#define GLIF2 12\n#endif\n\n#ifndef GLIF4\n#define GLIF4 14\n#endif\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <math.h>\n#include <time.h>\n#include <complex.h>\n#include <fftw3.h>\n#include <sys/time.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n\n#define maxisi 2.\n#define PFIRE_MAX 0.99999\n#define PFIRE_MIN 0.00001\n\n\nstruct PopParametersGLM{\n  double tref;\n  double taum;\n  double *taus1; //incoming synaptic time constants, decay time of 1st filter\n  double *taus2; //incoming synaptic time constants, decay time of 2nd filter\n  double *taur1; //incoming synaptic time constants, rise time of 1st filter\n  double *taur2; //incoming synaptic time constants, rise time of 2nd filter\n  double *a1;    //relative weight of fast synaptic current \n  double *a2;    //relative weight of slow synaptic current \n  double mu;\n  double c;\n  double deltaV;\n  double delay;\n  double vth;\n  double u_reset;      //reset potential for u in glif mode\n  int N;         //number of neurons in population\n  double *J;     //incoming synaptic weights\n  double *Iext;  //external input (in mV), i.e. Iext is actually R*I\n  double *tau_theta;\n  double *J_theta; //amplitudes of the N_theta exponential kernels in mV\n  int N_theta;  //number of exponentials for dynamic threshold\n\n  //internal constants\n  int K;\n  int end;\n  int indx;\n  double Em;\n  double Em2;\n  double *E_theta;  //Jtheta*exp(-t/tau_theta)};\n  double *E_theta2;  //exp(-dt/tau_theta)};\n  double *gamma_QR;  //deltaV*(1-exp(-gamma/deltaV))/N; gamma=sum_k Jtheta_k*exp(-t/tautheta_k)\n  double *w1;          // effective weight\n  double *w2;\n  double g;\n  double g2;\n  double dV;  // resolution of voltage grid for lookup table of hazard/firing prob\n  double Vmin;       //min value of voltage grid\n  double Vmax;       //max value of voltage grid (this value is not included, i.e. max is Vmax-dv)\n  double *Gtable;      //lookup table for firing prob P=1-exp(-lam*DT)\n};\n\n\nstruct PopVariablesGLM{\n  double h;\n  double *u;\n  double *Xsyn1; //incoming synaptic currents (filtered with fast decay time, e.g. AMPA, GABA)\n  double *Xsyn2; //incoming synaptic currents (filtered with slow decay time, e.g. NMDA)\n  double *Isyn1; //total incoming synaptic current (sum of Xsyn1+Xsyn2 filtered with short rise-time)\n  double *Isyn2; //total incoming synaptic current (sum of Xsyn1+Xsyn2 filtered with short rise-time)\n  unsigned int *n;\n  double *m0;\n  double *theta;  //threshold kernel\n  double *g; //QR threshold variables\n  double *v;\n  double z;\n  double x;\n  double Gfree;\n  double *G;\n};\n\n\n\n////////////////////////////////////////////////////////////////////////////////\ndouble **dmatrix(long nrow, long ncol);\ndouble *dvector(long n);\nvoid free_dvector(double *v);\nvoid free_dmatrix(double **m);\nvoid free_ivector(int *v);\nunsigned int *uivector(long n);\nvoid free_uivector(unsigned int *v);\n\n\ndouble get_mean(double *x,int n);\nvoid print_matrix1(int N,int M, double A[][M]);\nvoid print_matrix2(double **A,int N,int M);\nvoid print_matrix3(int N,int M, double *A[N]);\nvoid print_pop_parameters(struct PopParametersGLM p[], int Npop);\nunsigned long int random_seed();\nvoid init_synaptic_filters(double **Es1, double **Es2, double **Er1, double **Er2, struct PopParametersGLM p[], int Npop);\nvoid get_inputs(double *input, int k,double **Es1,double **Es2,double **Er1,double **Er2, struct PopParametersGLM p[], struct PopVariablesGLM pop[],int Npop);\ndouble cond_rate(double x,struct PopParametersGLM *p);\nvoid update(struct PopVariablesGLM *pop, double *nmean, double input,gsl_rng *rng,struct PopParametersGLM *p, int mode);\nvoid simulate(int Nbin,double **A,double **rate,struct PopVariablesGLM pop[],gsl_rng *rng,struct PopParametersGLM p[],int Npop, int mode, int dispprog);\ndouble threshold_kernel(double t, struct PopParametersGLM *p);\nvoid init_glm(struct PopParametersGLM p[],struct PopVariablesGLM pop[],int Npop, gsl_rng *rng, int mode);\nvoid free_pop(struct PopVariablesGLM pop[],struct PopParametersGLM p[],int Npop, int mode);\nvoid get_history_size(struct PopParametersGLM p[],int Npop);\nvoid get_psd_pop(double **SA,int Nbin,int Ntrials,struct PopParametersGLM neuron[],int Npop, int mode);\nvoid get_trajectory(double **A,double **rate,int Nbin, int Npop,struct PopParametersGLM neuron[],double dt, double dtbin, int mode, int seed);\nvoid init_population(struct PopParametersGLM p[], int Npop,double tref[], double taum[], double taus1[][Npop], double taus2[][Npop], double taur1[][Npop], double taur2[][Npop], double a1[][Npop], double a2[][Npop], double mu[], double c[], double deltaV[], double delay[], double vth[], double vreset[], int N[], double J[][Npop], double p_conn[][Npop], double **signal, int N_theta[], double J_ref[], double *J_theta[], double *tau_theta[], double sigma[]);\nvoid clean_population(struct PopParametersGLM p[], int Npop);\nvoid get_psd_with_fullparameterlist(double **SA, int Nbin, int Ntrials, int Npop, double *tref, double taum[], double taus1[][Npop], double taus2[][Npop], double taur1[][Npop], double taur2[][Npop], double a1[][Npop], double a2[][Npop], double mu[], double c[], double deltaV[], double delay[], double vth[], double vreset[], int N[], double J[][Npop], double p_conn[][Npop], int N_theta[], double Jref[], double *J_theta[], double *tau_theta[], double sigma[], double dt,double dtbin, int mode);\nvoid get_psd_with_2D_arrays(int Nf, double SA[][Nf], int Ntrials, int Npop, double *tref, double taum[], double taus1[][Npop], double taus2[][Npop], double taur1[][Npop], double taur2[][Npop], double a1[][Npop], double a2[][Npop], double mu[], double c[], double deltaV[], double delay[], double vth[], double vreset[], int N[], double J[][Npop], double p_conn[][Npop], int N_theta[], double Jref[], double J_theta[], double tau_theta[], double sigma[], double dt,double dtbin, int mode);\nvoid get_trajectory_with_fullparameterlist(double **A, double **rate, int Nbin, int Npop, double *tref, double taum[], double taus1[][Npop], double taus2[][Npop], double taur1[][Npop], double taur2[][Npop], double a1[][Npop], double a2[][Npop], double mu[], double c[], double deltaV[], double delay[], double vth[], double vreset[], int N[], double J[][Npop], double p_conn[][Npop], double **signal, int N_theta[], double Jref[], double *J_theta[], double *tau_theta[], double sigma[], double dt,double dtbin, int mode, int seed);\nvoid get_trajectory_with_2D_arrays(int Nbin, double A[][Nbin], double rate[][Nbin], int Npop, double *tref, double taum[], double taus1[][Npop], double taus2[][Npop], double taur1[][Npop], double taur2[][Npop], double a1[][Npop], double a2[][Npop], double mu[], double c[], double deltaV[], double delay[], double vth[], double vreset[], int N[], double J[][Npop], double p_conn[][Npop], double s[][Nbin], int N_theta[], double Jref[], double J_theta[], double tau_theta[], double sigma[], double dt,double dtbin, int mode, int seed);\n////////////////////////////////////////////////////////////////////////////////\n\n\n\n\n\n\n\n\n# endif // include guard\n", "meta": {"hexsha": "91525167879263ffb49081954bee754a300e6cce", "size": 7382, "ext": "h", "lang": "C", "max_stars_repo_path": "libs/EPFLLib/epfl.h", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "libs/EPFLLib/epfl.h", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "libs/EPFLLib/epfl.h", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 47.3205128205, "max_line_length": 534, "alphanum_fraction": 0.7014359252, "num_tokens": 2093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8519527982093666, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.3894589050654271}}
{"text": "#include <stdlib.h>\n#include <complex.h>\n#include <float.h>\n#include <math.h>\n#include <string.h>\n\n#ifdef _MACOSX\n#include <Accelerate/Accelerate.h>\n#else\n#include <cblas.h>\n#endif\n\n#include \"fastsphere.h\"\n#include \"spreflect.h\"\n#include \"translator.h\"\n#include \"scatmat.h\"\n#include \"fsht.h\"\n#include \"farfield.h\"\n#include \"util.h\"\n\n/* Reflect incoming plane waves from the surfaces of all spheres. */\nint sprflpw (complex double *rhs, spscat *spl, int nsph, shdata *shtr) {\n\tint i, nterm;\n\tcomplex double *vptr;\n\tspscat *sp;\n\n\tnterm = shtr->ntheta * shtr->nphi;\n\n#pragma omp parallel for private(i,vptr,sp) default(shared)\n\tfor (i = 0; i < nsph; ++i) {\n\t\tsp = spl + i;\n\t\tvptr = rhs + i * nterm;\n\n\t\t/* Multiply by the reflection coefficient in SH space. */\n\t\tffsht (vptr, shtr, sp->spdesc->deg);\n\t\tspreflect (vptr, vptr, (spl + i)->spdesc->reflect,\n\t\t\t\tsp->spdesc->deg, shtr->nphi, 0, 1);\n\t\tifsht (vptr, shtr, sp->spdesc->deg);\n\t}\n\n\treturn nsph;\n}\n\n/* Compute translations between all spheres. Augments the output vector, does\n * not overwrite it. */\nint sptrans (complex double *vout, complex double *vin,\n\t\tint nsph, trdesc *trans, shdata *shtr) {\n\tint nterm, nsq;\n\n\tnterm = shtr->ntheta * shtr->nphi;\n\tnsq = nsph * nsph;\n\n\t/* Perform the translations. */\n#pragma omp parallel default(shared)\n{\n\tcomplex double *voptr, *viptr;\n\tint i, j, off, k;\n\n#pragma omp for\n\tfor (off = 0; off < nsq; ++off) {\n\t\tj = off / nsph;\t/* Source sphere. */\n\t\ti = off % nsph;\t/* Destination sphere. */\n\n\t\t/* Don't bother with self-translations. Also ignore dense\n\t\t * translations for the moment. */\n\t\tif (i == j || trans[off].type != TRPLANE) continue;\n\n\t\t/* Do the diagonal, plane-wave translation. */\n\t\tvoptr = vout + i * nterm;\n\t\tviptr = vin + j * nterm;\n\t\t/* Copy to output, but only one thread at a time. */\n#pragma omp critical(outplane)\n\t\tfor (k = 0; k < nterm; ++k) \n\t\t\tvoptr[k] += trans[off].trdata[k] * viptr[k];\n\t}\n}\n\n\treturn nsph;\n}\n\n/* Compute the MVP between the scattering matrix and a specified vector. */\nint scatmat (complex double *vout, complex double *vin, spscat *spl,\n\t\tint nsph, trdesc *trans, shdata *shtr) {\n\tint nterm, n, i;\n\n\tnterm = shtr->ntheta * shtr->nphi;\n\tn = nterm * nsph;\n\n\t/* Initialize the output bufer. */\n\tmemset (vout, 0, n * sizeof(complex double));\n\n\t/* Compute the spherical translations. */\n\tsptrans (vout, vin, nsph, trans, shtr);\n\n\t/* Compute the reflections of plane waves at sphere surfaces. */\n\tsprflpw (vout, spl, nsph, shtr);\n\n\t/* Subtract the incoming field from the outgoing field. */\n#pragma omp parallel for private(i) default(shared)\n\tfor (i = 0; i < n; ++i) vout[i] = vin[i] - vout[i];\n\n\treturn nsph;\n}\n\nint bicgstab (complex double *sol, complex double *rhs, int guess, spscat *spl,\n\t\tint nsph, trdesc *trans, shdata *shtr, itconf *itc) {\n\tint i, j, n, nterm;\n\tcomplex double *r, *rhat, *v, *p, *t;\n\tcomplex double rho, alpha, omega, beta;\n\tdouble err, rhn;\n\n\tnterm = shtr->ntheta * shtr->nphi;\n\tn = nterm * nsph;\n\n\trho = alpha = omega = 1.;\n\n\t/* Allocate and zero the work arrays. */\n\tr = calloc (5 * n, sizeof(complex double));\n\trhat = r + n;\n\tv = rhat + n;\n\tp = v + n;\n\tt = p + n;\n\n\t/* Compute the norm of the right-hand side for residual scaling. */\n\trhn = cblas_dznrm2 (n, rhs, 1);\n\n\t/* Compute the inital matrix-vector product for the input guess. */\n\tif (guess) scatmat (r, sol, spl, nsph, trans, shtr);\n\n\t/* Subtract from the RHS to form the residual. */\n#pragma omp parallel for default(shared) private(j)\n\tfor (j = 0; j < n; ++j) r[j] = rhs[j] - r[j];\n\n\tif (!guess) memset (sol, 0, n * sizeof(complex double));\n\t\t\n\t/* Copy the initial residual as the test vector. */\n\tmemcpy (rhat, r, n * sizeof(complex double));\n\n\t/* Find the norm of the initial residual. */\n\terr = cblas_dznrm2(n, r, 1) / rhn;\n\tprintf (\"True residual: %g\\n\", err);\n\n\t/* Run iterations until convergence or the maximum is reached. */\n\tfor (i = 0; i < itc->iter && err > itc->eps; ++i) {\n\t\t/* Pre-compute portion of beta from previous iteration. */\n\t\tbeta = alpha / (rho * omega);\n\t\t/* Compute rho for this iteration. */\n\t\trho = pardot (rhat, r, n);\n\t\t/* Include the missing factor in beta. */\n\t\tbeta *= rho;\n\n\t\t/* Update the search vector. */\n#pragma omp parallel for default(shared) private(j)\n\t\tfor (j = 0; j < n; ++j)\n\t\t\tp[j] = r[j] + beta * (p[j] - omega * v[j]);\n\n\t\t/* Compute the first search step, v = A * p. */\n\t\tscatmat (v, p, spl, nsph, trans, shtr);\n\n\t\t/* Compute the next alpha. */\n\t\talpha = rho / pardot (rhat, v, n);\n\n#pragma omp parallel for default(shared) private(j)\n\t\tfor (j = 0; j < n; ++j) {\n\t\t\t/* Update the solution vector. */\n\t\t\tsol[j] += alpha * p[j];\n\t\t\t/* Update the residual vector. */\n\t\t\tr[j] -= alpha * v[j];\n\t\t}\n\n\t\t/* Compute the scaled residual norm and stop if convergence\n\t\t * has been achieved. */\n\t\terr = cblas_dznrm2 (n, r, 1) / rhn;\n\t\tprintf (\"BiCG-STAB(%0.1f): %g\\n\", 0.5 + i, err);\n\t\tif (err < itc->eps) break;\n\n\t\t/* Compute the next search step, t = A * r. */\n\t\tscatmat (t, r, spl, nsph, trans, shtr);\n\n\t\t/* Compute the update direction. */\n\t\tomega = pardot (t, r, n) / pardot (t, t, n);\n\n\t\t/* Update both the residual and the solution guess. */\n#pragma omp parallel for default(shared) private(j)\n\t\tfor (j = 0; j < n; ++j) {\n\t\t\t/* Update the solution vector. */\n\t\t\tsol[j] += omega * r[j];\n\t\t\t/* Update the residual vector. */\n\t\t\tr[j] -= omega * t[j];\n\t\t}\n\t\n\t\t/* Compute the scaled residual norm. */\n\t\terr = cblas_dznrm2 (n, r, 1) / rhn;\n\t\tprintf (\"BiCG-STAB(%d): %g\\n\", i + 1, err);\n\t}\n\n\tfree (r);\n\treturn i;\n}\n\nint gmres (complex double *sol, complex double *rhs, int guess, spscat *spl,\n\t\tint nsph, trdesc *trans, shdata *shtr, itconf *itc) {\n\tint nterm = shtr->ntheta * shtr->nphi, n = nterm * nsph;\n\tlong lwork;\n\tint i, j, one = 1, mit = itc->iter;\n\tcomplex double *h, *v, *beta, *y;\n\tcomplex double *vp, *hp, *s, cr, cone = 1.;\n\tdouble rhn, err, *c;\n\n\t/* Allocate space for all required complex vectors. */\n\tlwork = (mit + 1) * (mit + n + 1) + mit;\n\tv = calloc (lwork, sizeof(complex double));\t/* The Krylov subspace. */\n\tbeta = v + n * (mit + 1);\t\t/* The least-squares RHS. */\n\th = beta + mit + 1;\t\t\t/* The upper Hessenberg matrix. */\n\ts = h + (mit + 1) * mit;\t\t/* Givens rotation sines. */\n\n\t/* Allocate space for the Givens rotation cosines. */\n\tc = malloc (mit * sizeof(double));\n\n\t/* Compute the norm of the RHS for residual scaling. */\n\trhn = cblas_dznrm2 (n, rhs, 1);\n\n\t/* Compute the initial matrix-vector product for the input guess. */\n\tif (guess) scatmat (v, sol, spl, nsph, trans, shtr);\n\n\t/* Subtract from the RHS to form the residual. */\n#pragma omp parallel for default(shared) private(j)\n\tfor (j = 0; j < n; ++j) v[j] = rhs[j] - v[j];\n\n\t/* Zero the initial guess if one wasn't provided. */\n\tif (!guess) memset (sol, 0, n * sizeof(complex double));\n\n\t/* Find the norm of the initial residual. */\n\terr = cblas_dznrm2(n, v, 1);\n\n\t/* Construct the initial Arnoldi vector by normalizing the residual. */\n#pragma omp parallel for default(shared) private(j)\n\tfor (j = 0; j < n; ++j) v[j] /= err;\n\n\t/* Construct the vector beta for the minimization problem. */\n\tbeta[0] = err;\n\n\t/* Report the RRE. */\n\terr /= rhn;\n\tprintf (\"True residual: %g\\n\", err);\n\n\tfor (i = 0; i < mit && err > itc->eps; ++i) {\n\t\t/* Point to the working space for this iteration. */\n\t\tvp = v + i * n;\n\t\thp = h + i * (mit + 1);\n\n\t\t/* Compute the next expansion of the Krylov space. */\n\t\tscatmat (vp + n, vp, spl, nsph, trans, shtr);\n\t\t/* Perform modified Gram-Schmidt to orthogonalize the basis. */\n\t\t/* This also builds the Hessenberg matrix column. */\n\t\tcmgs (vp + n, hp, v, n, i + 1);\n\t\t/* Compute the norm of the next basis vector. */\n\t\thp[i + 1] = cblas_dznrm2(n, vp + n, 1);\n\n\t\t/* Avoid breakdown. */\n\t\tif (cabs(hp[i + 1]) <  DBL_EPSILON) {\n\t\t\t++i;\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Normalize the basis vector. */\n#pragma omp parallel for default(shared) private(j)\n\t\tfor (j = 0; j < n; ++j) vp[n + j] /= creal(hp[i + 1]);\n\n\t\t/* Apply previous Givens rotations to the Hessenberg column. */\n\t\tfor (j = 0; j < i; ++j) \n\t\t\tzrot_ (&one, (void *)(hp + j), &one,\n\t\t\t\t\t(void *)(hp + j + 1), &one,\n\t\t\t\t\t(void *)(c + j), (void *)(s + j));\n\n\t\t/* Compute the Givens rotation for the current iteration. */\n\t\tzlartg_ ((void *)(hp + i), (void *)(hp + i + 1), \n\t\t\t\t(void *)(c + i), (void *)(s + i), (void *)(&cr));\n\t\t/* Apply the current Givens rotation to the Hessenberg column. */\n\t\thp[i] = cr;\n\t\thp[i + 1] = 0;\n\t\t/* Perform the rotation on the vector beta. */\n\t\tzrot_ (&one, (void *)(beta + i), &one, \n\t\t\t\t(void *)(beta + i + 1), &one, \n\t\t\t\t(void *)(c + i), (void *)(s + i));\n\n\t\t/* Estimate the RRE for this iteration. */\n\t\terr = cabs(beta[i + 1]) / rhn;\n\t\tprintf (\"GMRES(%d): %g\\n\", i, err);\n\t}\n\n\t/* If there were any GMRES iterations, update the solution. */\n\tif (i > 0) {\n\t\t/* Compute the minimizer of the least-squares problem. */\n\t\tcblas_ztrsv (CblasColMajor, CblasUpper, CblasNoTrans,\n\t\t\t\tCblasNonUnit, i, h, mit + 1, beta, 1);\n\t\t\n\t\t/* Compute the update to the solution. */\n\t\tcblas_zgemv (CblasColMajor, CblasNoTrans, n, i,\n\t\t\t\t&cone, v, n, beta, 1, &cone, sol, 1);\n\t}\n\n\tfree (v);\n\tfree (c);\n\n\treturn i;\n}\n", "meta": {"hexsha": "a4d1cc2ff184a5c9f7202e7f3461f4fd6d3789e0", "size": 9038, "ext": "c", "lang": "C", "max_stars_repo_path": "scatmat.c", "max_stars_repo_name": "ahesford/fastsphere", "max_stars_repo_head_hexsha": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2", "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": "scatmat.c", "max_issues_repo_name": "ahesford/fastsphere", "max_issues_repo_head_hexsha": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scatmat.c", "max_forks_repo_name": "ahesford/fastsphere", "max_forks_repo_head_hexsha": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2", "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.3441558442, "max_line_length": 79, "alphanum_fraction": 0.6120823191, "num_tokens": 3033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.38916677921477244}}
{"text": "#include <math.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdbool.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <time.h>\n#include <string.h>\n//#include <pthread.h>\n#include <omp.h>\n#include <complex.h>\n#include <fftw3.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_roots.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n\n#include \"21cmFAST.h\"\n#include \"exceptions.h\"\n#include \"logger.h\"\n#include \"Constants.h\"\n#include \"Globals.h\"\n#include \"indexing.c\"\n#include \"UsefulFunctions.c\"\n#include \"ps.c\"\n#include \"dft.c\"\n#include \"PerturbField.c\"\n#include \"bubble_helper_progs.c\"\n#include \"elec_interp.c\"\n#include \"heating_helper_progs.c\"\n#include \"recombinations.c\"\n#include \"IonisationBox.c\"\n#include \"SpinTemperatureBox.c\"\n#include \"BrightnessTemperatureBox.c\"\n#include \"FindHaloes.c\"\n#include \"PerturbHaloField.c\"\n\n\n\nvoid adj_complex_conj(fftwf_complex *HIRES_box, struct UserParams *user_params, struct CosmoParams *cosmo_params){\n    /*****  Adjust the complex conjugate relations for a real array  *****/\n\n    int i, j, k;\n\n    // corners\n    HIRES_box[C_INDEX(0,0,0)] = 0;\n    HIRES_box[C_INDEX(0,0,MIDDLE)] = crealf(HIRES_box[C_INDEX(0,0,MIDDLE)]);\n    HIRES_box[C_INDEX(0,MIDDLE,0)] = crealf(HIRES_box[C_INDEX(0,MIDDLE,0)]);\n    HIRES_box[C_INDEX(0,MIDDLE,MIDDLE)] = crealf(HIRES_box[C_INDEX(0,MIDDLE,MIDDLE)]);\n    HIRES_box[C_INDEX(MIDDLE,0,0)] = crealf(HIRES_box[C_INDEX(MIDDLE,0,0)]);\n    HIRES_box[C_INDEX(MIDDLE,0,MIDDLE)] = crealf(HIRES_box[C_INDEX(MIDDLE,0,MIDDLE)]);\n    HIRES_box[C_INDEX(MIDDLE,MIDDLE,0)] = crealf(HIRES_box[C_INDEX(MIDDLE,MIDDLE,0)]);\n    HIRES_box[C_INDEX(MIDDLE,MIDDLE,MIDDLE)] = crealf(HIRES_box[C_INDEX(MIDDLE,MIDDLE,MIDDLE)]);\n\n    // do entire i except corners\n#pragma omp parallel shared(HIRES_box) private(i,j,k) num_threads(user_params->N_THREADS)\n    {\n#pragma omp for\n        for (i=1; i<MIDDLE; i++){\n            // just j corners\n            for (j=0; j<=MIDDLE; j+=MIDDLE){\n                for (k=0; k<=MIDDLE; k+=MIDDLE){\n                    HIRES_box[C_INDEX(i,j,k)] = conjf(HIRES_box[C_INDEX((user_params->DIM)-i,j,k)]);\n                }\n            }\n\n            // all of j\n            for (j=1; j<MIDDLE; j++){\n                for (k=0; k<=MIDDLE; k+=MIDDLE){\n                    HIRES_box[C_INDEX(i,j,k)] = conjf(HIRES_box[C_INDEX((user_params->DIM)-i,(user_params->DIM)-j,k)]);\n                    HIRES_box[C_INDEX(i,(user_params->DIM)-j,k)] = conjf(HIRES_box[C_INDEX((user_params->DIM)-i,j,k)]);\n                }\n            }\n        } // end loop over i\n    }\n\n    // now the i corners\n#pragma omp parallel shared(HIRES_box) private(i,j,k) num_threads(user_params->N_THREADS)\n    {\n#pragma omp for\n        for (i=0; i<=MIDDLE; i+=MIDDLE){\n            for (j=1; j<MIDDLE; j++){\n                for (k=0; k<=MIDDLE; k+=MIDDLE){\n                    HIRES_box[C_INDEX(i,j,k)] = conjf(HIRES_box[C_INDEX(i,(user_params->DIM)-j,k)]);\n                }\n            }\n        } // end loop over remaining j\n    }\n}\n\n// Re-write of init.c for original 21cmFAST\n\nint ComputeInitialConditions(\n    unsigned long long random_seed, struct UserParams *user_params,\n    struct CosmoParams *cosmo_params, struct InitialConditions *boxes\n){\n\n//     Generates the initial conditions: gaussian random density field (user_params->DIM^3) as well as the equal or lower resolution velocity fields, and smoothed density field (user_params->HII_DIM^3).\n//\n//     Author: Andrei Mesinger\n//     Date: 9/29/06\n\n    int status;\n\n    Try{ // This Try wraps the entire function so we don't indent.\n\n    // Makes the parameter structs visible to a variety of functions/macros\n    // Do each time to avoid Python garbage collection issues\n    Broadcast_struct_global_PS(user_params,cosmo_params);\n    Broadcast_struct_global_UF(user_params,cosmo_params);\n\n    unsigned long long ct;\n    int n_x, n_y, n_z, i, j, k, ii, thread_num, dimension;\n    float k_x, k_y, k_z, k_mag, p, a, b, k_sq;\n    double pixel_deltax;\n    float p_vcb, vcb_i;\n\n    float f_pixel_factor;\n\n    gsl_rng * r[user_params->N_THREADS];\n    gsl_rng * rseed = gsl_rng_alloc(gsl_rng_mt19937); // An RNG for generating seeds for multithreading\n\n    gsl_rng_set(rseed, random_seed);\n\n    omp_set_num_threads(user_params->N_THREADS);\n\n    switch(user_params->PERTURB_ON_HIGH_RES) {\n        case 0:\n            dimension = user_params->HII_DIM;\n            break;\n        case 1:\n            dimension = user_params->DIM;\n            break;\n    }\n\n    // ************  INITIALIZATION ********************** //\n    unsigned int seeds[user_params->N_THREADS];\n\n    // For multithreading, seeds for the RNGs are generated from an initial RNG (based on the input random_seed) and then shuffled (Author: Fred Davies)\n    int num_int = INT_MAX/16;\n    unsigned int *many_ints = (unsigned int *)malloc((size_t)(num_int*sizeof(unsigned int))); // Some large number of possible integers\n    for (i=0; i<num_int; i++) {\n        many_ints[i] = i;\n    }\n\n    gsl_ran_choose(rseed, seeds, user_params->N_THREADS, many_ints, num_int, sizeof(unsigned int)); // Populate the seeds array from the large list of integers\n    gsl_ran_shuffle(rseed, seeds, user_params->N_THREADS, sizeof(unsigned int)); // Shuffle the randomly selected integers\n\n    int checker;\n\n    checker = 0;\n    // seed the random number generators\n    for (thread_num = 0; thread_num < user_params->N_THREADS; thread_num++){\n        switch (checker){\n            case 0:\n                r[thread_num] = gsl_rng_alloc(gsl_rng_mt19937);\n                gsl_rng_set(r[thread_num], seeds[thread_num]);\n                break;\n            case 1:\n                r[thread_num] = gsl_rng_alloc(gsl_rng_gfsr4);\n                gsl_rng_set(r[thread_num], seeds[thread_num]);\n                break;\n            case 2:\n                r[thread_num] = gsl_rng_alloc(gsl_rng_cmrg);\n                gsl_rng_set(r[thread_num], seeds[thread_num]);\n                break;\n            case 3:\n                r[thread_num] = gsl_rng_alloc(gsl_rng_mrg);\n                gsl_rng_set(r[thread_num], seeds[thread_num]);\n                break;\n            case 4:\n                r[thread_num] = gsl_rng_alloc(gsl_rng_taus2);\n                gsl_rng_set(r[thread_num], seeds[thread_num]);\n                break;\n        } // end switch\n\n        checker += 1;\n\n        if(checker==5) {\n            checker = 0;\n        }\n    }\n\n    free(many_ints);\n\n    // allocate array for the k-space and real-space boxes\n    fftwf_complex *HIRES_box = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n    fftwf_complex *HIRES_box_saved = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n\n    // allocate array for the k-space and real-space boxes for vcb\n    fftwf_complex *HIRES_box_vcb_saved;\n    // HIRES_box_vcb_saved may be needed if FFTW_Wisdom doesn't exist -- currently unused\n    // but I am not going to allocate it until I am certain I needed it.\n\n\n\n\n    // find factor of HII pixel size / deltax pixel size\n    f_pixel_factor = user_params->DIM/(float)user_params->HII_DIM;\n\n    // ************  END INITIALIZATION ****************** //\n    LOG_DEBUG(\"Finished initialization.\");\n    // ************ CREATE K-SPACE GAUSSIAN RANDOM FIELD *********** //\n\n    init_ps();\n\n#pragma omp parallel shared(HIRES_box,r) \\\n                    private(n_x,n_y,n_z,k_x,k_y,k_z,k_mag,p,a,b,p_vcb) num_threads(user_params->N_THREADS)\n    {\n#pragma omp for\n        for (n_x=0; n_x<user_params->DIM; n_x++){\n            // convert index to numerical value for this component of the k-mode: k = (2*pi/L) * n\n            if (n_x>MIDDLE)\n                k_x =(n_x-user_params->DIM) * DELTA_K;  // wrap around for FFT convention\n            else\n                k_x = n_x * DELTA_K;\n\n            for (n_y=0; n_y<user_params->DIM; n_y++){\n                // convert index to numerical value for this component of the k-mode: k = (2*pi/L) * n\n                if (n_y>MIDDLE)\n                    k_y =(n_y-user_params->DIM) * DELTA_K;\n                else\n                    k_y = n_y * DELTA_K;\n\n                // since physical space field is real, only half contains independent modes\n                for (n_z=0; n_z<=MIDDLE; n_z++){\n                    // convert index to numerical value for this component of the k-mode: k = (2*pi/L) * n\n                    k_z = n_z * DELTA_K;\n\n                    // now get the power spectrum; remember, only the magnitude of k counts (due to issotropy)\n                    // this could be used to speed-up later maybe\n                    k_mag = sqrt(k_x*k_x + k_y*k_y + k_z*k_z);\n                    p = power_in_k(k_mag);\n\n                    // ok, now we can draw the values of the real and imaginary part\n                    // of our k entry from a Gaussian distribution\n                    if(user_params->NO_RNG) {\n                        a = 1.0;\n                        b = -1.0;\n                    }\n                    else {\n                        a = gsl_ran_ugaussian(r[omp_get_thread_num()]);\n                        b = gsl_ran_ugaussian(r[omp_get_thread_num()]);\n                    }\n\n                    HIRES_box[C_INDEX(n_x, n_y, n_z)] = sqrt(VOLUME*p/2.0) * (a + b*I);\n\n                }\n            }\n        }\n    }\n    LOG_DEBUG(\"Drawn random fields.\");\n\n    // *****  Adjust the complex conjugate relations for a real array  ***** //\n    adj_complex_conj(HIRES_box,user_params,cosmo_params);\n\n    memcpy(HIRES_box_saved, HIRES_box, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n\n    // FFT back to real space\n    int stat = dft_c2r_cube(user_params->USE_FFTW_WISDOM, user_params->DIM, user_params->N_THREADS, HIRES_box);\n    if(stat>0) Throw(stat);\n    LOG_DEBUG(\"FFT'd hires boxes.\");\n\n#pragma omp parallel shared(boxes,HIRES_box) private(i,j,k) num_threads(user_params->N_THREADS)\n    {\n#pragma omp for\n        for (i=0; i<user_params->DIM; i++){\n            for (j=0; j<user_params->DIM; j++){\n                for (k=0; k<user_params->DIM; k++){\n                    *((float *)boxes->hires_density + R_INDEX(i,j,k)) = *((float *)HIRES_box + R_FFT_INDEX(i,j,k))/VOLUME;\n                }\n            }\n        }\n    }\n\n    // *** If required, let's also create a lower-resolution version of the density field  *** //\n    memcpy(HIRES_box, HIRES_box_saved, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n\n\n    // Only filter if we are perturbing on the low-resolution grid\n    if(!user_params->PERTURB_ON_HIGH_RES) {\n        if (user_params->DIM != user_params->HII_DIM) {\n            filter_box(HIRES_box, 0, 0, L_FACTOR*user_params->BOX_LEN/(user_params->HII_DIM+0.0));\n        }\n\n        // FFT back to real space\n        dft_c2r_cube(user_params->USE_FFTW_WISDOM, user_params->DIM, user_params->N_THREADS, HIRES_box);\n\n        // Renormalise the FFT'd box (sample the high-res box if we are perturbing on the low-res grid)\n#pragma omp parallel shared(boxes,HIRES_box,f_pixel_factor) private(i,j,k) num_threads(user_params->N_THREADS)\n        {\n#pragma omp for\n            for (i=0; i<user_params->HII_DIM; i++){\n                for (j=0; j<user_params->HII_DIM; j++){\n                    for (k=0; k<user_params->HII_DIM; k++){\n                        boxes->lowres_density[HII_R_INDEX(i,j,k)] =\n                        *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5),\n                                                           (unsigned long long)(j*f_pixel_factor+0.5),\n                                                           (unsigned long long)(k*f_pixel_factor+0.5)))/VOLUME;\n                    }\n                }\n            }\n        }\n    }\n\n\n    // ******* Relative Velocity part ******* //\n  if(user_params->USE_RELATIVE_VELOCITIES){\n    //JBM: We use the memory allocated to HIRES_box as it's free.\n\n      for(ii=0;ii<3;ii++) {\n\n        memcpy(HIRES_box, HIRES_box_saved, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n\n#pragma omp parallel shared(HIRES_box,ii) private(n_x,n_y,n_z,k_x,k_y,k_z,k_mag,p,p_vcb) num_threads(user_params->N_THREADS)\n        {\n#pragma omp for\n            for (n_x=0; n_x<user_params->DIM; n_x++){\n                if (n_x>MIDDLE)\n                    k_x =(n_x-user_params->DIM) * DELTA_K;  // wrap around for FFT convention\n                else\n                    k_x = n_x * DELTA_K;\n\n                for (n_y=0; n_y<user_params->DIM; n_y++){\n                    if (n_y>MIDDLE)\n                        k_y =(n_y-user_params->DIM) * DELTA_K;\n                    else\n                        k_y = n_y * DELTA_K;\n\n                    for (n_z=0; n_z<=MIDDLE; n_z++){\n                        k_z = n_z * DELTA_K;\n\n                        k_mag = sqrt(k_x*k_x + k_y*k_y + k_z*k_z);\n                        p = power_in_k(k_mag);\n                        p_vcb = power_in_vcb(k_mag);\n\n\n                        // now set the velocities\n                        if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode\n                            HIRES_box[0] = 0;\n                        }\n                        else{\n                            if(ii==0) {\n                                HIRES_box[C_INDEX(n_x,n_y,n_z)] *= I * k_x/k_mag * sqrt(p_vcb/p) * C_KMS;\n                            }\n                            if(ii==1) {\n                                HIRES_box[C_INDEX(n_x,n_y,n_z)] *= I * k_y/k_mag * sqrt(p_vcb/p) * C_KMS;\n                            }\n                            if(ii==2) {\n                                HIRES_box[C_INDEX(n_x,n_y,n_z)] *= I * k_z/k_mag * sqrt(p_vcb/p) * C_KMS;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n\n//we only care about the lowres vcb box, so we filter it directly.\n      if (user_params->DIM != user_params->HII_DIM) {\n          filter_box(HIRES_box, 0, 0, L_FACTOR*user_params->BOX_LEN/(user_params->HII_DIM+0.0));\n      }\n\n//fft each velocity component back to real space\n      dft_c2r_cube(user_params->USE_FFTW_WISDOM, user_params->DIM, user_params->N_THREADS, HIRES_box);\n\n\n\n      #pragma omp parallel shared(boxes,HIRES_box,f_pixel_factor,ii) private(i,j,k,vcb_i) num_threads(user_params->N_THREADS)\n              {\n      #pragma omp for\n                  for (i=0; i<user_params->HII_DIM; i++){\n                      for (j=0; j<user_params->HII_DIM; j++){\n                          for (k=0; k<user_params->HII_DIM; k++){\n                            vcb_i = *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5),\n                                                             (unsigned long long)(j*f_pixel_factor+0.5),\n                                                             (unsigned long long)(k*f_pixel_factor+0.5)));\n                            boxes->lowres_vcb[HII_R_INDEX(i,j,k)] += vcb_i*vcb_i;\n                          }\n                      }\n                  }\n              }\n\n\n    }\n\n\n//now we take the sqrt of that and normalize the FFT\n    for (i=0; i<user_params->HII_DIM; i++){\n        for (j=0; j<user_params->HII_DIM; j++){\n            for (k=0; k<user_params->HII_DIM; k++){\n              boxes->lowres_vcb[HII_R_INDEX(i,j,k)] = sqrt(boxes->lowres_vcb[HII_R_INDEX(i,j,k)])/VOLUME;\n            }\n        }\n    }\n\n  }\n    LOG_DEBUG(\"Completed Relative velocities.\");\n    // ******* End of Relative Velocity part ******* //\n\n\n\n\n    // Now look at the velocities\n\n    for(ii=0;ii<3;ii++) {\n\n        memcpy(HIRES_box, HIRES_box_saved, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n        // Now let's set the velocity field/dD/dt (in comoving Mpc)\n\n#pragma omp parallel shared(HIRES_box,ii) private(n_x,n_y,n_z,k_x,k_y,k_z,k_sq) num_threads(user_params->N_THREADS)\n        {\n#pragma omp for\n            for (n_x=0; n_x<user_params->DIM; n_x++){\n                if (n_x>MIDDLE)\n                    k_x =(n_x-user_params->DIM) * DELTA_K;  // wrap around for FFT convention\n                else\n                    k_x = n_x * DELTA_K;\n\n                for (n_y=0; n_y<user_params->DIM; n_y++){\n                    if (n_y>MIDDLE)\n                        k_y =(n_y-user_params->DIM) * DELTA_K;\n                    else\n                        k_y = n_y * DELTA_K;\n\n                    for (n_z=0; n_z<=MIDDLE; n_z++){\n                        k_z = n_z * DELTA_K;\n\n                        k_sq = k_x*k_x + k_y*k_y + k_z*k_z;\n\n                        // now set the velocities\n                        if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode\n                            HIRES_box[0] = 0;\n                        }\n                        else{\n                            if(ii==0) {\n                                HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_x*I/k_sq/VOLUME;\n                            }\n                            if(ii==1) {\n                                HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_y*I/k_sq/VOLUME;\n                            }\n                            if(ii==2) {\n                                HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_z*I/k_sq/VOLUME;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        // Filter only if we require perturbing on the low-res grid\n        if(!user_params->PERTURB_ON_HIGH_RES) {\n            if (user_params->DIM != user_params->HII_DIM) {\n                filter_box(HIRES_box, 0, 0, L_FACTOR*user_params->BOX_LEN/(user_params->HII_DIM+0.0));\n            }\n        }\n\n        dft_c2r_cube(user_params->USE_FFTW_WISDOM, user_params->DIM, user_params->N_THREADS, HIRES_box);\n\n        // now sample to lower res\n        // now sample the filtered box\n#pragma omp parallel shared(boxes,HIRES_box,f_pixel_factor,ii,dimension) private(i,j,k) num_threads(user_params->N_THREADS)\n        {\n#pragma omp for\n            for (i=0; i<dimension; i++){\n                for (j=0; j<dimension; j++){\n                    for (k=0; k<dimension; k++){\n                        if(user_params->PERTURB_ON_HIGH_RES) {\n                            if(ii==0) {\n                                boxes->hires_vx[R_INDEX(i,j,k)] =\n                                *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),\n                                                                   (unsigned long long)(j),\n                                                                   (unsigned long long)(k)));\n                            }\n                            if(ii==1) {\n                                boxes->hires_vy[R_INDEX(i,j,k)] =\n                                *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),\n                                                                   (unsigned long long)(j),\n                                                                   (unsigned long long)(k)));\n                            }\n                            if(ii==2) {\n                                boxes->hires_vz[R_INDEX(i,j,k)] =\n                                *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),\n                                                                   (unsigned long long)(j),\n                                                                   (unsigned long long)(k)));\n                            }\n                        }\n                        else {\n                            if(ii==0) {\n                                boxes->lowres_vx[HII_R_INDEX(i,j,k)] =\n                                *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5),\n                                                                   (unsigned long long)(j*f_pixel_factor+0.5),\n                                                                   (unsigned long long)(k*f_pixel_factor+0.5)));\n                            }\n                            if(ii==1) {\n                                boxes->lowres_vy[HII_R_INDEX(i,j,k)] =\n                                *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5),\n                                                                   (unsigned long long)(j*f_pixel_factor+0.5),\n                                                                   (unsigned long long)(k*f_pixel_factor+0.5)));\n                            }\n                            if(ii==2) {\n                                boxes->lowres_vz[HII_R_INDEX(i,j,k)] =\n                                *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5),\n                                                                   (unsigned long long)(j*f_pixel_factor+0.5),\n                                                                   (unsigned long long)(k*f_pixel_factor+0.5)));\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    LOG_DEBUG(\"Done Inverse FT.\");\n\n    // * *************************************************** * //\n    // *              BEGIN 2LPT PART                        * //\n    // * *************************************************** * //\n\n    // Generation of the second order Lagrangian perturbation theory (2LPT) corrections to the ZA\n    // reference: Scoccimarro R., 1998, MNRAS, 299, 1097-1118 Appendix D\n\n    // Parameter set in ANAL_PARAMS.H\n    if(user_params->USE_2LPT){\n\n        // use six supplementary boxes to store the gradients of phi_1 (eq. D13b)\n        // Allocating the boxes\n#define PHI_INDEX(i, j) ((int) ((i) - (j)) + 3*((j)) - ((int)(j))/2  )\n        // ij -> INDEX\n        // 00 -> 0\n        // 11 -> 3\n        // 22 -> 5\n        // 10 -> 1\n        // 20 -> 2\n        // 21 -> 4\n\n        fftwf_complex *phi_1 = (fftwf_complex *) fftwf_malloc(sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n\n        // First generate the ii,jj phi_1 boxes\n\n        int phi_component;\n\n        float component_ii,component_jj,component_ij;\n\n        // Indexing for the various phy components\n        int phi_directions[3][2] = {{0,1},{0,2},{1,2}};\n\n#pragma omp parallel shared(HIRES_box,phi_1) private(i,j,k) num_threads(user_params->N_THREADS)\n        {\n#pragma omp for\n            for (i=0; i<user_params->DIM; i++){\n                for (j=0; j<user_params->DIM; j++){\n                    for (k=0; k<user_params->DIM; k++){\n                        *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),\n                                                           (unsigned long long)(j),\n                                                           (unsigned long long)(k)) ) = 0.;\n                    }\n                }\n            }\n        }\n\n        // First iterate over the i = j components to phi\n        // We'll also save these temporarily to the hires_vi_2LPT boxes which will get\n        // overwritten later with the correct 2LPT velocities\n        for(phi_component=0;phi_component<3;phi_component++) {\n\n            i = j = phi_component;\n\n                // generate the phi_1 boxes in Fourier transform\n#pragma omp parallel shared(HIRES_box,phi_1,i,j) private(n_x,n_y,n_z,k_x,k_y,k_z,k_sq,k) num_threads(user_params->N_THREADS)\n                {\n#pragma omp for\n                for (n_x=0; n_x<user_params->DIM; n_x++){\n                    if (n_x>MIDDLE)\n                        k_x =(n_x-user_params->DIM) * DELTA_K;  // wrap around for FFT convention\n                    else\n                        k_x = n_x * DELTA_K;\n\n                    for (n_y=0; n_y<user_params->DIM; n_y++){\n                        if (n_y>MIDDLE)\n                            k_y =(n_y-user_params->DIM) * DELTA_K;\n                        else\n                            k_y = n_y * DELTA_K;\n\n                        for (n_z=0; n_z<=MIDDLE; n_z++){\n                            k_z = n_z * DELTA_K;\n\n                            k_sq = k_x*k_x + k_y*k_y + k_z*k_z;\n\n                            float k[] = {k_x, k_y, k_z};\n                            // now set the velocities\n                            if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode\n                                phi_1[0] = 0;\n                            }\n                            else{\n                                phi_1[C_INDEX(n_x,n_y,n_z)] = -k[i]*k[j]*HIRES_box_saved[C_INDEX(n_x, n_y, n_z)]/k_sq/VOLUME;\n                                // note the last factor of 1/VOLUME accounts for the scaling in real-space, following the FFT\n                            }\n                        }\n                    }\n                }\n            }\n\n            dft_c2r_cube(user_params->USE_FFTW_WISDOM, user_params->DIM, user_params->N_THREADS, phi_1);\n\n            // Temporarily store in the allocated hires_vi_2LPT boxes\n#pragma omp parallel shared(boxes,phi_1,phi_component) private(i,j,k) num_threads(user_params->N_THREADS)\n            {\n#pragma omp for\n                for (i=0; i<user_params->DIM; i++){\n                    for (j=0; j<user_params->DIM; j++){\n                        for (k=0; k<user_params->DIM; k++){\n                            if(phi_component==0) {\n                                boxes->hires_vx_2LPT[R_INDEX(i,j,k)] = *((float *)phi_1 + R_FFT_INDEX((unsigned long long)(i),\n                                                                                                      (unsigned long long)(j),\n                                                                                                      (unsigned long long)(k)));\n                            }\n                            if(phi_component==1) {\n                                boxes->hires_vy_2LPT[R_INDEX(i,j,k)] = *((float *)phi_1 + R_FFT_INDEX((unsigned long long)(i),\n                                                                                                      (unsigned long long)(j),\n                                                                                                      (unsigned long long)(k)));\n                            }\n                            if(phi_component==2) {\n                                boxes->hires_vz_2LPT[R_INDEX(i,j,k)] = *((float *)phi_1 + R_FFT_INDEX((unsigned long long)(i),\n                                                                                                      (unsigned long long)(j),\n                                                                                                      (unsigned long long)(k)));\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        for(phi_component=0;phi_component<3;phi_component++) {\n            // Now calculate the cross components and start evaluating the 2LPT field\n            i = phi_directions[phi_component][0];\n            j = phi_directions[phi_component][1];\n\n            // generate the phi_1 boxes in Fourier transform\n#pragma omp parallel shared(HIRES_box,phi_1) private(n_x,n_y,n_z,k_x,k_y,k_z,k_sq,k) num_threads(user_params->N_THREADS)\n            {\n#pragma omp for\n                for (n_x=0; n_x<user_params->DIM; n_x++){\n                    if (n_x>MIDDLE)\n                        k_x =(n_x-user_params->DIM) * DELTA_K;  // wrap around for FFT convention\n                    else\n                        k_x = n_x * DELTA_K;\n\n                    for (n_y=0; n_y<user_params->DIM; n_y++){\n                        if (n_y>MIDDLE)\n                            k_y =(n_y-user_params->DIM) * DELTA_K;\n                        else\n                            k_y = n_y * DELTA_K;\n\n                        for (n_z=0; n_z<=MIDDLE; n_z++){\n                            k_z = n_z * DELTA_K;\n\n                            k_sq = k_x*k_x + k_y*k_y + k_z*k_z;\n\n                            float k[] = {k_x, k_y, k_z};\n                            // now set the velocities\n                            if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode\n                                phi_1[0] = 0;\n                            }\n                            else{\n                                phi_1[C_INDEX(n_x,n_y,n_z)] = -k[i]*k[j]*HIRES_box_saved[C_INDEX(n_x, n_y, n_z)]/k_sq/VOLUME;\n                                // note the last factor of 1/VOLUME accounts for the scaling in real-space, following the FFT\n                            }\n                        }\n                    }\n                }\n            }\n\n            dft_c2r_cube(user_params->USE_FFTW_WISDOM, user_params->DIM, user_params->N_THREADS, phi_1);\n\n            // Then we will have the laplacian of phi_2 (eq. D13b)\n            // After that we have to return in Fourier space and generate the Fourier transform of phi_2\n#pragma omp parallel shared(HIRES_box,phi_1,phi_component) private(i,j,k,component_ii,component_jj,component_ij) num_threads(user_params->N_THREADS)\n            {\n#pragma omp for\n                for (i=0; i<user_params->DIM; i++){\n                    for (j=0; j<user_params->DIM; j++){\n                        for (k=0; k<user_params->DIM; k++){\n                            // Note, I have temporarily stored the components into other arrays to minimise memory usage\n                            // phi - {0, 1, 2} -> {hires_vx_2LPT, hires_vy_2LPT, hires_vz_2LPT}\n                            // This may be opaque to the user, but this shouldn't need modification\n                            if(phi_component==0) {\n                                component_ii = boxes->hires_vx_2LPT[R_INDEX(i,j,k)];\n                                component_jj = boxes->hires_vy_2LPT[R_INDEX(i,j,k)];\n                                component_ij = *((float *)phi_1 + R_FFT_INDEX((unsigned long long)(i),\n                                                                              (unsigned long long)(j),\n                                                                              (unsigned long long)(k)));\n                            }\n                            if(phi_component==1) {\n                                component_ii = boxes->hires_vx_2LPT[R_INDEX(i,j,k)];\n                                component_jj = boxes->hires_vz_2LPT[R_INDEX(i,j,k)];\n                                component_ij = *((float *)phi_1 + R_FFT_INDEX((unsigned long long)(i),\n                                                                              (unsigned long long)(j),\n                                                                              (unsigned long long)(k)));\n                            }\n                            if(phi_component==2) {\n                                component_ii = boxes->hires_vy_2LPT[R_INDEX(i,j,k)];\n                                component_jj = boxes->hires_vz_2LPT[R_INDEX(i,j,k)];\n                                component_ij = *((float *)phi_1 + R_FFT_INDEX((unsigned long long)(i),\n                                                                              (unsigned long long)(j),\n                                                                              (unsigned long long)(k)));\n                            }\n\n                            // Kept in this form to maintain similar (possible) rounding errors\n                            *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),\n                                                               (unsigned long long)(j),\n                                                               (unsigned long long)(k)) ) += \\\n                            ( component_ii * component_jj );\n\n                            *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),\n                                                               (unsigned long long)(j),\n                                                               (unsigned long long)(k)) ) -= \\\n                            ( component_ij * component_ij );\n                        }\n                    }\n                }\n            }\n        }\n\n#pragma omp parallel shared(HIRES_box,phi_1) private(i,j,k) num_threads(user_params->N_THREADS)\n        {\n#pragma omp for\n            for (i=0; i<user_params->DIM; i++){\n                for (j=0; j<user_params->DIM; j++){\n                    for (k=0; k<user_params->DIM; k++){\n                        *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),(unsigned long long)(j),(unsigned long long)(k)) ) /= TOT_NUM_PIXELS;\n                    }\n                }\n            }\n        }\n\n        // Perform FFTs\n        dft_r2c_cube(user_params->USE_FFTW_WISDOM, user_params->DIM, user_params->N_THREADS, HIRES_box);\n\n        memcpy(HIRES_box_saved, HIRES_box, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n\n        // Now we can store the content of box in a back-up array\n        // Then we can generate the gradients of phi_2 (eq. D13b and D9)\n\n        // ***** Store back-up k-box RHS eq. D13b ***** //\n\n        // For each component, we generate the velocity field (same as the ZA part)\n\n        // Now let's set the velocity field/dD/dt (in comoving Mpc)\n\n        // read in the box\n        // TODO correct free of phi_1\n\n        for(ii=0;ii<3;ii++) {\n\n            if(ii>0) {\n                memcpy(HIRES_box, HIRES_box_saved, sizeof(fftwf_complex)*KSPACE_NUM_PIXELS);\n            }\n\n#pragma omp parallel shared(HIRES_box,ii) private(n_x,n_y,n_z,k_x,k_y,k_z,k_sq) num_threads(user_params->N_THREADS)\n            {\n#pragma omp for\n            // set velocities/dD/dt\n                for (n_x=0; n_x<user_params->DIM; n_x++){\n                    if (n_x>MIDDLE)\n                        k_x =(n_x-user_params->DIM) * DELTA_K;  // wrap around for FFT convention\n                    else\n                        k_x = n_x * DELTA_K;\n\n                    for (n_y=0; n_y<user_params->DIM; n_y++){\n                        if (n_y>MIDDLE)\n                            k_y =(n_y-user_params->DIM) * DELTA_K;\n                        else\n                            k_y = n_y * DELTA_K;\n\n                        for (n_z=0; n_z<=MIDDLE; n_z++){\n                            k_z = n_z * DELTA_K;\n\n                            k_sq = k_x*k_x + k_y*k_y + k_z*k_z;\n\n                            // now set the velocities\n                            if ((n_x==0) && (n_y==0) && (n_z==0)){ // DC mode\n                                HIRES_box[0] = 0;\n                            }\n                            else{\n                                if(ii==0) {\n                                    HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_x*I/k_sq;\n                                }\n                                if(ii==1) {\n                                    HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_y*I/k_sq;\n                                }\n                                if(ii==2) {\n                                    HIRES_box[C_INDEX(n_x,n_y,n_z)] *= k_z*I/k_sq;\n                                }\n                            }\n                        }\n                        // note the last factor of 1/VOLUME accounts for the scaling in real-space, following the FFT\n                    }\n                }\n            }\n\n            // Filter only if we require perturbing on the low-res grid\n            if(!user_params->PERTURB_ON_HIGH_RES) {\n                if (user_params->DIM != user_params->HII_DIM) {\n                    filter_box(HIRES_box, 0, 0, L_FACTOR*user_params->BOX_LEN/(user_params->HII_DIM+0.0));\n                }\n            }\n\n            dft_c2r_cube(user_params->USE_FFTW_WISDOM, user_params->DIM, user_params->N_THREADS, HIRES_box);\n\n            // now sample to lower res\n            // now sample the filtered box\n#pragma omp parallel shared(boxes,HIRES_box,f_pixel_factor,ii,dimension) private(i,j,k) num_threads(user_params->N_THREADS)\n            {\n#pragma omp for\n                for (i=0; i<dimension; i++){\n                    for (j=0; j<dimension; j++){\n                        for (k=0; k<dimension; k++){\n                            if(user_params->PERTURB_ON_HIGH_RES) {\n                                if(ii==0) {\n                                    boxes->hires_vx_2LPT[R_INDEX(i,j,k)] =\n                                    *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),\n                                                                       (unsigned long long)(j),\n                                                                       (unsigned long long)(k)));\n                                }\n                                if(ii==1) {\n                                    boxes->hires_vy_2LPT[R_INDEX(i,j,k)] =\n                                    *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),\n                                                                       (unsigned long long)(j),\n                                                                       (unsigned long long)(k)));\n                                }\n                                if(ii==2) {\n                                    boxes->hires_vz_2LPT[R_INDEX(i,j,k)] =\n                                    *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i),\n                                                                       (unsigned long long)(j),\n                                                                       (unsigned long long)(k)));\n                                }\n                            }\n                            else {\n                                if(ii==0) {\n                                    boxes->lowres_vx_2LPT[HII_R_INDEX(i,j,k)] =\n                                    *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5),\n                                                                       (unsigned long long)(j*f_pixel_factor+0.5),\n                                                                       (unsigned long long)(k*f_pixel_factor+0.5)));\n                                }\n                                if(ii==1) {\n                                    boxes->lowres_vy_2LPT[HII_R_INDEX(i,j,k)] =\n                                    *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5),\n                                                                       (unsigned long long)(j*f_pixel_factor+0.5),\n                                                                       (unsigned long long)(k*f_pixel_factor+0.5)));\n                                }\n                                if(ii==2) {\n                                    boxes->lowres_vz_2LPT[HII_R_INDEX(i,j,k)] =\n                                    *((float *)HIRES_box + R_FFT_INDEX((unsigned long long)(i*f_pixel_factor+0.5),\n                                                                       (unsigned long long)(j*f_pixel_factor+0.5),\n                                                                       (unsigned long long)(k*f_pixel_factor+0.5)));\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        // deallocate the supplementary boxes\n        fftwf_free(phi_1);\n\n    }\n    LOG_DEBUG(\"Done 2LPT.\");\n\n    // * *********************************************** * //\n    // *               END 2LPT PART                     * //\n    // * *********************************************** * //\n    fftwf_cleanup_threads();\n    fftwf_cleanup();\n    fftwf_forget_wisdom();\n\n    // deallocate\n    fftwf_free(HIRES_box);\n    fftwf_free(HIRES_box_saved);\n\n    free_ps();\n\n    for (i=0; i<user_params->N_THREADS; i++) {\n        gsl_rng_free (r[i]);\n    }\n    gsl_rng_free(rseed);\n    LOG_DEBUG(\"Cleaned Up.\");\n    } // End of Try{}\n\n    Catch(status){\n        return(status);\n    }\n    return(0);\n}\n", "meta": {"hexsha": "8f58a58954837473227a82a6b20e5967cdf986ad", "size": 39450, "ext": "c", "lang": "C", "max_stars_repo_path": "src/py21cmfast/src/GenerateICs.c", "max_stars_repo_name": "daviesje/21cmFAST", "max_stars_repo_head_hexsha": "f36885a813ace72f34c881d80473208d06e3829a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2019-10-02T08:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T08:02:28.000Z", "max_issues_repo_path": "src/py21cmfast/src/GenerateICs.c", "max_issues_repo_name": "debanjan-cosmo/21cmFAST", "max_issues_repo_head_hexsha": "b9f396ea5605440be419b7cf005fc4286ef1fd00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 232.0, "max_issues_repo_issues_event_min_datetime": "2019-06-13T22:36:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:45:06.000Z", "max_forks_repo_path": "src/py21cmfast/src/GenerateICs.c", "max_forks_repo_name": "debanjan-cosmo/21cmFAST", "max_forks_repo_head_hexsha": "b9f396ea5605440be419b7cf005fc4286ef1fd00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T16:53:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T19:50:17.000Z", "avg_line_length": 43.8820912125, "max_line_length": 202, "alphanum_fraction": 0.4542965779, "num_tokens": 8912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.38916677339456224}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C code for the implementation of the Fourier domain response for LISA-like detectors.\n *\n */\n\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"EOBNRv2HMROMstruct.h\"\n#include \"LISAgeometry.h\"\n#include \"LISAFDresponse.h\"\n\n\n/***************************************/\n/********* Core functions **************/\n\n/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LISA response, for given values of the inclination, position in the sky and polarization angle - here simplified version for just the y_21 observable */\n/* Older version of th FD response: two stages, first for the orbital delay (Bessel phase) and second for the constellation delay/modulation */\nint LISASimFDResponse21(\n  LISAconstellation *variant,                                 /* Provides specifics on the variant of LISA */\n  struct tagListmodesCAmpPhaseFrequencySeries **list,  /* Input/Output: list of modes in Frequency-domain amplitude and phase form as produced by the ROM, and output after FD response processing */\n  const double inclination,                                   /* Inclination of the source */\n  const double lambda,                                        /* First angle for the position in the sky */\n  const double beta,                                          /* Second angle for the position in the sky */\n  const double psi)                                           /* Polarization angle */\n{\n  /* Computing the complicated trigonometric coefficients */\n  //clock_t begsetcoeffs = clock();\n  SetCoeffsG(lambda, beta, psi);\n  //clock_t endsetcoeffs = clock();\n  //printf(\"Set Coeffs time: %g s\\n\", (double)(endsetcoeffs - begsetcoeffs) / CLOCKS_PER_SEC);\n\n  /* Main loop over the modes - goes through all the modes present */\n  ListmodesCAmpPhaseFrequencySeries* listelement = *list;\n  while(listelement) {\n\n    /* Definitions: l,m, frequency series and length */\n    int l = listelement->l;\n    int m = listelement->m;\n    CAmpPhaseFrequencySeries* freqseries = listelement->freqseries;\n    gsl_vector* freq = freqseries->freq;\n    gsl_vector* amp_real = freqseries->amp_real;\n    gsl_vector* amp_imag = freqseries->amp_imag;\n    gsl_vector* phase = freqseries->phase;\n    int len = (int) freq->size;\n    double f, tf, bphi;\n    double complex camp;\n\n    /* Computing the Ylm combined factors for plus and cross for this mode */\n    /* Capital Phi is set to 0 by convention */\n    double complex Yfactorplus;\n    double complex Yfactorcross;\n    if (!(l%2)) {\n      Yfactorplus = 1/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n      Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n    }\n    else {\n      Yfactorplus = 1/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n      Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n    }\n\n    /* First step of the processing: orbital delay */\n    /* Initializing spline for the phase */\n    gsl_spline* spline_phi = gsl_spline_alloc(gsl_interp_cspline, len);\n    gsl_interp_accel* accel_phi = gsl_interp_accel_alloc();\n    gsl_spline_init(spline_phi, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(phase, 0), len);\n    /* Vector keeping track of the Bessel Phase correction - to be used in the next step */\n    gsl_vector* besselphi = gsl_vector_alloc(len);\n\n    /* Loop over the frequencies - computing the correction due to the orbital delay */\n    for(int j=0; j<len; j++) {\n      f = gsl_vector_get(freq, j);\n      tf =  gsl_spline_eval_deriv(spline_phi, f, accel_phi)/(2*PI);\n      bphi = -2*PI*f*variant->OrbitR/C_SI*cos(beta) * cos( variant->OrbitOmega*tf + variant->OrbitPhi0 - lambda );\n      camp = gsl_vector_get(amp_real, j) * cexp(I*bphi); /* Amplitude is real before applying this first delay */\n      gsl_vector_set(amp_real, j, creal(camp));\n      gsl_vector_set(amp_imag, j, cimag(camp));\n      gsl_vector_set(besselphi, j, bphi);\n    }\n\n    /* Second step of the processing: constellation delay/modulation */\n    /* Initializing spline for the bessel phase */\n    gsl_spline* spline_besselphi = gsl_spline_alloc(gsl_interp_cspline, len);\n    gsl_interp_accel* accel_besselphi = gsl_interp_accel_alloc();\n    gsl_spline_init(spline_besselphi, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(besselphi, 0), len);\n    /* Loop over the frequencies - computing the correction due to the orbital delay */\n    for(int j=0; j<len; j++) {\n      f = gsl_vector_get(freq, j);\n      tf =  (gsl_spline_eval_deriv(spline_phi, f, accel_phi) + gsl_spline_eval_deriv(spline_besselphi, f, accel_besselphi))/(2*PI);\n      camp = G21mode(variant, f, tf, Yfactorplus, Yfactorcross) * (gsl_vector_get(amp_real, j) + I * gsl_vector_get(amp_imag, j));\n      /**/\n      gsl_vector_set(amp_real, j, creal(camp));\n      gsl_vector_set(amp_imag, j, cimag(camp));\n    }\n\n    listelement = listelement->next;\n\n    /* Clean up */\n    gsl_spline_free(spline_phi);\n    gsl_interp_accel_free(accel_phi);\n    gsl_vector_free(besselphi);\n    gsl_spline_free(spline_besselphi);\n    gsl_interp_accel_free(accel_besselphi);\n  }\n\n  return SUCCESS;\n}\n\n//WARNING: tRef is ignored for now in the response - i.e. set to 0\n/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LISA response, for given values of the inclination, position in the sky and polarization angle */\nint LISASimFDResponsey12(\n  LISAconstellation *variant,                                 /* Provides specifics on the variant of LISA */\n  struct tagListmodesCAmpPhaseFrequencySeries **list,      /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */\n  struct tagListmodesCAmpPhaseFrequencySeries **listy12,   /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the y12 observable */\n  const double torb,                                       /* Reference orbital time - tf as read from the hlm gives t-tinj, this arg allows to pass tinj to the response */\n  const double lambda,                                        /* First angle for the position in the sky */\n  const double beta,                                          /* Second angle for the position in the sky */\n  const double inclination,                                   /* Inclination of the source */\n  const double psi,                                           /* Polarization angle */\n  const int tagfrozenLISA,                                    /* Tag to treat LISA as frozen at its torb configuration  */\n  const ResponseApproxtag responseapprox)                     /* Tag to select possible low-f approximation level in FD response */\n{\n  /* Computing the complicated trigonometric coefficients */\n  //clock_t begsetcoeffs = clock();\n  SetCoeffsG(lambda, beta, psi);\n  //clock_t endsetcoeffs = clock();\n  //printf(\"Set Coeffs time: %g s\\n\", (double)(endsetcoeffs - begsetcoeffs) / CLOCKS_PER_SEC);\n\n  /* Main loop over the modes - goes through all the modes present, stopping when encountering NULL */\n  ListmodesCAmpPhaseFrequencySeries* listelement = *list;\n  while(listelement) {\n\n    /* Definitions: l,m, frequency series and length */\n    int l = listelement->l;\n    int m = listelement->m;\n    CAmpPhaseFrequencySeries* freqseries = listelement->freqseries;\n    gsl_vector* freq = freqseries->freq;\n    gsl_vector* amp_real = freqseries->amp_real;\n    gsl_vector* amp_imag = freqseries->amp_imag;\n    gsl_vector* phase = freqseries->phase;\n    int len = (int) freq->size;\n    double f, tf, tforb;\n    double complex g12mode = 0.;\n    double complex g21mode = 0.;\n    double complex g23mode = 0.;\n    double complex g32mode = 0.;\n    double complex g31mode = 0.;\n    double complex g13mode = 0.;\n    double complex camp_y;\n\n    /* Computing the Ylm combined factors for plus and cross for this mode */\n    /* Capital Phi is set to 0 by convention */\n    double complex Yfactorplus;\n    double complex Yfactorcross;\n    if (!(l%2)) {\n      Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n      Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n    }\n    else {\n      Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n      Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n    }\n\n    /* Initializing spline for the phase */\n    gsl_spline* spline_phi = gsl_spline_alloc(gsl_interp_cspline, len);\n    gsl_interp_accel* accel_phi = gsl_interp_accel_alloc();\n    gsl_spline_init(spline_phi, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(phase, 0), len);\n\n    /* Orbital delay, constellation delay/modulation */\n    /* Initializing frequency series structure for this mode, for each of the TDI observables */\n    CAmpPhaseFrequencySeries *modefreqseries = NULL;\n    CAmpPhaseFrequencySeries_Init(&modefreqseries, len);\n    gsl_vector* freq_y = modefreqseries->freq;\n    gsl_vector* amp_real_y = modefreqseries->amp_real;\n    gsl_vector* amp_imag_y = modefreqseries->amp_imag;\n    gsl_vector* phase_y = modefreqseries->phase;\n    /* Loop over the frequencies - computing the correction due to the constellation delay/modulation */\n    //clock_t tbegcontesllation = clock();\n    //double timingcumulativeGABmode = 0;\n    for(int j=0; j<len; j++) {\n      f = gsl_vector_get(freq, j);\n      tf = (gsl_spline_eval_deriv(spline_phi, f, accel_phi))/(2*PI);\n      /* tf read from hlm is t-tinj - here convert to orbital time */\n      if(!(tagfrozenLISA)) {\n        tforb = tf + torb;\n      } else {\n        tforb = torb;\n      }\n      //clock_t tbegGAB = clock();\n\t  EvaluateGABmode(variant, &g12mode, &g21mode, &g23mode, &g32mode, &g31mode, &g13mode, f, tforb, Yfactorplus, Yfactorcross, 1, responseapprox); /* does include the R-delay term */\n      //clock_t tendGAB = clock();\n      //timingcumulativeGABmode += (double) (tendGAB-tbegGAB) /CLOCKS_PER_SEC;\n      /**/\n      camp_y = (gsl_vector_get(amp_real, j) + I * gsl_vector_get(amp_imag, j)) * g12mode;\n      /**/\n      gsl_vector_set(amp_real_y, j, creal(camp_y));\n      gsl_vector_set(amp_imag_y, j, cimag(camp_y));\n    }\n    //clock_t tendcontesllation = clock();\n  //printf(\"Set constellation time: %g s\\n\", (double)(tendcontesllation - tbegcontesllation) / CLOCKS_PER_SEC);\n  //printf(\"GAB cumulated time: %g s\\n\", timingcumulativeGABmode);\n\n    /* Copying the vectors of frequencies and phases */\n    gsl_vector_memcpy(freq_y, freq);\n    gsl_vector_memcpy(phase_y, phase);\n\n    /* Append the modes to the ouput list-of-modes structures */\n    *listy12 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*listy12, modefreqseries, l, m);\n\n    /* Going to the next mode in the list */\n    listelement = listelement->next;\n\n    /* Clean up */\n    gsl_spline_free(spline_phi);\n    gsl_interp_accel_free(accel_phi);\n  }\n\n  return SUCCESS;\n}\n\n//WARNING: tRef is ignored for now in the response - i.e. set to 0\n/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LISA response, for given values of the inclination, position in the sky and polarization angle */\nint LISASimFDResponseTDI3Chan(\n  int tagtRefatLISA,                                          /* 0 to measure Tref from SSB arrival, 1 at LISA guiding center */\n  LISAconstellation *variant,                                 /* Provides specifics on the variant of LISA */\n  struct tagListmodesCAmpPhaseFrequencySeries **list,      /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */\n  struct tagListmodesCAmpPhaseFrequencySeries **listTDI1,  /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 1 */\n  struct tagListmodesCAmpPhaseFrequencySeries **listTDI2,  /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 2 */\n  struct tagListmodesCAmpPhaseFrequencySeries **listTDI3,  /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 3 */\n  const double torb,                                       /* Reference orbital time - tf as read from the hlm gives t-tinj, this arg allows to pass tinj to the response */\n  const double lambda,                                     /* First angle for the position in the sky */\n  const double beta,                                       /* Second angle for the position in the sky */\n  const double inclination,                                /* Inclination of the source */\n  const double psi,                                        /* Polarization angle */\n  const double m1,                                         /* m1 in solar masses - used for resampling */\n  const double m2,                                         /* m2 in solar masses - used for resampling */\n  const double maxf,                                       /* Maximal frequency to consider - used to ignore hard-to-resolve response at f>1Hz - NOTE: for now, no recomputation of the boundary, so when not resampling can lose a bit of support between the last frequency point covered and maxf */\n  const TDItag tditag,                                     /* Selector for the set of TDI observables */\n  const int tagfrozenLISA,                                 /* Tag to treat LISA as frozen at its torb configuration  */\n  const ResponseApproxtag responseapprox)                  /* Tag to select possible low-f approximation level in FD response */\n{\n  /* Computing the complicated trigonometric coefficients */\n  //clock_t begsetcoeffs = clock();\n  SetCoeffsG(lambda, beta, psi);\n  //clock_t endsetcoeffs = clock();\n  //printf(\"Set Coeffs time: %g s\\n\", (double)(endsetcoeffs - begsetcoeffs) / CLOCKS_PER_SEC);\n\n  /* Chirp mass for resampling */\n  double mchirp = Mchirpofm1m2(m1, m2);\n\n  /* Main loop over the modes - goes through all the modes present, stopping when encountering NULL */\n  ListmodesCAmpPhaseFrequencySeries* listelement = *list;\n  while(listelement) {\n\n    /* Definitions: l,m, frequency series and length */\n    int l = listelement->l;\n    int m = listelement->m;\n    CAmpPhaseFrequencySeries* freqseries = listelement->freqseries;\n    gsl_vector* freq = freqseries->freq;\n    gsl_vector* amp_real = freqseries->amp_real;\n    gsl_vector* amp_imag = freqseries->amp_imag;\n    gsl_vector* phase = freqseries->phase;\n    int len = (int) freq->size;\n\n    //\n    //printf(\"len: %d\\n\", len);\n    //\n    //if(l==2&&m==1) printf(\"no resampling 21\\n\");\n    //      if(l==2&&m==1) {for(int i=0; i<len; i++) printf(\"%d, %g, %g, %g, %g\\n\", i, gsl_vector_get(freq, i), gsl_vector_get(amp_real, i), gsl_vector_get(amp_imag, i), gsl_vector_get(phase, i));};\n\n    double f, tf, tforb;\n    double complex g21mode = 0.;\n    double complex g12mode = 0.;\n    double complex g32mode = 0.;\n    double complex g23mode = 0.;\n    double complex g13mode = 0.;\n    double complex g31mode = 0.;\n    double complex camp;\n    double complex camp1;\n    double complex camp2;\n    double complex camp3;\n    double complex factor1 = 0.;\n    double complex factor2 = 0.;\n    double complex factor3 = 0.;\n\n    /* Computing the Ylm combined factors for plus and cross for this mode */\n    /* Capital Phi is set to 0 by convention */\n    double complex Yfactorplus;\n    double complex Yfactorcross;\n    if (!(l%2)) {\n      Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n      Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n    }\n    else {\n      Yfactorplus = 1./2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) - conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n      Yfactorcross = I/2 * (SpinWeightedSphericalHarmonic(inclination, 0., -2, l, m) + conj(SpinWeightedSphericalHarmonic(inclination, 0., -2, l, -m)));\n    }\n\n    /* Initializing spline for the phase - will be used to compute tf */\n    gsl_spline* spline_phi = gsl_spline_alloc(gsl_interp_cspline, len);\n    gsl_interp_accel* accel_phi = gsl_interp_accel_alloc();\n    gsl_spline_init(spline_phi, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(phase, 0), len);\n\n    /* Resampling at high f to achieve a deltaf of at most 0.002 Hz */\n    /* Resample linearly at this deltaf when this threshold is reached */\n    /* NOTE: Assumes input frequencies are logarithmic (except maybe first interval) to evaluate when to resample */\n    gsl_vector* freqrhigh = NULL;\n    SetMaxdeltafResampledFrequencies(&freqrhigh, freq, maxf, 0.002); /* Use 0.002Hz as a default maximal deltaf */\n\n    /* Resampling at low f to achieve a deltat of at most 2 weeks */\n    /* Resample linearly in time until this threshold is reached */\n    /* NOTE: uses Newtonian estimates - also requires the chirp mass as extra information */\n    /* It would also be possible to use t(f) (more accurate), but we would also need to interpolate f(t) */\n    /* Accuracy in time of this resampling is not critical, estimate should be enough */\n    gsl_vector* freqr = NULL;\n    SetMaxdeltatResampledFrequencies(&freqr, freqrhigh, 1./24, mchirp, m); /* Use half a month as a default maximal deltaft */\n\n    /* Evaluate resampled waveform */\n    CAmpPhaseFrequencySeries* freqseriesr = NULL;\n    CAmpPhaseFrequencySeries_Resample(&freqseriesr, freqseries, freqr);\n    gsl_vector* freq_resample = freqseriesr->freq;\n    gsl_vector* amp_real_resample = freqseriesr->amp_real;\n    gsl_vector* amp_imag_resample = freqseriesr->amp_imag;\n    gsl_vector* phase_resample = freqseriesr->phase;\n    int len_resample = (int) freq_resample->size;\n\n    // /* Determine frequencies to use */\n    // /* Because we will need the interpolation on the Re/Im amplitude to resolve the structure of the L-response at high fequencies, we add points beyond 0.01 Hz, with a linear sampling */\n    // /* WARNING : It seemed 600 points between 0.1 and 3 Hz (deltaf=0.005) should give interpolation errors below 1e-4 - considering a simple sin(2 pi f L) */\n    // /* But first test with TDIA show the sampling should be reduced 10-fold - possibly large increase in cost */\n    // /* We use here deltaf=0.0005 until the cause is better understood */\n    // /* NOTE: the structure in the response due to the R-delay gives much larger interpolation errors - here we assume the R-delay term is now treated as a phase */\n    // int resampled = 0; /* Keeps track of wether or not we resampled and allocated new resources we need to free */\n    // double maxfsignal = gsl_vector_get(freq, len-1);\n    // double fHigh = fmin(maxf, maxfsignal);\n    // /* BEWARE : as Mathematica tests show, this is way too pessimistic - normally deltaf=0.002Hz sould work */\n    // /* To be investigated */\n    // double fHigh_log_samp = 0.002;\n    // double deltaflineartarget = 0.00002; //1e-5 better, but slower\n    // int ifmax = len-1; /* last index to be covered in original sampling overall */\n    // while((gsl_vector_get(freq, ifmax)>fHigh) && ifmax>0) ifmax--;\n    // int imaxlogsampling = ifmax; /* last index to be covered with original sampling */\n    // while((gsl_vector_get(freq, imaxlogsampling)>fHigh_log_samp) && imaxlogsampling>0) imaxlogsampling--;\n    // gsl_vector* freq_resample = NULL; /*  */\n    // gsl_vector* amp_real_resample = NULL;\n    // gsl_vector* amp_imag_resample = NULL;\n    // gsl_vector* phase_resample = NULL;\n    // int len_resample;\n    //\n    // if((fHigh>fHigh_log_samp) && ((fHigh - gsl_vector_get(freq, imaxlogsampling))/deltaflineartarget)>ifmax-imaxlogsampling) { /* condition to check if the linear sampling will add points - if not, do nothing */\n    //\n    //   resampled = 1;\n    //   /* Number of pts in resampled part */\n    //   int nbfreqlinear = ceil((fHigh - gsl_vector_get(freq, imaxlogsampling))/deltaflineartarget);\n    //   double deltaflinear = (fHigh - gsl_vector_get(freq, imaxlogsampling))/(nbfreqlinear + 1);\n    //   /* Initialize new vectors */\n    //   len_resample = imaxlogsampling + 1 + nbfreqlinear;\n    //   freq_resample = gsl_vector_alloc(len_resample);\n    //   amp_real_resample = gsl_vector_alloc(len_resample);\n    //   amp_imag_resample = gsl_vector_alloc(len_resample);\n    //   phase_resample = gsl_vector_alloc(len_resample);\n    //   /* Build interpolation for original amp_real, amp_imag and phase */\n    //   /* NOTE: we could use spline_phi here, written this way for clarity */\n    //   gsl_spline* spline_amp_real = gsl_spline_alloc(gsl_interp_cspline, len);\n    //   gsl_spline* spline_amp_imag = gsl_spline_alloc(gsl_interp_cspline, len);\n    //   gsl_spline* spline_phase = gsl_spline_alloc(gsl_interp_cspline, len);\n    //   gsl_interp_accel* accel_amp_real = gsl_interp_accel_alloc();\n    //   gsl_interp_accel* accel_amp_imag = gsl_interp_accel_alloc();\n    //   gsl_interp_accel* accel_phase = gsl_interp_accel_alloc();\n    //   gsl_spline_init(spline_amp_real, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(amp_real, 0), len);\n    //   gsl_spline_init(spline_amp_imag, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(amp_imag, 0), len);\n    //   gsl_spline_init(spline_phase, gsl_vector_const_ptr(freq, 0), gsl_vector_const_ptr(phase, 0), len);\n    //   /* Set resampled frequencies and values */\n    //   for(int j=0; j<=imaxlogsampling; j++) {\n    //     gsl_vector_set(freq_resample, j, gsl_vector_get(freq, j));\n    //     gsl_vector_set(amp_real_resample, j, gsl_vector_get(amp_real, j));\n    //     gsl_vector_set(amp_imag_resample, j, gsl_vector_get(amp_imag, j));\n    //     gsl_vector_set(phase_resample, j, gsl_vector_get(phase, j));\n    //   }\n    //   double fimax = gsl_vector_get(freq, imaxlogsampling);\n    //   for(int j=imaxlogsampling+1; j<len_resample; j++) {\n    //     f = fimax + (j-imaxlogsampling) * deltaflinear;\n    //     gsl_vector_set(freq_resample, j, f);\n    //     gsl_vector_set(amp_real_resample, j, gsl_spline_eval(spline_amp_real, f, accel_amp_real));\n    //     gsl_vector_set(amp_imag_resample, j, gsl_spline_eval(spline_amp_imag, f, accel_amp_imag));\n    //     gsl_vector_set(phase_resample, j, gsl_spline_eval(spline_phase, f, accel_phase));\n    //   }\n    //   /* Free interpolation functions */\n    //   gsl_spline_free(spline_amp_real);\n    //   gsl_spline_free(spline_amp_imag);\n    //   gsl_spline_free(spline_phase);\n    //   gsl_interp_accel_free(accel_amp_real);\n    //   gsl_interp_accel_free(accel_amp_imag);\n    //   gsl_interp_accel_free(accel_phase);\n    // }\n    // else { /* If no resampling, use the values we had as input */\n    //   resampled = 0;\n    //   len_resample = imaxlogsampling + 1; /* If maxf < maxfsignal, we will cut the signal above maxf by simply adjusting the range of indices included (NOTE: without recomputing the exact boundary, so some support is lost due to discretization) */\n    //   freq_resample = freq;\n    //   amp_real_resample = amp_real;\n    //   amp_imag_resample = amp_imag;\n    //   phase_resample = phase;\n    // }\n\n    /* Initializing frequency series structure for this mode, for each of the TDI observables */\n    CAmpPhaseFrequencySeries *modefreqseries1 = NULL;\n    CAmpPhaseFrequencySeries *modefreqseries2 = NULL;\n    CAmpPhaseFrequencySeries *modefreqseries3 = NULL;\n    CAmpPhaseFrequencySeries_Init(&modefreqseries1, len_resample);\n    CAmpPhaseFrequencySeries_Init(&modefreqseries2, len_resample);\n    CAmpPhaseFrequencySeries_Init(&modefreqseries3, len_resample);\n    gsl_vector* freq1 = modefreqseries1->freq;\n    gsl_vector* amp_real1 = modefreqseries1->amp_real;\n    gsl_vector* amp_imag1 = modefreqseries1->amp_imag;\n    gsl_vector* phase1 = modefreqseries1->phase;\n    gsl_vector* freq2 = modefreqseries2->freq;\n    gsl_vector* amp_real2 = modefreqseries2->amp_real;\n    gsl_vector* amp_imag2 = modefreqseries2->amp_imag;\n    gsl_vector* phase2 = modefreqseries2->phase;\n    gsl_vector* freq3 = modefreqseries3->freq;\n    gsl_vector* amp_real3 = modefreqseries3->amp_real;\n    gsl_vector* amp_imag3 = modefreqseries3->amp_imag;\n    gsl_vector* phase3 = modefreqseries3->phase;\n\n    /* Loop over the frequencies */\n    //clock_t tbegcontesllation = clock();\n    //double timingcumulativeGABmode = 0;\n    for(int j=0; j<len_resample; j++) {\n      f = gsl_vector_get(freq_resample, j);\n      tf = (gsl_spline_eval_deriv(spline_phi, f, accel_phi))/(2*PI);\n      /* tf read from hlm is t-tinj - here convert to orbital time using torb - ignore tf if orbit is frozen */\n      if(!(tagfrozenLISA)) {\n        tforb = tf + torb;\n      } else {\n        tforb = torb;\n      }\n      //clock_t tbegGAB = clock();\n      EvaluateGABmode(variant, &g12mode, &g21mode, &g23mode, &g32mode, &g31mode, &g13mode, f, tforb, Yfactorplus, Yfactorcross, 0, responseapprox); /* does not include the R-delay term */\n      //clock_t tendGAB = clock();\n      //timingcumulativeGABmode += (double) (tendGAB-tbegGAB) /CLOCKS_PER_SEC;\n      /**/\n      EvaluateTDIfactor3Chan(variant, &factor1, &factor2, &factor3, g12mode, g21mode, g23mode, g32mode, g31mode, g13mode, f, tditag, responseapprox);\n      double complex amphtilde = gsl_vector_get(amp_real_resample, j) + I * gsl_vector_get(amp_imag_resample, j);\n      camp1 = factor1 * amphtilde;\n      camp2 = factor2 * amphtilde;\n      camp3 = factor3 * amphtilde;\n      /* Phase term due to the R-delay, including correction to first order */\n      double phase=variant->OrbitOmega*tforb + variant->OrbitPhi0 - lambda;\n      double OrbitRoC=variant->OrbitR/C_SI;\n      //double phaseRdelay = -2*PI*R_SI/C_SI*f*cos(beta)*cos(Omega_SI*tf - lambda) * (1 + R_SI/C_SI*cos(beta)*Omega_SI*sin(Omega_SI*tf - lambda));\n      double phaseRdelay;\n      if(tagtRefatLISA==0){//delay so that tinj=torb refers to arrival time at SSB\n        phaseRdelay = -2*PI*OrbitRoC*f*cos(beta)*cos(phase) * (1 + cos(beta)*OrbitRoC*variant->OrbitOmega*sin(phase));\n      } else {\n        //In this version we delay so that tinj=torb is relative to LISAcenter arrival time, so there is no orbital delay when tf = tinj\n        //If the original delay realized td=t+d(t), now we want td=t+d(t)-d(t0), that we we change d(t) -> d(t) + d(t0)\n        //Then with the approximation d(td)=d(t)(1-ddot(t)),\n        double phase0 = variant->OrbitOmega*torb + variant->OrbitPhi0 - lambda;\n        phaseRdelay = -2*PI*OrbitRoC*f*cos(beta)*( cos(phase)-cos(phase0) ) * (1 + cos(beta)*OrbitRoC*variant->OrbitOmega*sin(phase));\n      }\n      if(responseapprox==lowf) { /* In the full low-f approximation, ignore this delay term */\n        phaseRdelay = 0.;\n      }\n      double phasewithRdelay = gsl_vector_get(phase_resample, j) + phaseRdelay;\n\n      /**/\n      gsl_vector_set(amp_real1, j, creal(camp1));\n      gsl_vector_set(amp_imag1, j, cimag(camp1));\n      gsl_vector_set(amp_real2, j, creal(camp2));\n      gsl_vector_set(amp_imag2, j, cimag(camp2));\n      gsl_vector_set(amp_real3, j, creal(camp3));\n      gsl_vector_set(amp_imag3, j, cimag(camp3));\n      gsl_vector_set(phase1, j, phasewithRdelay);\n      gsl_vector_set(phase2, j, phasewithRdelay);\n      gsl_vector_set(phase3, j, phasewithRdelay);\n    }\n    //clock_t tendconstellation = clock();\n    //printf(\"Set constellation time: %g s\\n\", (double)(tendconstellation - tbegconstellation) / CLOCKS_PER_SEC);\n    //printf(\"GAB cumulated time: %g s\\n\", timingcumulativeGABmode);\n\n    /* Copying the vectors of frequencies - we have to allow for the case where it has been shortened */\n    gsl_vector_view freq_resample_subview = gsl_vector_subvector(freq_resample, 0, len_resample);\n    gsl_vector_memcpy(freq1, &freq_resample_subview.vector);\n    gsl_vector_memcpy(freq2, &freq_resample_subview.vector);\n    gsl_vector_memcpy(freq3, &freq_resample_subview.vector);\n\n    /* Append the modes to the ouput list-of-modes structures */\n    *listTDI1 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*listTDI1, modefreqseries1, l, m);\n    *listTDI2 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*listTDI2, modefreqseries2, l, m);\n    *listTDI3 = ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(*listTDI3, modefreqseries3, l, m);\n\n    /* Going to the next mode in the list */\n    listelement = listelement->next;\n\n    /* Clean up */\n    gsl_spline_free(spline_phi);\n    gsl_interp_accel_free(accel_phi);\n    gsl_vector_free(freqrhigh);\n    gsl_vector_free(freqr);\n    CAmpPhaseFrequencySeries_Cleanup(freqseriesr);\n    // /* If we used resampling, then we need to free the additional resources that were allocated */\n    // if(resampled) {\n    //   gsl_vector_free(freq_resample);\n    //   gsl_vector_free(amp_real_resample);\n    //   gsl_vector_free(amp_imag_resample);\n    //   gsl_vector_free(phase_resample);\n    // }\n  }\n\n  return SUCCESS;\n}\n", "meta": {"hexsha": "9789e6ff9f8c6d9de507d2c57e6dc7bb6ad8a2fe", "size": 29793, "ext": "c", "lang": "C", "max_stars_repo_path": "LISAsim/LISAFDresponse.c", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "LISAsim/LISAFDresponse.c", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LISAsim/LISAFDresponse.c", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 55.2745825603, "max_line_length": 295, "alphanum_fraction": 0.6801262041, "num_tokens": 7992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.388598747349977}}
{"text": "#ifndef QDM_KNOTS_H\n#define QDM_KNOTS_H 1\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_vector.h>\n\ngsl_vector *\nqdm_knots_vector(\n  size_t spline_df,\n  gsl_vector *knots_inter\n);\n\nint\nqdm_knots_optimize(\n  gsl_vector *result,\n\n  gsl_rng *rng,\n\n  gsl_vector *sorted_data,\n  gsl_vector *middle,\n  gsl_vector *possible_knots,\n\n  size_t iterate_n,\n  size_t spline_df\n);\n\n#endif /* QDM_KNOTS_H */\n", "meta": {"hexsha": "45ed64e55681b7646a06eecedbbaa7f83f408ebe", "size": 390, "ext": "h", "lang": "C", "max_stars_repo_path": "include/qdm/knots.h", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/qdm/knots.h", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "include/qdm/knots.h", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9285714286, "max_line_length": 29, "alphanum_fraction": 0.7435897436, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.3884896312675441}}
{"text": "/*\n *  emu_noh.c\n *  \n *\n *  Created by Earl Lawrence on 9/17/09.\n *  Update 11/30/2012\n *\n *  This program was prepared by Los Alamos National Security, LLC at Los Alamos National Laboratory (LANL) \n *  under contract No. DE-AC52-06NA25396 with the U.S. Department of Energy (DOE). All rights in the program \n *  are reserved by the DOE and Los Alamos National Security, LLC.  Permission is granted to the public to \n *  copy and use this software without charge, provided that this Notice and any statement of authorship are \n *  reproduced on all copies.  Neither the U.S. Government nor LANS makes any warranty, express or implied, \n *  or assumes any liability or responsibility for the use of this software.  \n *\n *  \n */\n\n\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_errno.h>\n\n#include \"pcbasis_noh.h\"\n#include \"design_noh.h\"\n#include \"pcweights_noh.h\"\n#include \"corrlengths_noh.h\"\n#include \"precisions_noh.h\"\n#include \"meansd.h\"\n#include \"kemu.h\"\n#include \"ksim.h\"\n\n#ifndef M_PI\n#define M_PI           3.14159265358979323846\n#endif\n\n\n// Sizes of stuff and number of redshifts\nstatic int m=37, neta=5500, p=5, peta=6, rs=11, nsim=582;\n// Kriging basis computed by emuInit, sizes should be peta and m\nstatic double KrigBasis[6][37];\n\n\n// Initialization function that computes the Kriging basis\nvoid emuInit_noh() {\n    int i,j,k,l;\n    double cov;\n    gsl_matrix *SigmaSim = gsl_matrix_alloc(m,m);\n    gsl_vector *b = gsl_vector_alloc(m);\n    \n    // Do these one principal component at a time\n    for(i=0; i<peta; i++) {\n        // Fill in the covariance matrix for the principals components\n        // Also make a gsl_vector with the weights.\n        for(j=0; j<m; j++) {\n            // Diagonal\n            gsl_matrix_set(SigmaSim, j, j, (1.0/lamz[i]) + (1.0/lamws[i]));\n            // Off-diagonals\n            for(k=0; k<j; k++) {\n                // Compute the covariance\n                cov = 0.0;\n                for(l=0; l<p; l++) {\n                    cov -= beta[i][l]*pow(x[j][l]-x[k][l], 2.0);\n                }\n                cov = exp(cov)/lamz[i];\n                gsl_matrix_set(SigmaSim, j, k, cov);\n                gsl_matrix_set(SigmaSim, k, j, cov);\n            } // for(k=0; k<j; k++)\n            gsl_vector_set(b, j, w[i][j]);\n        } // for(j=0; j<m; j++)\n        \n        // Cholesky and solve\n        gsl_linalg_cholesky_decomp(SigmaSim);\n        gsl_linalg_cholesky_svx(SigmaSim, b);\n        \n        // Copy into the Kriging Basis\n        for(j=0; j<m; j++) {\n            KrigBasis[i][j] = gsl_vector_get(b, j);\n        }\n    } // for(i=0; i<peta; i++)\n    gsl_matrix_free(SigmaSim);\n    gsl_vector_free(b);\n}\n\n// The actual emulation\n// Cosmological parameters, placeholder for the output, type of output\nvoid emu_noh(double *xstar, double *ystar, int *outtype) {\n    static int inited=0;\n    int i, j, k;\n    double wstar[peta], Sigmastar[peta][m], ystaremu[neta], ystar_allz[rs*nsim], logc;\n    double xstarstd[p];\n    double zemu[rs], ybyz[rs];\n    FILE *fp;\n    // Interpolation stuff for k and then z\n    gsl_spline *lininterp_k = gsl_spline_alloc(gsl_interp_linear, neta/rs);\n    gsl_spline *lininterp_z = gsl_spline_alloc(gsl_interp_linear, rs);\n    gsl_interp_accel *accel = gsl_interp_accel_alloc();\n    \n    // Iinitialize if necessary\n    if(inited==0) {\n        emuInit_noh();\n        inited=1;\n    }\n    \n    // Check the inputs to make sure we're interpolating.\n    for(i=0; i<p; i++) {\n        if((xstar[i] < xmin[i]) || (xstar[i] > xmin[i]+xrange[i])) {\n            //printf(\"The inputs are outside the domain of the emulator.\\n\");\n            switch(i) {\n                case 0:\n                    printf(\"omega_b must be between %f and %f.\\n\", xmin[i], xmin[i]+xrange[i]);\n                    break;\n                case 1:\n                    printf(\"omega_m must be between %f and %f.\\n\", xmin[i], xmin[i]+xrange[i]);\n                    break;\n                case 2:\n                    printf(\"n_s must be between %f and %f.\\n\", xmin[i], xmin[i]+xrange[i]);\n                    break;\n                case 3:\n                    printf(\"w must be between %f and %f.\\n\", xmin[i], xmin[i]+xrange[i]);\n                    break;\n                case 4:\n                    printf(\"sigma_8 must be between %f and %f.\\n\", xmin[i], xmin[i]+xrange[i]);\n                    break;\n            }\n            exit(1);\n        }\n    } // for(i=0; i<p; i++)\n    \n    // Check redshift to make sure we're interpolating\n    if((xstar[p] < 0) || (xstar[p] > 4)) {\n        //printf(\"The inputs are outside the domain of the emulator.\\n\");\n        printf(\"z must between 0 and 4\\n\");\n        exit(1);\n    }\n    \n    // Standardize the inputs\n    for(i=0; i<p; i++) {\n        xstarstd[i] = (xstar[i] - xmin[i]) / xrange[i];\n    }\n    \n    // Compute the covariances between the new input and sims for all PCs\n    for(i=0; i<peta; i++) {\n        for(j=0; j<m; j++) {\n            logc = 0.0;\n            for(k=0; k<p; k++) {\n                logc -= beta[i][k]*pow(x[j][k]-xstarstd[k], 2.0);\n            }\n            Sigmastar[i][j] = exp(logc)/lamz[i];\n        }\n    }\n    \n    // Compute wstar, the predicted PC weights for the new input\n    for(i=0; i<peta; i++) {\n        wstar[i]=0.0;\n        for(j=0; j<m; j++) {\n            wstar[i] += Sigmastar[i][j] * KrigBasis[i][j];\n        }\n    }\n    \n    // Compute ystar, the new output\n    for(i=0; i<neta; i++) {\n        ystaremu[i] = 0.0;\n        for(j=0; j<peta; j++) {\n            ystaremu[i] += K[i][j]*wstar[j];\n        }\n        ystaremu[i] = ystaremu[i]*sd + mean[i];\n    }\n    \n    //printf(\"Emulated\\n\");\n    \n    \n    // Interpolate the emulated output onto the original domain.\n    for(i=0; i<rs; i++) {\n        gsl_spline_init(lininterp_k, kemu, &ystaremu[i*neta/rs], neta/rs);\n        for(j=0; j<nsim; j++) {\n            ystar_allz[i*nsim+j] = gsl_spline_eval(lininterp_k, ksim[j], accel);\n        }\n        gsl_interp_accel_reset(accel);\n    }\n    \n    //printf(\"k interped\\n\");\n    \n    // Fill in the k values for the final output\n    for(i=0; i<nsim; i++) {\n        ystar[i] = ksim[i];\n    }\n    \n    // Interpolate on to the desired redshift\n    // The order needs to be reversed here.\n    for(i=0; i<rs; i++) {\n        zemu[i] = (1/aemu[rs-i-1]) - 1.0;\n    }\n    for(i=0; i<nsim; i++) {\n        // Build an array with the values of y for a given value of z\n        // Reverse the order\n        for(j=0; j<rs; j++) {\n            ybyz[rs-j-1] = ystar_allz[j*nsim+i];\n        }\n        gsl_spline_init(lininterp_z, zemu, ybyz, rs);\n        ystar[nsim+i] = gsl_spline_eval(lininterp_z, xstar[p], accel);\n        gsl_interp_accel_reset(accel);\n    }\n    \n    //printf(\"z interped\\n\");\n    \n    switch(outtype[0]) {\n        default:\n\t   for(j=0; j<nsim; j++) {\n\t     ystar[nsim+j] = pow(10.0,ystar[nsim+j]);\n\t   }\n\n            break;\n        case 1:\n            // Transform to Delta^2\n            for(j=0; j<nsim; j++) {\n                ystar[nsim+j] = ystar[nsim+j] + 1.5*log10(ksim[j]);\n                ystar[nsim+j] = pow(10.0,ystar[nsim+j]);\n            }\n            break;\n        case 2:\n            // Transform to P(k)\n            for(j=0; j<nsim; j++) {\n                ystar[nsim+j] = ystar[nsim+j] - 1.5*log10(ksim[j]);\n                ystar[nsim+j] = pow(10.0,ystar[nsim+j])*2.0*M_PI*M_PI;\n            }\n            break;\n    }\n    \n    // Free some stuff.  I always forget this.  \n    // Thanks to Tim Eifler for discovering it (apparently the hard way).\n    gsl_spline_free(lininterp_z);\n    gsl_spline_free(lininterp_k);\n    gsl_interp_accel_free(accel);\n}\n\n// Linker function for use with Fortran\nvoid emu_noh_(double *x, double *y, int *outtype) {\n    void emu();\n    emu(x,y,outtype);\n}\n\n", "meta": {"hexsha": "3e586be9c1e0dc4963f79f4683a3aa6e3e46cac1", "size": 7829, "ext": "c", "lang": "C", "max_stars_repo_path": "cosmosis-standard-library/structure/FrankenEmu/emu_noh.c", "max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z", "max_issues_repo_path": "cosmosis-standard-library/structure/FrankenEmu/emu_noh.c", "max_issues_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cosmosis-standard-library/structure/FrankenEmu/emu_noh.c", "max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra", "max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z", "avg_line_length": 31.825203252, "max_line_length": 109, "alphanum_fraction": 0.5395325073, "num_tokens": 2365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.38825906654168746}}
{"text": "#ifndef TYPEDEFS\n#define TYPEDEFS\n\n#define MH_REPS 100\n#define TRUE 1\n#define FALSE 0\n\n#include <gsl/gsl_vector.h>\n#include \"utils.h\"\n\ntypedef struct topic\n{\n    double w_tot;                // total # of words assigned to the topic\n    gsl_vector* w_cnt;           // vector of word counts\n    gsl_vector* log_prob_w;      // vector of log probabilities\n    gsl_vector* lgam_w_plus_eta; // to prevent many repeated computations\n\n    double doc_tot;         // total number of doc-level instances\n    double log_doc_tot;     // precomputed log of doc_tot\n    int id;                 // a unique ID for this topic\n\n    int level;              // level in the tree\n    int nchild;             // number of children\n    double scaling;         // scaling factor for my DP\n    struct topic** child;   // array of pointers to child topics\n    struct topic* parent;   // pointer to the parent topic\n    struct tree* tr;        // pointer to my tree\n\n    double prob;            // probability (used to sample a path)\n} topic;\n\n\ntypedef struct tree\n{\n    int depth;              // depth of the tree\n    gsl_vector* eta;        // topic dirichlet parameter\n    gsl_vector* gam;        // scaling parameter (!!! not used; see G prior)\n    double scaling_shape;   // shape parameter for the G prior on scaling\n    double scaling_scale;   // scale parameter for the G prior on scaling\n    topic* root;            // root topic of the tree\n    int next_id;            // the next id for a new topic\n} tree;\n\n\ntypedef struct doc\n{\n    int_vector* word;            // each word\n    int_vector* levels;          // level assigned to each word\n\n    int id;\n    topic** path;                // path of topics\n    gsl_vector* tot_levels;      // level counts (convenience, for sampling)\n    gsl_vector* log_p_level;     // log p(level) [ unnormalized ]\n    double* gem_mean;\n    double* gem_scale;\n    double score;\n} doc;\n\n\ntypedef struct corpus\n{\n    double gem_mean;\n    double gem_scale;\n    int ndoc;\n    int nterms;\n    doc** doc;\n} corpus;\n\ntypedef struct gibbs_state\n{\n    // data and hidden variables\n    corpus* corp;\n    tree* tr;\n\n    // current scores and iteration\n    double score;\n    double gem_score;\n    double eta_score;\n    double gamma_score;\n    double max_score;\n    int iter;\n\n    // log files\n    char* run_dir;\n    FILE* score_log;\n    FILE* tree_structure_log;\n\n    // sampling parameters\n    int shuffle_lag;\n    int hyper_lag;\n    int level_lag;\n    int output_lag;\n    int sample_eta;\n    int sample_gem;\n    int sample_gam;\n} gibbs_state;\n\n#endif\n", "meta": {"hexsha": "efdf5a487d18fe8d409c01b164434d648dda8731", "size": 2562, "ext": "h", "lang": "C", "max_stars_repo_path": "Algorithms/OurAlgo/hlda-c/typedefs.h", "max_stars_repo_name": "thatindiandude/PGM-Project", "max_stars_repo_head_hexsha": "0200fca1bd80de290c5fc01e389d6f0fa736868d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Algorithms/OurAlgo/hlda-c/typedefs.h", "max_issues_repo_name": "thatindiandude/PGM-Project", "max_issues_repo_head_hexsha": "0200fca1bd80de290c5fc01e389d6f0fa736868d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Algorithms/OurAlgo/hlda-c/typedefs.h", "max_forks_repo_name": "thatindiandude/PGM-Project", "max_forks_repo_head_hexsha": "0200fca1bd80de290c5fc01e389d6f0fa736868d", "max_forks_repo_licenses": ["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.8787878788, "max_line_length": 76, "alphanum_fraction": 0.6206088993, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3878769457403569}}
{"text": "/* specfunc/debye.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n/* augmented to n=5 and 6 2005-11-08 by R. J. Mathar, http://www.strw.leidenuniv.nl/~mathar */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_debye.h>\n\n#include \"error.h\"\n#include \"check.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\nstatic double adeb1_data[17] = {\n   2.4006597190381410194,\n   0.1937213042189360089,\n  -0.62329124554895770e-02,\n   0.3511174770206480e-03,\n  -0.228222466701231e-04,\n   0.15805467875030e-05,\n  -0.1135378197072e-06,\n   0.83583361188e-08,\n  -0.6264424787e-09,\n   0.476033489e-10,\n  -0.36574154e-11,\n   0.2835431e-12,\n  -0.221473e-13,\n   0.17409e-14,\n  -0.1376e-15,\n   0.109e-16,\n  -0.9e-18\n};\nstatic cheb_series adeb1_cs = {\n  adeb1_data,\n  16,\n  -1.0, 1.0,\n  9\n};\n\nstatic double adeb2_data[18] = {\n   2.5943810232570770282,\n   0.2863357204530719834,\n  -0.102062656158046713e-01,\n   0.6049109775346844e-03,\n  -0.405257658950210e-04,\n   0.28633826328811e-05,\n  -0.2086394303065e-06,\n   0.155237875826e-07,\n  -0.11731280087e-08,\n   0.897358589e-10,\n  -0.69317614e-11,\n   0.5398057e-12,\n  -0.423241e-13,\n   0.33378e-14,\n  -0.2645e-15,\n   0.211e-16,\n  -0.17e-17,\n   0.1e-18\n};\nstatic cheb_series adeb2_cs = {\n  adeb2_data,\n  17,\n  -1.0, 1.0,\n  10\n};\n\nstatic double adeb3_data[17] = {\n   2.707737068327440945,\n   0.340068135211091751,\n  -0.12945150184440869e-01,\n   0.7963755380173816e-03,\n  -0.546360009590824e-04,\n   0.39243019598805e-05,\n  -0.2894032823539e-06,\n   0.217317613962e-07,\n  -0.16542099950e-08,\n   0.1272796189e-09,\n  -0.987963460e-11,\n   0.7725074e-12,\n  -0.607797e-13,\n   0.48076e-14,\n  -0.3820e-15,\n   0.305e-16,\n  -0.24e-17\n};\nstatic cheb_series adeb3_cs = {\n  adeb3_data,\n  16,\n  -1.0, 1.0,\n  10\n};\n\nstatic double adeb4_data[17] = {\n   2.781869415020523460,\n   0.374976783526892863,\n  -0.14940907399031583e-01,\n   0.945679811437042e-03,\n  -0.66132916138933e-04,\n   0.4815632982144e-05,\n  -0.3588083958759e-06,\n   0.271601187416e-07,\n  -0.20807099122e-08,\n   0.1609383869e-09,\n  -0.125470979e-10,\n   0.9847265e-12,\n  -0.777237e-13,\n   0.61648e-14,\n  -0.4911e-15,\n   0.393e-16,\n  -0.32e-17\n};\nstatic cheb_series adeb4_cs = {\n  adeb4_data,\n  16,\n  -1.0, 1.0,\n  10\n};\n\nstatic double adeb5_data[17] = {\n   2.8340269546834530149,\n   0.3994098857106266445,\n  -0.164566764773099646e-1,\n   0.10652138340664541e-2,\n  -0.756730374875418e-4,\n   0.55745985240273e-5,\n  -0.4190692330918e-6,\n   0.319456143678e-7,\n  -0.24613318171e-8,\n   0.1912801633e-9,\n  -0.149720049e-10,\n   0.11790312e-11,\n  -0.933329e-13,\n   0.74218e-14,\n  -0.5925e-15,\n   0.475e-16,\n  -0.39e-17\n};\nstatic cheb_series adeb5_cs = {\n  adeb5_data,\n  16,\n  -1.0, 1.0,\n  10\n};\n\nstatic double adeb6_data[17] = {\n  2.8726727134130122113,\n  0.4174375352339027746,\n -0.176453849354067873e-1,\n  0.11629852733494556e-2,\n -0.837118027357117e-4,\n  0.62283611596189e-5,\n -0.4718644465636e-6,\n  0.361950397806e-7,\n -0.28030368010e-8,\n  0.2187681983e-9,\n -0.171857387e-10,\n  0.13575809e-11,\n -0.1077580e-12,\n  0.85893e-14,\n -0.6872e-15,\n  0.552e-16,\n -0.44e-17\n};\nstatic cheb_series adeb6_cs = {\n  adeb6_data,\n  16,\n  -1.0, 1.0,\n  10\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_debye_1_e(const double x, gsl_sf_result * result)\n{\n  const double val_infinity = 1.64493406684822644;\n  const double xcut = -GSL_LOG_DBL_MIN;\n\n  /* CHECK_POINTER(result) */\n\n  if(x < 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x < 2.0*GSL_SQRT_DBL_EPSILON) {\n    result->val = 1.0 - 0.25*x + x*x/36.0;\n    result->err = GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x <= 4.0) {\n    const double t = x*x/8.0 - 1.0;\n    gsl_sf_result c;\n    cheb_eval_e(&adeb1_cs, t, &c);\n    result->val = c.val - 0.25 * x;\n    result->err = c.err + 0.25 * x * GSL_DBL_EPSILON;\n    return GSL_SUCCESS;\n  }\n  else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) {\n    const int nexp = floor(xcut/x);\n    const double ex  = exp(-x);\n    double sum = 0.0;\n    double xk  = nexp * x;\n    double rk  = nexp;\n    int i;\n    for(i=nexp; i>=1; i--) {\n      sum *= ex;\n      sum += (1.0 + 1.0/xk)/rk;\n      rk -= 1.0;\n      xk -= x;\n    }\n    result->val = val_infinity/x - sum*ex;\n    result->err = GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x < xcut) {\n    result->val = (val_infinity - exp(-x)*(x+1.0)) / x;\n    result->err = GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    result->val = val_infinity/x;\n    result->err = GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n}\n\n    \nint gsl_sf_debye_2_e(const double x, gsl_sf_result * result)\n{\n  const double val_infinity = 4.80822761263837714;\n  const double xcut = -GSL_LOG_DBL_MIN;\n\n  /* CHECK_POINTER(result) */\n\n  if(x < 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x < 2.0*M_SQRT2*GSL_SQRT_DBL_EPSILON) {\n    result->val = 1.0 - x/3.0 + x*x/24.0;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else if(x <= 4.0) {\n    const double t = x*x/8.0 - 1.0;\n    gsl_sf_result c;\n    cheb_eval_e(&adeb2_cs, t, &c);\n    result->val = c.val - x/3.0;\n    result->err = c.err + GSL_DBL_EPSILON * x/3.0;\n    return GSL_SUCCESS;\n  }\n  else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) {\n    const int nexp = floor(xcut/x);\n    const double ex  = exp(-x);\n    double xk  = nexp * x;\n    double rk  = nexp;\n    double sum = 0.0;\n    int i;\n    for(i=nexp; i>=1; i--) {\n      sum *= ex;\n      sum += (1.0 + 2.0/xk + 2.0/(xk*xk)) / rk;\n      rk -= 1.0;\n      xk -= x;\n    }\n    result->val = val_infinity/(x*x) - 2.0 * sum * ex;\n    result->err = GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x < xcut) {\n    const double x2  = x*x;\n    const double sum = 2.0 + 2.0*x + x2;\n    result->val = (val_infinity - 2.0 * sum * exp(-x)) / x2;\n    result->err = GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    result->val = (val_infinity/x)/x;\n    result->err = GSL_DBL_EPSILON * result->val;\n    CHECK_UNDERFLOW(result);\n    return GSL_SUCCESS;\n  }\n}\n\n\nint gsl_sf_debye_3_e(const double x, gsl_sf_result * result)\n{\n  const double val_infinity = 19.4818182068004875;\n  const double xcut = -GSL_LOG_DBL_MIN;\n\n  /* CHECK_POINTER(result) */\n\n  if(x < 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x < 2.0*M_SQRT2*GSL_SQRT_DBL_EPSILON) {\n    result->val = 1.0 - 3.0*x/8.0 + x*x/20.0;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else if(x <= 4.0) {\n    const double t = x*x/8.0 - 1.0;\n    gsl_sf_result c;\n    cheb_eval_e(&adeb3_cs, t, &c);\n    result->val = c.val - 0.375*x;\n    result->err = c.err + GSL_DBL_EPSILON * 0.375*x;\n    return GSL_SUCCESS;\n  }\n  else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) {\n    const int nexp = floor(xcut/x);\n    const double ex  = exp(-x);\n    double xk  = nexp * x;\n    double rk  = nexp;\n    double sum = 0.0;\n    int i;\n    for(i=nexp; i>=1; i--) {\n      double xk_inv = 1.0/xk;\n      sum *= ex;\n      sum += (((6.0*xk_inv + 6.0)*xk_inv + 3.0)*xk_inv + 1.0) / rk;\n      rk -= 1.0;\n      xk -= x;\n    }\n    result->val = val_infinity/(x*x*x) - 3.0 * sum * ex;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else if(x < xcut) {\n    const double x3 = x*x*x;\n    const double sum = 6.0 + 6.0*x + 3.0*x*x + x3;\n    result->val = (val_infinity - 3.0 * sum * exp(-x)) / x3;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else {\n    result->val = ((val_infinity/x)/x)/x;\n    result->err = GSL_DBL_EPSILON * result->val;\n    CHECK_UNDERFLOW(result);\n    return GSL_SUCCESS;\n  }\n}\n\n\nint gsl_sf_debye_4_e(const double x, gsl_sf_result * result)\n{\n  const double val_infinity = 99.5450644937635129;\n  const double xcut = -GSL_LOG_DBL_MIN;\n\n  /* CHECK_POINTER(result) */\n\n  if(x < 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x < 2.0*M_SQRT2*GSL_SQRT_DBL_EPSILON) {\n    result->val = 1.0 - 2.0*x/5.0 + x*x/18.0;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else if(x <= 4.0) {\n    const double t = x*x/8.0 - 1.0;\n    gsl_sf_result c;\n    cheb_eval_e(&adeb4_cs, t, &c);\n    result->val = c.val - 2.0*x/5.0;\n    result->err = c.err + GSL_DBL_EPSILON * 2.0*x/5.0;\n    return GSL_SUCCESS;\n  }\n  else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) {\n    const int nexp = floor(xcut/x);\n    const double ex  = exp(-x);\n    double xk  = nexp * x;\n    double rk  = nexp;\n    double sum = 0.0;\n    int i;\n    for(i=nexp; i>=1; i--) {\n      double xk_inv = 1.0/xk;\n      sum *= ex;\n      sum += ((((24.0*xk_inv + 24.0)*xk_inv + 12.0)*xk_inv + 4.0)*xk_inv + 1.0) / rk;\n      rk -= 1.0;\n      xk -= x;\n    }\n    result->val = val_infinity/(x*x*x*x) - 4.0 * sum * ex;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else if(x < xcut) {\n    const double x2 = x*x;\n    const double x4 = x2*x2;\n    const double sum = 24.0 + 24.0*x + 12.0*x2 + 4.0*x2*x + x4;\n    result->val = (val_infinity - 4.0 * sum * exp(-x)) / x4;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else {\n    result->val = (((val_infinity/x)/x)/x)/x;\n    result->err = GSL_DBL_EPSILON * result->val;\n    CHECK_UNDERFLOW(result);\n    return GSL_SUCCESS;\n  }\n}\n\nint gsl_sf_debye_5_e(const double x, gsl_sf_result * result)\n{\n  const double val_infinity = 610.405837190669483828710757875 ;\n  const double xcut = -GSL_LOG_DBL_MIN;\n\n  /* CHECK_POINTER(result) */\n\n  if(x < 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x < 2.0*M_SQRT2*GSL_SQRT_DBL_EPSILON) {\n    result->val = 1.0 - 5.0*x/12.0 + 5.0*x*x/84.0;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else if(x <= 4.0) {\n    const double t = x*x/8.0 - 1.0;\n    gsl_sf_result c;\n    cheb_eval_e(&adeb5_cs, t, &c);\n    result->val = c.val - 5.0*x/12.0;\n    result->err = c.err + GSL_DBL_EPSILON * 5.0*x/12.0;\n    return GSL_SUCCESS;\n  }\n  else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) {\n    const int nexp = floor(xcut/x);\n    const double ex  = exp(-x);\n    double xk  = nexp * x;\n    double rk  = nexp;\n    double sum = 0.0;\n    int i;\n    for(i=nexp; i>=1; i--) {\n      double xk_inv = 1.0/xk;\n      sum *= ex;\n      sum += (((((120.0*xk_inv + 120.0)*xk_inv + 60.0)*xk_inv + 20.0)*xk_inv + 5.0)*xk_inv+ 1.0) / rk;\n      rk -= 1.0;\n      xk -= x;\n    }\n    result->val = val_infinity/(x*x*x*x*x) - 5.0 * sum * ex;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else if(x < xcut) {\n    const double x2 = x*x;\n    const double x4 = x2*x2;\n    const double x5 = x4*x;\n    const double sum = 120.0 + 120.0*x + 60.0*x2 + 20.0*x2*x + 5.0*x4 + x5;\n    result->val = (val_infinity - 5.0 * sum * exp(-x)) / x5;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else {\n    result->val = ((((val_infinity/x)/x)/x)/x)/x;\n    result->err = GSL_DBL_EPSILON * result->val;\n    CHECK_UNDERFLOW(result);\n    return GSL_SUCCESS;\n  }\n}\n\nint gsl_sf_debye_6_e(const double x, gsl_sf_result * result)\n{\n  const double val_infinity = 4356.06887828990661194792541535 ;\n  const double xcut = -GSL_LOG_DBL_MIN;\n\n  /* CHECK_POINTER(result) */\n\n  if(x < 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x < 2.0*M_SQRT2*GSL_SQRT_DBL_EPSILON) {\n    result->val = 1.0 - 3.0*x/7.0 + x*x/16.0;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else if(x <= 4.0) {\n    const double t = x*x/8.0 - 1.0;\n    gsl_sf_result c;\n    cheb_eval_e(&adeb6_cs, t, &c);\n    result->val = c.val - 3.0*x/7.0;\n    result->err = c.err + GSL_DBL_EPSILON * 3.0*x/7.0;\n    return GSL_SUCCESS;\n  }\n  else if(x < -(M_LN2 + GSL_LOG_DBL_EPSILON)) {\n    const int nexp = floor(xcut/x);\n    const double ex  = exp(-x);\n    double xk  = nexp * x;\n    double rk  = nexp;\n    double sum = 0.0;\n    int i;\n    for(i=nexp; i>=1; i--) {\n      double xk_inv = 1.0/xk;\n      sum *= ex;\n      sum += ((((((720.0*xk_inv + 720.0)*xk_inv + 360.0)*xk_inv + 120.0)*xk_inv + 30.0)*xk_inv+ 6.0)*xk_inv+ 1.0) / rk;\n      rk -= 1.0;\n      xk -= x;\n    }\n    result->val = val_infinity/(x*x*x*x*x*x) - 6.0 * sum * ex;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else if(x < xcut) {\n    const double x2 = x*x;\n    const double x4 = x2*x2;\n    const double x6 = x4*x2;\n    const double sum = 720.0 + 720.0*x + 360.0*x2 + 120.0*x2*x + 30.0*x4 + 6.0*x4*x +x6 ;\n    result->val = (val_infinity - 6.0 * sum * exp(-x)) / x6;\n    result->err = GSL_DBL_EPSILON * result->val;\n    return GSL_SUCCESS;\n  }\n  else {\n    result->val = (((((val_infinity/x)/x)/x)/x)/x)/x ;\n    result->err = GSL_DBL_EPSILON * result->val;\n    CHECK_UNDERFLOW(result);\n    return GSL_SUCCESS;\n  }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_debye_1(const double x)\n{\n  EVAL_RESULT(gsl_sf_debye_1_e(x, &result));\n}\n\ndouble gsl_sf_debye_2(const double x)\n{\n  EVAL_RESULT(gsl_sf_debye_2_e(x, &result));\n}\n\ndouble gsl_sf_debye_3(const double x)\n{\n  EVAL_RESULT(gsl_sf_debye_3_e(x, &result));\n}\n\ndouble gsl_sf_debye_4(const double x)\n{\n  EVAL_RESULT(gsl_sf_debye_4_e(x, &result));\n}\n\ndouble gsl_sf_debye_5(const double x)\n{\n  EVAL_RESULT(gsl_sf_debye_5_e(x, &result));\n}\n\ndouble gsl_sf_debye_6(const double x)\n{\n  EVAL_RESULT(gsl_sf_debye_6_e(x, &result));\n}\n", "meta": {"hexsha": "07c2f570bdad60c643165d49933b72f2f4eb2d3c", "size": 14080, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/debye.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/debye.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/debye.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 24.8324514991, "max_line_length": 119, "alphanum_fraction": 0.6095170455, "num_tokens": 5569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.38775265990467467}}
{"text": "#pragma once\n\n#include \"rev/Utilities.h\"\n#include \"rev/geometry/Tools.h\"\n#include <array>\n#include <glm/glm.hpp>\n#include <gsl/gsl_assert>\n#include <iostream>\n#include <limits>\n#include <set>\n#include <unordered_set>\n#include <variant>\n#include <vector>\n\nnamespace rev {\n\ntemplate <typename SurfaceData>\nstruct Triangle {\n    std::array<glm::vec3, 3> vertices;\n    SurfaceData data;\n\n    AxisAlignedBoundingBox getBoundingBox() const\n    {\n        AxisAlignedBoundingBox box;\n        for (const auto& vertex : vertices) {\n            box.expandToVertex(vertex);\n        }\n        return box;\n    }\n\n    glm::vec3 getNormal() const\n    {\n        auto e1 = vertices[1] - vertices[0];\n        auto e2 = vertices[2] - vertices[0];\n        return glm::normalize(glm::cross(e1, e2));\n    }\n\n    bool isLeftOfPlane(const AxisAlignedPlane& plane) const\n    {\n        for (const auto& vertex : vertices) {\n            if (vertex[plane.dimensionIndex] < plane.boundary) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    bool isRightOfPlane(const AxisAlignedPlane& plane) const\n    {\n        for (const auto& vertex : vertices) {\n            if (vertex[plane.dimensionIndex] > plane.boundary) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    std::optional<AxisAlignedBoundingBox> clippedBoundingBox(const AxisAlignedBoundingBox& box)\n    {\n        // Alternate between these two buffers for input and output\n        std::array<glm::vec3, 9> buf1{};\n        std::array<glm::vec3, 9> buf2{};\n\n        // Fill the input buffer\n        for (int i = 0; i < 3; i++) {\n            buf1[i] = vertices[i];\n        }\n\n        // Clip the triangle by all sides of our bounding box\n        auto inputIter = buf1.data();\n        auto inputEnd = inputIter + 3;\n        auto outputIter = buf2.data();\n\n        // First the min planes in each dimension\n        for (uint8_t dim = 0; dim < 3; dim++) {\n            gsl::span<glm::vec3> inputRange(inputIter, inputEnd);\n            OutputIteratorPolygonBuilder builder(outputIter);\n            AxisAlignedPlane boundary = { dim, box.minimum[dim] };\n            boundary.splitConvexPolygon(inputRange, NullPolygonBuilder(), builder);\n\n            if (std::distance(outputIter, builder.getIterator()) < 3) {\n                return {};\n            }\n\n            std::swap(inputIter, outputIter);\n            inputEnd = builder.getIterator();\n        }\n\n        // Now the max planes in each dimension\n        for (uint8_t dim = 0; dim < 3; dim++) {\n            gsl::span<glm::vec3> inputRange(inputIter, inputEnd);\n            OutputIteratorPolygonBuilder builder(outputIter);\n            AxisAlignedPlane boundary = { dim, box.maximum[dim] };\n            boundary.splitConvexPolygon(inputRange, builder, NullPolygonBuilder());\n\n            if (std::distance(outputIter, builder.getIterator()) < 3) {\n                return {};\n            }\n\n            std::swap(inputIter, outputIter);\n            inputEnd = builder.getIterator();\n        }\n\n        gsl::span<glm::vec3> inputRange(inputIter, inputEnd);\n        auto clippedBox = smallestBoxContainingVertices(inputRange);\n        clippedBox.reduceToBox(box);\n        return clippedBox;\n    }\n\n    struct Hit {\n        glm::vec2 uv;\n        float t;\n    };\n\n    std::optional<Hit> castRay(const Ray& ray) const\n    {\n        glm::vec3 edge1 = vertices[1] - vertices[0];\n        glm::vec3 edge2 = vertices[2] - vertices[0];\n\n        glm::vec3 p = glm::cross(ray.direction, edge2);\n        float determinant = glm::dot(edge1, p);\n        if (abs(determinant) < std::numeric_limits<float>::epsilon()) {\n            // The ray is parallel.\n            return std::nullopt;\n        }\n\n        glm::vec3 fromV0 = ray.origin - vertices[0];\n        float u = glm::dot(fromV0, p) / determinant;\n        if (u < 0.0f || u > 1.0f) {\n            return std::nullopt;\n        }\n\n        glm::vec3 q = glm::cross(fromV0, edge1);\n        float v = glm::dot(ray.direction, q) / determinant;\n        if (v < 0.0f || v > 1.0f) {\n            return std::nullopt;\n        }\n\n        float t = glm::dot(edge2, q) / determinant;\n        if (t < 0.0f) {\n            return std::nullopt;\n        }\n\n        return Hit{ { u, v }, t };\n    }\n\n    glm::vec3 baryCentricToCartesian(glm::vec2 uv)\n    {\n        float u = uv[0];\n        float v = uv[1];\n        float w = 1.0f - (u + v);\n        return w * vertices[0] + u * vertices[1] + v * vertices[2];\n    }\n\n    glm::vec2 cartesianToBarycentric(glm::vec3 position)\n    {\n        glm::vec3 v0 = vertices[1] - vertices[0];\n        glm::vec3 v1 = vertices[2] - vertices[0];\n        glm::vec3 v2 = position - vertices[0];\n\n        float d00 = glm::dot(v0, v0);\n        float d01 = glm::dot(v0, v1);\n        float d11 = glm::dot(v1, v1);\n        float d20 = glm::dot(v2, v0);\n        float d21 = glm::dot(v2, v1);\n        float denom = d00 * d11 - d01 * d01;\n\n        float v = (d11 * d20 - d01 * d21) / denom;\n        float w = (d00 * d21 - d01 * d20) / denom;\n        float u = 1.0f - v - w;\n\n        return { u, v };\n    }\n\n    std::optional<float> intersectsSphere(const Sphere& sphere)\n    {\n        glm::vec3 normal = getNormal();\n        float t = glm::dot(normal, (vertices[0] - sphere.center));\n        if (sphere.radius < abs(t)) {\n            // Closest point to the triangle is outside the sphere.\n            return std::nullopt;\n        }\n\n        glm::vec3 closestPoint = sphere.center - (normal * t);\n        glm::vec2 cpBary = cartesianToBarycentric(closestPoint);\n        size_t outsideCount = 0;\n        glm::bvec3 isOutside{};\n        if (cpBary[0] < 0.0f) {\n            outsideCount++;\n            isOutside[0] = true;\n        }\n\n        if (cpBary[1] < 0.0f) {\n            outsideCount++;\n            isOutside[1] = true;\n        }\n\n        if ((1.0f - (cpBary[0] + cpBary[1])) < 0.0f) {\n            outsideCount++;\n            isOutside[2] = true;\n        }\n\n        if (outsideCount == 0) {\n            // Closest point is inside the triangle and inside the sphere.\n            return t;\n        }\n\n        // Calculate the square of the radius of the cross section of the sphere passing through\n        // the triangle's plane.\n        float r2 = (sphere.radius * sphere.radius) - (t * t);\n\n        if (outsideCount == 1) {\n            // We need to find the distance to the edge (squared) here.\n            glm::vec3 edge;\n            glm::vec3 toVertex;\n            if (isOutside[0]) {\n                edge = vertices[2] - vertices[1];\n                toVertex = closestPoint - vertices[1];\n            } else if (isOutside[1]) {\n                edge = vertices[2] - vertices[0];\n                toVertex = closestPoint - vertices[0];\n            } else {\n                edge = vertices[1] - vertices[0];\n                toVertex = closestPoint - vertices[0];\n            }\n\n            float toVertexLength = glm::length(toVertex);\n            float legLength = glm::dot(edge, toVertex) / toVertexLength;\n\n            return ((toVertexLength * toVertexLength) - (legLength * legLength)) < r2;\n        }\n\n        // Otherwise, one of the vertices is actually the closest point on the triangle.\n        glm::vec3 toVertex;\n        if (!isOutside[0]) {\n            toVertex = closestPoint - vertices[0];\n        } else if (!isOutside[1]) {\n            toVertex = closestPoint - vertices[1];\n        } else {\n            toVertex = closestPoint - vertices[2];\n        }\n\n        return glm::dot(toVertex, toVertex) < r2;\n    }\n};\n\ntemplate <typename SurfaceData>\nstruct LeafNode {\n    std::unordered_set<Triangle<SurfaceData>*> triangles;\n};\n\ntemplate <typename SurfaceData>\nstruct BranchNode;\n\ntemplate <typename SurfaceData>\nusing MapNode = std::variant<LeafNode<SurfaceData>, BranchNode<SurfaceData>>;\n\ntemplate <typename SurfaceData>\nstruct BranchNode {\n    AxisAlignedPlane split;\n\n    std::unique_ptr<MapNode<SurfaceData>> left;\n    std::unique_ptr<MapNode<SurfaceData>> right;\n};\n\ntemplate <typename SurfaceData>\nclass KDTree {\npublic:\n    KDTree(std::vector<std::unique_ptr<Triangle<SurfaceData>>> triangles,\n        std::unique_ptr<MapNode<SurfaceData>> root, const AxisAlignedBoundingBox boundingBox)\n        : _triangles(std::move(triangles))\n        , _root(std::move(root))\n        , _boundingBox(boundingBox)\n    {\n    }\n\n    struct Hit {\n        Triangle<SurfaceData>* triangle;\n        glm::vec2 uv;\n        float t;\n    };\n\n    std::optional<Hit> castRay(\n        const Ray& ray, float maxDistance = std::numeric_limits<float>::infinity()) const\n    {\n        if (_boundingBox.containsPoint(ray.origin)) {\n            AxisAlignedBoundingBox::Hit entryPoint{ ray.origin, 0.0f, 0 };\n            return getHit(*_root, ray, _boundingBox, entryPoint, maxDistance);\n        } else {\n            auto hit = _boundingBox.castExternalRay(ray);\n            if (!hit || (hit->t > maxDistance)) {\n                return std::nullopt;\n            }\n            return getHit(*_root, ray, _boundingBox, *hit, maxDistance);\n        }\n    }\n\n    template <typename Visitor>\n    void visitTrianglesIntersectingSphere(const Sphere& sphere, Visitor&& visitor) const\n    {\n        std::visit(\n            [this, &sphere, &visitor](const auto& node) {\n                visitTrianglesIntersectingSphereInNode(\n                    sphere, std::forward<Visitor>(visitor), _boundingBox, node);\n            },\n            *_root);\n    }\n\n    void dump() const\n    {\n        std::cout << \"[KDTree]{\" << std::endl;\n        printBoundingBox(_boundingBox, 2);\n        std::visit([this](const auto& root) { printNode(_boundingBox, root, 2); }, *_root);\n        std::cout << \"}\" << std::endl;\n    }\n\nprivate:\n    std::optional<Hit> getHit(const MapNode<SurfaceData>& node, const Ray& ray,\n        const AxisAlignedBoundingBox& box, AxisAlignedBoundingBox::Hit& entryPoint,\n        float maxDistance) const\n    {\n        return std::visit(\n            [this, &ray, &box, &entryPoint, maxDistance](\n                const auto& node) { return getHit(node, ray, box, entryPoint, maxDistance); },\n            node);\n    }\n\n    std::optional<Hit> getHit(const BranchNode<SurfaceData>& node, const Ray& ray,\n        const AxisAlignedBoundingBox& box, AxisAlignedBoundingBox::Hit& entryPoint,\n        float maxDistance) const\n    {\n        auto [leftBox, rightBox] = box.split(node.split);\n        float position = entryPoint.intersectionPoint[node.split.dimensionIndex];\n        bool goLeft;\n        if (position < node.split.boundary) {\n            goLeft = true;\n        } else if (position > node.split.boundary) {\n            goLeft = false;\n        } else if (ray.direction[node.split.dimensionIndex] < 0.0f) {\n            goLeft = false;\n        } else if (ray.direction[node.split.dimensionIndex] > 0.0f) {\n            goLeft = true;\n        } else {\n            return std::nullopt;\n        }\n\n        MapNode<SurfaceData>* childNode = goLeft ? node.left.get() : node.right.get();\n        auto hit = getHit(*childNode, ray, (goLeft ? leftBox : rightBox), entryPoint, maxDistance);\n        if (hit) {\n            return hit;\n        }\n        if (entryPoint.t > maxDistance) {\n            return std::nullopt;\n        }\n        if (entryPoint.planeDimension != node.split.dimensionIndex) {\n            return std::nullopt;\n        }\n\n        bool shouldTryOtherChild;\n        if (goLeft) {\n            shouldTryOtherChild = (ray.direction[node.split.dimensionIndex] > 0.0f);\n        } else {\n            shouldTryOtherChild = (ray.direction[node.split.dimensionIndex] < 0.0f);\n        }\n\n        if (shouldTryOtherChild) {\n            childNode = goLeft ? node.right.get() : node.left.get();\n            return getHit(*childNode, ray, (goLeft ? rightBox : leftBox), entryPoint, maxDistance);\n        }\n        return std::nullopt;\n    }\n\n    std::optional<Hit> getHit(const LeafNode<SurfaceData>& node, const Ray& ray,\n        const AxisAlignedBoundingBox& box, AxisAlignedBoundingBox::Hit& entryPoint,\n        float maxDistance) const\n    {\n        float t = std::numeric_limits<float>::infinity();\n        std::optional<Hit> bestHit;\n        for (const auto& triangle : node.triangles) {\n            auto hit = triangle->castRay(ray);\n            if (hit) {\n                if (!bestHit || (hit->t < bestHit->t)) {\n                    bestHit = Hit{ triangle, hit->uv, hit->t };\n                }\n            }\n        }\n\n        if (bestHit && !(bestHit->t > maxDistance)) {\n            return bestHit;\n        }\n\n        auto boxHit = box.castInternalRay(ray);\n        entryPoint = boxHit;\n\n        return std::nullopt;\n    }\n\n    template <typename Visitor>\n    void visitTrianglesIntersectingSphereInNode(const Sphere& sphere, Visitor&& visitor,\n        const AxisAlignedBoundingBox& box, const LeafNode<SurfaceData>& node) const\n    {\n        if (!box.intersectsSphere(sphere)) {\n            return;\n        }\n\n        for (const auto& triangle : node.triangles) {\n            auto hit = triangle->intersectsSphere(sphere);\n            if (hit) {\n                visitor(*triangle, *hit);\n            }\n        }\n    }\n\n    template <typename Visitor>\n    void visitTrianglesIntersectingSphereInNode(const Sphere& sphere, Visitor&& visitor,\n        const AxisAlignedBoundingBox& box, const BranchNode<SurfaceData>& node) const\n    {\n        if (!box.intersectsSphere(sphere)) {\n            return;\n        }\n\n        auto [leftBox, rightBox] = box.split(node.split);\n        std::visit(\n            [this, leftBox = leftBox, &sphere, &visitor](const auto& node) {\n                visitTrianglesIntersectingSphereInNode(\n                    sphere, std::forward<Visitor>(visitor), leftBox, node);\n            },\n            *node.left);\n        std::visit(\n            [this, rightBox = rightBox, &sphere, &visitor](const auto& node) {\n                visitTrianglesIntersectingSphereInNode(\n                    sphere, std::forward<Visitor>(visitor), rightBox, node);\n            },\n            *node.right);\n    }\n\n    void printIndent(size_t indent = 0) const\n    {\n        for (size_t i = 0; i < indent; i++) {\n            std::cout << \" \";\n        }\n    }\n\n    void printVertex(const glm::vec3& vertex) const\n    {\n        std::cout << \"(\" << vertex.x << \", \" << vertex.y << \", \" << vertex.z << \")\";\n    }\n\n    void printBoundingBox(const AxisAlignedBoundingBox& box, size_t indent = 0) const\n    {\n        printIndent(indent);\n        std::cout << \"[Box]{ Min: \";\n        printVertex(box.minimum);\n        std::cout << \" Max: \";\n        printVertex(box.maximum);\n        std::cout << \" }\" << std::endl;\n    }\n\n    void printTriangle(const Triangle<SurfaceData>& triangle, size_t indent = 0) const\n    {\n        printIndent(indent);\n        std::cout << \"[Triangle]{\" << std::endl;\n        for (const auto& vertex : triangle.vertices) {\n            printIndent(indent + 2);\n            printVertex(vertex);\n            std::cout << std::endl;\n        }\n        printIndent(indent);\n        std::cout << \"}\" << std::endl;\n    }\n\n    void printNode(const AxisAlignedBoundingBox& box, const LeafNode<SurfaceData>& node,\n        size_t indent = 0) const\n    {\n        printIndent(indent);\n        std::cout << \"[Leaf]{\" << std::endl;\n        printBoundingBox(box, indent + 2);\n        for (const auto& triangle : node.triangles) {\n            printTriangle(*triangle, indent + 2);\n        }\n        printIndent(indent);\n        std::cout << \"}\" << std::endl;\n    }\n\n    void printNode(const AxisAlignedBoundingBox& box, const BranchNode<SurfaceData>& node,\n        size_t indent = 0) const\n    {\n        printIndent(indent);\n        std::cout << \"[Branch]{\" << std::endl;\n        printBoundingBox(box, indent + 2);\n        auto [leftBox, rightBox] = box.split(node.split);\n        std::visit([this, indent, leftBox = leftBox](\n                       const auto& childNode) { printNode(leftBox, childNode, indent + 2); },\n            *node.left);\n        std::visit([this, indent, rightBox = rightBox](\n                       const auto& childNode) { printNode(rightBox, childNode, indent + 2); },\n            *node.right);\n        printIndent(indent);\n        std::cout << \"}\" << std::endl;\n    }\n\n    std::vector<std::unique_ptr<Triangle<SurfaceData>>> _triangles;\n    std::unique_ptr<MapNode<SurfaceData>> _root;\n    AxisAlignedBoundingBox _boundingBox;\n};\n\ntemplate <typename SurfaceData>\nclass KDTreeBuilder {\npublic:\n    void addTriangle(std::array<glm::vec3, 3> vertices, SurfaceData data)\n    {\n        Expects(!glm::any(glm::isnan(vertices[0])));\n        Expects(!glm::any(glm::isnan(vertices[1])));\n        Expects(!glm::any(glm::isnan(vertices[2])));\n\n        auto triangle\n            = std::make_unique<Triangle<SurfaceData>>(Triangle<SurfaceData>{ vertices, data });\n        auto boundingBox = smallestBoxContainingVertices(vertices);\n        _boundingBox.expandToBox(boundingBox);\n\n        for (const auto& event : buildTriangleEvents(boundingBox, triangle.get())) {\n            _events.insert(event);\n        }\n        _triangles.push_back(std::move(triangle));\n    }\n\n    KDTree<SurfaceData> build()\n    {\n        Expects(!_triangles.empty());\n        Expects(!_events.empty());\n\n        std::unordered_set<Triangle<SurfaceData>*> triangleSet;\n        for (const auto& triangle : _triangles) {\n            triangleSet.insert(triangle.get());\n        }\n        auto rootNode = createNode(_boundingBox, std::move(_events), triangleSet);\n        return KDTree<SurfaceData>{ std::move(_triangles), std::move(rootNode), _boundingBox };\n    }\n\nprivate:\n    static constexpr float kTraversalCost = 15.0f;\n    static constexpr float kIntersectionCost = 20.0f;\n    static constexpr float kEmptySplitDiscount = 0.8f;\n\n    enum class Side {\n        Left,\n        Right,\n    };\n\n    struct Event {\n        enum class Type {\n            Ending = 0,\n            Planar = 1,\n            Starting = 2,\n        };\n\n        bool operator<(const Event& other) const\n        {\n            auto tuplify = [](const Event& event) {\n                return std::tie(event.separationPlane.boundary,\n                    event.separationPlane.dimensionIndex, event.type, event.triangle);\n            };\n            return tuplify(*this) < tuplify(other);\n        }\n\n        Triangle<SurfaceData>* triangle;\n        AxisAlignedPlane separationPlane;\n        Type type;\n    };\n\n    std::unique_ptr<MapNode<SurfaceData>> createNode(const AxisAlignedBoundingBox& box,\n        std::set<Event> events, std::unordered_set<Triangle<SurfaceData>*> triangles)\n    {\n        size_t triangleCount = triangles.size();\n        if (triangleCount > 0) {\n            auto [plane, side, cost] = findBestSplit(box, events, triangleCount);\n            float terminateCost = static_cast<float>(triangleCount) * kIntersectionCost;\n            if (terminateCost > cost) {\n                std::unordered_set<Triangle<SurfaceData>*> leftTriangles;\n                std::unordered_set<Triangle<SurfaceData>*> rightTriangles;\n\n                for (const auto& event : events) {\n                    const auto& eventPlane = event.separationPlane;\n                    if (eventPlane.dimensionIndex != plane.dimensionIndex) {\n                        continue;\n                    }\n\n                    if (eventPlane.boundary < plane.boundary) {\n                        if (event.type != Event::Type::Starting) {\n                            size_t erased = triangles.erase(event.triangle);\n                            Expects(erased == 1);\n                            leftTriangles.insert(event.triangle);\n\n                            Expects(event.triangle->isLeftOfPlane(plane));\n                        }\n                    } else if (eventPlane.boundary > plane.boundary) {\n                        if (event.type != Event::Type::Ending) {\n                            size_t erased = triangles.erase(event.triangle);\n                            Expects(erased == 1);\n                            rightTriangles.insert(event.triangle);\n\n                            Expects(event.triangle->isRightOfPlane(plane));\n                        }\n                    } else {\n                        // On the boundary\n                        size_t erased = triangles.erase(event.triangle);\n                        Expects(erased == 1);\n                        switch (event.type) {\n                        case Event::Type::Starting:\n                            rightTriangles.insert(event.triangle);\n                            Expects(event.triangle->isRightOfPlane(plane));\n                            break;\n                        case Event::Type::Ending:\n                            leftTriangles.insert(event.triangle);\n                            Expects(event.triangle->isLeftOfPlane(plane));\n                            break;\n                        case Event::Type::Planar:\n                            if (side == Side::Left) {\n                                leftTriangles.insert(event.triangle);\n                            } else {\n                                rightTriangles.insert(event.triangle);\n                            }\n                            break;\n                        }\n                    }\n                }\n\n                std::set<Event> leftEvents;\n                std::set<Event> rightEvents;\n                for (const auto& event : events) {\n                    if (leftTriangles.count(event.triangle)) {\n                        leftEvents.insert(event);\n                    } else if (rightTriangles.count(event.triangle)) {\n                        rightEvents.insert(event);\n                    }\n                }\n\n                auto [leftBox, rightBox] = box.split(plane);\n                // Overlapping triangles remain\n                for (const auto& triangle : triangles) {\n                    Expects(triangle->isLeftOfPlane(plane));\n                    Expects(triangle->isRightOfPlane(plane));\n\n                    auto leftClipBox = triangle->clippedBoundingBox(leftBox);\n                    if (leftClipBox) {\n                        for (const auto& event : buildTriangleEvents(*leftClipBox, triangle))\n                        {\n                            leftEvents.insert(event);\n                        }\n                        leftTriangles.insert(triangle);\n                    }\n\n                    auto rightClipBox = triangle->clippedBoundingBox(rightBox);\n                    if (rightClipBox) {\n                        for (const auto& event : buildTriangleEvents(*rightClipBox, triangle))\n                        {\n                            rightEvents.insert(event);\n                        }\n                        rightTriangles.insert(triangle);\n                    }\n                }\n                triangles.clear();\n                events.clear();\n\n                return std::make_unique<MapNode<SurfaceData>>(BranchNode<SurfaceData>{\n                    plane,\n                    createNode(leftBox, std::move(leftEvents), std::move(leftTriangles)),\n                    createNode(rightBox, std::move(rightEvents), std::move(rightTriangles)),\n                });\n            }\n        }\n        return std::make_unique<MapNode<SurfaceData>>(\n            LeafNode<SurfaceData>{ std::move(triangles) });\n    }\n\n    std::set<Event> buildTriangleEvents(\n        const AxisAlignedBoundingBox& boundingBox, Triangle<SurfaceData>* triangle)\n    {\n        AxisAlignedBoundingBox actualBox = triangle->getBoundingBox();\n        std::set<Event> events;\n        for (uint8_t k = 0; k < 3; k++) {\n            float minimum = boundingBox.minimum[k];\n            float maximum = boundingBox.maximum[k];\n            Expects(!(minimum < actualBox.minimum[k]));\n            Expects(!(maximum > actualBox.maximum[k]));\n            if (minimum < maximum) {\n                events.insert(\n                    Event{ triangle, AxisAlignedPlane{ k, maximum }, Event::Type::Ending });\n                events.insert(\n                    Event{ triangle, AxisAlignedPlane{ k, minimum }, Event::Type::Starting });\n            } else {\n                events.insert(\n                    Event{ triangle, AxisAlignedPlane{ k, minimum }, Event::Type::Planar });\n            }\n        }\n        return events;\n    }\n\n    std::tuple<AxisAlignedPlane, Side, float> findBestSplit(\n        const AxisAlignedBoundingBox& box, const std::set<Event>& events, size_t triangleCount)\n    {\n        float bestCost = std::numeric_limits<float>::infinity();\n        AxisAlignedPlane bestPlane;\n        Side bestSide;\n\n        std::array<size_t, 3> leftTriangleCounts{ 0 };\n        std::array<size_t, 3> rightTriangleCounts{ triangleCount, triangleCount, triangleCount };\n        auto iter = events.begin();\n        auto eventsEnd = events.end();\n        while (iter != eventsEnd) {\n            const AxisAlignedPlane& candidatePlane = iter->separationPlane;\n            uint8_t dimension = candidatePlane.dimensionIndex;\n            size_t endingTriangleCount = 0;\n            size_t planarTriangleCount = 0;\n            size_t startingTriangleCount = 0;\n            auto validate = [&eventsEnd, &candidatePlane, dimension](const auto& iter) {\n                return (iter != eventsEnd)\n                    && !(iter->separationPlane.boundary > candidatePlane.boundary)\n                    && (iter->separationPlane.dimensionIndex == dimension);\n            };\n            while (validate(iter) && (iter->type == Event::Type::Ending)) {\n                endingTriangleCount++;\n                iter++;\n            }\n            while (validate(iter) && (iter->type == Event::Type::Planar)) {\n                planarTriangleCount++;\n                iter++;\n            }\n            while (validate(iter) && (iter->type == Event::Type::Starting)) {\n                startingTriangleCount++;\n                iter++;\n            }\n            rightTriangleCounts[dimension] -= planarTriangleCount;\n            rightTriangleCounts[dimension] -= endingTriangleCount;\n            auto [side, cost] = surfaceAreaCostHeuristic(box, candidatePlane,\n                leftTriangleCounts[dimension], planarTriangleCount, rightTriangleCounts[dimension]);\n            if (cost < bestCost) {\n                bestCost = cost;\n                bestPlane = candidatePlane;\n                bestSide = side;\n            }\n            leftTriangleCounts[dimension] += planarTriangleCount;\n            leftTriangleCounts[dimension] += startingTriangleCount;\n        }\n        return { bestPlane, bestSide, bestCost };\n    }\n\n    std::pair<Side, float> surfaceAreaCostHeuristic(const AxisAlignedBoundingBox& box,\n        const AxisAlignedPlane& splitPlane, size_t leftTriangleCount, size_t planarTriangleCount,\n        size_t rightTriangleCount)\n    {\n        auto [leftBox, rightBox] = box.split(splitPlane);\n        float boxSurfaceArea = box.getSurfaceArea();\n\n        float leftArea = leftBox.getSurfaceArea() / boxSurfaceArea;\n        float rightArea = rightBox.getSurfaceArea() / boxSurfaceArea;\n        bool removesVolume = (leftBox.getVolume() > 0.0f) && (rightBox.getVolume() > 0.0f);\n\n        auto cost = [leftArea, rightArea, removesVolume](\n                        size_t leftTriangleCount, size_t rightTriangleCount) {\n            float cost = static_cast<float>(leftTriangleCount) * leftArea\n                + static_cast<float>(rightTriangleCount) * rightArea;\n            if (removesVolume && (!leftTriangleCount || !rightTriangleCount)) {\n                // We slightly prefer splits that remove empty space.\n                cost *= kEmptySplitDiscount;\n            }\n            return cost;\n        };\n\n        float leftCost = cost(leftTriangleCount + planarTriangleCount, rightTriangleCount);\n        float rightCost = cost(leftTriangleCount, planarTriangleCount + rightTriangleCount);\n        if (leftCost < rightCost) {\n            return { Side::Left, (kIntersectionCost * leftCost) + kTraversalCost };\n        } else {\n            return { Side::Right, (kIntersectionCost * rightCost) + kTraversalCost };\n        }\n    }\n\n    AxisAlignedBoundingBox _boundingBox;\n    std::vector<std::unique_ptr<Triangle<SurfaceData>>> _triangles;\n    std::set<Event> _events;\n};\n}", "meta": {"hexsha": "b7d1d70a9ead2a0fe18e3804318ab2b14a0bb4d0", "size": 28151, "ext": "h", "lang": "C", "max_stars_repo_path": "engine/include/rev/geometry/KDTree.h", "max_stars_repo_name": "eyebrowsoffire/rev", "max_stars_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "engine/include/rev/geometry/KDTree.h", "max_issues_repo_name": "eyebrowsoffire/rev", "max_issues_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-27T16:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-27T16:52:41.000Z", "max_forks_repo_path": "engine/include/rev/geometry/KDTree.h", "max_forks_repo_name": "eyebrowsoffire/rev", "max_forks_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448", "max_forks_repo_licenses": ["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.9527458493, "max_line_length": 100, "alphanum_fraction": 0.5502468829, "num_tokens": 6382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.38764781765068385}}
{"text": "// PMILOS v2.0 (2020)\n// Parallel Milne-Eddington inversion code \n// (based on IDL code by D. Orozco & J.C. del Toro Iniesta)\n// Authors: Manuel Cabrera, Juan P. Cobos, Luis Bellot Rubio (IAA-CSIC)\n// Send questions and comments to Luis Bellot, lbellot@iaa.es\n\n\n#include \"mpi.h\"\n#include <time.h>\n#include \"defines.h\"\n#include <string.h>\n#include <stdio.h>\n#include <stddef.h>\n#include \"/opt/local/cfitsio/cfitsio-3.350/include/fitsio.h\" ///opt/local/cfitsio/cfitsio-3.350/include/\n#include \"utilsFits.h\"\n#include \"readConfig.h\"\n#include \"lib.h\"\n#include \"milosUtils.h\"\n#include <unistd.h>\n#include <complex.h>\n#include <fftw3.h> //always after complex.h\n#include <sys/types.h>\n#include <dirent.h>\n#include <sys/stat.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_eigen.h>\n#include <libgen.h>\n\n// ***************************** FUNCTIONS TO READ FITS FILE *********************************************************\n\nint NTERMS=11;\nCuantic *cuantic; // Global variable with cuantic information \nREAL *dtaux, *etai_gp3, *ext1, *ext2, *ext3, *ext4;\nREAL *gp1, *gp2, *dt, *dti, *gp3, *gp4, *gp5, *gp6, *etai_2;\nREAL *gp4_gp2_rhoq, *gp5_gp2_rhou, *gp6_gp2_rhov;\nREAL *dgp1, *dgp2, *dgp3, *dgp4, *dgp5, *dgp6, *d_dt;\nREAL *d_ei, *d_eq, *d_eu, *d_ev, *d_rq, *d_ru, *d_rv;\nREAL *dfi, *dshi;\nREAL CC, CC_2, sin_gm, azi_2, sinis, cosis, cosis_2, cosi, sina, cosa, sinda, cosda, sindi, cosdi, sinis_cosa, sinis_sina;\nREAL *fi_p, *fi_b, *fi_r, *shi_p, *shi_b, *shi_r;\nREAL *etain, *etaqn, *etaun, *etavn, *rhoqn, *rhoun, *rhovn;\nREAL *etai, *etaq, *etau, *etav, *rhoq, *rhou, *rhov;\nREAL *parcial1, *parcial2, *parcial3;\nREAL *nubB, *nupB, *nurB;\nREAL **uuGlobalInicial;\nREAL **HGlobalInicial;\nREAL **FGlobalInicial;\n\n\nPRECISION *GMAC,*GMAC_DERIV, *G; // GAUSSIAN MUST BE IN DOUBLE PRECISION \nPRECISION *dirConvPar; // AUX GLOBAL VECTOR for calculate direct convolutions\nREAL *resultConv; // aux global vector for store direct convolution\n\nREAL * opa;\nint FGlobal, HGlobal, uuGlobal;\n\nREAL *d_spectra, *spectra, *spectra_mac, *spectra_slight;\n\n// GLOBAL variables for FFT calculation \n\nfftw_complex * inSpectraFwPSF, *inSpectraBwPSF, *outSpectraFwPSF, *outSpectraBwPSF;\nfftw_complex * inSpectraFwMAC, *inSpectraBwMAC, *outSpectraFwMAC, *outSpectraBwMAC;\nfftw_plan planForwardPSF, planBackwardPSF;\nfftw_plan planForwardMAC, planBackwardMAC;\nfftw_complex * inFilterMAC, * inFilterMAC_DERIV, * outFilterMAC, * outFilterMAC_DERIV;\nfftw_plan planFilterMAC, planFilterMAC_DERIV;\nfftw_complex * fftw_G_PSF;\n\nfftw_complex * fftw_G_PSF, * fftw_G_MAC_PSF, * fftw_G_MAC_DERIV_PSF;\nfftw_complex * inPSF_MAC, * inMulMacPSF, * inPSF_MAC_DERIV, *inMulMacPSFDeriv, *outConvFilters, * outConvFiltersDeriv;\nfftw_plan planForwardPSF_MAC, planForwardPSF_MAC_DERIV,planBackwardPSF_MAC, planBackwardPSF_MAC_DERIV;\n\n//Convolutions values\nint sizeG = 0;\nPRECISION FWHM = 0;\n\nConfigControl configCrontrolFile;\n\n_Complex double  *z,* zden, * zdiv;\ngsl_vector *eval;\ngsl_matrix *evec;\ngsl_eigen_symmv_workspace * workspace;\n\nint main(int argc, char **argv)\n{\n\tint i;  // indexes \n\t\n\tint indexLine, free_params; // index to identify central line to read it \n\tPRECISION initialLambda, step, finalLambda;\n\t// INIT MPI  PROGRAM \n\tint numProcs, idProc;\n\tMPI_Init(&argc, &argv);\n\tMPI_Comm_size(MPI_COMM_WORLD, &numProcs);\n    MPI_Comm_rank(MPI_COMM_WORLD, &idProc);\n\n\t/** DEFINE MPI TYPE TO SEND MODELS **/\n\tMPI_Datatype mpiInitModel;\n\tconst int nitemsStructInitModel = 11;\n\tint blocklenghtInitModel [11] = {1,1,1,1,1,1,1,1,1,1,1};\n\tMPI_Datatype typesInitModel [11] = {MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE};\t\t\t\t\t\n\tMPI_Aint offsetsInitModel [11];\n\toffsetsInitModel[0] = offsetof(Init_Model, eta0);\n\toffsetsInitModel[1] = offsetof(Init_Model, B);\n\toffsetsInitModel[2] = offsetof(Init_Model, vlos);\n\toffsetsInitModel[3] = offsetof(Init_Model, dopp);\n\toffsetsInitModel[4] = offsetof(Init_Model, aa);\n\toffsetsInitModel[5] = offsetof(Init_Model, gm);\n\toffsetsInitModel[6] = offsetof(Init_Model, az);\n\toffsetsInitModel[7] = offsetof(Init_Model, S0);\n\toffsetsInitModel[8] = offsetof(Init_Model, S1);\n\toffsetsInitModel[9] = offsetof(Init_Model, mac);\n\toffsetsInitModel[10] = offsetof(Init_Model, alfa);\n\tMPI_Type_create_struct(nitemsStructInitModel, blocklenghtInitModel, offsetsInitModel, typesInitModel, &mpiInitModel);\n\tMPI_Type_commit(&mpiInitModel);\n\n\n\tMPI_Datatype mpiName;\n\tconst int nItemsStructName = 1;\n\tint blocklenghName [1] = {PATH_MAX};\n\tMPI_Datatype typesName [1] = {MPI_CHAR};\n\tMPI_Aint offsetName [1];\n\toffsetName[0] = offsetof(nameFile,name) ;\n\tMPI_Type_create_struct(nItemsStructName,blocklenghName,offsetName,typesName,&mpiName);\n\tMPI_Type_commit(&mpiName);\n\n\t/************************************/\n\tconst int root=0;\t\n\t// FINISH STARTING PROGRAM \n\n\tPRECISION *wlines;\n\tint nlambda, numPixels, indexPixel;\n\n\t//*****\n\tInit_Model INITIAL_MODEL;\n\tPRECISION * deltaLambda, * PSF;\n\tint N_SAMPLES_PSF;\n\t\n\ttime_t newestFileTimeInitial; // time for newest file in case invert all directory\n\t// CONFIGURACION DE PARAMETROS A INVERTIR\n\t//---------------------------------------\n\n\tfloat * slight = NULL;\n\tint nl_straylight, ns_straylight, nx_straylight=0,ny_straylight=0;\n\tint * vMask = NULL, numRowsMask, numColsMask;\n\tint nRowsMask, nColsMask;\n\n\n\tint numberOfFileSpectra;\n\n  nameFile * vInputFileSpectra = NULL; // was a space HERE\n\tnameFile * vInputFileSpectraParalell = NULL;\n\tnameFile * vInputFileSpectraDiv2Parallel = NULL;\n\tnameFile * vOutputNameModels = NULL;\n\tnameFile * vOutputNameModelsParalell = NULL;\n\tnameFile * vOutputNameModelsDiv2Parallel = NULL;\n\tnameFile * vOutputNameSynthesisAdjusted = NULL;\n\tnameFile * vOutputNameSynthesisAdjustedParallel = NULL;\n\tnameFile * vOutputNameSynthesisAdjustedDiv2Parallel = NULL;\n\tnameFile * vInputFileSpectraLocal = NULL;\n\tnameFile * vOutputNameModelsLocal = NULL;\n\tnameFile * vOutputNameSynthesisAdjustedLocal = NULL;\n\ttpuntero listFileNamesReaded = NULL; \n\t\n\tconst char\t* nameInputFilePSF ;\n\n\tFitsImage * fitsImage = NULL;\n\tPRECISION  dat[7];\n\n\tdouble local_start, local_finish, local_elapsed, elapsed;\n\tdouble local_start_execution, local_finish_execution, local_elapsed_execution, elapsed_execution;\n\tdouble local_start_scatter, local_finish_scatter, local_elapsed_scatter, elapsed_scatter;\n\tdouble local_start_gather, local_finish_gather, local_elapsed_gather, elapsed_gather;\n\t\n\tInit_Model * resultsInitModel;\n\tInit_Model * resultsInitModelTotal;\n\tfloat * chisqrfTotal, *vChisqrf;\n\tint * vNumIter, * vNumIterTotal; // to store the number of iterations used to converge for each pixel\n\tfloat  * vSpectraSplit, * vSpectraAdjustedSplit, * vSpectraAjustedTotal;\n\n\tint sendcountsPixels [numProcs] ; // array describing how many elements to send to each process\n\tint sendcountsSpectro [numProcs];\n\tint sendcountsLambda [numProcs];\n\tint sendcountsNameInputFiles [numProcs];  // how many files per process\n\tint displsPixels [numProcs];  // array describing the displacements where each segment begins\n\tint displsSpectro [numProcs];\n\tint displsNameInputFiles [numProcs]; // how many \n\n\t/********************* Read data input from file ******************************/\n\n\tloadInitialValues(&configCrontrolFile);\n\tif(!readInitFile(argv[1],&configCrontrolFile,(idProc==root))){\n\t\tif(idProc==root)\n\t\t\tprintf(\"\\n\\nERROR READING INIT FILE. \\n\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\t\n\t// check if type of file is FITS, else exit \n\tif(strcmp(configCrontrolFile.typeInputStokes,\"fits\")!=0){\n\t\tif(idProc==root)\n\t\t\tprintf(\"\\nERROR. The profiles must be given in FITS format.\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t// CHECK IF ONLY RECEIVED ONE FILE AND THE EXTENSION IS .FITS \n\tif(!configCrontrolFile.invertDirectory && !configCrontrolFile.loopInversion){\n\t\tif(configCrontrolFile.t1 == 0 && configCrontrolFile.t2 ==0){ // then process only one file\n\t\t\tif(strcmp(file_ext(configCrontrolFile.ObservedProfiles),FITS_FILE)!=0){ \n\t\t\t\tif(idProc==root){\n\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\tprintf(\"\\nERROR. A FITS file is expected in 'Observed Profiles'\\n\");\n\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t}\n\t\t\t\texit(EXIT_FAILURE);\t\n\t\t\t}\n\t\t}\n\t}\n\tnameInputFilePSF = configCrontrolFile.PSFFile;\n\tFWHM = configCrontrolFile.FWHM;\n\t/***************** READ INIT MODEL ********************************/\n\tif(!readInitialModel(&INITIAL_MODEL,configCrontrolFile.InitialGuessModel)){\n\t\tprintf(\"\\nERROR READING INITIAL MODEL. STOP \\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\tcheckInitialModel(&INITIAL_MODEL);\n\tif(INITIAL_MODEL.alfa<1 && access(configCrontrolFile.StrayLightFile,F_OK)){\n\t\tprintf(\"\\nERROR. Filling factor is less than 1 and straylight file %s does not exist\\n\",configCrontrolFile.StrayLightFile);\n\t\texit(EXIT_FAILURE);\n\t}\n\n\n\tif(configCrontrolFile.fix[10]==0) NTERMS--;\n\tif(INITIAL_MODEL.mac ==0 && configCrontrolFile.fix[9]==0){\n\t\t NTERMS--;\n\t}\n\n\t// allocate memory for eigen values\n\teval = gsl_vector_alloc (NTERMS);\n  \tevec = gsl_matrix_alloc (NTERMS, NTERMS);\n\tworkspace = gsl_eigen_symmv_alloc (NTERMS);\n\n\t/***************** READ WAVELENGTH FROM GRID OR FITS ********************************/\n\tPRECISION * vGlobalLambda, *vOffsetsLambda;\n\n\tif(configCrontrolFile.useMallaGrid){ // read lambda from grid file\n\t\tif(idProc==root){\n\t\t        printf(\"------------------------------------------------------------------------------------\\n\");\n\t\t\tprintf(\"\\nReading wavelength grid file: %s\\n\",configCrontrolFile.MallaGrid);\n\t\t        // printf(\"\\n------------------------------------------------------------------------------------\");\n\t\t}\n\t\tindexLine = readMallaGrid(configCrontrolFile.MallaGrid, &initialLambda, &step, &finalLambda, (idProc==root));      \n\t\tif(idProc==root){\n\t\t  // printf(\"------------------------------------------------------------------------------------------\\n\");\n\t\t}\n\t\tnlambda = ((finalLambda-initialLambda)/step)+1;\n\t\tvOffsetsLambda = calloc(nlambda,sizeof(PRECISION));\n\t\tvOffsetsLambda[0] = initialLambda;\n\t\tfor(i=1;i<nlambda;i++){\n\t\t\tvOffsetsLambda[i] = vOffsetsLambda[i-1]+step;\n\t\t}\n\t\t// pass to amstrong \n\t\tinitialLambda = initialLambda/1000;\n\t\tstep = step/1000;\n\t\tfinalLambda = finalLambda/1000;\n\t\tvGlobalLambda = calloc(nlambda,sizeof(PRECISION));\n\t\tif(idProc==root){\n\t\t\tprintf(\"\\nNumber of wavelengths in the wavelength grid: %d\\n\",nlambda);\n\t\t\t// printf(\"\\n-------------------------------------------------------------------------------\\n\");\n\t\t\tprintf(\"\\nReading atomic parameter files: %s\\n\",configCrontrolFile.AtomicParametersFile);\t\t\n\t\t}\n\t\tconfigCrontrolFile.CentralWaveLenght = readFileCuanticLines(configCrontrolFile.AtomicParametersFile,dat,indexLine,(idProc==root));\n\t\tif(configCrontrolFile.CentralWaveLenght==0){\n\t\t  printf(\"\\n SPECTRAL LINE NOT FOUND, CHECK THE ATOMIC PARAMETERS FILE. \");\n\t\t  printf(\"\\n INPUT CENTRAL WAVELENGTH: %f\",configCrontrolFile.CentralWaveLenght);\n\t\t\texit(1);\n\t\t}\n\t\tvGlobalLambda[0]=configCrontrolFile.CentralWaveLenght+(initialLambda);\n   \t\tfor(i=1;i<nlambda;i++){\n        \tvGlobalLambda[i]=vGlobalLambda[i-1]+step;\n     \t}\n\t}\n\telse{\n\t\tif(idProc==root){\n\t\t        printf(\"------------------------------------------------------------------------------------\\n\");\n\t\t\tprintf(\"\\nReading wavelength file: %s\\n\",configCrontrolFile.WavelengthFile);\n\t\t}\n\t\tvGlobalLambda = readFitsLambdaToArray(configCrontrolFile.WavelengthFile,&indexLine,&nlambda);\n\t\tif(vGlobalLambda==NULL){\n\t\t\tprintf(\"\\n WAVELENGTH FILE WAS NOT READ PROPERLY, please check it.\\n\");\n\t\t\tfree(vGlobalLambda);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tif(idProc==root){\n\n\t\t\tprintf(\"\\nNumber of wavelengths in the wavelength file: %d\\n\",nlambda);\n\t\t\t//printf(\"\\n-------------------------------------------------------------------------------\\n\");\n\t\t\t//printf(\"\\n-------------------------------------------------------------------------------\");\n\t\t\tprintf(\"\\nReading atomic parameter file: %s\\n\",configCrontrolFile.AtomicParametersFile);\t\t\t\n\t\t}\n\t\tconfigCrontrolFile.CentralWaveLenght = readFileCuanticLines(configCrontrolFile.AtomicParametersFile,dat,indexLine,(idProc==root));\n\t\tif(configCrontrolFile.CentralWaveLenght==0){\n\t\t\tprintf(\"\\n SPECTRAL LINE NOT FOUND, CHECK ATOMIC PARAMETER FILE. INPUT CENTRAL WAVELENGTH: %f\",configCrontrolFile.CentralWaveLenght);\n\t\t\texit(1);\n\t\t}\n\t}\n\n\t\n\tMPI_Barrier(MPI_COMM_WORLD);\n\t/*********************************************** INITIALIZE VARIABLES  *********************************/\n\tREAL * vSigma = malloc((nlambda*NPARMS)*sizeof(REAL));\n\tfor(i=0;i<nlambda*NPARMS;i++){\n\t\tvSigma[i] = configCrontrolFile.noise;\n\t}\n\n\tCC = PI / 180.0;\n\tCC_2 = CC * 2;\n\t\n\twlines = (PRECISION *)calloc(2, sizeof(PRECISION));\n\twlines[0] = 1;\n\twlines[1] = configCrontrolFile.CentralWaveLenght;\n\n\tnumPixels=0;\t\n\n\tprintf(configCrontrolFile.StrayLightFile);\n\t/******************* APPLY GAUSSIAN, CREATE CUANTINC AND INITIALIZE DINAMYC MEMORY*******************/\n\tMPI_Barrier(MPI_COMM_WORLD);\n\tcuantic = create_cuantic(dat,(idProc==root));\n\tMPI_Barrier(MPI_COMM_WORLD);\n\n\t/**************************************** READ FITS  STRAY LIGHT ******************************/\n\t\n\tif( configCrontrolFile.fix[10] && access(configCrontrolFile.StrayLightFile,F_OK)!=-1){ //  IF NOT EMPTY READ stray light file \n\t\tif(strcmp(file_ext(configCrontrolFile.StrayLightFile),PER_FILE)==0){\n\t\t\tslight = readPerStrayLightFile(configCrontrolFile.StrayLightFile,nlambda,vOffsetsLambda);\n\t\t\tnl_straylight = nlambda;\n\t\t}\n\t\telse if(strcmp(file_ext(configCrontrolFile.StrayLightFile),FITS_FILE)==0){\n\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\n\t\t\t\tslight= readFitsStrayLightFileSubSet(&configCrontrolFile,&nl_straylight,&ns_straylight,&nx_straylight, &ny_straylight);\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\tslight= readFitsStrayLightFile(&configCrontrolFile,&nl_straylight,&ns_straylight,&nx_straylight, &ny_straylight);\t\n\t\t\t}\n\t\t}\n\t}\n\n\t\n\t/**************************************** READ FITS  MASK  ******************************/\n\tint shareVMask = 0;\n\tif(idProc==root && access(configCrontrolFile.MaskFile,F_OK)!=-1){ //  IF NOT EMPTY READ MASK FILE\n\n\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\n\t\t\tvMask=readFitsMaskFileSubSet (configCrontrolFile.MaskFile,&numRowsMask,&numColsMask,&configCrontrolFile);\t\n\t\t}\n\t\telse{\n\t\t\tvMask=readFitsMaskFile (configCrontrolFile.MaskFile,&numRowsMask,&numColsMask);\n\t\t}\n\t\tif(vMask==NULL){\n\t\t\tprintf(\"\\n-----------------------------------------------------------------------\");\n\t\t\tprintf(\"\\nMask file not found or incorrect dimensions. Mask will not be used.    \");\n\t\t\tprintf(\"\\n---------------------------------------------------------------------\\n\");\n\t\t}\n\t\telse{\n\t\t\t// readsub set of VMAS\n\t\t\tshareVMask =1;\n\t\t}\n\t}\n\n\tMPI_Barrier(MPI_COMM_WORLD); // Wait UNTIL THE IMAGE HAS BEEN READED COMPLETELY\n\t//  BROADCAST THE NUMBER OF LAMBDAS READS FROM THE FILE AND THE NUMBER OF PIXELS\n\tMPI_Bcast(&numRowsMask, 1, MPI_INT, root , MPI_COMM_WORLD);\n\tMPI_Bcast(&numColsMask, 1, MPI_INT, root , MPI_COMM_WORLD);\n\tMPI_Bcast(&shareVMask, 1, MPI_INT, root , MPI_COMM_WORLD);\n\tMPI_Barrier(MPI_COMM_WORLD);\n\tif(shareVMask){\n\t\tif(idProc!=root)\n\t\t\tvMask = calloc(numRowsMask*numColsMask,sizeof(int));\n\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t\tMPI_Bcast(vMask, numRowsMask*numColsMask, MPI_INT, root , MPI_COMM_WORLD);\n\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t}\n\n\tif(idProc==root){\n\t\tfree_params=0;\n\t\tfor(i=0;i<11;i++){\n\t\t\tif(configCrontrolFile.fix[i])\n\t\t\t\tfree_params++;\n\t\t}\n\t}\n\t\n\t// ************************** DEFINE PLANS TO EXECUTE MACROTURBULENCE IF NECESSARY **********************************************//\n\t// MACROTURBULENCE PLANS\n\t\n\tinFilterMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\toutFilterMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\tplanFilterMAC = fftw_plan_dft_1d(nlambda, inFilterMAC, outFilterMAC, FFT_FORWARD, FFTW_MEASURE     );\n\tinFilterMAC_DERIV = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\toutFilterMAC_DERIV = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\tplanFilterMAC_DERIV = fftw_plan_dft_1d(nlambda, inFilterMAC_DERIV, outFilterMAC_DERIV, FFT_FORWARD, FFTW_MEASURE     );\n\n\n\tinSpectraFwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\toutSpectraFwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\tplanForwardMAC = fftw_plan_dft_1d(nlambda, inSpectraFwMAC, outSpectraFwMAC, FFT_FORWARD, FFTW_MEASURE    );\n\tinSpectraBwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\toutSpectraBwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\t\t\n\tplanBackwardMAC = fftw_plan_dft_1d(nlambda, inSpectraBwMAC, outSpectraBwMAC, FFT_BACKWARD, FFTW_MEASURE    );\n\n\t// ******************************* IF PSF HAS BEEN SPECIFIED IN CONTROL FILE,  READ PSF FILE OR CREATE GAUSSIAN FILTER ***********//\n\tif(configCrontrolFile.ConvolveWithPSF){\n\n\t\tif(configCrontrolFile.FWHM > 0){\n\t\t\tG = fgauss_WL(FWHM,vGlobalLambda[1]-vGlobalLambda[0],vGlobalLambda[0],vGlobalLambda[nlambda/2],nlambda,&sizeG);\n\t\t\t//char nameAux [4096];\n\t\t\t//char obsAux [4096];\n\t\t\t//if(configCrontrolFile.ObservedProfiles[0]!='\\0'){\n\t\t\t//\tstrcpy(obsAux,configCrontrolFile.ObservedProfiles);\n\t\t\t//\tstrcpy(nameAux,dirname(obsAux));\n\t\t\t//}\n\t\t\t//else{\n\t\t\t//\tstrcpy(obsAux,configCrontrolFile.InitialGuessModel);\n\t\t\t//\tstrcpy(nameAux,dirname(obsAux));\t\t\n\t\t\t//}\n\t\t\t//strcat(nameAux,\"/gaussian.psf\");\n\n\t\t\t//FILE *fptr = fopen(nameAux, \"w\");\n\n\t\t\tif(idProc==root){\n\t\t\t  printf(\"\\nGaussian PSF will be saved to file gaussian.psf \\n\"); \n\n\t\t\t  FILE *fptr = fopen(\"gaussian.psf\", \"w\");\n\t\t\t  if(fptr!=NULL){\n\t\t\t\tint kk;\n\t\t\t\tfor (kk = 0; kk < nlambda; kk++)\n\t\t\t\t{\n\t\t\t\t\tfprintf(fptr,\"\\t%f\\t%e\\n\", (vGlobalLambda[kk]-configCrontrolFile.CentralWaveLenght)*1000, G[kk]);\n\t\t\t\t}\n\t\t\t\tfclose(fptr);\n\t\t\t  }\n\t\t\t  else{\n\t\t\t  //    printf(\"\\nERROR !!! The output PSF file cannot be opened: %s\",nameAux);\n\t\t\t\tprintf(\"\\nERROR !!! The output PSF file cannot be opened: gaussian.psf\");\n\t\t\t  }\n\t\t\t}\n\t\t}\n\t\telse if(access(nameInputFilePSF,F_OK) != -1){\n\t\t\t// read the number of lines \n\t\t\tFILE *fp;\n\t\t\tchar ch;\n\t\t\tN_SAMPLES_PSF=0;\n\t\t\t//open file in read more\n\t\t\tfp=fopen(nameInputFilePSF,\"r\");\n\t\t\tif(fp==NULL)\n\t\t\t{\n\t\t\t\tprintf(\"\\n-------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"PSF File \\\"%s\\\" does not exist!\",nameInputFilePSF);\n\t\t\t\tprintf(\"\\n-------------------------------------------------------------------------------\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t//read character by character and check for new line\t\n\t\t\twhile((ch=fgetc(fp))!=EOF)\n\t\t\t{\n\t\t\t\tif(ch=='\\n')\n\t\t\t\t\tN_SAMPLES_PSF++;\n\t\t\t}\n\t\t\t\n\t\t\t//close the file\n\t\t\tfclose(fp);\n\t\t\tif(N_SAMPLES_PSF>0){\n\t\t\t\tdeltaLambda = calloc(N_SAMPLES_PSF,sizeof(PRECISION));\n\t\t\t\tPSF = calloc(N_SAMPLES_PSF,sizeof(PRECISION));\n\t\t\t\treadPSFFile(deltaLambda,PSF,nameInputFilePSF,configCrontrolFile.CentralWaveLenght);\n\t\t\t\t// CHECK if values of deltaLambda are in the same range of vLambda. To do that we truncate to 4 decimal places \n\t\t\t\tif( (trunc(vOffsetsLambda[0])) < (trunc(deltaLambda[0]))  || (trunc(vOffsetsLambda[nlambda-1])) > (trunc(deltaLambda[N_SAMPLES_PSF-1])) ){\n\t\t\t\t\tif(idProc==root){\n\t\t\t\t\t\tprintf(\"\\n\\n ERROR: The wavelength range in the PSF file is smaller than the range in the grid file [%lf,%lf] [%lf,%lf]  \\n\\n\",deltaLambda[0],vOffsetsLambda[0],deltaLambda[N_SAMPLES_PSF-1],vOffsetsLambda[nlambda-1]);\n\t\t\t\t\t}\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\t\tG = calloc(nlambda,sizeof(PRECISION));\n\t\t\t\tdouble offset =0;\n\t\t\t\tint posWL = 0;\n\t\t\t\tfor(i=0;i<nlambda && !posWL;i++){\n\t\t\t\t\tif( fabs(trunc(vOffsetsLambda[i]))==0)\n\t\t\t\t\t\tposWL = i;\n\t\t\t\t}\n\t\t\t\tif(posWL!= (nlambda/2)){ // move center to the middle of samples\n\t\t\t\t\toffset = (((nlambda/2)-posWL)*step)*1000;\n\t\t\t\t}\t\t\t\t\t\n\t\t\t\tinterpolationLinearPSF(deltaLambda,  PSF, vOffsetsLambda , N_SAMPLES_PSF, G, nlambda,offset);\t\t\n\t\t\t\tsizeG=nlambda;\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif(idProc==root)\n\t\t\t\t\tprintf(\"\\n************** ERROR. THE PSF FILE is empty or damaged**************\\n\");\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\tif(idProc==root){\n\t\t\t  //\tprintf(\"\\n-------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nPSF file read: %s\\n\", nameInputFilePSF);\n\t\t\t  //\tprintf(\"\\n-------------------------------------------------------------------------------\\n\");\n\t\t\t}\n\t\t}\n\n\t\t\n\t\t//PSF FILTER PLANS \n\t\tinSpectraFwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\toutSpectraFwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\tplanForwardPSF = fftw_plan_dft_1d(nlambda, inSpectraFwPSF, outSpectraFwPSF, FFT_FORWARD, FFTW_MEASURE     );\n\t\tinSpectraBwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\toutSpectraBwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\t\t\n\t\tplanBackwardPSF = fftw_plan_dft_1d(nlambda, inSpectraBwPSF, outSpectraBwPSF, FFT_BACKWARD, FFTW_MEASURE     );\n\n\t\tfftw_complex * in = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\tint i;\n\t\tfor (i = 0; i < nlambda; i++)\n\t\t{\n\t\t\tin[i] = G[i] + 0 * _Complex_I;\n\t\t}\n\t\tfftw_G_PSF = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\tfftw_plan p = fftw_plan_dft_1d(nlambda, in, fftw_G_PSF, FFT_FORWARD, FFTW_MEASURE   );\n\t\tfftw_execute(p);\n\t\tfor (i = 0; i < nlambda; i++)\n\t\t{\n\t\t\tfftw_G_PSF[i] = fftw_G_PSF[i] / nlambda;\n\t\t}\n\t\tfftw_destroy_plan(p);\n\t\tfftw_free(in);\n\t\t\n\t\tinPSF_MAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\tfftw_G_MAC_PSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\tplanForwardPSF_MAC = fftw_plan_dft_1d(nlambda, inPSF_MAC, fftw_G_MAC_PSF, FFT_FORWARD, FFTW_MEASURE     );\n\t\tinMulMacPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\toutConvFilters = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\tplanBackwardPSF_MAC = fftw_plan_dft_1d(nlambda, inMulMacPSF, outConvFilters, FFT_BACKWARD, FFTW_MEASURE     );\n\n\n\t\tinPSF_MAC_DERIV = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\tfftw_G_MAC_DERIV_PSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\tplanForwardPSF_MAC_DERIV = fftw_plan_dft_1d(nlambda, inPSF_MAC_DERIV, fftw_G_MAC_DERIV_PSF, FFT_FORWARD, FFTW_MEASURE     );\n\t\tinMulMacPSFDeriv = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\toutConvFiltersDeriv = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);\n\t\tplanBackwardPSF_MAC_DERIV = fftw_plan_dft_1d(nlambda, inMulMacPSFDeriv, outConvFiltersDeriv, FFT_BACKWARD, FFTW_MEASURE     );\t\t\t\n\n\t}\n\n\t/*****************************************************************************************************/\n\tMPI_Barrier(MPI_COMM_WORLD);\n\t// ROOT PROCESS READ IMAGE FROM FILE TO KNOW LIST OF FILES\n\tif(idProc==root){\n\t\tchar auxObservedProfiles1 [256];\n\t\tchar auxObservedProfiles2 [256];\n\t\tstrcpy(auxObservedProfiles1,configCrontrolFile.ObservedProfiles);\n\t\tstrcpy(auxObservedProfiles2,configCrontrolFile.ObservedProfiles);\n\t\tchar * dirNameObservedProfiles = dirname(auxObservedProfiles1);\n\t\tchar * fileNameObservedProfiles = basename(auxObservedProfiles2);\n\n\t\tchar newObservedProfiles [256];\n\t\tif(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\tstrcpy(newObservedProfiles,configCrontrolFile.outputPrefix);\n\t\t\tstrcat(newObservedProfiles,fileNameObservedProfiles);\n\t\t}\n\t\telse{\n\t\t\tstrcpy(newObservedProfiles,fileNameObservedProfiles);\n\t\t}\n\n\t\t/*if(strcmp(dirNameObservedProfiles,\".\")!=0){\n\t\t\tstrcpy(newObservedProfiles,dirNameObservedProfiles);\n\t\t\tstrcat(newObservedProfiles,\"/\");\n\t\t\tif(configCrontrolFile.outputPrefix[0]!='\\0')\n\t\t\t\tstrcat(newObservedProfiles,configCrontrolFile.outputPrefix);\n\t\t\tstrcat(newObservedProfiles,fileNameObservedProfiles);\n\t\t}\n\t\telse{\n\t\t\tif(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\tstrcpy(newObservedProfiles,configCrontrolFile.outputPrefix);\n\t\t\t\tstrcat(newObservedProfiles,fileNameObservedProfiles);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tstrcpy(newObservedProfiles,fileNameObservedProfiles);\n\t\t\t}\n\t\t}*/\n\n\t\t\n\n\t\tif(configCrontrolFile.loopInversion){\n\t\t\tif(configCrontrolFile.invertDirectory){ // read all directory \n\n\t\t\t\tstruct dirent **namelist;\n\t\t\t\tchar observedProAux[256];\n\t\t\t\tchar observedProAux2[256];\n\t\t\t\tstrcpy(observedProAux,configCrontrolFile.ObservedProfiles);\n\t\t\t\tstrcpy(observedProAux2,configCrontrolFile.ObservedProfiles);\n\t\t\t\tchar * dname = dirname(observedProAux);\n\t\t\t\tchar * bname = basename(observedProAux2);\n\t\t\t\t\n\t\t\t\tint numFileDirectory = scandir(dname, &namelist, 0, alphasort);\n    \t\t\tif (numFileDirectory < 0)\n        \t\t\tperror(\"scandir\");\n\t\t\t\telse{\n\t\t\t\t\tif(numFileDirectory>2){\n\n\t\t\t\t\t\tnumberOfFileSpectra=0;\n\t\t\t\t\t\tfor(i=0;i<numFileDirectory;i++){\n\t\t\t\t\t\t\tchar auxPathName[256];\n\t\t\t\t\t\t\tstrcpy(auxPathName,dname);\n\t\t\t\t\t\t\tstrcat(auxPathName,\"/\");\n\t\t\t\t\t\t\tstrcat(auxPathName,namelist[i]->d_name);\n\t\t\t\t\t\t\tif(!isDirectory(auxPathName) && strcmp(namelist[i]->d_name,\".\")!=0 && strcmp(namelist[i]->d_name,\"..\")!=0 && strcmp(namelist[i]->d_name,\"_mod\")!=0){\n\t\t\t\t\t\t\t\tnumberOfFileSpectra++;\n\t\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\tvInputFileSpectra = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\t\t\tvOutputNameModels = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\t\t\tvOutputNameSynthesisAdjusted = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\t\t\tint numberFiles[numberOfFileSpectra];\n\t\t\t\t\t\tint indexNumberFiles = 0;\n\t\t\t\t\t\tfor(i=0;i<numFileDirectory;i++){\n\t\t\t\t\t\t\tchar auxPathName[256];\n\t\t\t\t\t\t\tstrcpy(auxPathName,dname);\n\t\t\t\t\t\t\tstrcat(auxPathName,\"/\");\n\t\t\t\t\t\t\tstrcat(auxPathName,namelist[i]->d_name);\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(!isDirectory(auxPathName) && strcmp(namelist[i]->d_name,\".\")!=0 && strcmp(namelist[i]->d_name,\"..\")!=0 && strcmp(namelist[i]->d_name,\"_mod\")!=0){\n\t\t\t\t\t\t\t\tchar pathAux [256];\n\t\t\t\t\t\t\t\tstrcpy(pathAux,dname);\n\t\t\t\t\t\t\t\tstrcat(pathAux,\"/\");\n\t\t\t\t\t\t\t\tstrcat(pathAux,namelist[i]->d_name);\n\t\t\t\t\t\t\t\tchar * subString = strstr(pathAux,configCrontrolFile.ObservedProfiles);\n\t\t\t\t\t\t\t\tif(subString!=NULL){\n\t\t\t\t\t\t\t\t\tchar numChar [80];\n\t\t\t\t\t\t\t\t\tmySubString(get_basefilename(namelist[i]->d_name),strlen(bname),strlen(get_basefilename(namelist[i]->d_name))-strlen(bname),numChar);\n\t\t\t\t\t\t\t\t\tint numAux = atoi(numChar);\n\t\t\t\t\t\t\t\t\tnumberFiles[indexNumberFiles++] = numAux;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\t\n\n\t\t\t\t\t\tfor(i=0;i<numberOfFileSpectra;i++){\n\t\t\t\t\t\t\tchar strIndex[5];\n\t\t\t\t\t\t\tif(numberFiles[i]>=0 && numberFiles[i]<10)\n\t\t\t\t\t\t\t\tsprintf(strIndex, \"00%d\", numberFiles[i]);\n\t\t\t\t\t\t\telse if(numberFiles[i]>=10 && numberFiles[i]<100){\n\t\t\t\t\t\t\t\tsprintf(strIndex, \"0%d\", numberFiles[i]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tsprintf(strIndex, \"%d\", numberFiles[i]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tstrcpy(vInputFileSpectra[i].name, configCrontrolFile.ObservedProfiles);\n\t\t\t\t\t\t\tstrcat(vInputFileSpectra[i].name, strIndex);\n\t\t\t\t\t\t\tstrcat(vInputFileSpectra[i].name, FITS_FILE);\n\t\t\t\t\t\t\t// FILE NAME FOR OUTPUT MODELS \n\t\t\t\t\t\t\t//strcpy(vOutputNameModels[i].name, configCrontrolFile.ObservedProfiles);\n\t\t\t\t\t\t\tstrcpy(vOutputNameModels[i].name,newObservedProfiles);\n\t\t\t\t\t\t\tstrcat(vOutputNameModels[i].name, strIndex);\n\t\t\t\t\t\t\tstrcat(vOutputNameModels[i].name, \"_mod\");\n\t\t\t\t\t\t\t// if(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\t\t// \tstrcat(vOutputNameModels[i].name, \"_\");\n\t\t\t\t\t\t\t// \tstrcat(vOutputNameModels[i].name, configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t\t// }\n\t\t\t\t\t\t\tstrcat(vOutputNameModels[i].name,FITS_FILE);\n\t\t\t\t\t\t\t// FILE NAME FOR ADJUSTED SYNTHESIS \n\t\t\t\t\t\t\t//strcpy(vOutputNameSynthesisAdjusted[i].name, configCrontrolFile.ObservedProfiles);\n\t\t\t\t\t\t\tstrcpy(vOutputNameSynthesisAdjusted[i].name,newObservedProfiles);\n\t\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[i].name, strIndex);\n\t\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[i].name, \"_stokes\");\n\t\t\t\t\t\t\t/*if(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[i].name, \"_\");\n\t\t\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[i].name, configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t\t}*/\n\t\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[i].name,FITS_FILE);\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{  // read directory from number in t1 \n\t\t\t\tstruct dirent **namelist;\n\t\t\t\t\n\t\t\t\tchar observedProAux[256];\n\t\t\t\tchar observedProAux2[256];\n\t\t\t\tstrcpy(observedProAux,configCrontrolFile.ObservedProfiles);\n\t\t\t\tstrcpy(observedProAux2,configCrontrolFile.ObservedProfiles);\n\t\t\t\tchar * dname = dirname(observedProAux);\n\t\t\t\tchar * bname = basename(observedProAux2);\n\n\t\t\t\tint numFileDirectory = scandir(dname, &namelist, 0, alphasort);\n    \t\t\tif (numFileDirectory < 0){\n        \t\t\tperror(\"scandir\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\tint maxNumber = -1;\n\t\t\t\tfor(i=2;i<numFileDirectory;i++){\n\t\t\t\t\tif(strcmp(namelist[i]->d_name,\".\")!=0 && strcmp(namelist[i]->d_name,\"..\")!=0){\n\t\t\t\t\t\tchar pathAux [256];\n\t\t\t\t\t\tstrcpy(pathAux,dname);\n\t\t\t\t\t\tstrcat(pathAux,\"/\");\n\t\t\t\t\t\tstrcat(pathAux,namelist[i]->d_name);\n\t\t\t\t\t\tif(!isDirectory(pathAux)){\n\t\t\t\t\t\t\tchar * subString = strstr(pathAux,configCrontrolFile.ObservedProfiles);\n\t\t\t\t\t\t\tif(subString!=NULL){\n\t\t\t\t\t\t\t\tchar numChar [80];\n\t\t\t\t\t\t\t\tmySubString(get_basefilename(namelist[i]->d_name),strlen(bname),strlen(get_basefilename(namelist[i]->d_name))-strlen(bname),numChar);\n\t\t\t\t\t\t\t\tint numAux = atoi(numChar);\n\t\t\t\t\t\t\t\tif(numAux>maxNumber)\n\t\t\t\t\t\t\t\t\tmaxNumber  = numAux;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t\tif((maxNumber-configCrontrolFile.t1)+1>0){\n\t\t\t\t\tnumberOfFileSpectra = (maxNumber - configCrontrolFile.t1)+1;\n\t\t\t\t\tvInputFileSpectra = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\t\tvOutputNameModels = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\t\tvOutputNameSynthesisAdjusted = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));\n\n\n\t\t\t\t\tint indexName =0;\n\t\t\t\t\tfor(i=configCrontrolFile.t1;i<=maxNumber;i++){\n\t\t\t\t\t\tchar strIndex[5];\n\t\t\t\t\t\tif(i>=0 && i<10){\n\t\t\t\t\t\t\tsprintf(strIndex, \"00%d\", i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(i>=10 && i<100){\n\t\t\t\t\t\t\tsprintf(strIndex, \"0%d\", i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse \n\t\t\t\t\t\t\tsprintf(strIndex, \"%d\", i);\n\t\t\t\t\t\tstrcpy(vInputFileSpectra[indexName].name, configCrontrolFile.ObservedProfiles);\n\t\t\t\t\t\tstrcat(vInputFileSpectra[indexName].name, strIndex);\n\t\t\t\t\t\tstrcat(vInputFileSpectra[indexName].name, FITS_FILE);\n\t\t\t\t\t\t// FILE NAME FOR OUTPUT MODELS \n\t\t\t\t\t\t//strcpy(vOutputNameModels[indexName].name, configCrontrolFile.ObservedProfiles);\n\t\t\t\t\t\tprintf(\"%s\\n\", newObservedProfiles);\n\t\t\t\t\t\tprintf(\"%s\\n\", \"line 738\");\n\t\t\t\t\t\tstrcpy(vOutputNameModels[indexName].name,newObservedProfiles);\n\t\t\t\t\t\tstrcat(vOutputNameModels[indexName].name, strIndex);\n\t\t\t\t\t\tstrcat(vOutputNameModels[indexName].name, \"_mod\");\n\t\t\t\t\t\t/*if(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\t\tstrcat(vOutputNameModels[indexName].name, \"_\");\n\t\t\t\t\t\t\tstrcat(vOutputNameModels[indexName].name, configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t}*/\n\t\t\t\t\t\tstrcat(vOutputNameModels[indexName].name,FITS_FILE);\n\t\t\t\t\t\t// FILE NAME FOR ADJUSTED SYNTHESIS \n\t\t\t\t\t\t//strcpy(vOutputNameSynthesisAdjusted[indexName].name, configCrontrolFile.ObservedProfiles);\n\t\t\t\t\t\tstrcpy(vOutputNameSynthesisAdjusted[indexName].name, newObservedProfiles);\n\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[indexName].name, strIndex);\n\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[indexName].name, \"_stokes\");\n\t\t\t\t\t\t/*if(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[indexName].name, \"_\");\n\t\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[indexName].name, configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t}*/\n\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[indexName].name,FITS_FILE);\n\t\t\t\t\t\tindexName++;\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(i=0;i<numberOfFileSpectra;i++){\n\t\t\t\tinsert_in_linked_list(&listFileNamesReaded,vInputFileSpectra[i].name);\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\t// CHECK IF INPUT OBSERVED PROFILES COMES IN A DIRECTORY OR IS A FILE\n\t\t\tif(configCrontrolFile.t1 == 0 && configCrontrolFile.t2 ==0){ // then process only one file\n\t\t\t\tnumberOfFileSpectra = 1;\n\t\t\t\tvInputFileSpectra = (nameFile *)malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\tstrcpy(vInputFileSpectra[0].name,configCrontrolFile.ObservedProfiles);\n\t\t\t\tprintf(\"%s\\n\", vInputFileSpectra[0].name);\n\n\t\t\t\tvOutputNameModels = (nameFile *)malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\tif(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\tstrcpy(vOutputNameModels[0].name,configCrontrolFile.outputPrefix);\n\t\t\t\t\tget_basefilename_nofolder(configCrontrolFile.ObservedProfiles);\n\t\t\t\t\t//strcat(vOutputNameModels[0].name,get_basefilename_nofolder(configCrontrolFile.ObservedProfiles));\t// was initialguessmodel here\n\t\t\t\t\tstrcat(vOutputNameModels[0].name,MOD_FITS);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstrcpy(vOutputNameModels[0].name,get_basefilename(configCrontrolFile.InitialGuessModel));\t// was initialguessmodel here\n\t\t\t\t\tstrcat(vOutputNameModels[0].name,MOD_FITS);\n\t\t\t\t}\n\t\t\t\t\n\n\t\t\t\t\n\n\t\t\t\tvOutputNameSynthesisAdjusted = (nameFile *)malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\tstrcpy(vOutputNameSynthesisAdjusted[0].name,get_basefilename(configCrontrolFile.ObservedProfiles));\n\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[0].name,STOKES_FIT_EXT);\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\n\n\t\t\t\tnumberOfFileSpectra = (configCrontrolFile.t2 - configCrontrolFile.t1)+1;\n\t\t\t\tvInputFileSpectra = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\tvOutputNameModels = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\tvOutputNameSynthesisAdjusted = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));\n\t\t\t\t\n\t\t\t\tint indexName = 0;\n\n\t\t\t\tfor(i=configCrontrolFile.t1;i<=configCrontrolFile.t2;i++){\n\t\t\t\t\tchar strIndex[5];\n\t\t\t\t\tif(i>=0 && i<10){\n\t\t\t\t\t\tsprintf(strIndex, \"00%d\", i);\n\t\t\t\t\t}\n\t\t\t\t\telse if(i>=10 && i<100){\n\t\t\t\t\t\tsprintf(strIndex, \"0%d\", i);\n\t\t\t\t\t}\n\t\t\t\t\telse \n\t\t\t\t\t\tsprintf(strIndex, \"%d\", i);\n\t\t\t\t\t// FILE NAMES FOR INPUT IMAGES\n\t\t\t\t\tstrcpy(vInputFileSpectra[indexName].name, configCrontrolFile.ObservedProfiles);\n\t\t\t\t\tstrcat(vInputFileSpectra[indexName].name,strIndex);\n\t\t\t\t\tstrcat(vInputFileSpectra[indexName].name,FITS_FILE);\n\t\t\t\t\t// FILE NAME FOR OUTPUT MODELS \n\t\t\t\t\t//strcpy(vOutputNameModels[indexName].name, configCrontrolFile.ObservedProfiles);\n\t\t\t\t\tprintf(\"%s\\n\", \"line 809\");\n\t\t\t\t\tstrcpy(vOutputNameModels[indexName].name, newObservedProfiles);\n\t\t\t\t\tstrcat(vOutputNameModels[indexName].name, strIndex);\n\t\t\t\t\tstrcat(vOutputNameModels[indexName].name, \"_mod\");\n\t\t\t\t\t/*if(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\tstrcat(vOutputNameModels[indexName].name, \"_\");\n\t\t\t\t\t\tstrcat(vOutputNameModels[indexName].name, configCrontrolFile.outputPrefix);\n\t\t\t\t\t}*/\n\t\t\t\t\tstrcat(vOutputNameModels[indexName].name,FITS_FILE);\n\t\t\t\t\t// FILE NAME FOR ADJUSTED SYNTHESIS \n\t\t\t\t\t//strcpy(vOutputNameSynthesisAdjusted[indexName].name, configCrontrolFile.ObservedProfiles);\n\t\t\t\t\tstrcpy(vOutputNameSynthesisAdjusted[indexName].name, newObservedProfiles);\n\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[indexName].name, strIndex);\n\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[indexName].name, \"_stokes\");\n\t\t\t\t\t/*if(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[indexName].name, \"_\");\n\t\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[indexName].name, configCrontrolFile.outputPrefix);\n\t\t\t\t\t}*/\n\t\t\t\t\tstrcat(vOutputNameSynthesisAdjusted[indexName].name,FITS_FILE);\n\t\t\t\t\tindexName++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tMPI_Barrier(MPI_COMM_WORLD); // Wait UNTIL THE IMAGE HAS BEEN READED COMPLETELY\n\t//  BROADCAST THE NUMBER OF LAMBDAS READS FROM THE FILE AND THE NUMBER OF PIXELS\n\tMPI_Bcast(&numberOfFileSpectra, 1, MPI_INT, root , MPI_COMM_WORLD);\n\tMPI_Barrier(MPI_COMM_WORLD);\n\n\t/**\n\t * What we do know is the following: \n\t * --- If the number of files is greater than number of available processors , then scatter the list of files proporcionaly between N processores. \n\t * --- If the number of files is less than number of available processors, then we process each fits file sequentially doing a scatter of N pixels in the each Fits File. \n\t * */\n\n\t\n\tint numFilesPerProcess = numberOfFileSpectra / numProcs;\n\tint numFilesPerProcessParallel = numberOfFileSpectra % numProcs;\n\tint numFilesPer2ProcessParallel=0;\n\tif(numFilesPerProcessParallel>=(numProcs/2)){ // DIVIDE EACH FILE IN TWO PROCESS\n\t\tnumFilesPer2ProcessParallel = numProcs/2;\n\t\tnumFilesPerProcessParallel = numFilesPerProcessParallel - (numProcs/2);\n\t}\n\telse\n\t{\n\t\tnumFilesPer2ProcessParallel = 0;\n\t}\n\n\tint sum = 0;                // Sum of counts. Used to calculate displacements\n\n\tfor ( i = 0; i < numProcs; i++) {\n\t\tsendcountsNameInputFiles[i] = numFilesPerProcess;\n\t\tdisplsNameInputFiles[i] = sum;\n\t\tsum += sendcountsNameInputFiles[i];\n\t}\n\n\t//**************************************** CREATE GROUPS FOR DIVIDE IMAGE IN 2 ********************************************/\n\t\n\tMPI_Group world_group;\n\tMPI_Comm_group(MPI_COMM_WORLD, &world_group);\n\tint numGroups = numProcs/2;\n\tMPI_Group vGroups [numGroups]; // will contain the numbers of process of each group\n\n\tif(numProcs%2 ==0){\n\t\tfor(i=0;i<numProcs;i=i+2){\n\t\t\tint ranks[2];\n\t\t\tranks[0] = i;\n\t\t\tranks[1] = i+1;\n\t\t\tMPI_Group_incl(world_group, 2, ranks, &vGroups[i/2]);\n\t\t}\n\t}\n\telse{\n\t\tint indProc=0;\n\t\tfor(i=0;i<numGroups;i++){\n\t\t\tif(i==(numGroups-1)){ // add resto\n\t\t\t\tint ranks[3];\n\t\t\t\tranks[0]=indProc++;\n\t\t\t\tranks[1]=indProc++;\n\t\t\t\tranks[2]=indProc++;\n\t\t\t\tMPI_Group_incl(world_group, 3, ranks, &vGroups[i]);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tint ranks[2];\n\t\t\t\tranks[0]=indProc++;\n\t\t\t\tranks[1]=indProc++;\n\t\t\t\tMPI_Group_incl(world_group, 2, ranks, &vGroups[i]);\n\t\t\t}\n\t\t}\n\t}\n\t// Create the new communicator from that group of processes.\n\t\n\tMPI_Comm vCommunicators[numGroups];\n\tfor(i=0;i<numGroups;i++){\n\t\tMPI_Comm_create(MPI_COMM_WORLD, vGroups[i], &vCommunicators[i]);\n\t}\n\n\tMPI_Barrier(MPI_COMM_WORLD);\n\tint myGroup = idProc/2;\n\tif(myGroup==numGroups)\n\t\tmyGroup = myGroup-1;\n\t\n\tint myGroupRank;\n\tint groupRoot = 0; // process 0 of group will be the root \n\tint myGroupSize;\n\tif(numGroups>0){\n\t\tMPI_Group_rank(vGroups[myGroup], &myGroupRank);\t\t\n\t\tMPI_Group_size(vGroups[myGroup], &myGroupSize);\n\t}\n\tMPI_Barrier(MPI_COMM_WORLD);\n\t//**************************************** END OF CREATE GROUPS FOR DIVIDE IMAGE IN 2 ********************************************/\n\n\tif(idProc == root){\n\t\tif(numFilesPerProcess>=1){\n\t\t\tvInputFileSpectraDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));\n\t\t\tvOutputNameModelsDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));\n\t\t\tvOutputNameSynthesisAdjustedDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));\n\t\t\t\n\t\t\tfor(i=0;i<numFilesPer2ProcessParallel;i++){\n\t\t\t\tstrcpy(vInputFileSpectraDiv2Parallel[i].name,vInputFileSpectra[(numFilesPerProcess*numProcs)+i].name);\n\t\t\t\tstrcpy(vOutputNameModelsDiv2Parallel[i].name,vOutputNameModels[(numFilesPerProcess*numProcs)+i].name);\n\t\t\t\tstrcpy(vOutputNameSynthesisAdjustedDiv2Parallel[i].name,vOutputNameSynthesisAdjusted[(numFilesPerProcess*numProcs)+i].name);\n\t\t\t}\n\n\t\t\tif(numFilesPerProcessParallel>0){\n\t\t\t\tvInputFileSpectraParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));\n\t\t\t\tvOutputNameModelsParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));\n\t\t\t\tvOutputNameSynthesisAdjustedParallel = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));\n\t\t\t\t\n\t\t\t\tfor(i=0;i<numFilesPerProcessParallel;i++){\n\t\t\t\t\tstrcpy(vInputFileSpectraParalell[i].name,vInputFileSpectra[(numFilesPerProcess*numProcs)+numFilesPer2ProcessParallel+i].name);\n\t\t\t\t\tstrcpy(vOutputNameModelsParalell[i].name,vOutputNameModels[(numFilesPerProcess*numProcs)+numFilesPer2ProcessParallel+i].name);\n\t\t\t\t\tstrcpy(vOutputNameSynthesisAdjustedParallel[i].name,vOutputNameSynthesisAdjusted[(numFilesPerProcess*numProcs)+numFilesPer2ProcessParallel+i].name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnameFile * auxInput  = (nameFile *)malloc((numFilesPerProcess*numProcs)*sizeof(nameFile));\n\t\t\tnameFile * auxOutput = (nameFile *)malloc((numFilesPerProcess*numProcs)*sizeof(nameFile));\n\t\t\tnameFile * auxOutputSynthesisAdjusted = (nameFile *)malloc((numFilesPerProcess*numProcs)*sizeof(nameFile));\n\n\t\t\tfor(i=0;i<(numFilesPerProcess*numProcs);i++){\n\t\t\t\tstrcpy(auxInput[i].name,vInputFileSpectra[i].name);\n\t\t\t\tstrcpy(auxOutput[i].name,vOutputNameModels[i].name);\n\t\t\t\tstrcpy(auxOutputSynthesisAdjusted[i].name,vOutputNameSynthesisAdjusted[i].name);\n\t\t\t}\t\t\n\t\t\tfree(vInputFileSpectra);\n\t\t\tfree(vOutputNameModels);\n\t\t\tfree(vOutputNameSynthesisAdjusted);\n\t\t\tvInputFileSpectra = auxInput;\n\t\t\tvOutputNameModels = auxOutput;\n\t\t\tvOutputNameSynthesisAdjusted = auxOutputSynthesisAdjusted;\n\t\t}\n\t\telse{\n\t\t\tif(vInputFileSpectraDiv2Parallel!=NULL)\n\t\t\t\tfree(vInputFileSpectraDiv2Parallel);\n\t\t\tif(vOutputNameModelsDiv2Parallel!=NULL)\n\t\t\t\tfree(vOutputNameModelsDiv2Parallel);\n\t\t\tif(vOutputNameSynthesisAdjustedDiv2Parallel!=NULL)\n\t\t\t\tfree(vOutputNameSynthesisAdjustedDiv2Parallel);\t\t\t\n\t\t\tif(vInputFileSpectraParalell!=NULL)\n\t\t\t\tfree(vInputFileSpectraParalell);\n\t\t\tif(vOutputNameModelsParalell!=NULL)\n\t\t\t\tfree(vOutputNameModelsParalell);\n\t\t\tif(vOutputNameSynthesisAdjustedParallel!=NULL)\n\t\t\t\tfree(vOutputNameSynthesisAdjustedParallel);\n\n\t\t\tif(numFilesPer2ProcessParallel>0){\n\t\t\t\tvInputFileSpectraDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));\n\t\t\t\tvOutputNameModelsDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));\n\t\t\t\tvOutputNameSynthesisAdjustedDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));\t\t\t\t\n\t\t\t\tfor(i=0;i<numFilesPer2ProcessParallel;i++){\n\t\t\t\t\tstrcpy(vInputFileSpectraDiv2Parallel[i].name,vInputFileSpectra[i].name);\n\t\t\t\t\tstrcpy(vOutputNameModelsDiv2Parallel[i].name,vOutputNameModels[i].name);\n\t\t\t\t\tstrcpy(vOutputNameSynthesisAdjustedDiv2Parallel[i].name,vOutputNameSynthesisAdjusted[i].name);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tvInputFileSpectraParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));\n\t\t\tvOutputNameModelsParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));\n\t\t\tvOutputNameSynthesisAdjustedParallel = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));\n\n\t\t\tfor(i=0;i<numFilesPerProcessParallel;i++){\n\t\t\t\tstrcpy(vInputFileSpectraParalell[i].name,vInputFileSpectra[numFilesPer2ProcessParallel+i].name);\n\t\t\t\tstrcpy(vOutputNameModelsParalell[i].name,vOutputNameModels[numFilesPer2ProcessParallel+i].name);\n\t\t\t\tstrcpy(vOutputNameSynthesisAdjustedParallel[i].name,vOutputNameSynthesisAdjusted[numFilesPer2ProcessParallel+i].name);\n\t\t\t}\n\t\t\tfree(vInputFileSpectra);\n\t\t\tvInputFileSpectra = NULL;\n\t\t\tfree(vOutputNameModels);\n\t\t\tvOutputNameModels = NULL;\n\t\t\tfree(vOutputNameSynthesisAdjusted);\n\t\t\tvOutputNameSynthesisAdjusted = NULL;\t\t\t\n\t\t}\n\t}\n\n\t\n\tMPI_Barrier(MPI_COMM_WORLD);\n\n\tif(numFilesPer2ProcessParallel>0){ // CASE DIVIDE EACH IMAGE BETWEEN TWO PROCESS\n\t\tif(idProc!=root){\n\t\t\tvInputFileSpectraDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));\n\t\t\tvOutputNameModelsDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));\n\t\t\tvOutputNameSynthesisAdjustedDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));\t\t\n\t\t}\n\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t\tMPI_Bcast(vInputFileSpectraDiv2Parallel, numFilesPer2ProcessParallel,mpiName , root , MPI_COMM_WORLD);\n\t\tMPI_Bcast(vOutputNameModelsDiv2Parallel, numFilesPer2ProcessParallel,mpiName , root , MPI_COMM_WORLD);\n\t\tMPI_Bcast(vOutputNameSynthesisAdjustedDiv2Parallel, numFilesPer2ProcessParallel,mpiName , root , MPI_COMM_WORLD);\n\t\tMPI_Barrier(MPI_COMM_WORLD);\t\n\t}\n\n\tif(numFilesPerProcessParallel>0){\n\t\tif(idProc!=root){\n\t\t\tvInputFileSpectraParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));\n\t\t\tvOutputNameModelsParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));\n\t\t\tvOutputNameSynthesisAdjustedParallel = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));\t\t\n\t\t}\n\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t\tMPI_Bcast(vInputFileSpectraParalell, numFilesPerProcessParallel,mpiName , root , MPI_COMM_WORLD);\n\t\tMPI_Bcast(vOutputNameModelsParalell, numFilesPerProcessParallel,mpiName , root , MPI_COMM_WORLD);\n\t\tMPI_Bcast(vOutputNameSynthesisAdjustedParallel, numFilesPerProcessParallel,mpiName , root , MPI_COMM_WORLD);\n\t\tMPI_Barrier(MPI_COMM_WORLD);\t\t\n\t}\n\n\t// PRINT INFORMATION \n\tif(idProc==root){\n\t        //printf(\"\\n-------------------------------------------------------------------------------\");\n\t\tprintf(\"\\nNumber of free parameters to be inverted: %d\\n\", free_params);\n\t\t//printf(\"\\n-------------------------------------------------------------------------------\\n\");\t\t\n\t\tif(configCrontrolFile.ConvolveWithPSF && INITIAL_MODEL.mac>0){\n\t\t  //printf(\"\\n-----------------------------------------------------------\");\n\t\t\tprintf(\"\\nConvolution with instrumental PSF will be performed. Macoturbulence is different from zero\\n \");\n\t\t\t//printf(\"\\n-----------------------------------------------------------\\n\");\n\t\t}\n\t\telse if(configCrontrolFile.ConvolveWithPSF){\n\t\t  //printf(\"\\n-----------------------------------------------------------\");\n\t\t\tprintf(\"\\nConvolution with instrumental PSF will be performed\\n\");\n\t\t\t//printf(\"\\n-----------------------------------------------------------\\n\");\n\t\t}\n\t\telse if(INITIAL_MODEL.mac>0){\n\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t//printf(\"\\nConvolution will be performed: macroturbulence in initial model is different from zero\\n\");\n\t\t\t//printf(\"\\n-----------------------------------------------------------\\n\");\n\t\t}\n\t        printf(\"\\n--------------------------------- STARTING INVERSION -----------------------------------\\n\");\n\t\tprintf(\"\\n \");\n\t}\n\t\n\t\n\n\n\n\t// MEMORY IF SCATTER IMAGES \n\n\tFitsImage ** fitsImages;\n\tfitsImages = (FitsImage **)malloc(numFilesPerProcessParallel*sizeof(FitsImage*));\n\tMPI_Request * vMpiRequestScatter = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));\n\tMPI_Request * vMpiRequestInitModel = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));\n\tMPI_Request * vMpiRequestChisqr = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));\n\tMPI_Request * vMpiRequestIter = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));\n\tMPI_Request * vMpiRequestSpectraAd = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));\n\tMPI_Request * vMpiRequestReduceExecution = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));\n\tint * vNumPixelsImage = malloc(numFilesPerProcessParallel*sizeof(int));\n\tInit_Model ** resultsInitModel_L = (Init_Model **)malloc(numFilesPerProcessParallel*sizeof(Init_Model*));\n\tInit_Model ** resultsInitModelTotal_L = (Init_Model **)malloc(numFilesPerProcessParallel*sizeof(Init_Model*));\n\tfloat ** chisqrfTotal_L = (float **) malloc(numFilesPerProcessParallel*sizeof(float*));\n\tfloat **vChisqrf_L = (float **) malloc(numFilesPerProcessParallel*sizeof(float*));\n\tint **vNumIter_L = (int **) malloc(numFilesPerProcessParallel*sizeof(int*));\n\tint **vNumIterTotal_L = (int **) malloc(numFilesPerProcessParallel*sizeof(int*));\n\tfloat  **vSpectraSplit_L = (float **) malloc(numFilesPerProcessParallel*sizeof(float*));\n\tfloat  **vSpectraAdjustedSplit_L = (float **) malloc(numFilesPerProcessParallel*sizeof(float*));\n\tfloat  **vSpectraAjustedTotal_L = (float **) malloc(numFilesPerProcessParallel*sizeof(float*));\n\t\n\tint sendcountsPixels_L [numFilesPerProcessParallel][numProcs] ; // array describing how many elements to send to each process\n\tint sendcountsSpectro_L [numFilesPerProcessParallel][numProcs];\n\tint sendcountsLambda_L [numFilesPerProcessParallel][numProcs];\n\t\n\tint displsPixels_L [numFilesPerProcessParallel][numProcs];  // array describing the displacements where each segment begins\n\tint displsSpectro_L [numFilesPerProcessParallel][numProcs];\n\t//int displsLambda [numProcs];\n\t\n\n\t\n\n\tdouble * vElapsed_execution = calloc(numFilesPerProcessParallel,sizeof(double));\n\tint indexInputFits;\n\n\tif(numFilesPerProcess>=1){\n\t\tvInputFileSpectraLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));\n\t\tvOutputNameModelsLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));\n\t\tvOutputNameSynthesisAdjustedLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));\n\t\t\n\t\tif( root == idProc){\n\t\t\tMPI_Scatterv(vInputFileSpectra, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vInputFileSpectraLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t\tMPI_Scatterv(vOutputNameModels, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vOutputNameModelsLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t\tMPI_Scatterv(vOutputNameSynthesisAdjusted, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vOutputNameSynthesisAdjustedLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t}\n\t\telse{\n\t\t\tMPI_Scatterv(NULL, NULL,NULL, mpiName, vInputFileSpectraLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t\tMPI_Scatterv(NULL, NULL,NULL, mpiName, vOutputNameModelsLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t\tMPI_Scatterv(NULL, NULL,NULL, mpiName, vOutputNameSynthesisAdjustedLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t}\n\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t}\n\tif(numFilesPerProcessParallel){\n\t\t// FIRST SCATTER ALL PIXELS BETWEEN ALL PROCESS\n\t\tclock_t t = clock();\n\t\tfor(indexInputFits=0;indexInputFits<numFilesPerProcessParallel;indexInputFits++){\n\t\t\tif(idProc==root){\n\n\t\t\t\tif((access(vInputFileSpectraParalell[indexInputFits].name,F_OK)!=-1)){\n\t\t\t\t\tclock_t t = clock();\n\t\t\t\t\t\n\t\t\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\n\t\t\t\t\t\tfitsImages[indexInputFits] = readFitsSpectroImageRectangular(vInputFileSpectraParalell[indexInputFits].name,&configCrontrolFile,1,nlambda);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tfitsImages[indexInputFits] = readFitsSpectroImage(vInputFileSpectraParalell[indexInputFits].name,1,nlambda);\n\t\t\t\t\t}\n\n\t\t\t\t\t// CHECK SIZE MASK FILE \n\t\t\t\t\tif(vMask!=NULL && (numRowsMask!=fitsImages[indexInputFits]->rows || numColsMask!=fitsImages[indexInputFits]->cols) ){\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\tprintf(\"\\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND MASK FILE %s  [rows: %d , cols: %d ] ARE DIFFERENT. \",vInputFileSpectraParalell[indexInputFits].name, fitsImages[indexInputFits]->rows, fitsImages[indexInputFits]->cols,configCrontrolFile.MaskFile,numRowsMask,numColsMask);\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t}\n\n\t\t\t\t\t// CHECK SIZE STRAY LIGHT \n\n\t\t\t\t\tif(slight!=NULL){\n\n\t\t\t\t\t\tif(nl_straylight!=nlambda){\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\tprintf(\"\\n Number of wavelengths in straylight file %d is different from wavelength grid file %d\",nl_straylight,nlambda);\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(nx_straylight!=0 && ny_straylight!=0){\n\t\t\t\t\t\t\tif(nx_straylight!= fitsImages[indexInputFits]->rows || ny_straylight !=fitsImages[indexInputFits]->cols ){\n\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\t\tprintf(\"\\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND STRAYLIGHT FILE %s  [rows: %d , cols: %d ] ARE DIFFERENT. \",vInputFileSpectraParalell[indexInputFits].name, fitsImages[indexInputFits]->rows, fitsImages[indexInputFits]->cols,configCrontrolFile.StrayLightFile,nx_straylight,ny_straylight);\n\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tt = clock() - t;\n\t\t\t\t\tPRECISION timeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds \n\t\t\t\t\t//printf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\nTIME TO READ CUBE %s: %5.2f s. PIXELS READ: %d\",vInputFileSpectraParalell[indexInputFits].name, timeReadImage,fitsImages[indexInputFits]->numPixels); \n\t\t\t\t\t//printf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\tvNumPixelsImage[indexInputFits] = fitsImages[indexInputFits]->numPixels;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\tMPI_Barrier(MPI_COMM_WORLD); // Wait UNTIL THE IMAGE HAS BEEN READED COMPLETELY\n\t\t\t//  BROADCAST THE NUMBER OF PIXELS\n\t\t\tMPI_Bcast(&vNumPixelsImage[indexInputFits], 1, MPI_INT, root , MPI_COMM_WORLD);\n\t\t\tMPI_Barrier(MPI_COMM_WORLD); // WAIT UNTIL G HAS BEEN READ\n\n\t\t\t// IF THE NUMBER OF PIXELS IS NOT GREATER THAN 0 WE DON'T CONITUNUE \n\t\t\tif(vNumPixelsImage[indexInputFits] > 0){\n\t\t\t\t\n\t\t\t\tif(idProc == root){\n\t\t\t\t  //printf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\nDOING INVERSION:  %s \\n\",vInputFileSpectraParalell[indexInputFits].name );\n\t\t\t\t\t//printf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\n\t\t\t\t\tresultsInitModelTotal_L[indexInputFits] = calloc (vNumPixelsImage[indexInputFits] , sizeof(Init_Model));\n\t\t\t\t\tchisqrfTotal_L[indexInputFits] = calloc (vNumPixelsImage[indexInputFits] , sizeof(float));\n\t\t\t\t\tvNumIterTotal_L[indexInputFits] = calloc (vNumPixelsImage[indexInputFits], sizeof(int));\n\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\t\tvSpectraAjustedTotal_L[indexInputFits] = calloc (vNumPixelsImage[indexInputFits]*nlambda*NPARMS,sizeof(float));\n\t\t\t\t}\n\t\t\t\t// allocate memory in all processes \n\n\t\t\t\tint numPixelsProceso = vNumPixelsImage[indexInputFits]/(numProcs);\n\t\t\t\tint resto = vNumPixelsImage[indexInputFits] % (numProcs);\n\t\t\t\tint sum = 0;                // Sum of counts. Used to calculate displacements\n\t\t\t\tint sumSpectro = 0;\n\t\t\t\tint sumLambda = 0;\n\t\t\t\tsendcountsPixels_L[indexInputFits][0] = 0;\n\t\t\t\tsendcountsSpectro_L[indexInputFits][0] = 0;\n\t\t\t\tsendcountsLambda_L[indexInputFits][0] = 0;\n\t\t\t\tdisplsPixels_L[indexInputFits][0] = 0;\n\t\t\t\tdisplsSpectro_L[indexInputFits][0] = 0;\n\t\t\t\tfor ( i = 0; i < numProcs; i++) {\n\t\t\t\t\tsendcountsPixels_L[indexInputFits][i] = numPixelsProceso;\n\t\t\t\t\tif (resto > 0) {\n\t\t\t\t\t\t\tsendcountsPixels_L[indexInputFits][i]++;\n\t\t\t\t\t\t\tresto--;\n\t\t\t\t\t}\n\t\t\t\t\tsendcountsSpectro_L[indexInputFits][i] = (sendcountsPixels_L[indexInputFits][i])*nlambda*NPARMS;\n\t\t\t\t\tsendcountsLambda_L[indexInputFits][i] = (sendcountsPixels_L[indexInputFits][i])*nlambda;\n\t\t\t\t\tdisplsPixels_L[indexInputFits][i] = sum;\n\t\t\t\t\tdisplsSpectro_L[indexInputFits][i] = sumSpectro;\n\t\t\t\t\t//displsLambda[i] = sumLambda;\n\t\t\t\t\tsum += sendcountsPixels_L[indexInputFits][i];\n\t\t\t\t\tsumSpectro += sendcountsSpectro_L[indexInputFits][i];\n\t\t\t\t\tsumLambda += sendcountsLambda_L[indexInputFits][i];\n\t\t\t\t}\n\n\t\t\t\tMPI_Barrier(MPI_COMM_WORLD); // Wait until all processes have their vlambda\n\t\t\t\tlocal_start = MPI_Wtime();\n\n\t\t\t\t// SCATTER VPIXELS \n\t\t\t\tvSpectraSplit_L[indexInputFits] = calloc(sendcountsSpectro_L[indexInputFits][idProc],sizeof(float));\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\tvSpectraAdjustedSplit_L[indexInputFits] = calloc(sendcountsSpectro_L[indexInputFits][idProc],sizeof(float));\n\t\t\t\t\n\t\t\t\tlocal_start_scatter = MPI_Wtime();\n\t\t\t\tMPI_Barrier(MPI_COMM_WORLD); // Wait until all processes have their vlambda\t\t\t\t\n\t\t\t\tif( root == idProc){\n\t\t\t\t\t//MPI_Scatterv(fitsImages[indexInputFits]->spectroImagen, sendcountsSpectro_L[indexInputFits], displsSpectro_L[indexInputFits], MPI_FLOAT, vSpectraSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, root, MPI_COMM_WORLD);\n\t\t\t\t\tMPI_Iscatterv(fitsImages[indexInputFits]->spectroImagen, sendcountsSpectro_L[indexInputFits], displsSpectro_L[indexInputFits], MPI_FLOAT, vSpectraSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestScatter[indexInputFits]);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t//MPI_Scatterv(NULL, NULL,NULL, MPI_FLOAT, vSpectraSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, root, MPI_COMM_WORLD);\n\t\t\t\t\tMPI_Iscatterv(NULL, NULL,NULL, MPI_FLOAT, vSpectraSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestScatter[indexInputFits]);\n\t\t\t\t}\t\t\n\t\t\t\tlocal_finish_scatter = MPI_Wtime();\n\n\t\t\t\tresultsInitModel_L[indexInputFits] = calloc(sendcountsPixels_L[indexInputFits][idProc], sizeof(Init_Model));\n\t\t\t\tvChisqrf_L[indexInputFits] = calloc(sendcountsPixels_L[indexInputFits][idProc], sizeof(float));\n\t\t\t\tvNumIter_L[indexInputFits] = calloc(sendcountsPixels_L[indexInputFits][idProc], sizeof(int));\n\t\t\t}\n\t\t\telse if (idProc==root){\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\tprintf(\"\\n------------- FITS FILE CANNOT BE READ  %s \",vInputFileSpectraParalell[indexInputFits].name);\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t}\n\t\t}\n\t\tMPI_Waitall(numFilesPerProcessParallel,vMpiRequestScatter,MPI_STATUSES_IGNORE);\n\t\tif(idProc==root){\n\t\t\tt = clock() - t;\n\t\t\tPRECISION timeTotalExecution = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds \n\t\t\t//printf(\"\\n-----------------------------------------------------------\");\n\t\t\tprintf(\"\\nTOTAL TIME TO READ AND SCATTER CUBES: %6.2f s\",timeTotalExecution);\n\t\t\tprintf(\"\\n----------------------------------------------------------------------------------------\\n\");\n\t\t}\n\t}\n\tAllocateMemoryDerivedSynthesis(nlambda);\n\t//*************************************** ONE IMAGE PER PROCESSOR *********************************\n\n\tif(numFilesPerProcessParallel){\n\n\t\t//clock_t t = clock();\n\t\t// EACH PROC PROCESS THER PIXELS \n\t\tfor(indexInputFits=0;indexInputFits<numFilesPerProcessParallel;indexInputFits++){\n\t\t\tif(vNumPixelsImage[indexInputFits] > 0){\n\t\t\t\tlocal_start_execution = MPI_Wtime();\n\t\t\t\tfor(indexPixel = 0; indexPixel < sendcountsPixels_L[indexInputFits][idProc]; indexPixel++){\n\t\t\t\t\tint invertir = 1;\n\t\t\t\t\tif(vMask!=NULL && !vMask[ displsPixels_L[indexInputFits][idProc] + indexPixel]){\n\t\t\t\t\t\tinvertir=0;\n\t\t\t\t\t}\n\t\t\t\t\tif(invertir){\n\t\t\t\t\t\tfloat * vAuxSpectraSplit = vSpectraSplit_L[indexInputFits];\n\t\t\t\t\t\t//Initial Model\n\t\t\t\t\t\tInit_Model initModel;\n\t\t\t\t\t\tinitModel.eta0 = INITIAL_MODEL.eta0;\n\t\t\t\t\t\tinitModel.B = INITIAL_MODEL.B; \n\t\t\t\t\t\tinitModel.gm = INITIAL_MODEL.gm;\n\t\t\t\t\t\tinitModel.az = INITIAL_MODEL.az;\n\t\t\t\t\t\tinitModel.vlos = INITIAL_MODEL.vlos; //km/s 0\n\t\t\t\t\t\tinitModel.mac = INITIAL_MODEL.mac;\n\t\t\t\t\t\tinitModel.dopp = INITIAL_MODEL.dopp;\n\t\t\t\t\t\tinitModel.aa = INITIAL_MODEL.aa;\n\t\t\t\t\t\tinitModel.alfa = INITIAL_MODEL.alfa; \n\t\t\t\t\t\tinitModel.S0 = INITIAL_MODEL.S0;\n\t\t\t\t\t\tinitModel.S1 = INITIAL_MODEL.S1;\n\n\t\t\t\t\t\t// CLASSICAL ESTIMATES TO GET B, GAMMA, vlos, azimuth\n\t\t\t\t\t\testimacionesClasicas(wlines[1], vGlobalLambda, nlambda, vAuxSpectraSplit+(indexPixel*(nlambda*NPARMS)), &initModel,1);\n\t\t\t\t\t\tif (isnan(initModel.B))\n\t\t\t\t\t\t\tinitModel.B = 1;\n\t\t\t\t\t\tif (isnan(initModel.vlos))\n\t\t\t\t\t\t\tinitModel.vlos = 1e-3;\n\t\t\t\t\t\tif (isnan(initModel.gm))\n\t\t\t\t\t\t\tinitModel.gm = 1;\t\t\t\t\t\t\n\t\t\t\t\t\tif (isnan(initModel.az))\n\t\t\t\t\t\t\tinitModel.az = 1;\n\t\t\t\t\t\t// INVERSION RTE\n\t\t\t\t\t\t\n\t\t\t\t\t\tfloat * slightPixel;\n\t\t\t\t\t\tif(slight==NULL) \n\t\t\t\t\t\t\tslightPixel = NULL;\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tif(nx_straylight && ny_straylight){\n\t\t\t\t\t\t\t\tslightPixel = slight+ (nlambda*NPARMS*indexPixel)+displsSpectro_L[indexInputFits][idProc];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tslightPixel = slight;\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\tvNumIter_L[indexInputFits][indexPixel] = -1;\n\t\t\t\t\t\tlm_mils(cuantic, wlines, vGlobalLambda, nlambda, vAuxSpectraSplit+(indexPixel*(nlambda*NPARMS)), nlambda, &initModel, spectra, &(vChisqrf_L[indexInputFits][indexPixel]), slightPixel, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles,\n\t\t\t\t\t\t\tconfigCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise, configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&(vNumIter_L[indexInputFits][indexPixel]),configCrontrolFile.mu,configCrontrolFile.logclambda);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tresultsInitModel_L[indexInputFits][indexPixel] = initModel;\n\t\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\t\tint kk;\n\t\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvSpectraAdjustedSplit_L[indexInputFits][ (indexPixel*(nlambda * NPARMS))+kk] = spectra[kk] ;\n\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}\n\t\t\t\t\telse{\n\t\t\t\t\t\tInit_Model initModel;\n\t\t\t\t\t\tinitModel.eta0 = 0;\n\t\t\t\t\t\tinitModel.B = 0; \n\t\t\t\t\t\tinitModel.gm = 0;\n\t\t\t\t\t\tinitModel.az = 0;\n\t\t\t\t\t\tinitModel.vlos = 0; //km/s 0\n\t\t\t\t\t\tinitModel.mac = 0;\n\t\t\t\t\t\tinitModel.dopp = 0;\n\t\t\t\t\t\tinitModel.aa = 0;\n\t\t\t\t\t\tinitModel.alfa = 0; \n\t\t\t\t\t\tinitModel.S0 = 0;\n\t\t\t\t\t\tinitModel.S1 = 0;\n\t\t\t\t\t\tresultsInitModel_L[indexInputFits][indexPixel] = initModel;\n\t\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\t\tint kk;\n\t\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvSpectraAdjustedSplit_L[indexInputFits][ (indexPixel*(nlambda * NPARMS))+kk] = 0 ;\n\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}\n\t\t\t\t}\n\n\t\t\t\t/*MPI_Igatherv(resultsInitModel_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], mpiInitModel, resultsInitModelTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], mpiInitModel, root, MPI_COMM_WORLD,&vMpiRequestInitModel[indexInputFits]);\n\t\t\t\tMPI_Igatherv(vChisqrf_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], MPI_FLOAT, chisqrfTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestChisqr[indexInputFits]);\t\t\n\t\t\t\tMPI_Igatherv(vNumIter_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], MPI_INT, vNumIterTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], MPI_INT, root, MPI_COMM_WORLD,&vMpiRequestIter[indexInputFits]);\t\t\n\t\t\t\t\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\tMPI_Igatherv(vSpectraAdjustedSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, vSpectraAjustedTotal_L[indexInputFits], sendcountsSpectro_L[indexInputFits], displsSpectro_L[indexInputFits], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestSpectraAd[indexInputFits]);\t\t\n\t\t\t\tlocal_elapsed_execution = MPI_Wtime() - local_start_execution;\n\t\t\t\tMPI_Ireduce(&local_elapsed_execution, &vElapsed_execution[indexInputFits], 1, MPI_DOUBLE, MPI_MAX, root, MPI_COMM_WORLD,&vMpiRequestReduceExecution[indexInputFits]);*/\n\n\t\t\t\tMPI_Gatherv(resultsInitModel_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], mpiInitModel, resultsInitModelTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], mpiInitModel, root, MPI_COMM_WORLD);\n\t\t\t\tMPI_Gatherv(vChisqrf_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], MPI_FLOAT, chisqrfTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], MPI_FLOAT, root, MPI_COMM_WORLD);\t\t\n\t\t\t\tMPI_Gatherv(vNumIter_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], MPI_INT, vNumIterTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], MPI_INT, root, MPI_COMM_WORLD);\t\t\n\t\t\t\t\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\tMPI_Gatherv(vSpectraAdjustedSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, vSpectraAjustedTotal_L[indexInputFits], sendcountsSpectro_L[indexInputFits], displsSpectro_L[indexInputFits], MPI_FLOAT, root, MPI_COMM_WORLD);\t\t\n\t\t\t\tlocal_elapsed_execution = MPI_Wtime() - local_start_execution;\n\t\t\t\tMPI_Reduce(&local_elapsed_execution, &vElapsed_execution[indexInputFits], 1, MPI_DOUBLE, MPI_MAX, root, MPI_COMM_WORLD);\n\n\t\t\t}\n\t\t}\n\n\n\t\tif(idProc==root){\n\t\t\tint indexInputFits = 0;\n\t\t\tdo{\n\t\t\t\t/*MPI_Wait(&vMpiRequestInitModel[indexInputFits],MPI_STATUS_IGNORE);\n\t\t\t\tMPI_Wait(&vMpiRequestChisqr[indexInputFits],MPI_STATUS_IGNORE);\n\t\t\t\tMPI_Wait(&vMpiRequestIter[indexInputFits],MPI_STATUS_IGNORE);\n\t\t\t\tMPI_Wait(&vMpiRequestReduceExecution[indexInputFits],MPI_STATUS_IGNORE);\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\tMPI_Wait(&vMpiRequestSpectraAd[indexInputFits],MPI_STATUS_IGNORE);*/\n\n\t\t\t\tdouble timeWriteImage;\n\t\t\t\tclock_t t;\n\t\t\t\tt = clock();\n\n\t\t\t\tprintf(\"%s\\n\",vOutputNameModelsParalell[indexInputFits].name);\n\n\t\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\n\t\t\t\t\tif(!writeFitsImageModelsSubSet(vOutputNameModelsParalell[indexInputFits].name,fitsImages[indexInputFits]->rows_original,fitsImages[indexInputFits]->cols_original,configCrontrolFile,resultsInitModelTotal_L[indexInputFits],chisqrfTotal_L[indexInputFits],vNumIterTotal_L[indexInputFits],configCrontrolFile.saveChisqr)){\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT MODELS: %s\",vOutputNameModelsParalell[indexInputFits].name);\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tif(!writeFitsImageModels(vOutputNameModelsParalell[indexInputFits].name,fitsImages[indexInputFits]->rows,fitsImages[indexInputFits]->cols,resultsInitModelTotal_L[indexInputFits],chisqrfTotal_L[indexInputFits],vNumIterTotal_L[indexInputFits],configCrontrolFile.saveChisqr)){\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT MODELS: %s\",vOutputNameModelsParalell[indexInputFits].name);\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tt = clock() - t;\n\t\t\t\ttimeWriteImage = ((double)t)/CLOCKS_PER_SEC; // in seconds \n\t\t\t\t\n\t\t\t\t// PROCESS FILE OF SYNTETIC PROFILES\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\tfitsImages[indexInputFits]->pixels = calloc(fitsImages[indexInputFits]->numPixels, sizeof(vpixels));\n\t\t\t\t\tfor( i=0;i<fitsImages[indexInputFits]->numPixels;i++){\n\t\t\t\t\t\tfitsImages[indexInputFits]->pixels[i].spectro = calloc ((fitsImages[indexInputFits]->numStokes*fitsImages[indexInputFits]->nLambdas),sizeof(float));\n\t\t\t\t\t}\t\t\n\t\t\t\t\tfor(indexPixel=0;indexPixel<fitsImages[indexInputFits]->numPixels;indexPixel++)\n\t\t\t\t\t{\t\n\t\t\t\t\t\tint kk;\n\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfitsImages[indexInputFits]->pixels[indexPixel].spectro[kk] = vSpectraAjustedTotal_L[indexInputFits][kk+(indexPixel*(nlambda * NPARMS))] ;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\t// WRITE SINTHETIC PROFILES TO FITS FILE\n\t\t\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\t\t\t\t\t\t\t\n\t\t\t\t\t\tif(!writeFitsImageProfilesSubSet(vOutputNameSynthesisAdjustedParallel[indexInputFits].name,vInputFileSpectraParalell[indexInputFits].name,fitsImages[indexInputFits],configCrontrolFile)){\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT PROFILES: %s\",vOutputNameSynthesisAdjustedParallel[indexInputFits].name);\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\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\n\t\t\t\t\t\tif(!writeFitsImageProfiles(vOutputNameSynthesisAdjustedParallel[indexInputFits].name,vInputFileSpectraParalell[indexInputFits].name,fitsImages[indexInputFits])){\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT PROFILES: %s\",vOutputNameSynthesisAdjustedParallel[indexInputFits].name);\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfor( i=0;i<fitsImages[indexInputFits]->numPixels;i++){\n\t\t\t\t\t\tfree(fitsImages[indexInputFits]->pixels[i].spectro);\n\t\t\t\t\t\tfitsImages[indexInputFits]->pixels[i].spectro = NULL;\n\t\t\t\t\t}\t\t\t\t\t\t\t\n\t\t\t\t\tfree(fitsImages[indexInputFits]->pixels);\n\t\t\t\t\tfitsImages[indexInputFits]->pixels = NULL;\n\t\t\t\t}\n\n\t\t\t\tfree(resultsInitModelTotal_L[indexInputFits]);\t\t\n\t\t\t\tfree(chisqrfTotal_L[indexInputFits]);\n\t\t\t\tfree(vNumIterTotal_L[indexInputFits]);\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\tfree(vSpectraAjustedTotal_L[indexInputFits]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tprintf(\"\\n----------------------------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nCUBE %s INVERTED USING ALL CORES! EXECUTION TIME: %6.2f s\", vInputFileSpectraParalell[indexInputFits].name,vElapsed_execution[indexInputFits]);\n\t\t\t\t//printf(\"\\n EXECUTION TIME = %lf s.\\n\", vElapsed_execution[indexInputFits]);\n\t\t\t\tprintf(\"\\nTIME TO WRITE FITS IMAGE: %5.2f s.\", timeWriteImage);\n\t\t\t\tprintf(\"\\n----------------------------------------------------------------------------------------------------\\n\");\n\t\t\t\tfreeFitsImage(fitsImages[indexInputFits]);\n\t\t\t\tindexInputFits++;\t\t\t\n\t\t\t}while(indexInputFits<numFilesPerProcessParallel);\n\t\t}\n\n\t\tfree(fitsImages);\n\t\tfree(vMpiRequestScatter);\n\t\tfree(vMpiRequestInitModel);\n\t\tfree(vMpiRequestChisqr);\n\t\tfree(vMpiRequestIter);\n\t\tfree(vMpiRequestSpectraAd);\n\t\tfree(vNumPixelsImage);\n\t\tfree(vMpiRequestReduceExecution);\n\t\tfree(resultsInitModel_L);\n\t\tfree(resultsInitModelTotal_L);\n\t\tfree(chisqrfTotal_L);\n\t\tfree(vChisqrf_L);\n\t\tfree(vNumIter_L);\n\t\tfree(vNumIterTotal_L);\n\t\tfree(vSpectraSplit_L);\n\t\tfree(vSpectraAdjustedSplit_L);\n\t\tfree(vSpectraAjustedTotal_L);\n\t\t//MPI_Barrier(MPI_COMM_WORLD);\n\t}\n\n\n\tif(numFilesPerProcess>=1){ // ONE IMAGE PER PROCESSOR\n\t\tInit_Model *vModels;\n\n\t\t/*vInputFileSpectraLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));\n\t\tvOutputNameModelsLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));\n\t\tvOutputNameSynthesisAdjustedLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));\n\t\t\n\t\tif( root == idProc){\n\t\t\tMPI_Scatterv(vInputFileSpectra, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vInputFileSpectraLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t\tMPI_Scatterv(vOutputNameModels, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vOutputNameModelsLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t\tMPI_Scatterv(vOutputNameSynthesisAdjusted, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vOutputNameSynthesisAdjustedLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t}\n\t\telse{\n\t\t\tMPI_Scatterv(NULL, NULL,NULL, mpiName, vInputFileSpectraLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t\tMPI_Scatterv(NULL, NULL,NULL, mpiName, vOutputNameModelsLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t\tMPI_Scatterv(NULL, NULL,NULL, mpiName, vOutputNameSynthesisAdjustedLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);\n\t\t}\n\t\tMPI_Barrier(MPI_COMM_WORLD);*/\n\n\t\t//  PROCESS INVERSION OVER EACH FILE ON THE CURRENT PROCESSOR \n\t\tint indexInputFits;\n\t\tfor(indexInputFits=0;indexInputFits<sendcountsNameInputFiles[idProc];indexInputFits++){\n\t\t\t/****************************************************************************************************/\n\t\t\t// READ PIXELS FROM IMAGE \n\t\t\tPRECISION timeReadImage\t;\n\t\t\tclock_t t, timeTotal;\n\t\t\tt = clock();\n\t\t\ttimeTotal = clock();\n\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\n\t\t\t\tfitsImage = readFitsSpectroImageRectangular(vInputFileSpectraLocal[indexInputFits].name,&configCrontrolFile,0,nlambda);\n\t\t\t}\n\t\t\telse\n\t\t\t\tfitsImage = readFitsSpectroImage(vInputFileSpectraLocal[indexInputFits].name,0,nlambda);\n\n\t\t\tif(vMask!=NULL && (numRowsMask!=fitsImage->rows || numColsMask!=fitsImage->cols)){\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\tprintf(\"\\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND MASK FILE %s  [rows: %d , cols: %d ] ARE DIFFERENT. \",vInputFileSpectraLocal[indexInputFits].name, fitsImage->rows, fitsImage->cols,configCrontrolFile.MaskFile,numRowsMask,numColsMask);\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\t// CHECK SIZE STRAY LIGHT \n\t\t\tif(slight!=NULL){\n\t\t\t\tif(nl_straylight!=nlambda){\n\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\n Number of wavelengths in straylight file %d is different from wavelength grid file %d\",nl_straylight,nlambda);\n\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\t\tif(nx_straylight!=0 && ny_straylight!=0){\n\t\t\t\t\tif(nx_straylight!= fitsImage->rows || ny_straylight !=fitsImage->cols ){\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\tprintf(\"\\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND STRAYLIGHT FILE %s  [rows: %d , cols: %d ] ARE DIFFERENT. \",vInputFileSpectraParalell[indexInputFits].name, fitsImage->rows, fitsImage->cols,configCrontrolFile.StrayLightFile,nx_straylight,ny_straylight);\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\tt = clock() - t;\n\t\t\ttimeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds \n\t\t\t\n\t\t\t//printf(\"\\n-----------------------------------------------------------------------------------------\");\n\t\t\tprintf(\"ID:%3d --> TIME TO READ CUBE %s: %5.2f s. PIXELS READ: %d\",idProc, vInputFileSpectraLocal[indexInputFits].name, timeReadImage,fitsImage->numPixels); \n\t\t\t//printf(\"\\n-----------------------------------------------------------------------------------------\\n\");\n\n\t\t\tif(fitsImage!=NULL){\n\n\t\t\t\t// FITS IMAGE TO STORE OUTPUT PROFILES ADJUSTED\n\t\t\t\tFitsImage * imageStokesAdjust = NULL;\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\timageStokesAdjust = malloc(sizeof(FitsImage));\n\t\t\t\t\timageStokesAdjust->rows = fitsImage->rows;\n\t\t\t\t\timageStokesAdjust->cols = fitsImage->cols;\n\t\t\t\t\timageStokesAdjust->nLambdas = fitsImage->nLambdas;\n\t\t\t\t\timageStokesAdjust->numStokes = fitsImage->numStokes;\n\t\t\t\t\timageStokesAdjust->pos_col = fitsImage->pos_col;\n\t\t\t\t\timageStokesAdjust->pos_row = fitsImage->pos_row;\n\t\t\t\t\timageStokesAdjust->pos_lambda = fitsImage->pos_lambda;\n\t\t\t\t\timageStokesAdjust->pos_stokes_parameters = fitsImage->pos_stokes_parameters;\n\t\t\t\t\timageStokesAdjust->numPixels = fitsImage->numPixels;\n\t\t\t\t\timageStokesAdjust->pixels = calloc(imageStokesAdjust->numPixels, sizeof(vpixels));\n\t\t\t\t\timageStokesAdjust->naxes = fitsImage->naxes;\n\t\t\t\t\timageStokesAdjust->vCard = fitsImage->vCard;\n\t\t\t\t\timageStokesAdjust->vKeyname = fitsImage->vKeyname;\n\t\t\t\t\timageStokesAdjust->nkeys = fitsImage->nkeys;\n\t\t\t\t\timageStokesAdjust->naxis = fitsImage->naxis;\n\t\t\t\t\timageStokesAdjust->bitpix = fitsImage->bitpix;\n\t\t\t\t\timageStokesAdjust->rows_original = fitsImage->rows_original;\n\t\t\t\t\timageStokesAdjust->cols_original = fitsImage->cols_original;\n\t\t\t\t\timageStokesAdjust->naxes_original = fitsImage->naxes_original;\n\t\t\t\t\tfor( i=0;i<imageStokesAdjust->numPixels;i++){\n\t\t\t\t\t\timageStokesAdjust->pixels[i].spectro = calloc (nlambda*NPARMS,sizeof(float));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//***************************************** INIT MEMORY WITH SIZE OF LAMBDA ****************************************************//\n\t\t\t\t\n\t\t\t\tint indexPixel = 0;\n\n\t\t\t\t// ALLOCATE MEMORY FOR STORE THE RESULTS \n\n\t\t\t\tvModels = calloc (fitsImage->numPixels , sizeof(Init_Model));\n\t\t\t\tvChisqrf = calloc (fitsImage->numPixels , sizeof(float));\n\t\t\t\tvNumIter = calloc (fitsImage->numPixels, sizeof(int));\n\t\t\t\t//t = clock();\n\t\t\t\t\n\t\t\t\t//printf(\"\\n------------------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nID:%3d --> DOING INVERSION:  %s\\n\",idProc,vInputFileSpectraLocal[indexInputFits].name);\n\t\t\t\t//printf(\"\\n------------------------------------------------------------------------------------------/n\");\n\t\t\t\tprintf(\"\\n \"); \n\n\t\t\t\tfor(indexPixel = 0; indexPixel < fitsImage->numPixels; indexPixel++){\n\t\t\t\t\t\n\t\t\t\t\tint invertir =1;\n\t\t\t\t\tif(vMask!=NULL && !vMask[indexPixel]){\n\t\t\t\t\t\tinvertir=0;\n\t\t\t\t\t}\n\t\t\t\t\tif(invertir){\n\t\t\t\t\t\t//Initial Model\n\t\t\t\t\t\tInit_Model initModel;\n\t\t\t\t\t\tinitModel.eta0 = INITIAL_MODEL.eta0;\n\t\t\t\t\t\tinitModel.B = INITIAL_MODEL.B; //200 700\n\t\t\t\t\t\tinitModel.gm = INITIAL_MODEL.gm;\n\t\t\t\t\t\tinitModel.az = INITIAL_MODEL.az;\n\t\t\t\t\t\tinitModel.vlos = INITIAL_MODEL.vlos; //km/s 0\n\t\t\t\t\t\tinitModel.mac = INITIAL_MODEL.mac;\n\t\t\t\t\t\tinitModel.dopp = INITIAL_MODEL.dopp;\n\t\t\t\t\t\tinitModel.aa = INITIAL_MODEL.aa;\n\t\t\t\t\t\tinitModel.alfa = INITIAL_MODEL.alfa; //0.38; //stray light factor\n\t\t\t\t\t\tinitModel.S0 = INITIAL_MODEL.S0;\n\t\t\t\t\t\tinitModel.S1 = INITIAL_MODEL.S1;\n\t\t\t\t\t\t\n\t\t\t\t\t\t// CLASSICAL ESTIMATES TO GET B, GAMMA, vlos, azimuth\n\t\t\t\t\t\testimacionesClasicas(wlines[1], vGlobalLambda, nlambda, fitsImage->pixels[indexPixel].spectro, &initModel,1);\n\t\t\t\t\t\tif (isnan(initModel.B))\n\t\t\t\t\t\t\tinitModel.B = 1;\n\t\t\t\t\t\tif (isnan(initModel.vlos))\n\t\t\t\t\t\t\tinitModel.vlos = 1e-3;\n\t\t\t\t\t\tif (isnan(initModel.gm))\n\t\t\t\t\t\t\tinitModel.gm = 1;\n\t\t\t\t\t\tif (isnan(initModel.az))\n\t\t\t\t\t\t\tinitModel.az = 1;\n\t\t\t\t\t\t// INVERSION RTE\n\n\t\t\t\t\t\tfloat * slightPixel;\n\t\t\t\t\t\tif(slight==NULL) \n\t\t\t\t\t\t\tslightPixel = NULL;\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tif(nx_straylight && ny_straylight){\n\t\t\t\t\t\t\t\tslightPixel = slight+ (nlambda*NPARMS*indexPixel);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tslightPixel = slight;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvNumIter[indexPixel] = -1;\n\t\t\t\t\t\tlm_mils(cuantic, wlines, vGlobalLambda, nlambda, fitsImage->pixels[indexPixel].spectro, nlambda, &initModel, spectra, &vChisqrf[indexPixel], slightPixel, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles,\n\t\t\t\t\t\t\t\tconfigCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise, configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&vNumIter[indexPixel],configCrontrolFile.mu,configCrontrolFile.logclambda);\t\t\t\t\t\t\n\n\t\t\t\t\t\tvModels[indexPixel] = initModel;\n\t\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\t\tint kk;\n\t\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\timageStokesAdjust->pixels[indexPixel].spectro[kk] = spectra[kk] ;\n\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}else\n\t\t\t\t\t{\n\t\t\t\t\t\tInit_Model initModel;\n\t\t\t\t\t\tinitModel.eta0 = 0;\n\t\t\t\t\t\tinitModel.B = 0; //200 700\n\t\t\t\t\t\tinitModel.gm = 0;\n\t\t\t\t\t\tinitModel.az = 0;\n\t\t\t\t\t\tinitModel.vlos = 0; //km/s 0\n\t\t\t\t\t\tinitModel.mac = 0;\n\t\t\t\t\t\tinitModel.dopp = 0;\n\t\t\t\t\t\tinitModel.aa = 0;\n\t\t\t\t\t\tinitModel.alfa = 0; //0.38; //stray light factor\n\t\t\t\t\t\tinitModel.S0 = 0;\n\t\t\t\t\t\tinitModel.S1 = 0;\n\t\t\t\t\t\tvModels[indexPixel] = initModel;\n\t\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\t\tint kk;\n\t\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\timageStokesAdjust->pixels[indexPixel].spectro[kk] = 0 ;\n\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}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tclock_t t_write = clock();\n\t\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\n\t\t\t\t\tif(!writeFitsImageModelsSubSet(vOutputNameModelsLocal[indexInputFits].name,fitsImage->rows_original,fitsImage->cols_original,configCrontrolFile,vModels,vChisqrf,vNumIter,configCrontrolFile.saveChisqr)){\t\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT MODELS: %s\",vOutputNameModelsParalell[indexInputFits].name);\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t// WRITE SINTHETIC PROFILES TO FITS FILE\n\t\t\t\t\t\tif(!writeFitsImageProfilesSubSet(vOutputNameSynthesisAdjustedLocal[indexInputFits].name,vInputFileSpectraLocal[indexInputFits].name,imageStokesAdjust,configCrontrolFile)){\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT PROFILES: %s\",vOutputNameSynthesisAdjustedLocal[indexInputFits].name);\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tif(!writeFitsImageModels(vOutputNameModelsLocal[indexInputFits].name,fitsImage->rows,fitsImage->cols,vModels,vChisqrf,vNumIter,configCrontrolFile.saveChisqr)){\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT MODELS: %s\",vOutputNameModelsLocal[indexInputFits].name);\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t// WRITE SINTHETIC PROFILES TO FITS FILE\n\t\t\t\t\t\tif(!writeFitsImageProfiles(vOutputNameSynthesisAdjustedLocal[indexInputFits].name,vInputFileSpectraLocal[indexInputFits].name,imageStokesAdjust)){\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT PROFILES: %s\",vOutputNameSynthesisAdjustedLocal[indexInputFits].name);\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// PROCESS FILE OF SYNTETIC PROFILES\n\n\t\t\t\ttimeTotal = clock() - timeTotal;\n\t\t\t\tt_write = clock() - t_write;\n\t\t\t\tPRECISION timeTotalExecution = ((PRECISION)timeTotal)/CLOCKS_PER_SEC; // in seconds \n\t\t\t\t\n\t\t\t\t//printf(\"\\n----------------------------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nID:%3d --> CUBE %s INVERTED USING ONE CORE! TIME: %6.2f s\", idProc, vInputFileSpectraLocal[indexInputFits].name,timeTotalExecution);\n\t\t\t\t//printf(\"\\n----------------------------------------------------------------------------------------------------\\n\");\t\t\t\n\t\t\t\t\n\t\t\t\tPRECISION timeToWriteImage = ((PRECISION)t_write)/CLOCKS_PER_SEC; // in seconds \n\t\t\t\t\n\t\t\t\t//printf(\"\\n----------------------------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nID:%3d --> TIME TO WRITE FITS CUBE: %5.2f s\", idProc, timeToWriteImage);\n\t\t\t\tprintf(\"\\n----------------------------------------------------------------------------------------------------\\n\");\t\t\t\n\t\t\t\tif(imageStokesAdjust!=NULL){\n\t\t\t\t\tfor( i=0;i<imageStokesAdjust->numPixels;i++){\n\t\t\t\t\t\tfree(imageStokesAdjust->pixels[i].spectro);\n\t\t\t\t\t}\n\t\t\t\t\tfree(imageStokesAdjust->pixels);\n\t\t\t\t\tfree(imageStokesAdjust);\n\t\t\t\t}\n\t\t\t\tfree(vModels);\n\t\t\t\tfree(vChisqrf);\n\t\t\t\tfree(vNumIter);\n\n\n\t\t\t}\n\t\t\telse{\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nID:%3d --> FILE %s WITH PROFILES CANNOT BE READ ************\",idProc, vInputFileSpectraLocal[indexInputFits].name);\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\n\t\t\t}\n\n\t\t\tfreeFitsImage(fitsImage);\n\t\t\t//FreeMemoryDerivedSynthesis();\n\t\t}\n\t\t\n\t\tfree(vInputFileSpectraLocal);\n\t\tfree(vOutputNameModelsLocal);\n\t\tfree(vOutputNameSynthesisAdjustedLocal);\n\t\tvInputFileSpectraLocal = NULL;\n\t\tvOutputNameModelsLocal = NULL;\n\t\tvOutputNameSynthesisAdjustedLocal = NULL;\n\t}\n\n\n\tif(numFilesPer2ProcessParallel>0){ // CASE DIVIDE EACH IMAGE BETWEEN TWO PROCESS\n\n\t\t// Get the group or processes of the default communicator\n\n\t\t// EACH GROUP PROCESS ONE IMAGE\n\t\tMPI_Barrier(vCommunicators[myGroup]);\n\t\tnumPixels=0;\n\t\tclock_t timeTotal;\n\n\t\tif(myGroupRank==groupRoot && access(vInputFileSpectraDiv2Parallel[myGroup].name,F_OK)!=-1){\n\t\t\t\n\t\t\tclock_t t = clock();\n\t\t\ttimeTotal = clock();\n\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\n\t\t\t\tfitsImage = readFitsSpectroImageRectangular(vInputFileSpectraDiv2Parallel[myGroup].name,&configCrontrolFile,1,nlambda);\n\t\t\t}\n\t\t\telse\n\t\t\t\tfitsImage = readFitsSpectroImage(vInputFileSpectraDiv2Parallel[myGroup].name,1,nlambda);\n\t\t\t\n\t\t\tif(vMask!=NULL && (numRowsMask!=fitsImage->rows || numColsMask!=fitsImage->cols)){\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\tprintf(\"\\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND MASK FILE %s  [rows: %d , cols: %d ] ARE DIFFERENT. \",vInputFileSpectraDiv2Parallel[myGroup].name, fitsImage->rows, fitsImage->cols,configCrontrolFile.MaskFile,numRowsMask,numColsMask);\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\t// CHECK SIZE STRAY LIGHT \n\t\t\tif(slight!=NULL){\n\t\t\t\tif(nl_straylight!=nlambda){\n\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\n Number of wavelengths in straylight file %d is different from wavelength grid file %d\",nl_straylight,nlambda);\n\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\t\tif(nx_straylight!=0 && ny_straylight!=0){\n\t\t\t\t\tif(nx_straylight!= fitsImage->rows || ny_straylight !=fitsImage->cols ){\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\tprintf(\"\\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND STRAYLIGHT FILE %s  [rows: %d , cols: %d ] ARE DIFFERENT. \",vInputFileSpectraParalell[indexInputFits].name, fitsImage->rows, fitsImage->cols,configCrontrolFile.StrayLightFile,nx_straylight,ny_straylight);\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t\t\t\t\n\t\t\tt = clock() - t;\n\t\t\tPRECISION timeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds\n\t\t\t//printf(\"\\n-----------------------------------------------------------\"); \n\t\t\tprintf(\"\\nTIME TO READ CUBE %s: %5.2f s. PIXELS READ: %d\",vInputFileSpectraDiv2Parallel[myGroup].name, timeReadImage,fitsImage->numPixels); \n\t\t\t//printf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\tnumPixels = fitsImage->numPixels;\n\t\t}\n\n\t\tMPI_Barrier(vCommunicators[myGroup]); // Wait UNTIL THE IMAGE HAS BEEN READED COMPLETELY by my group \n\t\tMPI_Bcast(&numPixels, 1, MPI_INT, groupRoot , vCommunicators[myGroup]);\n\t\tMPI_Barrier(vCommunicators[myGroup]);\n\n\n\n\t\tif(numPixels > 0){\n\t\t\tif(myGroupRank==groupRoot){\n\t\t\t  //printf(\"\\n-----------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nDOING INVERSION:  %s \\n\",vInputFileSpectraDiv2Parallel[myGroup].name );\n\t\t\t\t//printf(\"\\n-----------------------------------------------------------\");\n\t\t\t\tresultsInitModelTotal = calloc (numPixels , sizeof(Init_Model));\n\t\t\t\tchisqrfTotal = calloc (numPixels , sizeof(float));\n\t\t\t\tvNumIterTotal = calloc (numPixels, sizeof(int));\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\tvSpectraAjustedTotal = calloc (numPixels*nlambda*NPARMS,sizeof(float));\n\t\t\t}\t\t\t\t\n\n\t\t\tint numPixelsProceso = numPixels/myGroupSize;\n\t\t\tint resto = numPixels % myGroupSize;\n\t\t\tint sum = 0;                // Sum of counts. Used to calculate displacements\n\t\t\tint sumSpectro = 0;\n\t\t\tint sumLambda = 0;\n\t\t\tint sendcountsDiv2Pixels [myGroupSize] ; // array describing how many elements to send to each process\n\t\t\tint sendcountsDiv2Spectro [myGroupSize];\n\t\t\tint sendcountsDiv2Lambda [myGroupSize];\n\t\t\tint displsDiv2Pixels [myGroupSize];\n\t\t\tint displsDiv2Spectro [myGroupSize];\n\t\t\tfor ( i = 0; i < myGroupSize; i++) {\n\t\t\t\tsendcountsDiv2Pixels[i] = numPixelsProceso;\n\t\t\t\tif (resto > 0) {\n\t\t\t\t\t\tsendcountsDiv2Pixels[i]++;\n\t\t\t\t\t\tresto--;\n\t\t\t\t}\n\t\t\t\tsendcountsDiv2Spectro[i] = sendcountsDiv2Pixels[i]*nlambda*NPARMS;\n\t\t\t\tsendcountsDiv2Lambda[i] = sendcountsDiv2Pixels[i]*nlambda;\n\t\t\t\tdisplsDiv2Pixels[i] = sum;\n\t\t\t\tdisplsDiv2Spectro[i] = sumSpectro;\n\t\t\t\tsum += sendcountsDiv2Pixels[i];\n\t\t\t\tsumSpectro += sendcountsDiv2Spectro[i];\n\t\t\t\tsumLambda += sendcountsDiv2Lambda[i];\n\t\t\t}\n\t\t\tMPI_Barrier(vCommunicators[myGroup]);\t\n\t\t\t// SCATTER VPIXELS \n\t\t\tlocal_start = MPI_Wtime();\n\t\t\tlocal_start_scatter = MPI_Wtime();\n\t\t\tvSpectraSplit = calloc(sendcountsDiv2Spectro[myGroupRank],sizeof(float));\n\t\t\t\n\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\tvSpectraAdjustedSplit = calloc(sendcountsDiv2Spectro[myGroupRank],sizeof(float));\n\n\t\t\tif(myGroupRank==groupRoot){\n\t\t\t\tMPI_Scatterv(fitsImage->spectroImagen, sendcountsDiv2Spectro, displsDiv2Spectro, MPI_FLOAT, vSpectraSplit, sendcountsDiv2Spectro[myGroupRank], MPI_FLOAT, groupRoot, vCommunicators[myGroup]);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tMPI_Scatterv(NULL, NULL,NULL, MPI_FLOAT, vSpectraSplit, sendcountsDiv2Spectro[myGroupRank], MPI_FLOAT, groupRoot, vCommunicators[myGroup]);\n\t\t\t}\t\n\t\t\tlocal_finish_scatter = MPI_Wtime();\n\n\t\t\tresultsInitModel = calloc(sendcountsDiv2Pixels[myGroupRank], sizeof(Init_Model));\n\t\t\tvChisqrf = calloc(sendcountsDiv2Pixels[myGroupRank], sizeof(float));\n\t\t\tvNumIter = calloc(sendcountsDiv2Pixels[myGroupRank], sizeof(int));\n\n\t\t\tlocal_start_execution = MPI_Wtime();\n\t\t\tfor(indexPixel = 0; indexPixel < sendcountsDiv2Pixels[myGroupRank]; indexPixel++){\n\t\t\t\tint invertir = 1;\n\t\t\t\tif(vMask!=NULL && !vMask[ displsDiv2Pixels[myGroupRank] + indexPixel]){\n\t\t\t\t\tinvertir=0;\n\t\t\t\t}\n\t\t\t\tif(invertir){\n\t\t\t\t\t//Initial Model\n\t\t\t\t\tInit_Model initModel;\n\t\t\t\t\tinitModel.eta0 = INITIAL_MODEL.eta0;\n\t\t\t\t\tinitModel.B = INITIAL_MODEL.B; \n\t\t\t\t\tinitModel.gm = INITIAL_MODEL.gm;\n\t\t\t\t\tinitModel.az = INITIAL_MODEL.az;\n\t\t\t\t\tinitModel.vlos = INITIAL_MODEL.vlos; //km/s 0\n\t\t\t\t\tinitModel.mac = INITIAL_MODEL.mac;\n\t\t\t\t\tinitModel.dopp = INITIAL_MODEL.dopp;\n\t\t\t\t\tinitModel.aa = INITIAL_MODEL.aa;\n\t\t\t\t\tinitModel.alfa = INITIAL_MODEL.alfa; \n\t\t\t\t\tinitModel.S0 = INITIAL_MODEL.S0;\n\t\t\t\t\tinitModel.S1 = INITIAL_MODEL.S1;\n\n\t\t\t\t\t// CLASSICAL ESTIMATES TO GET B, GAMMA, vlos, azimuth\n\t\t\t\t\testimacionesClasicas(wlines[1], vGlobalLambda, nlambda, vSpectraSplit+(indexPixel*(nlambda*NPARMS)), &initModel,1);\n\n\t\t\t\t\tif (isnan(initModel.B))\n\t\t\t\t\t\tinitModel.B = 1;\n\t\t\t\t\tif (isnan(initModel.vlos))\n\t\t\t\t\t\tinitModel.vlos = 1e-3;\n\t\t\t\t\tif (isnan(initModel.gm))\n\t\t\t\t\t\tinitModel.gm = 1;\t\t\t\t\t\t\n\t\t\t\t\tif (isnan(initModel.az))\n\t\t\t\t\t\tinitModel.az = 1;\n\n\t\t\t\t\t// INVERSION RTE\n\t\t\t\t\t\n\t\t\t\t\tfloat * slightPixel;\n\t\t\t\t\tif(slight==NULL) \n\t\t\t\t\t\tslightPixel = NULL;\n\t\t\t\t\telse{\n\t\t\t\t\t\tif(nx_straylight && ny_straylight){\n\t\t\t\t\t\t\tslightPixel = slight+ (nlambda*NPARMS* indexPixel) + displsDiv2Spectro[myGroupRank];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tslightPixel = slight;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tvNumIter[indexPixel] = -1;\n\t\t\t\t\tlm_mils(cuantic, wlines, vGlobalLambda, nlambda, vSpectraSplit+(indexPixel*(nlambda*NPARMS)), nlambda, &initModel, spectra, &vChisqrf[indexPixel], slightPixel, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles,\n\t\t\t\t\t\tconfigCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma,  configCrontrolFile.noise,configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&vNumIter[indexPixel],configCrontrolFile.mu,configCrontrolFile.logclambda);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tresultsInitModel[indexPixel] = initModel;\n\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\tint kk;\n\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvSpectraAdjustedSplit[ (indexPixel*(nlambda * NPARMS))+kk] = spectra[kk] ;\n\t\t\t\t\t\t}\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\t//Initial Model\n\t\t\t\t\tInit_Model initModel;\n\t\t\t\t\tinitModel.eta0 = 0;\n\t\t\t\t\tinitModel.B = 0; \n\t\t\t\t\tinitModel.gm = 0;\n\t\t\t\t\tinitModel.az = 0;\n\t\t\t\t\tinitModel.vlos = 0; //km/s 0\n\t\t\t\t\tinitModel.mac = 0;\n\t\t\t\t\tinitModel.dopp = 0;\n\t\t\t\t\tinitModel.aa = 0;\n\t\t\t\t\tinitModel.alfa = 0; \n\t\t\t\t\tinitModel.S0 = 0;\n\t\t\t\t\tinitModel.S1 = 0;\n\t\t\t\t\tresultsInitModel[indexPixel] = initModel;\n\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\tint kk;\n\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvSpectraAdjustedSplit[ (indexPixel*(nlambda * NPARMS))+kk] = 0 ;\n\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlocal_finish_execution = MPI_Wtime();\n\t\t\tlocal_start_gather = MPI_Wtime();\t\t\t\n\t\t\tMPI_Gatherv(resultsInitModel, sendcountsDiv2Pixels[myGroupRank], mpiInitModel, resultsInitModelTotal, sendcountsDiv2Pixels, displsDiv2Pixels, mpiInitModel, groupRoot, vCommunicators[myGroup]);\n\t\t\tMPI_Gatherv(vChisqrf, sendcountsDiv2Pixels[myGroupRank], MPI_FLOAT, chisqrfTotal, sendcountsDiv2Pixels, displsDiv2Pixels, MPI_FLOAT, groupRoot, vCommunicators[myGroup]);\t\t\n\t\t\tMPI_Gatherv(vNumIter, sendcountsDiv2Pixels[myGroupRank], MPI_INT, vNumIterTotal, sendcountsDiv2Pixels, displsDiv2Pixels, MPI_INT, groupRoot, vCommunicators[myGroup]);\t\t\n\n\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\tMPI_Gatherv(vSpectraAdjustedSplit, sendcountsDiv2Spectro[myGroupRank], MPI_FLOAT, vSpectraAjustedTotal, sendcountsDiv2Spectro, displsDiv2Spectro, MPI_FLOAT, groupRoot, vCommunicators[myGroup]);\n\n\t\t\tlocal_finish_gather = MPI_Wtime();\n\t\t\tlocal_finish = MPI_Wtime();\n\t\t\tlocal_elapsed = local_finish - local_start;\n\t\t\tlocal_elapsed_execution = local_finish_execution - local_start_execution;\n\t\t\tlocal_elapsed_scatter = local_finish_scatter - local_start_scatter;\n\t\t\tlocal_elapsed_gather = local_finish_gather - local_start_gather;\n\t\t\tMPI_Reduce(&local_elapsed, &elapsed, 1, MPI_DOUBLE, MPI_MAX, groupRoot, vCommunicators[myGroup]);\n\t\t\tMPI_Reduce(&local_elapsed_execution, &elapsed_execution, 1, MPI_DOUBLE, MPI_MAX, groupRoot, vCommunicators[myGroup]);\n\t\t\tMPI_Reduce(&local_elapsed_scatter, &elapsed_scatter, 1, MPI_DOUBLE, MPI_MAX, groupRoot, vCommunicators[myGroup]);\n\t\t\tMPI_Reduce(&local_elapsed_gather, &elapsed_gather, 1, MPI_DOUBLE, MPI_MAX, groupRoot, vCommunicators[myGroup]);\n\n\t\t\tif(myGroupRank==groupRoot){\n\t\t\t\t/*printf(\"\\n Elapsed SCATTER time = %lf seconds\\n\", elapsed_scatter);\n\t\t\t\tprintf(\"\\n-----------------------------------\\n\");\n\t\t\t\tprintf(\"\\n Elapsed GATHER time = %lf seconds\\n\", elapsed_gather);\n\t\t\t\tprintf(\"\\n-----------------------------------\\n\");\t\t\t\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\tprintf(\"\\n MAX EXECUTION time = %lf seconds\", elapsed_execution);\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\tprintf(\"\\n Elapsed TOTAL time = %lf seconds\\n\", elapsed);\n\t\t\t\tprintf(\"\\n-----------------------------------\\n\");*/\n\t\t\t\tdouble timeWriteImage;\n\t\t\t\tclock_t t;\n\t\t\t\tt = clock();\n\t\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\n\t\t\t\t\tif(!writeFitsImageModelsSubSet(vOutputNameModelsDiv2Parallel[myGroup].name,fitsImage->rows_original,fitsImage->cols_original,configCrontrolFile,resultsInitModelTotal,chisqrfTotal,vNumIterTotal,configCrontrolFile.saveChisqr)){\t\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT MODELS: %s\",vOutputNameModelsParalell[indexInputFits].name);\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tif(!writeFitsImageModels(vOutputNameModelsDiv2Parallel[myGroup].name,fitsImage->rows,fitsImage->cols,resultsInitModelTotal,chisqrfTotal,vNumIterTotal,configCrontrolFile.saveChisqr)){\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT MODELS: %s\",vOutputNameModelsDiv2Parallel[myGroup].name);\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tt = clock() - t;\n\t\t\t\ttimeWriteImage = ((double)t)/CLOCKS_PER_SEC; // in seconds \n\t\t\t\tprintf(\"\\n------------------------------------------------------------------------------------------\\n\");\n\t\t\t\tprintf(\"TIME TO WRITE FITS CUBE: %5.2f s.\", timeWriteImage);\n\t\t\t\t//printf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\tfitsImage->pixels = calloc(fitsImage->numPixels, sizeof(vpixels));\n\t\t\t\t\tfor( i=0;i<fitsImage->numPixels;i++){\n\t\t\t\t\t\tfitsImage->pixels[i].spectro = calloc ((fitsImage->numStokes*fitsImage->nLambdas),sizeof(float));\n\t\t\t\t\t}\t\t\n\t\t\t\t\tfor(indexPixel=0;indexPixel<numPixels;indexPixel++)\n\t\t\t\t\t{\t\n\t\t\t\t\t\tint kk;\n\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfitsImage->pixels[indexPixel].spectro[kk] = vSpectraAjustedTotal[kk+(indexPixel*(nlambda * NPARMS))] ;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\t// WRITE SINTHETIC PROFILES TO FITS FILE\n\t\t\t\t\tif(!writeFitsImageProfiles(vOutputNameSynthesisAdjustedDiv2Parallel[myGroup].name,vInputFileSpectraDiv2Parallel[myGroup].name,fitsImage)){\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT PROFILES: %s\",vOutputNameSynthesisAdjustedDiv2Parallel[myGroup].name);\n\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfor( i=0;i<fitsImage->numPixels;i++){\n\t\t\t\t\t\tfree(fitsImage->pixels[i].spectro);\n\t\t\t\t\t\tfitsImage->pixels[i].spectro = NULL;\n\t\t\t\t\t}\t\t\t\t\t\t\t\n\t\t\t\t\tfree(fitsImage->pixels);\n\t\t\t\t\tfitsImage->pixels = NULL;\n\t\t\t\t}\n\t\t\t\ttimeTotal = clock() - timeTotal;\n\t\t\t\tPRECISION timeTotalExecution = ((PRECISION)timeTotal)/CLOCKS_PER_SEC; // in seconds \n\t\t\t\tfree(resultsInitModelTotal);\t\t\n\t\t\t\tfree(chisqrfTotal);\n\t\t\t\tfree(vNumIterTotal);\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\tfree(vSpectraAjustedTotal);\n\t\t\t\t}\n\t\t\t\t//printf(\"\\n----------------------------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nCUBE %s INVERTED USING TWO CORES. TIME: %7.2f s\", vInputFileSpectraDiv2Parallel[myGroup].name,timeTotalExecution);\n\t\t\t\tprintf(\"\\n------------------------------------------------------------------------------------------\\n\");\t\t\t\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\tfree(vSpectraAdjustedSplit);\n\t\t\t\tfree(vSpectraSplit);\n\t\t\t\tfree(resultsInitModel);\t\t\t\t\n\t\t\t\tfree(vChisqrf);\n\t\t\t\tfree(vNumIter);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(myGroupRank==groupRoot){\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nFITS FILE CANNOT BE READ: %s \",vInputFileSpectraDiv2Parallel[myGroup].name);\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t}\n\t\t}\n\t\tif(myGroupRank==groupRoot){\n\t\t\tfreeFitsImage(fitsImage);\n\t\t}\n\t}\n\n\tif(configCrontrolFile.loopInversion){\n\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t\tint fileNew = 0;\n\t\tint exitProgram = 0;\n\t\tchar newestFileName [256];\n\t\tdo{\n\t\t\tif(idProc==root){\n\t\t\t\ttime_t start_time,current_time;\n\t\t\t\t\n\t\t\t\tfileNew = 0;\n\t\t\t\tint directory = 1;\n\t\t\t\ttime(&start_time);\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\tprintf(\"\\n\\tWAITING FOR NEW DATA CUBES IN DIRECTORY\");\n\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\tprintf(\"\\n\");\n\t\t\t\tdo{\n\t\t\t\t\tDIR *d;\n\t\t\t\t\tstruct dirent *dir;\n\t\t\t\t\tchar observedProfilesAux[256];\n\t\t\t\t\tstrcpy(observedProfilesAux,configCrontrolFile.ObservedProfiles);\n\t\t\t\t\tchar * dname = dirname(observedProfilesAux);\n\t\t\t\t\t//d = opendir(dname);\n\t\t\t\t\tstruct dirent **namelist;\n\t\t\t\t\tint numFiles = scandir(dname, &namelist, 0, alphasort);\n\t\t\t\t\tif(numFiles>0){\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor(i=2;i<numFiles && !fileNew;i++){\t\n\t\t\t\t\t\t\tif(strcmp(namelist[i]->d_name,\".\")!=0 && strcmp(namelist[i]->d_name,\"..\")!=0 && strstr(namelist[i]->d_name,\"_mod_\")==NULL && strstr(namelist[i]->d_name,\"_stokes_\")==NULL){\n\t\t\t\t\t\t\t\tchar pathAux[256];\n\t\t\t\t\t\t\t\tstrcpy(pathAux,dname);\n\t\t\t\t\t\t\t\tstrcat(pathAux,\"/\");\n\t\t\t\t\t\t\t\t//strcat(pathAux,dir->d_name);\n\t\t\t\t\t\t\t\tstrcat(pathAux,namelist[i]->d_name);\n\t\t\t\t\t\t\t\t//stat(pathAux,&filestat);\n\t\t\t\t\t\t\t\tif(!isDirectory(pathAux) && !checkNameInLista(listFileNamesReaded,pathAux)){\n\t\t\t\t\t\t\t\t\tinsert_in_linked_list(&listFileNamesReaded,pathAux);\n\t\t\t\t\t\t\t\t\tfileNew = 1;\n\t\t\t\t\t\t\t\t\tstrcpy(newestFileName,pathAux);\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\t\t\tprintf(\"\\nTHERE IS A NEW DATA CUBE IN DIRECTORY: %s\",newestFileName);\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\t\t\tprintf(\"\\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}\t\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tprintf(\"\\nERROR, the path %s does not point to a valid directory\\n. \",dname);\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t\ttime(&current_time);\n\t\t\t\t\tif(difftime(current_time,start_time)>=TIMEOUT_FILE)\n\t\t\t\t\t\texitProgram = 1;\n\t\t\t\t\telse\n\t\t\t\t\t\tsleep(5);\n\t\t\t\t}while(!fileNew && !exitProgram);\n\n\t\t\t}\n\t\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t\t\tMPI_Bcast(&fileNew, 1, MPI_INT, root , MPI_COMM_WORLD);\n\t\t\tMPI_Bcast(&exitProgram, 1, MPI_INT, root , MPI_COMM_WORLD);\n\t\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t\t\tFitsImage * fitsImageLoop;\n\t\t\tint numPixelImageLoop;\n\t\t\tInit_Model * resultsInitModelLoop;\n\t\t\tInit_Model * resultsInitModelTotalLoop;\n\t\t\tfloat * chisqrfTotalLoop;\n\t\t\tfloat * vChisqrfLoop;\n\t\t\tint * vNumIterLoop;\n\t\t\tint * vNumIterTotalLoop;\n\t\t\tint sendcountsPixelsLoop [numProcs] ; // array describing how many elements to send to each process\n\t\t\tint sendcountsSpectroLoop [numProcs];\n\t\t\tint sendcountsLambdaLoop [numProcs];\n\t\t\tint displsPixelsLoop[numProcs]; \n\t\t\tint displsSpectroLoop [numProcs];\t\t\t\n\t\t\tfloat * vSpectraSplitLoop;\n\t\t\tfloat * vSpectraAdjustedSplitLoop;\n\t\t\tfloat * vSpectraAjustedTotalLoop;\n\t\t\t\n\t\t\tif(fileNew){\n\t\t\t\t\n\t\t\t\tif(idProc==root){\n\n\t\t\t\t\tif((access(newestFileName,F_OK)!=-1)){\n\t\t\t\t\t\tclock_t t = clock();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\n\t\t\t\t\t\t\tfitsImageLoop = readFitsSpectroImageRectangular(newestFileName,&configCrontrolFile,1,nlambda);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tfitsImageLoop = readFitsSpectroImage(newestFileName,1,nlambda);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// CHECK SIZE MASK FILE \n\t\t\t\t\t\tif(vMask!=NULL && (numRowsMask!=fitsImageLoop->rows || numColsMask!=fitsImageLoop->cols) ){\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\tprintf(\"\\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND MASK FILE %s  [rows: %d , cols: %d ] ARE DIFFERENT. \",vInputFileSpectraParalell[indexInputFits].name, fitsImages[indexInputFits]->rows, fitsImages[indexInputFits]->cols,configCrontrolFile.MaskFile,numRowsMask,numColsMask);\n\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// CHECK SIZE STRAY LIGHT \n\n\t\t\t\t\t\tif(slight!=NULL){\n\n\t\t\t\t\t\t\tif(nl_straylight!=nlambda){\n\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\t\tprintf(\"\\n Number of wavelengths in straylight file %d is different from wavelength grid file %d\",nl_straylight,nlambda);\n\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(nx_straylight!=0 && ny_straylight!=0){\n\t\t\t\t\t\t\t\tif(nx_straylight!= fitsImageLoop->rows || ny_straylight !=fitsImageLoop->cols ){\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\t\t\tprintf(\"\\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND STRAYLIGHT FILE %s  [rows: %d , cols: %d ] ARE DIFFERENT. \",newestFileName, fitsImageLoop->rows, fitsImageLoop->cols,configCrontrolFile.StrayLightFile,nx_straylight,ny_straylight);\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tt = clock() - t;\n\t\t\t\t\t\tPRECISION timeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds \n\t\t\t\t\t\t//printf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\tprintf(\"\\nTIME TO READ CUBE %s: %5.2f s. PIXELS READ: %d \",newestFileName, timeReadImage,fitsImageLoop->numPixels); \n\t\t\t\t\t\t//printf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\tnumPixelImageLoop = fitsImageLoop->numPixels;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tMPI_Barrier(MPI_COMM_WORLD); // Wait UNTIL THE IMAGE HAS BEEN READ COMPLETELY\n\t\t\t\t//  BROADCAST THE NUMBER OF PIXELS\n\t\t\t\tMPI_Bcast(&numPixelImageLoop, 1, MPI_INT, root , MPI_COMM_WORLD);\n\t\t\t\tMPI_Barrier(MPI_COMM_WORLD); // WAIT UNTIL numPixelImageLoop HAS BEEN READ\n\n\t\t\t\t// IF THE NUMBER OF PIXELS IS NOT GREATER THAN 0 WE DON'T CONITUNUE \n\t\t\t\tif(numPixelImageLoop > 0){\n\t\t\t\t\t\n\t\t\t\t\tif(idProc == root){\n\t\t\t\t\t  //printf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\tprintf(\"\\nDOING INVERSION:  %s \\n\",newestFileName );\n\t\t\t\t\t\t//printf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\n\t\t\t\t\t\tresultsInitModelTotalLoop = calloc (numPixelImageLoop , sizeof(Init_Model));\n\t\t\t\t\t\tchisqrfTotalLoop = calloc (numPixelImageLoop , sizeof(float));\n\t\t\t\t\t\tvNumIterTotalLoop = calloc (numPixelImageLoop, sizeof(int));\n\t\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\t\t\tvSpectraAjustedTotalLoop = calloc (numPixelImageLoop*nlambda*NPARMS,sizeof(float));\n\t\t\t\t\t}\n\t\t\t\t\t// allocate memory in all processes \n\n\t\t\t\t\tint numPixelsProceso = numPixelImageLoop/(numProcs);\n\t\t\t\t\tint resto = numPixelImageLoop % (numProcs);\n\t\t\t\t\tint sum = 0;                // Sum of counts. Used to calculate displacements\n\t\t\t\t\tint sumSpectro = 0;\n\t\t\t\t\tint sumLambda = 0;\n\t\t\t\t\tsendcountsPixelsLoop[0] = 0;\n\t\t\t\t\tsendcountsSpectroLoop[0] = 0;\n\t\t\t\t\tsendcountsLambdaLoop[0] = 0;\n\t\t\t\t\tdisplsPixelsLoop[0] = 0;\n\t\t\t\t\tdisplsSpectroLoop[0] = 0;\n\t\t\t\t\tfor ( i = 0; i < numProcs; i++) {\n\t\t\t\t\t\tsendcountsPixelsLoop[i] = numPixelsProceso;\n\t\t\t\t\t\tif (resto > 0) {\n\t\t\t\t\t\t\t\tsendcountsPixelsLoop[i]++;\n\t\t\t\t\t\t\t\tresto--;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsendcountsSpectroLoop[i] = (sendcountsPixelsLoop[i])*nlambda*NPARMS;\n\t\t\t\t\t\tsendcountsLambdaLoop[i] = (sendcountsPixelsLoop[i])*nlambda;\n\t\t\t\t\t\tdisplsPixelsLoop[i] = sum;\n\t\t\t\t\t\tdisplsSpectroLoop[i] = sumSpectro;\n\t\t\t\t\t\tsum += sendcountsPixelsLoop[i];\n\t\t\t\t\t\tsumSpectro += sendcountsSpectroLoop[i];\n\t\t\t\t\t\tsumLambda += sendcountsLambdaLoop[i];\n\t\t\t\t\t}\n\n\t\t\t\t\tMPI_Barrier(MPI_COMM_WORLD); // Wait until all processes have their vlambda\n\t\t\t\t\t// SCATTER VPIXELS \n\t\t\t\t\tvSpectraSplitLoop = calloc(sendcountsSpectroLoop[idProc],sizeof(float));\n\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\t\tvSpectraAdjustedSplitLoop = calloc(sendcountsSpectroLoop[idProc],sizeof(float));\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tMPI_Barrier(MPI_COMM_WORLD); // Wait until all processes have their vlambda\t\t\t\t\n\t\t\t\t\tif( root == idProc){\n\t\t\t\t\t\tMPI_Scatterv(fitsImageLoop->spectroImagen, sendcountsSpectroLoop, displsSpectroLoop, MPI_FLOAT, vSpectraSplitLoop, sendcountsSpectroLoop[idProc], MPI_FLOAT, root, MPI_COMM_WORLD);\n\t\t\t\t\t\t//MPI_Iscatterv(fitsImageLoop->spectroImagen, sendcountsSpectroLoop, displsSpectroLoop, MPI_FLOAT, vSpectraSplitLoop, sendcountsSpectroLoop[idProc], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestScatter[indexInputFits]);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tMPI_Scatterv(NULL, NULL,NULL, MPI_FLOAT, vSpectraSplitLoop, sendcountsSpectroLoop[idProc], MPI_FLOAT, root, MPI_COMM_WORLD);\n\t\t\t\t\t\t//MPI_Iscatterv(NULL, NULL,NULL, MPI_FLOAT, vSpectraSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestScatter[indexInputFits]);\n\t\t\t\t\t}\t\t\n\t\t\t\t\t\n\n\t\t\t\t\tresultsInitModelLoop = calloc(sendcountsPixelsLoop[idProc], sizeof(Init_Model));\n\t\t\t\t\tvChisqrfLoop = calloc(sendcountsPixelsLoop[idProc], sizeof(float));\n\t\t\t\t\tvNumIterLoop = calloc(sendcountsPixelsLoop[idProc], sizeof(int));\n\t\t\t\t}\n\t\t\t\telse if (idProc==root){\n\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\n------------ FITS FILE CANNOT BE READ:  %s \",vInputFileSpectraParalell[indexInputFits].name);\n\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// DO INVERSION \t\t\t\t\n\t\t\t\tif(numPixelImageLoop > 0){\n\t\t\t\t\tlocal_start_execution = MPI_Wtime();\n\t\t\t\t\tfor(indexPixel = 0; indexPixel < sendcountsPixelsLoop[idProc]; indexPixel++){\n\t\t\t\t\t\tint invertir = 1;\n\t\t\t\t\t\tif(vMask!=NULL && !vMask[ displsPixelsLoop[idProc] + indexPixel]){\n\t\t\t\t\t\t\tinvertir=0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(invertir){\n\t\t\t\t\t\t\tfloat * vAuxSpectraSplit = vSpectraSplitLoop;\n\t\t\t\t\t\t\t//Initial Model\n\t\t\t\t\t\t\tInit_Model initModel;\n\t\t\t\t\t\t\tinitModel.eta0 = INITIAL_MODEL.eta0;\n\t\t\t\t\t\t\tinitModel.B = INITIAL_MODEL.B; \n\t\t\t\t\t\t\tinitModel.gm = INITIAL_MODEL.gm;\n\t\t\t\t\t\t\tinitModel.az = INITIAL_MODEL.az;\n\t\t\t\t\t\t\tinitModel.vlos = INITIAL_MODEL.vlos; //km/s 0\n\t\t\t\t\t\t\tinitModel.mac = INITIAL_MODEL.mac;\n\t\t\t\t\t\t\tinitModel.dopp = INITIAL_MODEL.dopp;\n\t\t\t\t\t\t\tinitModel.aa = INITIAL_MODEL.aa;\n\t\t\t\t\t\t\tinitModel.alfa = INITIAL_MODEL.alfa; \n\t\t\t\t\t\t\tinitModel.S0 = INITIAL_MODEL.S0;\n\t\t\t\t\t\t\tinitModel.S1 = INITIAL_MODEL.S1;\n\n\t\t\t\t\t\t\t// CLASSICAL ESTIMATES TO GET B, GAMMA, vlos, azimuth\n\t\t\t\t\t\t\testimacionesClasicas(wlines[1], vGlobalLambda, nlambda, vAuxSpectraSplit+(indexPixel*(nlambda*NPARMS)), &initModel,1);\n\t\t\t\t\t\t\tif (isnan(initModel.B))\n\t\t\t\t\t\t\t\tinitModel.B = 1;\n\t\t\t\t\t\t\tif (isnan(initModel.vlos))\n\t\t\t\t\t\t\t\tinitModel.vlos = 1e-3;\n\t\t\t\t\t\t\tif (isnan(initModel.gm))\n\t\t\t\t\t\t\t\tinitModel.gm = 1;\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (isnan(initModel.az))\n\t\t\t\t\t\t\t\tinitModel.az = 1;\n\t\t\t\t\t\t\t// INVERSION RTE\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfloat * slightPixel;\n\t\t\t\t\t\t\tif(slight==NULL) \n\t\t\t\t\t\t\t\tslightPixel = NULL;\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tif(nx_straylight && ny_straylight){\n\t\t\t\t\t\t\t\t\tslightPixel = slight+ (nlambda*NPARMS*indexPixel)+displsSpectroLoop[idProc];\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\tslightPixel = slight;\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\tvNumIterLoop[indexPixel] = -1;\n\t\t\t\t\t\t\tlm_mils(cuantic, wlines, vGlobalLambda, nlambda, vAuxSpectraSplit+(indexPixel*(nlambda*NPARMS)), nlambda, &initModel, spectra, &(vChisqrfLoop[indexPixel]), slightPixel, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles,\n\t\t\t\t\t\t\t\tconfigCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise, configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&(vNumIterLoop[indexPixel]),configCrontrolFile.mu,configCrontrolFile.logclambda);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tresultsInitModelLoop[indexPixel] = initModel;\n\t\t\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\t\t\tint kk;\n\t\t\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvSpectraAdjustedSplitLoop[ (indexPixel*(nlambda * NPARMS))+kk] = spectra[kk] ;\n\t\t\t\t\t\t\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\telse{\n\t\t\t\t\t\t\tInit_Model initModel;\n\t\t\t\t\t\t\tinitModel.eta0 = 0;\n\t\t\t\t\t\t\tinitModel.B = 0; \n\t\t\t\t\t\t\tinitModel.gm = 0;\n\t\t\t\t\t\t\tinitModel.az = 0;\n\t\t\t\t\t\t\tinitModel.vlos = 0; //km/s 0\n\t\t\t\t\t\t\tinitModel.mac = 0;\n\t\t\t\t\t\t\tinitModel.dopp = 0;\n\t\t\t\t\t\t\tinitModel.aa = 0;\n\t\t\t\t\t\t\tinitModel.alfa = 0; \n\t\t\t\t\t\t\tinitModel.S0 = 0;\n\t\t\t\t\t\t\tinitModel.S1 = 0;\n\t\t\t\t\t\t\tresultsInitModelLoop[indexPixel] = initModel;\n\t\t\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\t\t\tint kk;\n\t\t\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvSpectraAdjustedSplitLoop[ (indexPixel*(nlambda * NPARMS))+kk] = 0 ;\n\t\t\t\t\t\t\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\n\t\t\t\t\t//printf(\"\\n ESTOY EN EL PROCESO %d Y HE TERMINADO MIS PIXELS. \\n\",idProc);\n\t\t\t\t\tMPI_Gatherv(resultsInitModelLoop, sendcountsPixelsLoop[idProc], mpiInitModel, resultsInitModelTotalLoop, sendcountsPixelsLoop, displsPixelsLoop, mpiInitModel, root, MPI_COMM_WORLD);\n\t\t\t\t\tMPI_Gatherv(vChisqrfLoop, sendcountsPixelsLoop[idProc], MPI_FLOAT, chisqrfTotalLoop, sendcountsPixelsLoop, displsPixelsLoop, MPI_FLOAT, root, MPI_COMM_WORLD);\t\t\n\t\t\t\t\tMPI_Gatherv(vNumIterLoop, sendcountsPixelsLoop[idProc], MPI_INT, vNumIterTotalLoop, sendcountsPixelsLoop, displsPixelsLoop, MPI_INT, root, MPI_COMM_WORLD);\t\t\n\t\t\t\t\t\n\t\t\t\t\t//printf(\"\\n ESTOY EN EL PROCESO %d GATHER REALIZADO . \\n\",idProc);\n\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\t\tMPI_Gatherv(vSpectraAdjustedSplitLoop, sendcountsSpectroLoop[idProc], MPI_FLOAT, vSpectraAjustedTotalLoop, sendcountsSpectroLoop, displsSpectroLoop, MPI_FLOAT, root, MPI_COMM_WORLD);\t\t\n\t\t\t\t\tlocal_elapsed_execution = MPI_Wtime() - local_start_execution;\n\t\t\t\t\tMPI_Reduce(&local_elapsed_execution, &elapsed_execution, 1, MPI_DOUBLE, MPI_MAX, root, MPI_COMM_WORLD);\n\n\t\t\t\t\tif(idProc==root){\n\t\t\t\t\t\t\n\t\t\t\t\t\tchar outputNameModelsLoop[256];\n\t\t\t\t\t\tchar outputNameSynthesisAdjustedLoop[256];\n\t\t\t\t\t\tchar auxObservedProfiles1 [256];\n\t\t\t\t\t\tchar auxObservedProfiles2 [256];\n\t\t\t\t\t\tstrcpy(auxObservedProfiles1,newestFileName);\n\t\t\t\t\t\tstrcpy(auxObservedProfiles2,newestFileName);\n\t\t\t\t\t\tchar * dirNameObservedProfiles = dirname(auxObservedProfiles1);\n\t\t\t\t\t\tchar * fileNameObservedProfiles = basename(auxObservedProfiles2);\n\t\t\t\t\t\t/*if(strcmp(dirNameObservedProfiles,\".\")!=0){\n\t\t\t\t\t\t\tstrcpy(outputNameModelsLoop,dirNameObservedProfiles);\n\t\t\t\t\t\t\tstrcat(outputNameModelsLoop,\"/\");\n\t\t\t\t\t\t\tstrcpy(outputNameSynthesisAdjustedLoop,dirNameObservedProfiles);\n\t\t\t\t\t\t\tstrcat(outputNameSynthesisAdjustedLoop,\"/\");\n\t\t\t\t\t\t\tif(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\t\t\tstrcat(outputNameModelsLoop,configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t\t\tstrcat(outputNameSynthesisAdjustedLoop,configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstrcat(outputNameModelsLoop,fileNameObservedProfiles);\n\t\t\t\t\t\t\tstrcat(outputNameSynthesisAdjustedLoop,fileNameObservedProfiles);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tif(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\t\t\tstrcpy(outputNameModelsLoop,configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t\t\tstrcat(outputNameModelsLoop,fileNameObservedProfiles);\n\t\t\t\t\t\t\t\tstrcpy(outputNameSynthesisAdjustedLoop,configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t\t\tstrcat(outputNameSynthesisAdjustedLoop,fileNameObservedProfiles);\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tstrcpy(outputNameModelsLoop,fileNameObservedProfiles);\n\t\t\t\t\t\t\t\tstrcpy(outputNameSynthesisAdjustedLoop,fileNameObservedProfiles);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}*/\n\n\t\t\t\t\t\tif(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\t\tstrcpy(outputNameModelsLoop,configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t\tprintf(\"%s\", fileNameObservedProfiles);\n\t\t\t\t\t\t\tstrcat(outputNameModelsLoop,fileNameObservedProfiles);\n\t\t\t\t\t\t\tstrcpy(outputNameSynthesisAdjustedLoop,configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t\tstrcat(outputNameSynthesisAdjustedLoop,fileNameObservedProfiles);\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tstrcpy(outputNameModelsLoop,fileNameObservedProfiles);\n\t\t\t\t\t\t\tstrcpy(outputNameSynthesisAdjustedLoop,fileNameObservedProfiles);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//strcpy(outputNameModelsLoop,get_basefilename(newestFileName));\n\t\t\t\t\t\tprintf(\"%s\", \"line 2405\");\n\t\t\t\t\t\tstrcat(outputNameModelsLoop, \"_mod\");\n\t\t\t\t\t\t/*if(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\t\tstrcat(outputNameModelsLoop, \"_\");\n\t\t\t\t\t\t\tstrcat(outputNameModelsLoop, configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t}*/\n\t\t\t\t\t\tstrcat(outputNameModelsLoop,FITS_FILE);\t\t\t\t\t\t\n\n\t\t\t\t\t\t//strcpy(outputNameSynthesisAdjustedLoop,get_basefilename(newestFileName));\n\t\t\t\t\t\tstrcat(outputNameSynthesisAdjustedLoop, \"_stokes\");\n\t\t\t\t\t\t/*if(configCrontrolFile.outputPrefix[0]!='\\0'){\n\t\t\t\t\t\t\tstrcat(outputNameSynthesisAdjustedLoop, \"_\");\n\t\t\t\t\t\t\tstrcat(outputNameSynthesisAdjustedLoop, configCrontrolFile.outputPrefix);\n\t\t\t\t\t\t}*/\n\t\t\t\t\t\tstrcat(outputNameSynthesisAdjustedLoop,FITS_FILE);\n\n\t\t\t\t\t\tdouble timeWriteImage;\n\t\t\t\t\t\tclock_t t;\n\t\t\t\t\t\tt = clock();\n\n\t\t\t\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\n\t\t\t\t\t\t\tif(!writeFitsImageModelsSubSet(outputNameModelsLoop,fitsImageLoop->rows_original,fitsImageLoop->cols_original,configCrontrolFile,resultsInitModelTotalLoop,chisqrfTotalLoop,vNumIterTotalLoop,configCrontrolFile.saveChisqr)){\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT MODELS: %s\",outputNameModelsLoop);\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tif(!writeFitsImageModels(outputNameModelsLoop,fitsImageLoop->rows,fitsImageLoop->cols,resultsInitModelTotalLoop,chisqrfTotalLoop,vNumIterTotalLoop,configCrontrolFile.saveChisqr)){\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT MODELS: %s\",outputNameModelsLoop);\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tt = clock() - t;\n\t\t\t\t\t\ttimeWriteImage = ((double)t)/CLOCKS_PER_SEC; // in seconds \n\t\t\t\t\t\t\n\t\t\t\t\t\t// PROCESS FILE OF SYNTETIC PROFILES\n\t\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\t\tfree(fitsImageLoop->pixels);\n\t\t\t\t\t\t\tfitsImageLoop->pixels = calloc(fitsImageLoop->numPixels, sizeof(vpixels));\n\t\t\t\t\t\t\tfor( i=0;i<fitsImageLoop->numPixels;i++){\n\t\t\t\t\t\t\t\tfitsImageLoop->pixels[i].spectro = calloc ((fitsImageLoop->numStokes*fitsImageLoop->nLambdas),sizeof(float));\n\t\t\t\t\t\t\t}\t\t\n\t\t\t\t\t\t\tfor(indexPixel=0;indexPixel<fitsImageLoop->numPixels;indexPixel++)\n\t\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\t\tint kk;\n\t\t\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfitsImageLoop->pixels[indexPixel].spectro[kk] = vSpectraAjustedTotalLoop[kk+(indexPixel*(nlambda * NPARMS))] ;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\t\t\t// WRITE SINTHETIC PROFILES TO FITS FILE\n\t\t\t\t\t\t\tif(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(!writeFitsImageProfilesSubSet(outputNameSynthesisAdjustedLoop,newestFileName,fitsImageLoop,configCrontrolFile)){\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT PROFILES: %s\",outputNameSynthesisAdjustedLoop);\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tif(!writeFitsImageProfiles(outputNameSynthesisAdjustedLoop,newestFileName,fitsImageLoop)){\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\");\n\t\t\t\t\t\t\t\t\tprintf(\"\\nERROR WRITING OUTPUT PROFILES: %s\",outputNameSynthesisAdjustedLoop);\n\t\t\t\t\t\t\t\t\tprintf(\"\\n-----------------------------------------------------------\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor( i=0;i<fitsImageLoop->numPixels;i++){\n\t\t\t\t\t\t\t\tfree(fitsImageLoop->pixels[i].spectro);\n\t\t\t\t\t\t\t\tfitsImageLoop->pixels[i].spectro = NULL;\n\t\t\t\t\t\t\t}\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfree(fitsImageLoop->pixels);\n\t\t\t\t\t\t\tfitsImageLoop->pixels = NULL;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfree(resultsInitModelTotalLoop);\t\t\n\t\t\t\t\t\tfree(chisqrfTotalLoop);\n\t\t\t\t\t\tfree(vNumIterTotalLoop);\n\t\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\t\tfree(vSpectraAjustedTotalLoop);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tprintf(\"\\n----------------------------------------------------------------------------------------------------\");\n\t\t\t\t\t\tprintf(\"\\nCUBE %s INVERTED! EXECUTION TIME: %6.2f s\", newestFileName,elapsed_execution);\n\t\t\t\t\t\tprintf(\"\\nTIME TO WRITE FITS :  %5.2f \", timeWriteImage);\n\t\t\t\t\t\tprintf(\"\\n----------------------------------------------------------------------------------------------------\\n\");\n\t\t\t\t\t\tfreeFitsImage(fitsImageLoop);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t\t\t\tfree(resultsInitModelLoop);\n\t\t\t\tfree(vChisqrfLoop);\n\t\t\t\tfree(vNumIterLoop);\n\t\t\t\tfree(vSpectraSplitLoop);\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\tfree(vSpectraAdjustedSplitLoop);\n\t\t\t\tfileNew = 0;\n\t\t\t}\n\t\t}while(!exitProgram);\n\t}\n\n\tdeleteList(&listFileNamesReaded);\n\n\tFreeMemoryDerivedSynthesis();\n\n\tfftw_free(inFilterMAC);\n\tfftw_free(outFilterMAC);\n\tfftw_destroy_plan(planFilterMAC);\n\tfftw_free(inFilterMAC_DERIV);\n\tfftw_free(outFilterMAC_DERIV);\n\tfftw_destroy_plan(planFilterMAC_DERIV);\n\tfftw_free(inSpectraFwMAC);\n\tfftw_free(outSpectraFwMAC);\n\tfftw_destroy_plan(planForwardMAC);\n\tfftw_free(inSpectraBwMAC);\n\tfftw_free(outSpectraBwMAC);\n\tfftw_destroy_plan(planBackwardMAC);\n\n\tif(configCrontrolFile.ConvolveWithPSF){\n\t\tfftw_free(inSpectraFwPSF);\n\t\tfftw_free(outSpectraFwPSF);\n\t\tfftw_destroy_plan(planForwardPSF);\n\t\tfftw_free(inSpectraBwPSF);\n\t\tfftw_free(outSpectraBwPSF);\n\t\tfftw_destroy_plan(planBackwardPSF);\n\n\t\tfftw_free(fftw_G_PSF);\n\t\tfftw_free(fftw_G_MAC_PSF);\n\t\tfftw_free(fftw_G_MAC_DERIV_PSF);\n\n\t\tfftw_free(inPSF_MAC);\n\t\tfftw_free(inMulMacPSF);\n\t\tfftw_free(inPSF_MAC_DERIV);\n\t\tfftw_free(inMulMacPSFDeriv);\n\t\tfftw_free(outConvFilters);\n\t\tfftw_free(outConvFiltersDeriv);\t\n\n\t\tfftw_destroy_plan(planForwardPSF_MAC);\n\t\tfftw_destroy_plan(planForwardPSF_MAC_DERIV);\n\t\tfftw_destroy_plan(planBackwardPSF_MAC);\n\t\tfftw_destroy_plan(planBackwardPSF_MAC_DERIV);\t\t\n\t}\n\n\tif(vInputFileSpectra != NULL) free(vInputFileSpectra);\n\tif(vInputFileSpectraParalell != NULL) free(vInputFileSpectraParalell);\n\tif(vInputFileSpectraDiv2Parallel != NULL) free(vInputFileSpectraDiv2Parallel);\n\tif(vOutputNameModels != NULL) free(vOutputNameModels);\n\tif(vOutputNameModelsParalell != NULL) free(vOutputNameModelsParalell);\n\tif(vOutputNameModelsDiv2Parallel != NULL) free(vOutputNameModelsDiv2Parallel);\n\tif(vOutputNameSynthesisAdjusted != NULL) free(vOutputNameSynthesisAdjusted);\n\tif(vOutputNameSynthesisAdjustedParallel != NULL) free(vOutputNameSynthesisAdjustedParallel);\n\tif(vOutputNameSynthesisAdjustedDiv2Parallel != NULL) free(vOutputNameSynthesisAdjustedDiv2Parallel);\n\tif(vInputFileSpectraLocal != NULL) free(vInputFileSpectraLocal);\n\tif(vOutputNameModelsLocal != NULL) free(vOutputNameModelsLocal);\n\tif(vOutputNameSynthesisAdjustedLocal != NULL) free(vOutputNameSynthesisAdjustedLocal);\n\t\n\tfree(cuantic);\n\tfree(wlines);\n\tfree(vGlobalLambda);\n\t\n\t// FREE TYPE OF MPI\n\tMPI_Type_free(&mpiInitModel);\n\tMPI_Finalize() ;\n\tfree(G);\n\tfree(vSigma);\n\tgsl_eigen_symmv_free (workspace);\n\tgsl_vector_free(eval);\n\tgsl_matrix_free(evec);\n\t\n\treturn 0;\n}\n\n", "meta": {"hexsha": "7f122ed6cd1057ce55b0231ffb8ccf2bfc293cb4", "size": 119529, "ext": "c", "lang": "C", "max_stars_repo_path": "p-milos/src/pmilos.c", "max_stars_repo_name": "dcalc/hrt_pipeline", "max_stars_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_stars_repo_licenses": ["MIT"], "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-milos/src/pmilos.c", "max_issues_repo_name": "dcalc/hrt_pipeline", "max_issues_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-11-05T14:03:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T14:18:48.000Z", "max_forks_repo_path": "p-milos/src/pmilos.c", "max_forks_repo_name": "dcalc/hrt_pipeline", "max_forks_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-14T12:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T19:10:00.000Z", "avg_line_length": 46.16801854, "max_line_length": 321, "alphanum_fraction": 0.6568531486, "num_tokens": 32365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3876478109273936}}
{"text": "/* rng/taus113.c\n * Copyright (C) 2002 Atakan Gurkan\n * Based on the file taus.c which has the notice\n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* This is a maximally equidistributed combined, collision free \n   Tausworthe generator, with a period ~2^{113}. The sequence is,\n\n   x_n = (z1_n ^ z2_n ^ z3_n ^ z4_n)  \n\n   b = (((z1_n <<  6) ^ z1_n) >> 13)\n   z1_{n+1} = (((z1_n & 4294967294) << 18) ^ b)\n   b = (((z2_n <<  2) ^ z2_n) >> 27)\n   z2_{n+1} = (((z2_n & 4294967288) <<  2) ^ b)\n   b = (((z3_n << 13) ^ z3_n) >> 21)\n   z3_{n+1} = (((z3_n & 4294967280) <<  7) ^ b)\n   b = (((z4_n <<  3)  ^ z4_n) >> 12)\n   z4_{n+1} = (((z4_n & 4294967168) << 13) ^ b)\n\n   computed modulo 2^32. In the formulas above '^' means exclusive-or \n   (C-notation), not exponentiation. \n   The algorithm is for 32-bit integers, hence a bitmask is used to clear \n   all but least significant 32 bits, after left shifts, to make the code \n   work on architectures where integers are 64-bit.\n\n   The generator is initialized with \n   zi = (69069 * z{i+1}) MOD 2^32 where z0 is the seed provided\n   During initialization a check is done to make sure that the initial seeds \n   have a required number of their most significant bits set.\n   After this, the state is passed through the RNG 10 times to ensure the\n   state satisfies a recurrence relation.\n\n   References:\n   P. L'Ecuyer, \"Tables of Maximally-Equidistributed Combined LFSR Generators\",\n   Mathematics of Computation, 68, 225 (1999), 261--269.\n     http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps\n   P. L'Ecuyer, \"Maximally Equidistributed Combined Tausworthe Generators\", \n   Mathematics of Computation, 65, 213 (1996), 203--213.\n     http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme.ps\n   the online version of the latter contains corrections to the print version.\n*/\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n\n#define LCG(n) ((69069UL * n) & 0xffffffffUL)\n#define MASK 0xffffffffUL\n\nstatic inline unsigned long int taus113_get (void *vstate);\nstatic double taus113_get_double (void *vstate);\nstatic void taus113_set (void *state, unsigned long int s);\n\ntypedef struct\n{\n  unsigned long int z1, z2, z3, z4;\n}\ntaus113_state_t;\n\nstatic inline unsigned long\ntaus113_get (void *vstate)\n{\n  taus113_state_t *state = (taus113_state_t *) vstate;\n  unsigned long b1, b2, b3, b4;\n\n  b1 = ((((state->z1 << 6UL) & MASK) ^ state->z1) >> 13UL);\n  state->z1 = ((((state->z1 & 4294967294UL) << 18UL) & MASK) ^ b1);\n\n  b2 = ((((state->z2 << 2UL) & MASK) ^ state->z2) >> 27UL);\n  state->z2 = ((((state->z2 & 4294967288UL) << 2UL) & MASK) ^ b2);\n\n  b3 = ((((state->z3 << 13UL) & MASK) ^ state->z3) >> 21UL);\n  state->z3 = ((((state->z3 & 4294967280UL) << 7UL) & MASK) ^ b3);\n\n  b4 = ((((state->z4 << 3UL) & MASK) ^ state->z4) >> 12UL);\n  state->z4 = ((((state->z4 & 4294967168UL) << 13UL) & MASK) ^ b4);\n\n  return (state->z1 ^ state->z2 ^ state->z3 ^ state->z4);\n\n}\n\nstatic double\ntaus113_get_double (void *vstate)\n{\n  return taus113_get (vstate) / 4294967296.0;\n}\n\nstatic void\ntaus113_set (void *vstate, unsigned long int s)\n{\n  taus113_state_t *state = (taus113_state_t *) vstate;\n\n  if (!s)\n    s = 1UL;                    /* default seed is 1 */\n\n  state->z1 = LCG (s);\n  if (state->z1 < 2UL)\n    state->z1 += 2UL;\n  state->z2 = LCG (state->z1);\n  if (state->z2 < 8UL)\n    state->z2 += 8UL;\n  state->z3 = LCG (state->z2);\n  if (state->z3 < 16UL)\n    state->z3 += 16UL;\n  state->z4 = LCG (state->z3);\n  if (state->z4 < 128UL)\n    state->z4 += 128UL;\n\n  /* Calling RNG ten times to satify recurrence condition */\n  taus113_get (state);\n  taus113_get (state);\n  taus113_get (state);\n  taus113_get (state);\n  taus113_get (state);\n  taus113_get (state);\n  taus113_get (state);\n  taus113_get (state);\n  taus113_get (state);\n  taus113_get (state);\n\n  return;\n}\n\nstatic const gsl_rng_type taus113_type = {\n  \"taus113\",                    /* name */\n  0xffffffffUL,                 /* RAND_MAX */\n  0,                            /* RAND_MIN */\n  sizeof (taus113_state_t),\n  &taus113_set,\n  &taus113_get,\n  &taus113_get_double\n};\n\nconst gsl_rng_type *gsl_rng_taus113 = &taus113_type;\n\n\n/*  Rules for analytic calculations using GNU Emacs Calc:\n    (used to find the values for the test program)\n\n  [ LCG(n) := n * 69069 mod (2^32) ]\n  \n  [ b1(x) := rsh(xor(lsh(x, 6), x), 13),\n  q1(x) := xor(lsh(and(x, 4294967294), 18), b1(x)),\n  b2(x) := rsh(xor(lsh(x, 2), x), 27),\n  q2(x) := xor(lsh(and(x, 4294967288), 2), b2(x)),\n  b3(x) := rsh(xor(lsh(x, 13), x), 21),\n  q3(x) := xor(lsh(and(x, 4294967280), 7), b3(x)),\n  b4(x) := rsh(xor(lsh(x, 3), x), 12),\n  q4(x) := xor(lsh(and(x, 4294967168), 13), b4(x))\n  ]\n  \n  [ S([z1,z2,z3,z4]) := [q1(z1), q2(z2), q3(z3), q4(z4)] ]\n*/\n", "meta": {"hexsha": "04da6a893f3928e7a2c67215eaa69180b0f8c937", "size": 5495, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/rng/taus113.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/taus113.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "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/BaselineMethods/MNE/C++/gsl-2.4/rng/taus113.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 32.5147928994, "max_line_length": 81, "alphanum_fraction": 0.6358507734, "num_tokens": 1921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.387647804204103}}
{"text": "/*\n * Copyright 2021 The DAPHNE Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 SRC_RUNTIME_LOCAL_KERNELS_SYRK_H\n#define SRC_RUNTIME_LOCAL_KERNELS_SYRK_H\n\n#include <runtime/local/context/DaphneContext.h>\n#include <runtime/local/datastructures/CSRMatrix.h>\n#include <runtime/local/datastructures/DataObjectFactory.h>\n#include <runtime/local/datastructures/DenseMatrix.h>\n\n#include <cblas.h>\n\n// ****************************************************************************\n// Struct for partial template specialization\n// ****************************************************************************\n\ntemplate<class DTRes, class DTArg>\nstruct Syrk {\n    static void apply(DTRes *& res, const DTArg * arg, DCTX(ctx)) = delete;\n};\n\n// ****************************************************************************\n// Convenience function\n// ****************************************************************************\n\ntemplate<class DTRes, class DTArg>\nvoid syrk(DTRes *& res, const DTArg * arg, DCTX(ctx)) {\n    Syrk<DTRes, DTArg>::apply(res, arg, ctx);\n}\n\n// ****************************************************************************\n// (Partial) template specializations for different data/value types\n// ****************************************************************************\n\n// ----------------------------------------------------------------------------\n// DenseMatrix <- DenseMatrix\n// ----------------------------------------------------------------------------\n\ntemplate<>\nstruct Syrk<DenseMatrix<double>, DenseMatrix<double>> {\n    static void apply(DenseMatrix<double> *& res, const DenseMatrix<double> * arg, DCTX(ctx)) {\n        const size_t numRows = arg->getNumRows();\n        const size_t numCols = arg->getNumCols();\n\n        if(res == nullptr)\n            res = DataObjectFactory::create<DenseMatrix<double>>(numCols, numCols, false);\n\n        cblas_dsyrk(CblasRowMajor,\n            CblasUpper,\n            CblasTrans,\n            numCols,\n            numRows,\n            1.0,\n            arg->getValues(),\n            arg->getRowSkip(),\n            0.0,\n            res->getValues(),\n            res->getRowSkip());\n        for (auto r = 0u; r < numCols; ++r) {\n            for (auto c = r + 1; c < numCols; ++c) {\n                res->set(c, r, res->get(r, c));\n            }\n        }\n    }\n};\n\ntemplate<>\nstruct Syrk<DenseMatrix<float>, DenseMatrix<float>> {\n    static void apply(DenseMatrix<float> *& res, const DenseMatrix<float> * arg, DCTX(ctx)) {\n        const size_t numRows = arg->getNumRows();\n        const size_t numCols = arg->getNumCols();\n\n        if(res == nullptr)\n            res = DataObjectFactory::create<DenseMatrix<float>>(numCols, numCols, false);\n\n        cblas_ssyrk(CblasRowMajor,\n            CblasUpper,\n            CblasTrans,\n            numCols,\n            numRows,\n            1.0,\n            arg->getValues(),\n            arg->getRowSkip(),\n            0.0,\n            res->getValues(),\n            res->getRowSkip());\n        for (auto r = 0u; r < numCols; ++r) {\n            for (auto c = r + 1; c < numCols; ++c) {\n                res->set(c, r, res->get(r, c));\n            }\n        }\n    }\n};\n\n// ----------------------------------------------------------------------------\n// CSRMatrix <- CSRMatrix\n// ----------------------------------------------------------------------------\n\ntemplate<typename VT>\nstruct Syrk<CSRMatrix<VT>, CSRMatrix<VT>> {\n    static void apply(CSRMatrix<VT> *& res, const CSRMatrix<VT> * arg, DCTX(ctx)) {\n        const size_t numRows = arg->getNumRows();\n        const size_t numCols = arg->getNumCols();\n        \n        if(res == nullptr)\n            res = DataObjectFactory::create<CSRMatrix<VT>>(numCols, numRows, arg->getNumNonZeros(), false);\n        assert(false && \"TODO: Syrk for Sparse\");\n    }\n};\n\n#endif //SRC_RUNTIME_LOCAL_KERNELS_SYRK_H", "meta": {"hexsha": "e26d66318ec5ea31d7e9e67d95bb74c8207d01c5", "size": 4376, "ext": "h", "lang": "C", "max_stars_repo_path": "src/runtime/local/kernels/Syrk.h", "max_stars_repo_name": "daphne-eu/daphne", "max_stars_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T21:49:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:37:06.000Z", "max_issues_repo_path": "src/runtime/local/kernels/Syrk.h", "max_issues_repo_name": "daphne-eu/daphne", "max_issues_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-03-31T22:10:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:46:30.000Z", "max_forks_repo_path": "src/runtime/local/kernels/Syrk.h", "max_forks_repo_name": "daphne-eu/daphne", "max_forks_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_forks_repo_licenses": ["Apache-2.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.008, "max_line_length": 107, "alphanum_fraction": 0.5031992687, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.3876351218847605}}
{"text": "/* multimin/gsl_multimin.h\r\n * \r\n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * 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 this program; 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/* Modified by Tuomo Keskitalo to include fminimizer and \r\n   Nelder Mead related lines */\r\n\r\n#ifndef __GSL_MULTIMIN_H__\r\n#define __GSL_MULTIMIN_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_types.h>\r\n#include <gsl/gsl_math.h>\r\n#include <gsl/gsl_vector.h>\r\n#include <gsl/gsl_matrix.h>\r\n#include <gsl/gsl_min.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\n/* Definition of an arbitrary real-valued function with gsl_vector input and */\r\n/* parameters */\r\nstruct gsl_multimin_function_struct \r\n{\r\n  double (* f) (const gsl_vector * x, void * params);\r\n  size_t n;\r\n  void * params;\r\n};\r\n\r\ntypedef struct gsl_multimin_function_struct gsl_multimin_function;\r\n\r\n#define GSL_MULTIMIN_FN_EVAL(F,x) (*((F)->f))(x,(F)->params)\r\n\r\n/* Definition of an arbitrary differentiable real-valued function */\r\n/* with gsl_vector input and parameters */\r\nstruct gsl_multimin_function_fdf_struct \r\n{\r\n  double (* f) (const gsl_vector  * x, void * params);\r\n  void (* df) (const gsl_vector * x, void * params,gsl_vector * df);\r\n  void (* fdf) (const gsl_vector * x, void * params,double *f,gsl_vector * df);\r\n  size_t n;\r\n  void * params;\r\n};\r\n\r\ntypedef struct gsl_multimin_function_fdf_struct gsl_multimin_function_fdf;\r\n\r\n#define GSL_MULTIMIN_FN_EVAL_F(F,x) (*((F)->f))(x,(F)->params)\r\n#define GSL_MULTIMIN_FN_EVAL_DF(F,x,g) (*((F)->df))(x,(F)->params,(g))\r\n#define GSL_MULTIMIN_FN_EVAL_F_DF(F,x,y,g) (*((F)->fdf))(x,(F)->params,(y),(g))\r\n\r\nGSL_FUN int gsl_multimin_diff (const gsl_multimin_function * f,\r\n                       const gsl_vector * x, gsl_vector * g);\r\n\r\n/* minimization of non-differentiable functions */\r\n\r\ntypedef struct \r\n{\r\n  const char *name;\r\n  size_t size;\r\n  int (*alloc) (void *state, size_t n);\r\n  int (*set) (void *state, gsl_multimin_function * f,\r\n              const gsl_vector * x, \r\n              double * size,\r\n              const gsl_vector * step_size);\r\n  int (*iterate) (void *state, gsl_multimin_function * f, \r\n                  gsl_vector * x, \r\n                  double * size,\r\n                  double * fval);\r\n  void (*free) (void *state);\r\n}\r\ngsl_multimin_fminimizer_type;\r\n\r\ntypedef struct \r\n{\r\n  /* multi dimensional part */\r\n  const gsl_multimin_fminimizer_type *type;\r\n  gsl_multimin_function *f;\r\n\r\n  double fval;\r\n  gsl_vector * x;\r\n  \r\n  double size;\r\n\r\n  void *state;\r\n}\r\ngsl_multimin_fminimizer;\r\n\r\nGSL_FUN gsl_multimin_fminimizer *\r\ngsl_multimin_fminimizer_alloc(const gsl_multimin_fminimizer_type *T,\r\n                              size_t n);\r\n\r\nGSL_FUN int \r\ngsl_multimin_fminimizer_set (gsl_multimin_fminimizer * s,\r\n                             gsl_multimin_function * f,\r\n                             const gsl_vector * x,\r\n                             const gsl_vector * step_size);\r\n\r\nGSL_FUN void\r\ngsl_multimin_fminimizer_free(gsl_multimin_fminimizer *s);\r\n\r\nGSL_FUN const char * \r\ngsl_multimin_fminimizer_name (const gsl_multimin_fminimizer * s);\r\n\r\nGSL_FUN int\r\ngsl_multimin_fminimizer_iterate(gsl_multimin_fminimizer *s);\r\n\r\nGSL_FUN gsl_vector * \r\ngsl_multimin_fminimizer_x (const gsl_multimin_fminimizer * s);\r\n\r\nGSL_FUN double \r\ngsl_multimin_fminimizer_minimum (const gsl_multimin_fminimizer * s);\r\n\r\nGSL_FUN double\r\ngsl_multimin_fminimizer_size (const gsl_multimin_fminimizer * s);\r\n\r\n/* Convergence test functions */\r\n\r\nGSL_FUN int\r\ngsl_multimin_test_gradient(const gsl_vector * g,double epsabs);\r\n\r\nGSL_FUN int\r\ngsl_multimin_test_size(const double size ,double epsabs);\r\n\r\n/* minimisation of differentiable functions */\r\n\r\ntypedef struct \r\n{\r\n  const char *name;\r\n  size_t size;\r\n  int (*alloc) (void *state, size_t n);\r\n  int (*set) (void *state, gsl_multimin_function_fdf * fdf,\r\n              const gsl_vector * x, double * f, \r\n              gsl_vector * gradient, double step_size, double tol);\r\n  int (*iterate) (void *state,gsl_multimin_function_fdf * fdf, \r\n                  gsl_vector * x, double * f, \r\n                  gsl_vector * gradient, gsl_vector * dx);\r\n  int (*restart) (void *state);\r\n  void (*free) (void *state);\r\n}\r\ngsl_multimin_fdfminimizer_type;\r\n\r\ntypedef struct \r\n{\r\n  /* multi dimensional part */\r\n  const gsl_multimin_fdfminimizer_type *type;\r\n  gsl_multimin_function_fdf *fdf;\r\n\r\n  double f;\r\n  gsl_vector * x;\r\n  gsl_vector * gradient;\r\n  gsl_vector * dx;\r\n\r\n  void *state;\r\n}\r\ngsl_multimin_fdfminimizer;\r\n\r\nGSL_FUN gsl_multimin_fdfminimizer *\r\ngsl_multimin_fdfminimizer_alloc(const gsl_multimin_fdfminimizer_type *T,\r\n                                size_t n);\r\n\r\nGSL_FUN int \r\ngsl_multimin_fdfminimizer_set (gsl_multimin_fdfminimizer * s,\r\n                               gsl_multimin_function_fdf *fdf,\r\n                               const gsl_vector * x,\r\n                               double step_size, double tol);\r\n\r\nGSL_FUN void\r\ngsl_multimin_fdfminimizer_free(gsl_multimin_fdfminimizer *s);\r\n\r\nGSL_FUN const char * \r\ngsl_multimin_fdfminimizer_name (const gsl_multimin_fdfminimizer * s);\r\n\r\nGSL_FUN int\r\ngsl_multimin_fdfminimizer_iterate(gsl_multimin_fdfminimizer *s);\r\n\r\nGSL_FUN int\r\ngsl_multimin_fdfminimizer_restart(gsl_multimin_fdfminimizer *s);\r\n\r\nGSL_FUN gsl_vector * \r\ngsl_multimin_fdfminimizer_x (const gsl_multimin_fdfminimizer * s);\r\n\r\nGSL_FUN gsl_vector * \r\ngsl_multimin_fdfminimizer_dx (const gsl_multimin_fdfminimizer * s);\r\n\r\nGSL_FUN gsl_vector * \r\ngsl_multimin_fdfminimizer_gradient (const gsl_multimin_fdfminimizer * s);\r\n\r\nGSL_FUN double \r\ngsl_multimin_fdfminimizer_minimum (const gsl_multimin_fdfminimizer * s);\r\n\r\nGSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_steepest_descent;\r\nGSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_conjugate_pr;\r\nGSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_conjugate_fr;\r\nGSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_vector_bfgs;\r\nGSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_vector_bfgs2;\r\nGSL_VAR const gsl_multimin_fminimizer_type *gsl_multimin_fminimizer_nmsimplex;\r\nGSL_VAR const gsl_multimin_fminimizer_type *gsl_multimin_fminimizer_nmsimplex2;\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MULTIMIN_H__ */\r\n", "meta": {"hexsha": "2cb4bf3a31e465faaf50922854f22cb236916288", "size": 7346, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_multimin.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_multimin.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_multimin.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["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.1271186441, "max_line_length": 90, "alphanum_fraction": 0.7051456575, "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241632752914, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.38743338132899}}
{"text": "/* rng/r250.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n\n/* This is a shift-register random number generator. The sequence is\n\n   x_n = x_{n-103} ^ x_{n-250}        (\"^\" means XOR)\n\n   defined on 32-bit words.\n\n   The first 250 elements x_1 .. x_250 are first initialized as x_n =\n   s_n, where s_n = (69069*s_{n-1}) mod 2^32 and s_0=s is the\n   user-supplied seed. To ensure that the sequence does not lie on a\n   subspace we force 32 of the entries to be linearly independent.  We\n   take the 32 elements x[3], x[10], x[17], x[24], ..., 213 and apply\n   the following operations,\n\n   x[3]   &= 11111111111111111111111111111111\n   x[3]   |= 10000000000000000000000000000000 \n   x[10]  &= 01111111111111111111111111111111\n   x[10]  |= 01000000000000000000000000000000 \n   x[17]  &= 00111111111111111111111111111111\n   x[17]  |= 00100000000000000000000000000000 \n   ....      ...\n   x[206] &= 00000000000000000000000000000111\n   x[206] |= 00000000000000000000000000000100 \n   x[213] &= 00000000000000000000000000000011\n   x[213] |= 00000000000000000000000000000010 \n   x[220] &= 00000000000000000000000000000001\n   x[220] |= 00000000000000000000000000000001 \n\n   i.e. if we consider the bits of the 32 elements as forming a 32x32\n   array then we are setting the diagonal bits of the array to one and\n   masking the lower triangle below the diagonal to zero.\n\n   With this initialization procedure the theoretical value of\n   x_{10001} is 1100653588 for s = 1 (Actually I got this by running\n   the original code). The subscript 10001 means (1) seed the\n   generator with s = 1 and then do 10000 actual iterations.\n\n   The period of this generator is about 2^250.\n\n   The algorithm works for any number of bits. It is implemented here\n   for 32 bits.\n\n   From: S. Kirkpatrick and E. Stoll, \"A very fast shift-register\n   sequence random number generator\", Journal of Computational Physics,\n   40, 517-526 (1981). */\n\nstatic inline unsigned long int r250_get (void *vstate);\nstatic double r250_get_double (void *vstate);\nstatic void r250_set (void *state, unsigned long int s);\n\ntypedef struct\n  {\n    int i;\n    unsigned long x[250];\n  }\nr250_state_t;\n\nstatic inline unsigned long int\nr250_get (void *vstate)\n{\n  r250_state_t *state = (r250_state_t *) vstate;\n  unsigned long int k;\n  int j;\n\n  int i = state->i;\n\n  if (i >= 147)\n    {\n      j = i - 147;\n    }\n  else\n    {\n      j = i + 103;\n    }\n\n  k = state->x[i] ^ state->x[j];\n  state->x[i] = k;\n\n  if (i >= 249)\n    {\n      state->i = 0;\n    }\n  else\n    {\n      state->i = i + 1;\n    }\n\n  return k;\n}\n\nstatic double \nr250_get_double (void *vstate)\n{\n  return r250_get (vstate) /  4294967296.0 ;\n}\n\nstatic void\nr250_set (void *vstate, unsigned long int s)\n{\n  r250_state_t *state = (r250_state_t *) vstate;\n\n  int i;\n\n  if (s == 0)\n    s = 1;\t/* default seed is 1 */\n\n  state->i = 0;\n\n#define LCG(n) ((69069 * n) & 0xffffffffUL)\n\n  for (i = 0; i < 250; i++)\t/* Fill the buffer  */\n    {\n      s = LCG (s);\n      state->x[i] = s;\n    }\n\n  {\n    /* Masks for turning on the diagonal bit and turning off the\n       leftmost bits */\n\n    unsigned long int msb = 0x80000000UL;\n    unsigned long int mask = 0xffffffffUL;\n\n    for (i = 0; i < 32; i++)\n      {\n\tint k = 7 * i + 3;\t/* Select a word to operate on        */\n\tstate->x[k] &= mask;\t/* Turn off bits left of the diagonal */\n\tstate->x[k] |= msb;\t/* Turn on the diagonal bit           */\n\tmask >>= 1;\n\tmsb >>= 1;\n      }\n  }\n\n  return;\n}\n\nstatic const gsl_rng_type r250_type =\n{\"r250\",\t\t\t/* name */\n 0xffffffffUL,\t\t\t/* RAND_MAX */\n 0,\t\t\t        /* RAND_MIN */\n sizeof (r250_state_t),\n &r250_set,\n &r250_get,\n &r250_get_double};\n\nconst gsl_rng_type *gsl_rng_r250 = &r250_type;\n", "meta": {"hexsha": "aa25e4b27a7b30b4059bea513701c111e07b8f80", "size": 4491, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/r250.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/r250.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/rng/r250.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 26.573964497, "max_line_length": 72, "alphanum_fraction": 0.6588733022, "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3873667127268533}}
{"text": "/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\n**                                                                                  **\n** This file forms part of the Underworld geophysics modelling application.         **\n**                                                                                  **\n** For full license and copyright information, please refer to the LICENSE.md file  **\n** located at the project root, or contact the authors.                             **\n**                                                                                  **\n**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/\n/*\n\nGiven a block system\nA x = b,\nor\n( K G )(u) = (f)\n( D C )(p)   (h)\n\nWe define a symmetrically scaled system,\nL A R R^-1 x = L b,\t\tA'x' = b'\nwhere L = diag(L1, L2), R = diag(R1,R2) are block diagonal\nand L_i and R_i are both diagonal matrirces.\n\nThe scaling produces\n( L1   )( K G )( R1   )( R1   )^-1(u) = ( L1   )(f)\n(   L2 )( D C )(   R2 )(   R2 )   (p)   (   L2 )(h)\nand we solve\n( L1   )( K G )( R1   )(v) = ( L1   )(f)\n(   L2 )( D C )(   R2 )(q)   (   L2 )(h)\nor\n( L1KR1 L1GR2 )(v) = (L1f)\n( L2DR1 L2CR2 )(q)   (L2h)\n\nThe solution u,p is recovered via\n(u) = ( R1   )(v)\n(p)   (   R2 )(q) \n\n*/\n\n#include <petsc.h>\n#include <petscmat.h>\n#include <petscvec.h>\n\n#include <StGermain/StGermain.h>\n#include <StgDomain/StgDomain.h>\n\n#include \"common-driver-utils.h\"\n#include \"stokes_block_scaling.h\"\n\n/* private prototypes */\nPetscErrorCode BSSCR_MatStokesBlock_ApplyScaling( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym );\n\n\n\n/* A x = b -> A'x' = b' */\n/*\nNote this routine actually modifies the matrix and rhs b.\n*/\n\n// updated\nPetscErrorCode BSSCR_MatStokesBlock_ApplyScaling( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym )\n{\n\tMat K,G,D,C;\n\tVec L1,L2, R1,R2;\n\tVec f,h, u,p;\n\t\n\t\n\t/* Get the scalings out the block mat data */\n\tVecNestGetSubVec( BA->Lz, 0, &L1 );\n\tVecNestGetSubVec( BA->Lz, 1, &L2 );\n\tVecNestGetSubVec( BA->Rz, 0, &R1 );\n\tVecNestGetSubVec( BA->Rz, 1, &R2 );\n\t\n\t\n\t/* get the subblock solution and rhs */\n\tif( x != PETSC_NULL ) {\n\t\tVecNestGetSubVec( x, 0, &u );\n\t\tVecNestGetSubVec( x, 1, &p );\n\t\t\n\t\tVecPointwiseDivide( u, u,R1); /* x <- x * 1/R1 */\n\t\tVecPointwiseDivide( p, p,R2);\n\t\t\n\t}\n\tif( b != PETSC_NULL ) {\n\t\tVecNestGetSubVec( b, 0, &f );\n\t\tVecNestGetSubVec( b, 1, &h );\n\t\t\n\t\tVecPointwiseMult( f, f,L1); /* f <- f * L1 */\n\t\tVecPointwiseMult( h, h,L2);\n\t\t\n\t}\n\t\n\t\n\t/* Scale matrices */\n\tMatNestGetSubMat( A, 0,0, &K );\n\tMatNestGetSubMat( A, 0,1, &G );\n\tMatNestGetSubMat( A, 1,0, &D );\n\tMatNestGetSubMat( A, 1,1, &C );\n\t\n\tif( K != PETSC_NULL ) {\t\tMatDiagonalScale( K, L1,R1 );\t\t}\n\tif( G != PETSC_NULL ) {\t\tMatDiagonalScale( G, L1,R2 );\t\t}\n\tif( D != PETSC_NULL && !sym ) {\tMatDiagonalScale( D, L2,R1 );\t\t}\n\tif( C != PETSC_NULL ) {\t\tMatDiagonalScale( C, L2,R2 );\t\t}\n\tif( S != PETSC_NULL ) {\t\tMatDiagonalScale( S, L2,R2 );\t\t}\n\n\tPetscFunctionReturn(0);\n}\nPetscErrorCode BSSCR_MatStokesBlock_ApplyScaling2( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, Mat M, PetscTruth sym )\n{\n\tMat K,G,D,C;\n\tVec L1,L2, R1,R2;\n\tVec f,h, u,p;\n\t\n\t\n\t/* Get the scalings out the block mat data */\n\tVecNestGetSubVec( BA->Lz, 0, &L1 );\n\tVecNestGetSubVec( BA->Lz, 1, &L2 );\n\tVecNestGetSubVec( BA->Rz, 0, &R1 );\n\tVecNestGetSubVec( BA->Rz, 1, &R2 );\n\t\n\t\n\t/* get the subblock solution and rhs */\n\tif( x != PETSC_NULL ) {\n\t\tVecNestGetSubVec( x, 0, &u );\n\t\tVecNestGetSubVec( x, 1, &p );\n\t\t\n\t\tVecPointwiseDivide( u, u,R1); /* x <- x * 1/R1 */\n\t\tVecPointwiseDivide( p, p,R2);\n\t\t\n\t}\n\tif( b != PETSC_NULL ) {\n\t\tVecNestGetSubVec( b, 0, &f );\n\t\tVecNestGetSubVec( b, 1, &h );\n\t\t\n\t\tVecPointwiseMult( f, f,L1); /* f <- f * L1 */\n\t\tVecPointwiseMult( h, h,L2);\n\t\t\n\t}\n\t\n\t\n\t/* Scale matrices */\n\tMatNestGetSubMat( A, 0,0, &K );\n\tMatNestGetSubMat( A, 0,1, &G );\n\tMatNestGetSubMat( A, 1,0, &D );\n\tMatNestGetSubMat( A, 1,1, &C );\n\t\n\tif( K != PETSC_NULL ) {\t\tMatDiagonalScale( K, L1,R1 );\t\t}\n\tif( G != PETSC_NULL ) {\t\tMatDiagonalScale( G, L1,R2 );\t\t}\n\tif( D != PETSC_NULL && !sym ) {\tMatDiagonalScale( D, L2,R1 );\t\t}\n\tif( C != PETSC_NULL ) {\t\tMatDiagonalScale( C, L2,R2 );\t\t}\n\tif( S != PETSC_NULL ) {\t\tMatDiagonalScale( S, L2,R2 );\t\t}\n\tif( M != PETSC_NULL ) {\t\tMatDiagonalScale( M, L2,R2 );\t\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\n// updated\nPetscErrorCode BSSCR_MatStokesBlockScalingCreate( MatStokesBlockScaling *_BA )\n{\n\tMatStokesBlockScaling BA;\n\t\n\tPetscMalloc( sizeof(struct _p_MatStokesBlockScaling), &BA );\n\t\n\tBA->Lz = PETSC_NULL;\n\tBA->Rz = PETSC_NULL;\n\t\n\tBA->scaling_exists              = PETSC_FALSE;\n\tBA->scalings_have_been_inverted = PETSC_FALSE;\n\tBA->system_has_been_scaled      = PETSC_FALSE;\n\t\n\t*_BA = BA;\n\t\n\tPetscFunctionReturn(0);\n}\n\n// updated\nPetscErrorCode BSSCR_MatStokesBlockScalingDestroy( MatStokesBlockScaling BA )\n{\n\t\n\tif( BA->scaling_exists == PETSC_FALSE ) PetscFunctionReturn(0); \n\t\n\tif( BA->Lz != PETSC_NULL ) {\n\t\tStg_VecDestroy(&BA->Lz );\n\t\tBA->Lz = PETSC_NULL;\n\t}\n\t\n\tif( BA->Rz != PETSC_NULL ) {\n\t\tStg_VecDestroy(&BA->Rz );\n\t\tBA->Rz = PETSC_NULL;\n\t}\n\t\n\tPetscFree( BA );\n\t\n\tPetscFunctionReturn(0);\n}\n\n/*\nA is 2x2 block matrix\nb and x are 2x1 block vectors\n*/\n// updated\nPetscErrorCode BSSCR_MatBlock_ConstructScaling( MatStokesBlockScaling BA, Mat A, Vec b, Vec x )\n{\n    if( BA->scaling_exists == PETSC_FALSE ) {\n\t\t\n\tVecDuplicate( x, &BA->Lz ); \n\tVecDuplicate( x, &BA->Rz );\n\t\t\n\tBA->scaling_exists = PETSC_TRUE;\t\n\tBSSCR_MatStokesBlockDefaultBuildScaling( BA,A );\n\tBA->scalings_have_been_inverted = PETSC_FALSE;\n    }\n\t\n    PetscFunctionReturn(0);\n}\n\n// updated\nPetscErrorCode BSSCR_mat_block_invert_scalings( MatStokesBlockScaling BA )\n{\n\tVec L1,L2, R1,R2;\n\t\n\tVecNestGetSubVec( BA->Lz, 0, &L1 );\n\tVecNestGetSubVec( BA->Lz, 1, &L2 );\n\tVecNestGetSubVec( BA->Rz, 0, &R1 );\n\tVecNestGetSubVec( BA->Rz, 1, &R2 );\n\t\n\t\n\tVecReciprocal(L1);\n\tVecReciprocal(L2);\n\tVecReciprocal(R1);\n\tVecReciprocal(R2);\n\t\n\t/* toggle inversion flag */\n\tif( BA->scalings_have_been_inverted == PETSC_TRUE ) {   BA->scalings_have_been_inverted = PETSC_FALSE;  }\n\tif( BA->scalings_have_been_inverted == PETSC_FALSE ) {  BA->scalings_have_been_inverted = PETSC_TRUE;   }\n\t\n\tPetscFunctionReturn(0);\n}\n\n/* updated */\nPetscErrorCode BSSCR_MatStokesBlockScaleSystem( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym )\n{\n\tif( BA->scaling_exists == PETSC_FALSE ) {\n\t\tBSSCR_MatBlock_ConstructScaling( BA,A,b,x );\n\t}\n\t\n\tif( BA->scalings_have_been_inverted == PETSC_TRUE ) {\n\t\tBSSCR_mat_block_invert_scalings(BA); /* to undo inversion */\n\t}\n\t\n\tBSSCR_MatStokesBlock_ApplyScaling(BA,A,b,x,S,sym);\n\tBA->system_has_been_scaled = PETSC_TRUE;\n\t\n\t/*\n\tPetscPrintf( PETSC_COMM_WORLD, \"Post Scaling \\n\");\n\tMatBlock_ReportOperatorScales(A);\n\t*/\n\t\n\tPetscFunctionReturn(0);\n}\nPetscErrorCode BSSCR_MatStokesBlockScaleSystem2( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, Mat M, PetscTruth sym )\n{\n\tif( BA->scaling_exists == PETSC_FALSE ) {\n\t\tBSSCR_MatBlock_ConstructScaling( BA,A,b,x );\n\t}\n\t\n\tif( BA->scalings_have_been_inverted == PETSC_TRUE ) {\n\t\tBSSCR_mat_block_invert_scalings(BA); /* to undo inversion */\n\t}\n\t\n\tBSSCR_MatStokesBlock_ApplyScaling2(BA,A,b,x,S,M,sym);\n\tBA->system_has_been_scaled = PETSC_TRUE;\n\t\n\t/*\n\tPetscPrintf( PETSC_COMM_WORLD, \"Post Scaling \\n\");\n\tMatBlock_ReportOperatorScales(A);\n\t*/\n\t\n\tPetscFunctionReturn(0);\n}\n\n// updated\nPetscErrorCode BSSCR_MatStokesBlockUnScaleSystem( MatStokesBlockScaling BA, Mat A, Vec b, Vec x, Mat S, PetscTruth sym )\n{\n\t\n\tif( BA->system_has_been_scaled == PETSC_FALSE ) {\n\t\tprintf(\"Warning: MatBlock has not been scaled !! \\n\");\n\t\tPetscFunctionReturn(0);\n\t}\n\t\n\tif( BA->scalings_have_been_inverted == PETSC_FALSE ) {\n\t\tBSSCR_mat_block_invert_scalings(BA);\n\t}\n\t\n\tBSSCR_MatStokesBlock_ApplyScaling(BA,A,b,x,S,sym);\n\tBA->system_has_been_scaled = PETSC_FALSE;\n\t\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCR_MatStokesBlockReportOperatorScales( Mat A, PetscTruth sym )\n{\n\tVec rA, rG;\n\tPetscInt loc;\n\tPetscReal min, max;\n\tMat K,G,D,C;\n\t\n\tMatNestGetSubMat( A, 0,0, &K );\n\tMatNestGetSubMat( A, 0,1, &G );\n\tMatNestGetSubMat( A, 1,0, &D );\n\tMatNestGetSubMat( A, 1,1, &C );\n\t\n\t\n\tMatGetVecs( K, PETSC_NULL, &rA );\n\tVecDuplicate( rA, &rG );\n\t\n\t/* Report the row max and mins */\n\tif (K!=PETSC_NULL) {\n                PetscReal KNorm;\n\t\tMatGetRowMax( K, rA, PETSC_NULL );\n\t\tVecMax( rA, &loc, &max );\n\t\tPetscPrintf( PETSC_COMM_WORLD, \"Sup_max(K) = %g \\n\", max );\n\t\t\n\t\tMatGetRowMinAbs( K, rA, PETSC_NULL );\n\t\tVecMin( rA, &loc, &min );\n\t\tPetscPrintf( PETSC_COMM_WORLD, \"Sup_min(K) = %g \\n\", min );\n\n\t\tMatNorm(K,NORM_1,&KNorm);\n\t\tPetscPrintf( PETSC_COMM_WORLD, \"norm_1(K)  = %g \\n\\n\",KNorm);\n\t}\n\t\n\tif( G != PETSC_NULL ) {       \n\t\tMatGetRowMax( G, rG, PETSC_NULL );\n\t\tVecMax( rG, &loc, &max );\n\t\tPetscPrintf( PETSC_COMM_WORLD, \"Sup_max(G) = %g \\n\", max );\n\t\t\n\t\tMatGetRowMinAbs( G, rG, PETSC_NULL );\n\t\tVecMin( rG, &loc, &min );\n\t\tPetscPrintf( PETSC_COMM_WORLD, \"Sup_min(G) = %g \\n\", min );\n\t}\n\t\n\tif( D != PETSC_NULL && !sym ) {\n                Vec rD;\n\n                MatGetVecs( D, PETSC_NULL, &rD );\n\t\tMatGetRowMax( D, rD, PETSC_NULL );\n\t\tVecMax( rD, &loc, &max );\n\t\tPetscPrintf( PETSC_COMM_WORLD, \"Sup_max(D) = %g \\n\", max );\n\t\t\n\t\tMatGetRowMinAbs( D, rD, PETSC_NULL );\n\t\tVecMin( rD, &loc, &min );\n\t\tPetscPrintf( PETSC_COMM_WORLD, \"Sup_min(D) = %g \\n\", min );\n\n                Stg_VecDestroy(&rD );\n\t}\n\t\n\tif( C != PETSC_NULL ) {\n\t\tVec cG;\n\n\t\tMatGetVecs( G, &cG, PETSC_NULL );\n\t\tMatGetRowMax( C, cG, PETSC_NULL );\n\t\tVecMax( cG, &loc, &max );\n\t\tPetscPrintf( PETSC_COMM_WORLD, \"Sup_max(C) = %g \\n\", max );\n\t\t\n\t\tMatGetRowMin( C, cG, PETSC_NULL );\n\t\tVecMin( cG, &loc, &min );\n\t\tPetscPrintf( PETSC_COMM_WORLD, \"Sup_min(C) = %g \\n\\n\", min );\n\t\n\t\tStg_VecDestroy(&cG);\n\t}\n\t\n\t\n\tStg_VecDestroy(&rA );\n\tStg_VecDestroy(&rG );\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n// updated\nPetscErrorCode BSSCR_MatStokesBlockDefaultBuildScaling( MatStokesBlockScaling BA, Mat A )\n{\n\tMat K,G,D,C;\n\tVec rG;\n\tPetscScalar rg2, rg, ra;  \n\tPetscInt N;\n\tVec rA, rC;\n\tVec L1,L2, R1,R2;\n\t\n\t\n\tVecNestGetSubVec( BA->Lz, 0, &L1 );\n\tVecNestGetSubVec( BA->Lz, 1, &L2 );\n\t\n\tVecNestGetSubVec( BA->Rz, 0, &R1 );\n\tVecNestGetSubVec( BA->Rz, 1, &R2 );\n\t\n\trA = L1;\n\trC = L2;\n\t\n\tMatNestGetSubMat( A, 0,0, &K );\n\tMatNestGetSubMat( A, 0,1, &G );\n\tMatNestGetSubMat( A, 1,0, &D );\n\tMatNestGetSubMat( A, 1,1, &C );\n\t\n\tVecDuplicate( rA, &rG );\n\t\n\t\n\t/* Get magnitude of K */  \n\t//px_MatGetAbsRowSum( K, rA );\n\tMatGetRowMax( K, rA, PETSC_NULL );\n\t\n\tVecSqrt( rA );  \n\tVecReciprocal( rA );\n\t\n\tVecDot( rA,rA, &ra );\n\tVecGetSize( rA, &N );\n\tra = PetscSqrtScalar( ra/N );\n\t\n\t\n\t/* Get magnitude of G */\n\t//px_MatGetAbsRowSum( G, rG );\n\tMatGetRowMax( G, rG, PETSC_NULL );\n\t\n\tVecDot( rG, rG, &rg2 );\n\tVecGetSize( rG, &N );\n\trg = PetscSqrtScalar(rg2/N);\n\t//      printf(\"rg = %f \\n\", rg );\n\t\n\tVecSet( rC, 1.0/(rg*ra) );\n\t\n\tStg_VecDestroy(&rG );\n\t\n\tVecCopy( L1, R1 );\n\tVecCopy( L2, R2 );\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n", "meta": {"hexsha": "537c73cf02c2ef2492459279d03a5241e88c4218", "size": 10903, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_block_scaling.c", "max_stars_repo_name": "longgangfan/underworld2", "max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_block_scaling.c", "max_issues_repo_name": "longgangfan/underworld2", "max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 561.0, "max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z", "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_block_scaling.c", "max_forks_repo_name": "longgangfan/underworld2", "max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z", "avg_line_length": 24.8926940639, "max_line_length": 128, "alphanum_fraction": 0.6143263322, "num_tokens": 4135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.38731032007595007}}
{"text": "#if !defined(THDM_H)\n#define THDM_H\n\n#include \"SM.h\"\n#include <complex>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_matrix.h>\n\n#include \"CouplingFunctionTypeI.h\"\n#include \"CouplingFunctionTypeII.h\"\n#include \"CouplingFunctionTypeLS.h\"\n#include \"CouplingFunctionTypeFL.h\"\n\nusing namespace std;\n\n\n/**\n* \\mainpage 2HDMC Class documentation\n* 2HDMC is a general-purpose calculator for the two-Higgs doublet model. \n* It allows parametrization of the Higgs potential in many different ways, \n* convenient specification of generic Yukawa sectors, the evaluation of decay \n* widths, theoretical constraints and much more.\n*/\n\n/**\n* @brief Specifies a general two-Higgs doublet model\n*\n* This class implements a description of a general two-Higgs doublet model\n* in terms of the potential parameters and Yukawa couplings necessary for\n* a full specification of the model. Several methods are available to set\n* the model parameters to various special cases.\n* \n* From a THDM object, all the couplings between physical states can be \n* accessed, including Higgs-fermion, Higgs-Vector, Higgs-Higgs, 3H and 4H\n* couplings.\n*/\n//static int thdmc_set_param(int key, int npara, double *para, double *res);\n\nint thdmc_set_param(int key, double smpara[], double para[], double res[], int slha);\n\ntypedef ComplexType (*CFunc_NLO)(double, double, double, double, double, double, double, double, double, double, SM);\nComplexType ZEROCOUPLING(double MHL2, double MHH2, double MHA2, double MHp2, double M2, double beta, double alpha, double m12, double m22, double m32, SM sm);\n// For simplicity, even though SVV, SSV and SSS coupling is independent of the Yukawa type, I still use them to indicate the formula.\n#define UPID 10\n#define DOID 20\n#define LEID 30\n#define NUID 40\nenum NLOSTATUS\n{\n    NLOGOOD = 1,\n    NOTIMPLEMENT = 0\n};\nint GetNLOFuncSFF(int S1,int F1,int F2,int type,CFunc_NLO &func);\nint GetNLOFuncSFFC(int S1,int F1,int F2,int type,CFunc_NLO &func_PL, CFunc_NLO &func_PR);\nint GetNLOFuncSVV(int S1,int V1,int V2,int type,CFunc_NLO &func_gmunu, CFunc_NLO &func_kmuqnu);\nint GetNLOFuncSSV(int S1,int S2,int V1,int type,CFunc_NLO &func);\nint GetNLOFuncSSS(int S1,int S2,int S3,int type,CFunc_NLO &func);\n\nclass THDM {\n\n public: \n  \n\n  \n  /** \n  * @brief Default constructor.\n  *   \n  * Empty default constructor which does nothing except initialization of this\n  * THDM object. The model is not specified in any way by using this constructor.\n  */\n  THDM();\n  // ~THDM();\n\n\n  /**\n  * @brief Sets the underlying SM\n  *\n  * This method can be used to specify the SM parameters which this 2HDM \n  * is using.\n  *\n  * @param sm_in SM object specifying the parameters to use in this 2HDM\n  */\n  void set_SM(SM sm_in);  \n\n  /**\n  * @brief Returns the underlying SM\n  *\n  * @returns The SM object specifying the parameters used in this 2HDM\n  */\n  SM get_SM();\n\n  /** \n  * @brief Specifies 2HDM using generic potential\n  *   \n  * This method lets the user specify the 2HDM using a generic basis.\n  * For details on the basis choices available for the Higgs potential, we \n  * refer to the complete <a href=\"http://arxiv.org/abs/0902.0851\">manual</a>.\n  * \n  * @param lambda1 Value of \\f$ \\lambda_1 \\f$\n  * @param lambda2 Value of \\f$ \\lambda_2 \\f$\n  * @param lambda3 Value of \\f$ \\lambda_3 \\f$\n  * @param lambda4 Value of \\f$ \\lambda_4 \\f$\n  * @param lambda5 Value of \\f$ \\lambda_5 \\f$\n  * @param lambda6 Value of \\f$ \\lambda_6 \\f$\n  * @param lambda7 Value of \\f$ \\lambda_7 \\f$\n  * @param m12_2 Soft \\f$ Z_2 \\f$-breaking parameter\n  * @param tan_beta Ratio of vevs, \\f$ \\tan\\beta=v_2/v_1 \\f$\n  * \n  * @returns Boolean \\a true if all parameters were set correctly, \\a false otherwise\n  */\n  bool set_param_gen(double lambda1, double lambda2, double lambda3,\n                     double lambda4, double lambda5, double lambda6, \n                     double lambda7, double m12_2, double tan_beta);\n\n  /** \n  * @brief Specifies 2HDM in the Higgs basis\n  *   \n  * This method lets the user specify the 2HDM in the Higgs basis \\f$ (v_2\\equiv 0) \\f$.\n  * For details on the basis choices available for the Higgs potential, we \n  * refer to the complete <a href=\"http://arxiv.org/abs/0902.0851\">manual</a>.\n  * \n  * @param Lambda1 Value of \\f$ \\Lambda_1 \\f$\n  * @param Lambda2 Value of \\f$ \\Lambda_2 \\f$\n  * @param Lambda3 Value of \\f$ \\Lambda_3 \\f$\n  * @param Lambda4 Value of \\f$ \\Lambda_4 \\f$\n  * @param Lambda5 Value of \\f$ \\Lambda_5 \\f$\n  * @param Lambda6 Value of \\f$ \\Lambda_6 \\f$\n  * @param Lambda7 Value of \\f$ \\Lambda_7 \\f$\n  * @param m_Hp    Mass of the charged Higgs\n  * \n  * @returns Boolean \\a true if all parameters were set correctly, \\a false otherwise\n  */\n  bool set_param_higgs(double Lambda1, double Lambda2, double Lambda3,\n                       double Lambda4, double Lambda5, double Lambda6, \n                       double Lambda7, double m_Hp);\n\n  /** \n  * @brief Specifies 2HDM in the hybrid basis of 1507.04281\n  *   \n  * @param mh Value of light CP-even Higgs mass \\f$ m_h \\f$\n  * @param mH Value of heavy CP-even Higgs mass \\f$ m_H \\f$\n  * @param cba Mixing parameter \\f$ \\cos(\\beta-\\alpha) \\f$. Valid range: -1 < cba <= 1.\n  * @param Z_4 Value of \\f$ Z_4 \\f$\n  * @param Z_5 Value of \\f$ Z_5 \\f$\n  * @param Z_7 Value of \\f$ Z_7 \\f$\n  * @param tanb Ratio of vevs, \\f$ \\tan\\beta=v_2/v_1 \\f$\n  * \n  * @returns Boolean \\a true if all parameters were set correctly, \\a false otherwise\n  */\n  bool set_param_hybrid(double mh, double mH, double cba, double Z4,double Z5, double Z7, double tanb);\n\n  /** \n  * @brief Specifies 2HDM in the hybrid basis of 1507.04281, but with sba instead of cba\n  *   \n  * @param mh Value of light CP-even Higgs mass \\f$ m_h \\f$\n  * @param mH Value of heavy CP-even Higgs mass \\f$ m_H \\f$\n  * @param sba Mixing parameter \\f$ \\sin(\\beta-\\alpha) \\f$. Valid range: -1 < cba <= 1.\n  * @param Z_4 Value of \\f$ Z_4 \\f$\n  * @param Z_5 Value of \\f$ Z_5 \\f$\n  * @param Z_7 Value of \\f$ Z_7 \\f$\n  * @param tanb Ratio of vevs, \\f$ \\tan\\beta=v_2/v_1 \\f$\n  * \n  * @returns Boolean \\a true if all parameters were set correctly, \\a false otherwise\n  */\n  bool set_param_hybrid_sba(double mh, double mH, double sba, double Z4,double Z5, double Z7, double tanb);\n\n  /** \n  * @brief Specifies 2HDM using potential from the Higgs Hunter's Guide\n  *   \n  * This method lets the user specify the 2HDM using the CP-conserving form\n  * of the potential given by Eq. (4.8) in \"The Higgs Hunter's Guide\".\n  * For details on the basis choices available for the Higgs potential, we \n  * refer to the complete <a href=\"http://arxiv.org/abs/0902.0851\">manual</a>.\n  * \n  * @param lambda1 Value of \\f$ \\lambda_1 \\f$\n  * @param lambda2 Value of \\f$ \\lambda_2 \\f$\n  * @param lambda3 Value of \\f$ \\lambda_3 \\f$\n  * @param lambda4 Value of \\f$ \\lambda_4 \\f$\n  * @param lambda5 Value of \\f$ \\lambda_5 \\f$\n  * @param lambda6 Value of \\f$ \\lambda_6 \\f$\n  * @param tan_beta Ratio of vevs, \\f$ \\tan\\beta=v_2/v_1 \\f$\n  * \n  * @returns Boolean \\a true if all parameters were set correctly, \\a false otherwise\n  */\n  bool set_param_HHG(double lambda1, double lambda2, double lambda3,\n                     double lambda4, double lambda5, double lambda6, \n                     double tan_beta);\n\n  /** \n  * @brief Specifies 2HDM in the physical basis\n  *   \n  * This method lets the user specify the 2HDM using the basis of physical\n  * Higgs masses. For details on the basis choices available for the Higgs \n  * potential, we refer to the complete <a href=\"http://arxiv.org/abs/0902.0851\">manual</a>.\n  * \n  * @param m_h  Mass of lightest CP-even Higgs \\f$ h \\f$\n  * @param m_H  Mass of heavier CP-even Higgs \\f$ H \\f$\n  * @param m_A  Mass of CP-odd Higgs \\f$ A \\f$\n  * @param m_Hp Mass of charged Higgs\n  * @param sba  Mixing parameter \\f$ \\sin(\\beta-\\alpha) \\f$. NB: Correct sign on \\f$ \\sin(\\beta-\\alpha) \\f$ must be determined from the condition \\f$ \\cos(\\beta-\\alpha) \\geq 0 \\f$\n  * @param lambda6  Value of \\f$ \\lambda_6 \\f$ in generic potential\n  * @param lambda7  Value of \\f$ \\lambda_7 \\f$ in generic potential\n  * @param m12_2    Soft \\f$ Z_2 \\f$-breaking parameter\n  * @param tan_beta Ratio of vevs, \\f$ \\tan\\beta=v_2/v_1 \\f$\n  * \n  * @returns Boolean \\a true if all parameters were set correctly, \\a false otherwise\n  */\n  bool set_param_phys(double m_h,double m_H, double m_A, double m_Hp,\n                      double sba, double lambda6, double lambda7,\n                      double m12_2, double tan_beta);\n\n  bool set_param_sm(double mh);\n\n\n  /** \n  * @brief Specifies the 2HDM of the tree-level MSSM\n  *   \n  * This method lets the user specify a 2HDM with the properties of the tree-level\n  * MSSM in terms of masses and coupling relations. The Yukawa sector is also\n  * automatically selected to be of type II.\n  * \n  * @param m_A      Mass of CP-odd Higgs \\f$ A \\f$\n  * @param tan_beta Ratio of vevs, \\f$ \\tan\\beta=v_2/v_1 \\f$\n  * \n  * @returns Boolean \\a true if all parameters were set correctly, \\a false otherwise\n  */\n  bool set_MSSM(double m_A, double tan_beta);\n\n  /** \n  * @brief Specifies the 2HDM of the tree-level MSSM + mass corrections to h (\"hMSSM\")\n  *   \n  * This method lets the user specify a 2HDM with the properties of the tree-level\n  * MSSM, with additional mass corrections from the lambda_2 contribution to the (2,2)\n  * element of the mass matrix. These can be identified as the leading (mt^4) MSSM \n  * corrections. The Yukawa sector is automatically selected to be of type II.\n  * \n  * @param m_h      Mass of light CP-even Higgs \\f$ h \\f$\n  * @param m_A      Mass of CP-odd Higgs \\f$ A \\f$\n  * @param tan_beta Ratio of vevs, \\f$ \\tan\\beta=v_2/v_1 \\f$\n  * \n  * @returns Boolean \\a true if all parameters were set correctly, \\a false otherwise\n  */\n  bool set_hMSSM(double mh, double mA, double tanb);\n\n\n  /** \n  * @brief Specifies the 2HDM with one \"inert Higgs\" doublet\n  *   \n  * This method lets the user specify a 2HDM with special properties as follows:\n  * only one of the doublets acquires a vev, there is an exact \\f$ Z_2 \\f$-symmetry,\n  * preventing interdoublet mixing, and the doublet without a vev has no Yukawa \n  * couplings. This results in one doublet being \"inert\" (or dark). The lightest \n  * Higgs originating from this doublet is then stable, thus a dark matter candidate.\n  * The conventions used for specifying the parameters for this model are the same as\n  * in <a href=\"http://arxiv.org/abs/0810.3924\">arXiv:0810.3924</a>.\n  * \n  * @param m_h  Mass of \"SM-like\" Higgs - NB: Changed meaning compared to \"physical\" basis\n  * @param m_H  Mass of CP-even \"inert\" Higgs - NB: Changed meaning compared to \"physical\" basis\n  * @param m_A  Mass of CP-odd \"inert\" Higgs\n  * @param m_Hp Mass of charged \"inert\" Higgs\n  * @param lambda2 Value of \\f$ \\lambda_2 \\f$ parameter\n  * @param lambda3 Value of \\f$ \\lambda_2 \\f$ parameter\n  * \n  * @returns Boolean \\a true if all parameters were set correctly, \\a false otherwise\n  */\n  bool set_inert(double m_h,double m_H, double m_A, double m_Hp, double lambda2, double lambda3);\n\n\n  /**\n  * @brief Returns parameter set in the generic basis\n  * \n  * This method returns a consistent set of parameter values describing the \n  * current model in the generic basis.\n  * \n  * @param lambda1 Returned value of \\f$ \\lambda_1 \\f$\n  * @param lambda2 Returned value of \\f$ \\lambda_2 \\f$\n  * @param lambda3 Returned value of \\f$ \\lambda_3 \\f$ \n  * @param lambda4 Returned value of \\f$ \\lambda_4 \\f$ \n  * @param lambda5 Returned value of \\f$ \\lambda_5 \\f$ \n  * @param lambda6 Returned value of \\f$ \\lambda_6 \\f$ \n  * @param lambda7 Returned value of \\f$ \\lambda_7 \\f$ \n  * @param m12_2   Returned value of \\f$ m_{12}^2 \\f$ \n  * @param tan_beta Returned value of \\f$ \\tan\\beta \\f$ \n  */\n  void get_param_gen(double &lambda1, double &lambda2, double &lambda3,\n                     double &lambda4, double &lambda5, double &lambda6, \n                     double &lambda7, double &m12_2,   double &tan_beta);\n\n\n  /**\n  * @brief Returns parameter set in the Higgs basis\n  * \n  * This method returns a consistent set of parameter values describing the \n  * current model in the Higgs basis.\n  * \n  * @param Lambda1 Returned value of \\f$ \\Lambda_1 \\f$\n  * @param Lambda2 Returned value of \\f$ \\Lambda_2 \\f$\n  * @param Lambda3 Returned value of \\f$ \\Lambda_3 \\f$ \n  * @param Lambda4 Returned value of \\f$ \\Lambda_4 \\f$ \n  * @param Lambda5 Returned value of \\f$ \\Lambda_5 \\f$ \n  * @param Lambda6 Returned value of \\f$ \\Lambda_6 \\f$ \n  * @param Lambda7 Returned value of \\f$ \\Lambda_7 \\f$ \n  * @param m_Hp    Returned value of the charged Higgs mass\n  */\n  void get_param_higgs(double &Lambda1, double &Lambda2, double &Lambda3,\n                       double &Lambda4, double &Lambda5, double &Lambda6, \n                       double &Lambda7, double &m_Hp);\n\n  void get_param_hybrid(double &m_h, double &m_H, double &sba,\n                        double &Z4, double &Z5, double &Z7, double &tan_beta);\n\n\n  /**\n  * @brief Returns parameter set in Higgs Hunter's Guide basis\n  * \n  * This method returns a consistent set of parameter values describing the \n  * current model in the basis used in the Higgs Hunter's Guide. NB: The use\n  * of this method assumes \\f$ \\lambda_6=\\lambda_7=0 \\f$ in the generic basis.\n  * \n  * @param lambda1 Returned value of \\f$ \\lambda_1 \\f$\n  * @param lambda2 Returned value of \\f$ \\lambda_2 \\f$\n  * @param lambda3 Returned value of \\f$ \\lambda_3 \\f$ \n  * @param lambda4 Returned value of \\f$ \\lambda_4 \\f$ \n  * @param lambda5 Returned value of \\f$ \\lambda_5 \\f$ \n  * @param lambda6 Returned value of \\f$ \\lambda_6 \\f$ \n  * @param tan_beta Returned value of \\f$ \\tan\\beta \\f$ \n  */\n  void get_param_HHG(double &lambda1, double &lambda2, double &lambda3,\n                     double &lambda4, double &lambda5, double &lambda6, \n                     double &tan_beta);\n\n\n  /**\n  * @brief Returns parameter set in physical basis\n  * \n  * This method returns a consistent set of parameter values describing the \n  * current model in the \"physical\" basis.\n  * \n  * @param m_h      Returned value of lightest CP-even Higgs mass\n  * @param m_H      Returned value of heaviest CP-even Higgs mass\n  * @param m_A      Returned value of CP-odd Higgs mass\n  * @param m_Hp     Returned value of charged Higgs mass\n  * @param sba      Returned value of \\f$ \\sin(\\beta-\\alpha) \\f$ \n  * @param lambda6  Returned value of \\f$ \\lambda_6 \\f$\n  * @param lambda7  Returned value of \\f$ \\lambda_7 \\f$  \n  * @param m12_2    Returned value of \\f$ m_{12}^2 \\f$ \n  * @param tan_beta Returned value of \\f$ \\tan\\beta \\f$ \n  */\n  void get_param_phys(double &m_h,double &m_H, double &m_A, double &m_Hp,\n                      double &sba, double &lambda6, double &lambda7,\n                      double &m12_2, double &tan_beta);\n\n\n  /**\n  * @brief Changes basis for the Higgs doublets\n  * \n  * This method performs a change of basis, changing the value of \n  * \\f$ \\tan\\beta \\f$. This results in a recalculation of all the other\n  * potential parameters, but the physical couplings remain unchanged.\n  * Yukawa couplings are not modified. \n  * \n  * @param tan_beta Value of \\f$ \\tan\\beta \\f$ to use in the new basis\n  */\n  void recalc_tan_beta(double tan_beta);\n\n  /**\n  * @brief Returns the mass of physical Higgs bosons\n  * \n  * This method returns the mass of a physical Higgs Boson. The numbering\n  * convention corresponds to (1,2,3,4 = h,H,A,H+) where always \\f$ m_h < m_H \\f$.\n  * \n  * @param h Index of Higgs boson\n  * \n  * @returns The mass of Higgs boson \\a h\n  */\n  double get_hmass(int h);\n\n  /**\n  * @brief Returns invariant \\f$ \\sin(\\beta-\\alpha) \\f$\n  * \n  * @returns Value of \\f$ \\sin(\\beta-\\alpha) \\f$ in model\n  */\n  double get_sba();\n\n  /**\n  * @brief Returns invariant \\f$ \\cos(\\beta-\\alpha) \\f$\n  * \n  * @returns Value of \\f$ \\cos(\\beta-\\alpha) \\f$ in model\n  */\n  double get_cba();\n\n\n  /**\n  * @brief Higgs coupling \\f$ q_{ki} \\f$ factors\n  * \n  * This method returns the invariants \\f$ q_{ki} \\f$ (<a href=\"\n  * http://arxiv.org/abs/hep-ph/0602242\">hep-ph/0602242</a>) which are used\n  * for the triple and quartic Higgs couplings.\n  * \n  * @param k Higgs index (1--4)\n  * @param i Coupling index (1--2)\n  * \n  * @returns The value of the coefficient \\f$ q_{ki} \\f$\n  */\n  complex <double> get_qki(int k, int i);\n\n\n  /**\n  * @brief Initializes complete Yukawa sector to a specific type\n  *\n  * This method is used to specify a type of Yukawa sector for the 2HDM.\n  * The types (1-4) implemented follow the convention of <a href=\"\"></a>.\n  * \n  * @param type Type of Yukawa sector (1--4)\n  */\n  void set_yukawas_type(int type);\n\n  /**\n  * @brief Initializes and sets diagonal Yukawa couplings for down-type quarks\n  *\n  * This method initializes and sets the Yukawa couplings for the down-type quarks.\n  * The diagonal matrix \\f$ \\kappa^D \\f$ is automatically specified to comply with\n  * the quark pole masses, whereas the diagonal elements of \\f$ \\rho^D \\f$ can be \n  * specified as input.\n  * \n  * @param rhod Diagonal element of \\f$ \\rho^D \\f$ for the \\f$ d \\f$ quark\n  * @param rhos Diagonal element of \\f$ \\rho^D \\f$ for the \\f$ s \\f$ quark\n  * @param rhob Diagonal element of \\f$ \\rho^D \\f$ for the \\f$ b \\f$ quark\n  * \n  * @see set_yukawas_up, set_yukawas_lepton\n  */\n  void set_yukawas_down(double rhod, double rhos, double rhob);\n\n\n  /**\n  * @brief Initializes and sets diagonal Yukawa couplings for up-type quarks\n  *\n  * This method initializes and sets the Yukawa couplings for the up-type quarks.\n  * The diagonal matrix \\f$ \\kappa^U \\f$ is automatically specified to comply with\n  * the quark pole masses, whereas the diagonal elements of \\f$ \\rho^U \\f$ can be \n  * specified as input.\n  * \n  * @param rhou Diagonal element of \\f$ \\rho^U \\f$ for the \\f$ u \\f$ quark\n  * @param rhoc Diagonal element of \\f$ \\rho^U \\f$ for the \\f$ c \\f$ quark\n  * @param rhot Diagonal element of \\f$ \\rho^U \\f$ for the \\f$ t \\f$ quark\n  * \n  * @see set_yukawas_down, set_yukawas_lepton\n  */\n  void set_yukawas_up(double rhou, double rhoc, double rhot);\n\n  /**\n  * @brief Initializes and sets diagonal Yukawa couplings for the charged leptons\n  *\n  * This method initializes and sets the Yukawa couplings for the leptons.\n  * The diagonal matrix \\f$ \\kappa^L \\f$ is automatically specified to comply with\n  * the lepton pole masses, whereas the diagonal element of \\f$ \\rho^L \\f$ can be \n  * specified as input.\n  * \n  * @param rhoe   Diagonal element of \\f$ \\rho^L \\f$ for \\f$ e \\f$\n  * @param rhomu  Diagonal element of \\f$ \\rho^L \\f$ for \\f$ \\mu \\f$\n  * @param rhotau Diagonal element of \\f$ \\rho^L \\f$ for \\f$ \\tau \\f$\n  *\n  * @see set_yukawas_down, set_yukawas_up\n  */\n  void set_yukawas_lepton(double rhoe, double rhomu, double rhotau);\n \n\n  /**\n  * @brief Initializes and sets Yukawa couplings for down-type quarks\n  *\n  * This method initializes and sets the Yukawa couplings for the down-type quarks.\n  * The diagonal matrix \\f$ \\kappa^D \\f$ is automatically specified to comply with\n  * the quark pole masses, whereas the symmetric matrix \\f$ \\rho^D \\f$ is given by\n  * the six elements specified as input.\n  * \n  * @param rho11 Yukawa coupling \\f$ \\rho^D_{dd} \\f$\n  * @param rho22 Yukawa coupling \\f$ \\rho^D_{ss} \\f$\n  * @param rho33 Yukawa coupling \\f$ \\rho^D_{bb} \\f$\n  * @param rho12 Yukawa coupling \\f$ \\rho^D_{ds} \\f$\n  * @param rho13 Yukawa coupling \\f$ \\rho^D_{db} \\f$\n  * @param rho23 Yukawa coupling \\f$ \\rho^D_{sb} \\f$\n  */\n  void set_yukawas_down(double rho11,double rho22,double rho33,double rho12,double rho13,double rho23);\n\n \n  /**\n  * @brief Initializes and sets Yukawa couplings for up-type quarks\n  *\n  * This method initializes and sets the Yukawa couplings for the up-type quarks.\n  * The diagonal matrix \\f$ \\kappa^U \\f$ is automatically specified to comply with\n  * the quark pole masses, whereas the symmetric matrix \\f$ \\rho^U \\f$ is given by\n  * the six elements specified as input.\n  * \n  * @param rho11 Yukawa coupling \\f$ \\rho^U_{uu} \\f$\n  * @param rho22 Yukawa coupling \\f$ \\rho^U_{cc} \\f$\n  * @param rho33 Yukawa coupling \\f$ \\rho^U_{tt} \\f$\n  * @param rho12 Yukawa coupling \\f$ \\rho^U_{uc} \\f$\n  * @param rho13 Yukawa coupling \\f$ \\rho^U_{ut} \\f$\n  * @param rho23 Yukawa coupling \\f$ \\rho^U_{ct} \\f$\n  */\n  void set_yukawas_up(double rho11,double rho22,double rho33,double rho12,double rho13,double rho23);\n  \n  \n  /**\n  * @brief Initializes and sets Yukawa couplings for leptons\n  *\n  * This method initializes and sets the Yukawa couplings for the leptons.\n  * The diagonal matrix \\f$ \\kappa^L \\f$ is automatically specified to comply with\n  * the lepton masses, whereas the symmetric matrix \\f$ \\rho^L \\f$ is given by\n  * the six elements specified as input.\n  * \n  * @param rho11 Yukawa coupling \\f$ \\rho^L_{ee} \\f$\n  * @param rho22 Yukawa coupling \\f$ \\rho^L_{\\mu\\mu} \\f$\n  * @param rho33 Yukawa coupling \\f$ \\rho^L_{\\tau\\tau} \\f$\n  * @param rho12 Yukawa coupling \\f$ \\rho^L_{e\\mu} \\f$\n  * @param rho13 Yukawa coupling \\f$ \\rho^L_{e\\tau} \\f$\n  * @param rho23 Yukawa coupling \\f$ \\rho^L_{\\mu\\tau} \\f$\n  */\n  void set_yukawas_lepton(double rho11,double rho22,double rho33,double rho12,double rho13,double rho23);\n  \n  /**\n  * @brief Initializes and sets Yukawa couplings for the inert 2HDM\n  *\n  * This method initializes and sets the Yukawa couplings for the \"inert\"\n  * model. That means there are no Yukawa couplings of any type, except what\n  * is necessary for the mass terms, i.e. all \\f$ \\rho = 0 \\f$.\n  */\n  void set_yukawas_inert();\n\n \n  /**\n  * @brief Returns diagonal elements of Yukawa matrix for down-type quarks\n  * \n  * @param rhod Returned value of \\f$ \\rho^D_{dd} \\f$\n  * @param rhos Returned value of \\f$ \\rho^D_{ss} \\f$ \n  * @param rhob Returned value of \\f$ \\rho^D_{bb} \\f$\n  */\n  void get_yukawas_down(double &rhod, double &rhos, double &rhob);\n\n \n  /**\n  * @brief Returns diagonal elements of Yukawa matrix for up-type quarks\n  * \n  * @param rhou Returned value of \\f$ \\rho^U_{uu} \\f$\n  * @param rhoc Returned value of \\f$ \\rho^U_{cc} \\f$ \n  * @param rhot Returned value of \\f$ \\rho^U_{tt} \\f$\n  */\n  void get_yukawas_up(double &rhou, double &rhoc, double &rhot);\n  \n\n  /**\n  * @brief Returns diagonal elements of Yukawa matrix for leptons\n  * \n  * @param rhoe Returned value of \\f$ \\rho^L_{ee} \\f$\n  * @param rhomu Returned value of \\f$ \\rho^L_{\\mu\\mu} \\f$ \n  * @param rhotau Returned value of \\f$ \\rho^L_{\\tau\\tau} \\f$\n  */\n  void get_yukawas_lepton(double &rhoe, double &rhomu, double &rhotau);\n\n\n  void get_kappa_down(double &kd, double &ks, double &kb);\n  void get_kappa_up(double &ku, double &kc, double &kt);\n  void get_kappa_lepton(double &ke, double &kmu, double &ktau);\n \n  void get_kappa_down(double mu, double &kd, double &ks, double &kb);\n  void get_kappa_up(double mu, double &ku, double &kc, double &kt);\n  void get_kappa_lepton(double mu, double &ke, double &kmu, double &ktau);\n  void get_rho_down(double mu, double &rd, double &rs, double &rb);\n  void get_rho_up(double mu, double &ru, double &rc, double &rt);\n  void get_rho_lepton(double mu, double &re, double &rmu, double &rtau);\n  \n  /**\n  * @brief Returns Yukawa matrix for down-type quarks\n  * \n  * @param rho_D_out Returned Yukawa matrix \\f$ \\rho^D \\f$\n  */\n  void get_yukawas_down(gsl_matrix *rho_D_out);\n\n \n  /**\n  * @brief Returns Yukawa matrix for up-type quarks\n  * \n  * @param rho_U_out Returned Yukawa matrix \\f$ \\rho^U \\f$\n  */\n  void get_yukawas_up(gsl_matrix *rho_U_out);\n\n  \n  /**\n  * @brief Returns Yukawa matrix for leptons\n  * \n  * @param rho_L_out Returned Yukawa matrix \\f$ \\rho^L \\f$\n  */\n  void get_yukawas_lepton(gsl_matrix *rho_L_out);\n\n\n  /**\n  * @brief Couplings of Higgses to down-type fermions\n  * \n  * Calculates the coupling \\f$ hdd \\f$ between one physical Higgs state, specified\n  * by \\a h, and two down-type quarks \\a f1 and \\a f2.\n  * \n  * @param h  Index of Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param f1 First fermion (1,2,3 = d,s,b)\n  * @param f2 Second fermion (1,2,3 = d,s,b)\n  * @param cs Returned (complex) value for scalar coupling\n  * @param cp Returned (complex) value for pseudoscalar coupling \n  */\n  void get_coupling_hdd(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);\n  void get_coupling_hdd_NLO(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);\n\n  /**\n  * @brief Couplings of Higgses to up-type fermions\n  * \n  * Calculates the coupling \\f$ huu \\f$ between one physical Higgs state, specified\n  * by \\a h, and two up-type quarks \\a f1 and \\a f2.\n  * \n  * @param h  Index of Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param f1 First fermion (1,2,3 = u,c,t)\n  * @param f2 Second fermion (1,2,3 = u,c,t)\n  * @param cs Returned (complex) value for scalar coupling\n  * @param cp Returned (complex) value for pseudoscalar coupling \n  */\n  void get_coupling_huu(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);\n  void get_coupling_huu_NLO(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);\n  \n\n  /**\n  * @brief Couplings of Higgses to mixed type fermions\n  * \n  * Calculates the coupling \\f$ hdu \\f$ between one physical Higgs state, specified\n  * by \\a h (only relevant one is charged Higgs), and two quarks \\a f1 and \\a f2.\n  * \n  * @param h  Index of Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param d Down-type fermion (1,2,3 = d,s,b)\n  * @param u Up-type fermion (1,2,3 = u,c,t)\n  * @param cs Returned (complex) value for scalar coupling\n  * @param cp Returned (complex) value for pseudoscalar coupling \n  */\n  void get_coupling_hdu(int h,int d,int u,complex <double> &cs, complex <double> &cp);\n  void get_coupling_hdu_NLO(int h,int d,int u,complex <double> &cs, complex <double> &cp);\n\n  /**\n  * @brief Couplings of Higgses to charged leptons\n  * \n  * Calculates the coupling \\f$ hll \\f$ between one physical Higgs state, specified\n  * by \\a h, and two leptons \\a f1 and \\a f2.\n  * \n  * @param h  Index of Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param f1 First fermion (1,2,3 = \\f$ e,\\mu,\\tau \\f$)\n  * @param f2 Second fermion (1,2,3 = \\f$ e,\\mu,\\tau \\f$)\n  * @param cs Returned (complex) value for scalar coupling\n  * @param cp Returned (complex) value for pseudoscalar coupling \n  */\n  void get_coupling_hll(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);\n  void get_coupling_hll_NLO(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);\n  /** \n  * @brief Couplings of Higgses to mixed leptons\n  * \n  * Calculates the coupling \\f$ hl\\nu_l \\f$ between one physical Higgs state, specified\n  * by \\a h (only relevant one is charged Higgs), and two leptons \\a f1 and \\a f2.\n  * \n  * @param h  Index of Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param l  Charged lepton (1,2,3 = \\f$ e,\\mu,\\tau \\f$)\n  * @param n  Neutrino (1,2,3 = \\f$ \\nu_e,\\nu_\\mu,\\nu_\\tau \\f$)\n  * @param cs Returned (complex) value for scalar coupling\n  * @param cp Returned (complex) value for pseudoscalar coupling \n  */\n  void get_coupling_hln(int h,int l,int n,complex <double> &cs, complex <double> &cp);\n  void get_coupling_hln_NLO(int h,int l,int n,complex <double> &cs, complex <double> &cp);\n\n  \n  /** \n  * @brief Couplings of Higgses to pairs of vector bosons\n  * \n  * Calculates the coupling \\f$ hV_1 V_2 \\f$ between one physical Higgs state, specified\n  * by \\a h , and two vector bosons \\a v1 and \\a v2. NB: Neutral Higgses have no coupling\n  * to photons implemented, but the loop mediated decays \\f$ h\\to \\gamma \\gamma \\f$ can \n  * nevertheless be calculated using the DecayTable class. Conventions are according to hep-ph/0602242.\n  * \n  * @param v1 Index of first vector boson (1,2,3 = \\f$ \\gamma,Z,W^+ \\f$)\n  * @param v2 Index of second vector boson (1,2,3 = \\f$ \\gamma,Z,W^+ \\f$)\n  * @param h  Index of Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param c  Returned (complex) value for coupling\n  */\n  void get_coupling_vvh(int v1,int v2,int h,complex <double> &c);\n  void get_coupling_vvh_NLO(int v1,int v2,int h,complex <double> &c_gmunu,complex <double> &c_kmuqnu);\n\n  /** \n  * @brief Couplings of vector bosons to pairs of Higgses\n  * \n  * Calculates the coupling \\f$ Vh_1 h_2 \\f$ between two physical Higgs states, specified\n  * by \\a h1 and \\a h2, and one vector boson \\a v. Conventions are according to hep-ph/0602242.\n  * \n  * @param h1 Index of first Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param h2 Index of second Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param v  Index of vector boson (1,2,3 = \\f$ \\gamma,Z,W^+ \\f$)\n  * @param c  Returned (complex) value for coupling\n  */\n  void get_coupling_vhh(int v,int h1,int h2,complex <double> &c);\n  void get_coupling_vhh_NLO(int v,int h1,int h2,complex <double> &c);\n  \n\n  /** \n  * @brief Triple Higgs couplings\n  * \n  * Calculates the coupling \\f$ h_1 h_2 h_3 \\f$ between three physical Higgs states. \n  * Conventions are according to hep-ph/0602242\n  * \n  * @param h1 Index of first Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param h2 Index of second Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param h3 Index of third Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param c  Returned (complex) value for coupling\n  */\n  void get_coupling_hhh(int h1,int h2,int h3,complex <double> &c);\n  void get_coupling_hhh_NLO(int h1,int h2,int h3,complex <double> &c);\n\n  /** \n  * @brief Couplings of two vector bosons and two Higgses\n  * \n  * Calculates the coupling \\f$ V_1 V_2 h_1 h_2 \\f$ between two vector bosons and\n  * two physical Higgs states. Conventions are according to hep-ph/0602242\n  * \n  * @param v1 Index of first vector boson (1,2,3 = \\f$ \\gamma,Z,W^+ \\f$)\n  * @param v2 Index of second vector boson (1,2,3 = \\f$ \\gamma,Z,W^+ \\f$)\n  * @param h1 Index of first Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param h2 Index of second Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param c  Returned (complex) value for coupling\n  */ \n  void get_coupling_vvhh(int v1,int v2,int h1,int h2,complex <double> &c);\n  \n  /** \n  * @brief Quartic Higgs couplings\n  * \n  * Calculates the coupling \\f$ h_1 h_2 h_3 h_4 \\f$ between four physical Higgs states.\n  * Conventions are according to hep-ph/0602242\n  * \n  * @param h1 Index of first Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param h2 Index of second Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param h3 Index of third Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param h4 Index of fourth Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param c  Returned (complex) value for coupling\n  */\n  void get_coupling_hhhh(int h1,int h2,int h3,int h4,complex <double> &c);\n\n\n  /** \n  * @brief Calculates tree-level unitarity constraints\n  * \n  * This method calculates the eigenvalues of the S-matrix for Higgs-Higgs scattering \n  * as defined in <a href=\"http://xxx.lanl.gov/abs/hep-ph/0508020\">hep-ph/0508020</a>.\n  * \n  * @returns Value of largest eigenvalue\n  */\n  double calc_unitarity();\n  \n  /** \n  * @brief Checks tree-level unitarity constraints\n  * \n  * This method checks whether the parameters of the Higgs potential results\n  * in an S-matrix for Higgs-Higgs scattering that fullfills tree-level unitarity,\n  * as discussed in <a href=\"http://xxx.lanl.gov/abs/hep-ph/0508020\">hep-ph/0508020</a>.\n  * \n  * @param unitarity_limit optional value to be used for unitarity limit (default = \\f$ 16\\pi \\f$)\n  * \n  * @returns Boolean \\a true if the unitarity constraint is satisfied, \\a false otherwise\n  */\n  bool check_unitarity(double unitarity_limit = 16*M_PI);\n  \n\n  /** \n  * @brief Calculates largest quartic Higgs coupling\n  * \n  * This method calculates all the quartic Higgs boson couplings and returns the largest one as well as the indices of the four Higgs bosons\n  * \n  * @param gmax  Returned (complex) value for coupling \n  * @param imax  Returned index of first Higgs boson (1,2,3,4 = h,H,A,H+)\n  * @param jmax  Returned index of second boson (1,2,3,4 = h,H,A,H+)\n  * @param kmax  Returned index of third boson (1,2,3,4 = h,H,A,H+)\n  * @param lmax  Returned index of fourth boson (1,2,3,4 = h,H,A,H+)\n  */\n  void calc_perturbativity(complex <double> &gmax,int &imax,int &jmax,int &kmax,int &lmax);\n  \n  /** \n  * @brief Checks perturbativity\n  * \n  * This method checks whether the couplings of the Higgs and Gauge bosons fullfills perturbativity \n  * \n  * @param perturbativity_limit optional value to be used for perturbativity limit (default = \\f$ 4\\pi \\f$)\n  * \n  * @returns Boolean \\a true if the perturbativity constraint is satisfied, \\a false otherwise\n  */\n  bool check_perturbativity(double perturbativity_limit = 4*M_PI);\n    \n  /** \n  * @brief Checks the stability of the Higgs potential\n  * \n  * This method checks whether the Higgs potential is stable, i.e. if no\n  * directions exist in field space for which \\f$ V\\to -\\infty \\f$ for large\n  * values of the fields. This is done through a combination of analytical and numerical\n  * algorithms, depending on the generality of the specified potential.\n  * \n  * @returns Boolean \\a true if the potential is deemed stable, \\a false otherwise\n  */\n  bool check_stability();\n\n  /** \n  * @brief Prints the potential parameters in the generic basis to stdout\n  */\n  void print_param_gen();\n  \n  /** \n  * @brief Prints the potential parameters in the Higgs basis to stdout\n  */\n  void print_param_higgs();\n\n  \n  /** \n  * @brief Prints the potential parameters in the hybrid basis to stdout\n  */\n  void print_param_hybrid();\n  \n\n  /** \n  * @brief Prints the potential parameters in the physical basis to stdout\n  */\n  void print_param_phys();\n  \n  /** \n  * @brief Prints the potential parameters in the Higgs Hunter's Guide basis to stdout\n  */\n  void print_param_HHG();\n  \n  /** \n  * @brief Prints the Yukawa matrices to stdout\n  */\n  void print_yukawas();\n\n  void print_hdecay();\n\n  /** \n  * @brief Reads the 2HDM parameters from a LesHouches compliant file\n  * \n  * This method reads the parameters necessary to specify the 2HDM (and the %SM)\n  * from a file complying with the LesHouches standard. There are several options\n  * for how to prepare this file (see <a href=\"http://arxiv.org/abs/0902.0851\">manual</a> for details,\n  * or the code distribution for examples).\n  * \n  * @param file The name of the file to read\n  * \n  * @returns Boolean \\a true if the file could be opened and read correctly AND \n  *          a 2HDM was correctly specified in the file, \\a false otherwise\n  */\n  bool read_LesHouches(const char* file);\n\n  /** \n  * @brief Writes output in a LesHouches compliant file format\n  * \n  * This method writes the potential parameters and other selected output to\n  * a specified file in LesHouches-compliant file format which can then be\n  * further processed by other codes.\n  *\n  * @param file The name of the file which is to be written\n  * @param fulldecay If \\a true, decay modes of the Higgs bosons in LesHouches\n  *                  format are written to the file\n  * @param couplings If \\a true, all couplings (> 200 values) for the Higgs bosons \n  *                  are written to the file. Should be used when supplying input \n  *                  for MadGraph/MadEvent 2HDMC model\n  * @param qcd_on    Turns QCD corrections on or off, default is on. Should be \n  *                  turned off when supplying input for MadGraph/MadEvent 2HDMC model\n  */\n  void write_LesHouches(const char* file, bool fulldecay, bool couplings, bool qcd_on=true, bool HBHS=true);\n\n  void write_model(const char* file);\n\n  double get_alpha();\n\n  /**\n\t* @brief Small value\n\t* \n\t*  Minimum value used for widths, branching ratios etc. to determine when\n\t*  something should be considered zero.\n\t*/\n  const static double EPS = 1E-15;\n\n private:\n  double      lambda[8];\n  double      beta;\n  double      m22_2;\n  double      sinba;\n  bool        params_set;\n  double      v2;\n  gsl_matrix *kappa_D;\n  gsl_matrix *kappa_U;\n  gsl_matrix *kappa_L;\n  gsl_matrix *rho_D;\n  gsl_matrix *rho_U;\n  gsl_matrix *rho_L;\n  gsl_matrix *rho_N;\n  int         yukawas_type;\n\n  static bool first_run;\n  const static char *version;\n\n  SM sm;\n  \n  void init();  \n  double get_m12_2();\n  void set_kappa();\n  void set_kappa_D();\n  void set_kappa_U();\n  void set_kappa_L();\n\n  void print_info();\n\n// Added by Y.Wu\n  bool Updated;\n  bool HpmUpdated;\n  double L_MHL2, L_MHH2, L_MHA2, L_MHP2;\n  double L_MHL, L_MHH, L_MHA, L_MHP, L_sba, L_L6, L_L7, L_M122, L_tb;\n  double L_beta, L_alp;\n  double L_M2;\n  gsl_matrix *rho_D_NLO;\n  gsl_matrix *rho_U_NLO;\n  gsl_matrix *RD_NLO;// = gsl_matrix_alloc(3,3); \n  gsl_matrix *RU_NLO;// = gsl_matrix_alloc(3,3);\n\n  // To save time, we can first check `Updated` to see if we need to rerun this function\n  void store_param_phys();\n  // void store_Hpmff_Couplings();\n\n};\n\n#endif\n", "meta": {"hexsha": "7e063ee43f14cfe0f2eeed4d814a64c6d4bc91e3", "size": 36339, "ext": "h", "lang": "C", "max_stars_repo_path": "src/THDM.h", "max_stars_repo_name": "shiggs90/2HDMC-NLO-master-wei", "max_stars_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/THDM.h", "max_issues_repo_name": "shiggs90/2HDMC-NLO-master-wei", "max_issues_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/THDM.h", "max_forks_repo_name": "shiggs90/2HDMC-NLO-master-wei", "max_forks_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-27T14:59:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-27T14:59:29.000Z", "avg_line_length": 38.9068522484, "max_line_length": 179, "alphanum_fraction": 0.673050992, "num_tokens": 11642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3871133566700572}}
{"text": "/* specfunc/legendre.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author:  G. Jungman */\n\n/* Declare private but non-local support functions\n * used in various Legendre function evaluations.\n */\n\n#include <gsl/gsl_sf_result.h>\n\n\n/* Large negative mu asymptotic\n * P^{-mu}_{-1/2 + I tau}, mu -> Inf\n * |x| < 1\n */\nint\ngsl_sf_conicalP_xlt1_large_neg_mu_e(double mu, double tau, double x,\n                                       gsl_sf_result * result, double * ln_multiplier);\n\n\n/* Large tau uniform asymptotics\n * P^{-mu}_{-1/2 + I tau}, tau -> Inf\n * 1 < x\n */\nint\ngsl_sf_conicalP_xgt1_neg_mu_largetau_e(const double mu, const double tau,\n                                          const double x, double acosh_x,\n                                          gsl_sf_result * result, double * ln_multiplier);\n\n\n/* Large tau uniform asymptotics\n * P^{-mu}_{-1/2 + I tau}, tau -> Inf \n * -1 < x < 1\n */\nint\ngsl_sf_conicalP_xlt1_neg_mu_largetau_e(const double mu, const double tau,\n                                          const double x, const double acos_x,\n                                          gsl_sf_result * result, double * ln_multiplier);\n\n\n/* P^{mu}_{-1/2 + I tau}\n * x->Inf\n *\n *  * This is effective to precision EPS for\n *\n *    (mu^2 + tau^2)/((1 + tau^2)^(1/2) x^2) < EPS^{1/3}\n *\n * since it goes only to a fixed order, based on the\n * representation in terms of hypegeometric functions\n * of argument 1/x^2.\n * [Zhurina+Karmazina, (3.8)]\n */\nint\ngsl_sf_conicalP_large_x_e(const double mu, const double tau, const double x,\n                             gsl_sf_result * result, double * ln_multiplier);\n", "meta": {"hexsha": "002591a3843f36e0315c24465a9ef9904512e7b3", "size": 2346, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/legendre.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/legendre.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/specfunc/legendre.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 32.1369863014, "max_line_length": 90, "alphanum_fraction": 0.6342710997, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3870317751081239}}
{"text": "/**\r\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\r\n *\r\n * \\brief C code for example generation of waveforms with the EOBNRv2HM reduced order model,\r\n * processing through the Fourier-domain LISA response and SNR calculation.\r\n *\r\n */\r\n\r\n\r\n#define _XOPEN_SOURCE 500\r\n\r\n#ifdef __GNUC__\r\n#define UNUSED __attribute__ ((unused))\r\n#else\r\n#define UNUSED\r\n#endif\r\n\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <math.h>\r\n#include <complex.h>\r\n#include <time.h>\r\n#include <unistd.h>\r\n#include <getopt.h>\r\n#include <stdbool.h>\r\n#include <string.h>\r\n\r\n#include <gsl/gsl_errno.h>\r\n#include <gsl/gsl_bspline.h>\r\n#include <gsl/gsl_blas.h>\r\n#include <gsl/gsl_min.h>\r\n#include <gsl/gsl_spline.h>\r\n#include <gsl/gsl_complex.h>\r\n\r\n#include \"constants.h\"\r\n#include \"struct.h\"\r\n#include \"EOBNRv2HMROMstruct.h\"\r\n#include \"EOBNRv2HMROM.h\"\r\n#include \"wip.h\"\r\n#include \"LISAgeometry.h\"\r\n#include \"LISAFDresponse.h\"\r\n\r\n/* Parameters for the generation of a ROM waveform (in the form of a list of modes) */\r\n/* All parameters are to be given in SI units! */\r\ntypedef struct tagROMParams {\r\n  int nbmode;                /* Number of modes to generate (starting with the 22) - defaults to 1 (22 mode only) */\r\n  double tRef;               /* shift in time with respect to the 22-fit-removed waveform */\r\n  double phiRef;             /* phase at fRef */\r\n  double fRef;               /* reference frequency */\r\n  double m1;                 /* mass of companion 1 */\r\n  double m2;                 /* mass of companion 2 */\r\n  double distance;           /* distance of source */\r\n  char outname[256];         /* file to which output should be written */\r\n} ROMParams;\r\n\r\n/* Parameters for the generation of a ROM waveform (in the form of a list of modes) */\r\n/* All parameters are in SI units in the internals */\r\n/* Angle definitions are taken from the Krolak&al paper gr-qc/0401108 */\r\ntypedef struct tagLISAParams {\r\n  int nbmode;                /* Number of modes to generate (starting with the 22) - defaults to 1 (22 mode only) */\r\n  double tRef;               /* shift in time with respect to the 22-fit-removed waveform */\r\n  double phiRef;             /* phase at fRef */\r\n  double fRef;               /* reference frequency */\r\n  double m1;                 /* mass of companion 1 */\r\n  double m2;                 /* mass of companion 2 */\r\n  double distance;           /* distance of source */\r\n  double inclination;        /* inclination of L relative to line of sight */\r\n  double lambda;             /* First angle for the position in the sky of the source */\r\n  double beta;               /* Second angle for the position in the sky of the source */\r\n  double psi;                /* Polarization angle */\r\n  char outname[256];         /* file to which output should be written */\r\n} LISAParams;\r\n\r\n/* Parse command line and return a newly allocated ROMParams object\r\n * Masses are input in solar masses and distances in Mpc - converted in SI for the internals */\r\nstatic ROMParams* parse_args_ROM(ssize_t argc, char **argv) {\r\n    ssize_t i;\r\n    ROMParams* params;\r\n    params = (ROMParams*) malloc(sizeof(ROMParams));\r\n    memset(params, 0, sizeof(ROMParams));\r\n\r\n    /* Set default values to the arguments */\r\n    params->nbmode = 1;\r\n    params->tRef = 0.;\r\n    params->phiRef = 0.;\r\n    params->fRef = 0.;\r\n    params->m1 = 1. * 1e6 * MSUN_SI;\r\n    params->m2 = 1. * 1e6 * MSUN_SI;\r\n    params->distance = 1. * 1e9 * PC_SI;\r\n\r\n    /* consume command line */\r\n    for (i = 1; i < argc; ++i) {\r\n        if (strcmp(argv[i], \"--nbmode\") == 0) {\r\n            params->nbmode = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--tRef\") == 0) {\r\n            params->tRef = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--phiRef\") == 0) {\r\n            params->phiRef = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--fRef\") == 0) {\r\n            params->fRef = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--m1\") == 0) {\r\n            params->m1 = atof(argv[++i]) * MSUN_SI;\r\n        } else if (strcmp(argv[i], \"--m2\") == 0) {\r\n            params->m2 = atof(argv[++i]) * MSUN_SI;\r\n        } else if (strcmp(argv[i], \"--distance\") == 0) {\r\n            params->distance = atof(argv[++i]) * 1e6 * PC_SI;\r\n        } else if (strcmp(argv[i], \"--outname\") == 0) {\r\n            strncpy(params->outname, argv[++i], 256);\r\n        } else {\r\n            printf(\"Error: invalid option: %s\\n\", argv[i]);\r\n            goto fail;\r\n        }\r\n    }\r\n\r\n    return params;\r\n\r\n    fail:\r\n    free(params);\r\n    exit(1);\r\n}\r\n\r\n/* Parse command line and return a newly allocated LISAParams object\r\n * Masses are input in solar masses and distances in Mpc - converted in SI for the internals */\r\nstatic LISAParams* parse_args_LISA(ssize_t argc, char **argv) {\r\n    ssize_t i;\r\n    LISAParams* params;\r\n    params = (LISAParams*) malloc(sizeof(LISAParams));\r\n    memset(params, 0, sizeof(LISAParams));\r\n\r\n    /* Set default values to the arguments */\r\n    params->nbmode = 1;\r\n    params->tRef = 0.;\r\n    params->phiRef = 0.;\r\n    params->fRef = 0.;\r\n    params->m1 = 1. * 1e6 * MSUN_SI;\r\n    params->m2 = 1. * 1e6 * MSUN_SI;\r\n    params->distance = 1. * 1e9 * PC_SI;\r\n    params->inclination = 0.;\r\n    params->lambda = 0.;\r\n    params->beta = 0.;\r\n    params->psi = 0.;\r\n    sprintf(params->outname, \"\");\r\n\r\n    /* consume command line */\r\n    for (i = 1; i < argc; ++i) {\r\n        if (strcmp(argv[i], \"--nbmode\") == 0) {\r\n            params->nbmode = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--tRef\") == 0) {\r\n            params->tRef = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--phiRef\") == 0) {\r\n            params->phiRef = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--fRef\") == 0) {\r\n            params->fRef = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--m1\") == 0) {\r\n            params->m1 = atof(argv[++i]) * MSUN_SI;\r\n        } else if (strcmp(argv[i], \"--m2\") == 0) {\r\n            params->m2 = atof(argv[++i]) * MSUN_SI;\r\n        } else if (strcmp(argv[i], \"--distance\") == 0) {\r\n            params->distance = atof(argv[++i]) * 1e6 * PC_SI;\r\n        } else if (strcmp(argv[i], \"--inclination\") == 0) {\r\n            params->inclination = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--lambda\") == 0) {\r\n            params->lambda = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--beta\") == 0) {\r\n            params->beta = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--psi\") == 0) {\r\n            params->psi = atof(argv[++i]);\r\n        } else if (strcmp(argv[i], \"--outname\") == 0) {\r\n            strncpy(params->outname, argv[++i], 256);\r\n        } else {\r\n            printf(\"Error: invalid option: %s\\n\", argv[i]);\r\n            goto fail;\r\n        }\r\n    }\r\n\r\n    return params;\r\n\r\n    fail:\r\n    free(params);\r\n    exit(1);\r\n}\r\n\r\n/* Function to output to a file an AmpPhaseFrequencySeries; each mode will be output to a separate file using this function */\r\nstatic int Write_CAmpPhaseFrequencySeries(FILE* f, CAmpPhaseFrequencySeries* freqseries) {\r\n    gsl_vector* freq = freqseries->freq;\r\n    gsl_vector* amp_real = freqseries->amp_real;\r\n    gsl_vector* amp_imag = freqseries->amp_imag;\r\n    gsl_vector* phase = freqseries->phase;\r\n\r\n    int len = (int) freq->size;\r\n    /*Here, we could add a check on the length of the gsl_vectors*/\r\n\r\n    fprintf(f, \"# f amp_re amp_im phase\\n\");\r\n    for (int i=0; i<len; i++) {\r\n      fprintf(f, \"%.16e %.16e %.16e %.16e\\n\", gsl_vector_get(freq, i), gsl_vector_get(amp_real, i), gsl_vector_get(amp_imag, i), gsl_vector_get(phase, i));\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n/*\r\n * Swhitenoise\r\n * a simple noise function\r\n */\r\ndouble Swhitenoise(double x){\r\n  return 1;\r\n};\r\n\r\n/*\r\n * main\r\n */\r\nint main (int argc , char **argv) {\r\n    FILE* f;\r\n    ListmodesCAmpPhaseFrequencySeries* listROM = NULL;\r\n    ListmodesCAmpPhaseFrequencySeries* listA = NULL;\r\n    ListmodesCAmpPhaseFrequencySeries* listE = NULL;\r\n    ListmodesCAmpPhaseFrequencySeries* listT = NULL;\r\n    //ROMParams* params;\r\n    LISAParams* params;\r\n\r\n    /* parse commandline */\r\n    //params = parse_args_ROM(argc, argv);\r\n    params = parse_args_LISA(argc, argv);\r\n\r\n    /* Generate the waveform with the ROM */\r\n    SimEOBNRv2HMROM(&listROM, params->nbmode, params->tRef, params->phiRef, params->fRef, params->m1, params->m2, params->distance);\r\n    /* Process the waveform through the LISA response */\r\n    LISASimFDResponseTDI(&listROM, &listA, &listE, &listT, params->inclination, params->lambda, params->beta, params->psi);\r\n\r\n    ListmodesCAmpPhaseFrequencySeries* listelementA;\r\n    ListmodesCAmpPhaseFrequencySeries* listelementE;\r\n    ListmodesCAmpPhaseFrequencySeries* listelementT;\r\n    int l,m;\r\n    int status = 0;\r\n    /* Loop over the modes */\r\n    for(int i=0; i<params->nbmode; i++){\r\n      l = listmode[i][0];\r\n      m = listmode[i][1];\r\n      listelementA = ListmodesCAmpPhaseFrequencySeries_GetMode(listA, l, m);\r\n      listelementE = ListmodesCAmpPhaseFrequencySeries_GetMode(listE, l, m);\r\n      listelementT = ListmodesCAmpPhaseFrequencySeries_GetMode(listT, l, m);\r\n      /* Write files - suffix _A,E,T_lm.dat imposed to each file name, attached to the string given by outname */\r\n      /* If outname is still the default empty string, we do not output and skip this stage */\r\n      if(!(strcmp(params->outname, \"\") == 0)){\r\n\tchar *filenameA = malloc(strlen(params->outname)+64);\r\n\tchar *filenameE = malloc(strlen(params->outname)+64);\r\n\tchar *filenameT = malloc(strlen(params->outname)+64);\r\n\tsprintf(filenameA, \"%s%s%d%d%s\", params->outname, \"_A_\", l, m, \".dat\");\r\n\tsprintf(filenameE, \"%s%s%d%d%s\", params->outname, \"_E_\", l, m, \".dat\");\r\n\tsprintf(filenameT, \"%s%s%d%d%s\", params->outname, \"_T_\", l, m, \".dat\");\r\n\tf = fopen(filenameA, \"w\");\r\n\tstatus |= Write_CAmpPhaseFrequencySeries(f, listelementA->freqseries);\r\n\tfclose(f);\r\n\tf = fopen(filenameE, \"w\");\r\n\tstatus |= Write_CAmpPhaseFrequencySeries(f, listelementE->freqseries);\r\n\tfclose(f);\r\n\tf = fopen(filenameT, \"w\");\r\n\tstatus |= Write_CAmpPhaseFrequencySeries(f, listelementT->freqseries);\r\n\tfclose(f);\r\n\tif (status) goto fail;\r\n      }\r\n\r\n      /* Example SNR calculation, taking the A observable */\r\n      double *f1=listelementA->freqseries->freq->data;\r\n      int n1=listelementA->freqseries->freq->size;\r\n      double *s1Ar=listelementA->freqseries->amp_real->data;\r\n      double *s1Ai=listelementA->freqseries->amp_imag->data;\r\n      double *s1p=listelementA->freqseries->phase->data;\r\n      double *f2=listelementA->freqseries->freq->data;\r\n      int n2=listelementA->freqseries->freq->size;\r\n      double *s2Ar=listelementA->freqseries->amp_real->data;\r\n      double *s2Ai=listelementA->freqseries->amp_imag->data;\r\n      double *s2p=listelementA->freqseries->phase->data;\r\n\r\n      printf(\"n1: %d\\n\", n1);\r\n      printf(\"s1Ar[299]: %g\\n\", s1Ar[299]);\r\n\r\n      double start=((double)clock())/CLOCKS_PER_SEC;\r\n      //JGB: Set these somehwere else where it makes sense.  f_min or f_max <= 0 means use intersection of signal domains.\r\n      double f_min=-1.0;\r\n      double f_max=-1.0;\r\n      double rho2= wip_phase (f1, n1, f2, n2, s1Ar, s1Ai, s1p, s2Ar, s2Ai, s2p, Swhitenoise, 1.0, f_min, f_max);\r\n      double end=((double)clock())/CLOCKS_PER_SEC;\r\n      printf( \"SNR2 = %g,   SNR time = %g\\n\", rho2, end-start);\r\n      printf( \"SNR = %g,   SNR time = %g\\n\",sqrt(rho2), end-start);\r\n\r\n    }\r\n\r\n    /* clean up */\r\n    free(params);\r\n    ListmodesCAmpPhaseFrequencySeries_Destroy(listROM);\r\n    ListmodesCAmpPhaseFrequencySeries_Destroy(listA);\r\n    ListmodesCAmpPhaseFrequencySeries_Destroy(listE);\r\n    ListmodesCAmpPhaseFrequencySeries_Destroy(listT);\r\n    return 0;\r\n\r\n    fail:\r\n    free(params);\r\n    ListmodesCAmpPhaseFrequencySeries_Destroy(listROM);\r\n    ListmodesCAmpPhaseFrequencySeries_Destroy(listA);\r\n    ListmodesCAmpPhaseFrequencySeries_Destroy(listE);\r\n    ListmodesCAmpPhaseFrequencySeries_Destroy(listT);\r\n    return 1;\r\n}\r\n\r\n", "meta": {"hexsha": "30fb12cfe7504993998ceefed58acaa900e92c19", "size": 11934, "ext": "c", "lang": "C", "max_stars_repo_path": "LISAsim/LISAexampleSNR_old.c", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "LISAsim/LISAexampleSNR_old.c", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LISAsim/LISAexampleSNR_old.c", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 39.0, "max_line_length": 156, "alphanum_fraction": 0.6024803084, "num_tokens": 3259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.38670738204482324}}
{"text": "#include \"../precision.h\"\n\n#undef SKIP\n\n#ifdef GSL_FLOAT\n#ifdef MATLAB_FLOAT_H\n#define SKIP\n#else\n#define MATLAB_FLOAT_H\n#endif\n#endif\n\n#ifdef GSL_DOUBLE\n#ifdef MATLAB_H\n#define SKIP\n#else\n#define MATLAB_H\n#endif\n#endif\n\n#ifdef GSL_LONG_DOUBLE\n#ifdef MATLAB_LONG_DOUBLE_H\n#define SKIP\n#else\n#define MATLAB_LONG_DOUBLE_H\n#endif\n#endif\n\n#ifndef SKIP\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_vector.h>\n#include <limits>\n#include <string>\n\nnamespace MATLAB_NAMESPACE {\n\t\n\t// Functions\n\tVECTOR_T* abs(const VECTOR_T* v);\n\tMATRIX_T* abs(const MATRIX_T* m);\n\tint all(const VECTOR_T* v);\n\tVECTOR_T* all(const MATRIX_T* m, int dim = 1);\n\tint any(const VECTOR_T* v);\n\tVECTOR_T* any(const MATRIX_T* m, int dim = 1);\n\tstd::string dec2bin(int n);\n\tstd::string dec2bin(int n, int len);\n\tMATRIX_T* diag(const VECTOR_T* v, int k = 0);\n\tVECTOR_T* diag(const MATRIX_T* m, int k = 0);\n\tMATRIX_T* eye(int size);\n\tMATRIX_T* eye(int size1, int size2);\n\tVECTOR_T* find(const VECTOR_T* v, int n = std::numeric_limits<int>::max(), const std::string& direction = \"first\");\n\tVECTOR_T* find(const MATRIX_T* m, int n = std::numeric_limits<int>::max(), const std::string& direction = \"first\");\n\tMATRIX_T* find_ij(const MATRIX_T* m, int n = std::numeric_limits<int>::max(), const std::string& direction = \"first\");\n\tVECTOR_T* hist(const VECTOR_T* v, int n = 10);\n\tVECTOR_T* hist(const VECTOR_T* v, const VECTOR_T* centers);\n\tMATRIX_T* inv(const MATRIX_T* m);\n\tint length(const VECTOR_T* v);\n\tint length(const MATRIX_T* m);\n\tFP_T max(FP_T x, FP_T y);\n\tFP_T max(const VECTOR_T* v);\n\tVECTOR_T* max(const MATRIX_T* m, int dim = 1);\n\tFP_T mean(const VECTOR_T* v, const std::string& opt = \"a\");\n\tVECTOR_T* mean(const MATRIX_T* m, int dim = 1, const std::string& opt = \"a\");\n\tFP_T min(FP_T x, FP_T y);\n\tFP_T min(const VECTOR_T* v);\n\tVECTOR_T* min(const MATRIX_T* m, int dim = 1);\n\tint nnz(const VECTOR_T* v);\n\tint nnz(const MATRIX_T* m);\n\tVECTOR_T* nonzeros(const MATRIX_T* m);\n\tFP_T norm(const VECTOR_T* v, int p);\n\tVECTOR_T* normpdf(const VECTOR_T* v, FP_T mean, FP_T stdev);\n\tMATRIX_T* ones(int size);\n\tMATRIX_T* ones(int size1, int size2);\n\tVECTOR_T* ones_vector(int size);\n\tFP_T prod(const VECTOR_T* v);\n\tVECTOR_T* prod(const MATRIX_T* m, int dim = 1);\n\tMATRIX_T* rand(int size);\n\tMATRIX_T* rand(int size1, int size2);\n\tVECTOR_T* rand_vector(int size);\n\tgsl_permutation* randperm(int size);\n\tVECTOR_T* reverse(const VECTOR_T* v);\n\tVECTOR_T* setxor(const VECTOR_T* v1, const VECTOR_T* v2);\n\tVECTOR_T* sort(const VECTOR_T* v, const std::string& mode = \"ascend\", VECTOR_T** ind = NULL);\n\tMATRIX_T* sort(const MATRIX_T* m, int dim = 1, const std::string& mode = \"ascend\", MATRIX_T** ind = NULL);\n\tVECTOR_T* sortrows(const VECTOR_T* v, VECTOR_T** ind = NULL);\n\tMATRIX_T* sortrows(const MATRIX_T* m, VECTOR_T** ind = NULL);\n\tFP_T std(const VECTOR_T* v, int opt = 0);\n\tVECTOR_T* std(const MATRIX_T* m, int opt = 0, int dim = 1);\n\tFP_T sum(const VECTOR_T* v);\n\tVECTOR_T* sum(const MATRIX_T* m, int dim = 1);\n\tMATRIX_T* toeplitz(const VECTOR_T* column, const VECTOR_T* row = NULL);\n\tMATRIX_T* tril(const MATRIX_T* m, int k = 0);\n\tMATRIX_T* triu(const MATRIX_T* m, int k = 0);\n\tVECTOR_T* unique(const VECTOR_T* v, const std::string& first_or_last = \"last\", VECTOR_T** i = NULL, VECTOR_T** j = NULL);\n\tVECTOR_T* unique(const MATRIX_T* m, const std::string& first_or_last = \"last\", VECTOR_T** i = NULL, VECTOR_T** j = NULL);\n\tMATRIX_T* unique_rows(const MATRIX_T* m, const std::string& first_or_last = \"last\", VECTOR_T** i = NULL, VECTOR_T** j = NULL);\n\tMATRIX_T* zeros(int size);\n\tMATRIX_T* zeros(int size1, int size2);\n\tVECTOR_T* zeros_vector(int size);\n\t\n\t// Operators\n\tVECTOR_T* concatenate(const VECTOR_T* v, FP_T x);\n\tVECTOR_T* concatenate(FP_T x, const VECTOR_T* v);\n\tVECTOR_T* concatenate(const VECTOR_T* v1, const VECTOR_T* v2);\n\tMATRIX_T* concatenate_columns(const VECTOR_T* v1, const VECTOR_T* v2);\n\tMATRIX_T* concatenate_columns(const MATRIX_T* m, const VECTOR_T* v);\n\tMATRIX_T* concatenate_columns(const VECTOR_T* v, const MATRIX_T* m);\n\tMATRIX_T* concatenate_columns(const MATRIX_T* m1, const MATRIX_T* m2);\n\tMATRIX_T* concatenate_rows(const VECTOR_T* v1, const VECTOR_T* v2);\n\tMATRIX_T* concatenate_rows(const MATRIX_T* m, const VECTOR_T* v);\n\tMATRIX_T* concatenate_rows(const VECTOR_T* v, const MATRIX_T* m);\n\tMATRIX_T* concatenate_rows(const MATRIX_T* m1, const MATRIX_T* m2);\n\tVECTOR_T* copy(const VECTOR_T* v);\n\tMATRIX_T* copy(const MATRIX_T* m);\n\tMATRIX_T* div_left(const MATRIX_T* m1, const MATRIX_T* m2);\n\tMATRIX_T* div_right(const MATRIX_T* m1, const MATRIX_T* m2);\n\tVECTOR_T* logical_and(const VECTOR_T* v1, const VECTOR_T* v2);\n\tMATRIX_T* logical_and(const MATRIX_T* m1, const MATRIX_T* m2);\n\tVECTOR_T* logical_not(const VECTOR_T* v);\n\tMATRIX_T* logical_not(const MATRIX_T* m);\n\tVECTOR_T* logical_or(const VECTOR_T* v1, const VECTOR_T* v2);\n\tMATRIX_T* logical_or(const MATRIX_T* m1, const MATRIX_T* m2);\n\tMATRIX_T* mul(const MATRIX_T* m1, const MATRIX_T* m2);\n\tMATRIX_T* pow(const MATRIX_T* m, int power);\n\tVECTOR_T* pow_elements(const VECTOR_T* v, FP_T power);\n\tVECTOR_T* pow_elements(const VECTOR_T* v, const VECTOR_T* powers);\n\tMATRIX_T* pow_elements(const MATRIX_T* m, FP_T power);\n\tMATRIX_T* pow_elements(const MATRIX_T* m, const MATRIX_T* powers);\n\tVECTOR_T* sequence(int start, int end);\n\tVECTOR_T* sequence(int start, int step, int end);\n\t\n\t// Floating-point comparison\n\textern FP_T epsilon;\n\tint fp_compare(FP_T x, FP_T y);\n\tbool fp_zero(FP_T x);\n\tbool fp_nonzero(FP_T x);\n\tbool fp_equal(FP_T x, FP_T y);\n\tbool fp_not_equal(FP_T x, FP_T y);\n\tbool fp_less(FP_T x, FP_T y);\n\tbool fp_less_or_equal(FP_T x, FP_T y);\n\tbool fp_greater(FP_T x, FP_T y);\n\tbool fp_greater_or_equal(FP_T x, FP_T y);\n\t\n\t// Vector/matrix comparison\n\ttypedef bool (*comparator)(FP_T, FP_T);\n\tint compare_vectors(const VECTOR_T* v1, const VECTOR_T* v2);\n\tbool vector_less(VECTOR_T* v1, VECTOR_T* v2);\n\tint compare_matrices(const MATRIX_T* m1, const MATRIX_T* m2);\n\tbool matrix_less(MATRIX_T* m1, MATRIX_T* m2);\n\tVECTOR_T* compare_elements(const VECTOR_T* v, comparator compare, FP_T x);\n\tVECTOR_T* compare_elements(const VECTOR_T* v1, comparator compare, const VECTOR_T* v2);\n\tMATRIX_T* compare_elements(const MATRIX_T* m, comparator compare, FP_T x);\n\tMATRIX_T* compare_elements(const MATRIX_T* m1, comparator compare, const MATRIX_T* m2);\n\t\n\t// Vector-by-vector indexing\n\tVECTOR_T* ordinal_index(const VECTOR_T* v, const VECTOR_T* indices);\n\tvoid ordinal_index_assign(VECTOR_T* v, const VECTOR_T* indices, FP_T value);\n\tvoid ordinal_index_assign(VECTOR_T* v, const VECTOR_T* indices, const VECTOR_T* values);\n\tVECTOR_T* logical_index(const VECTOR_T* v, const VECTOR_T* logical_v);\n\tvoid logical_index_assign(VECTOR_T* v, const VECTOR_T* logical_v, FP_T value);\n\tvoid logical_index_assign(VECTOR_T* v, const VECTOR_T* logical_v, const VECTOR_T* values);\n\t\n\t// Matrix-by-integer indexing\n\tFP_T ordinal_index(const MATRIX_T* m, int index);\n\tvoid ordinal_index_assign(MATRIX_T* m, int index, FP_T value);\n\t\n\t// Matrix-by-vector indexing\n\tVECTOR_T* ordinal_index(const MATRIX_T* m, const VECTOR_T* indices);\n\tvoid ordinal_index_assign(MATRIX_T* m, const VECTOR_T* indices, FP_T value);\n\tvoid ordinal_index_assign(MATRIX_T* m, const VECTOR_T* indices, const VECTOR_T* values);\n\tVECTOR_T* logical_index(const MATRIX_T* m, const VECTOR_T* logical_v);\n\tvoid logical_index_assign(MATRIX_T* m, const VECTOR_T* logical_v, FP_T value);\n\tvoid logical_index_assign(MATRIX_T* m, const VECTOR_T* logical_v, const VECTOR_T* values);\n\t\n\t// Matrix-by-two-vectors indexing (non-mixed)\n\tMATRIX_T* ordinal_index(const MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* columns);\n\tvoid ordinal_index_assign(MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* columns, FP_T value);\n\tvoid ordinal_index_assign(MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* columns, const MATRIX_T* values);\n\tMATRIX_T* logical_index(const MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* logical_columns);\n\tvoid logical_index_assign(MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* logical_columns, FP_T value);\n\tvoid logical_index_assign(MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* logical_columns, const MATRIX_T* values);\n\t\n\t// Matrix-by-two-vectors indexing (mixed)\n\tMATRIX_T* ord_log_index(const MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* logical_columns);\n\tvoid ord_log_index_assign(MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* logical_columns, FP_T value);\n\tvoid ord_log_index_assign(MATRIX_T* m, const VECTOR_T* rows, const VECTOR_T* logical_columns, const MATRIX_T* values);\n\tMATRIX_T* log_ord_index(const MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* columns);\n\tvoid log_ord_index_assign(MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* columns, FP_T value);\n\tvoid log_ord_index_assign(MATRIX_T* m, const VECTOR_T* logical_rows, const VECTOR_T* columns, const MATRIX_T* values);\n\t\n\t// Matrix-by-matrix indexing\n\tMATRIX_T* ordinal_index(const MATRIX_T* m, const MATRIX_T* indices);\n\tvoid ordinal_index_assign(MATRIX_T* m, const MATRIX_T* indices, FP_T value);\n\tvoid ordinal_index_assign(MATRIX_T* m, const MATRIX_T* indices, const MATRIX_T* values);\n\tVECTOR_T* logical_index(const MATRIX_T* m, const MATRIX_T* logical_m);\n\tvoid logical_index_assign(MATRIX_T* m, const MATRIX_T* logical_m, FP_T value);\n\tvoid logical_index_assign(MATRIX_T* m, const MATRIX_T* logical_m, const VECTOR_T* values);\n\t\n\t// Vector/matrix conversion\n\tvoid to_array(const VECTOR_T* v, FP_T* array);\n\tbool to_bool(const VECTOR_T* v);\n\tbool to_bool(const MATRIX_T* m);\n\tVECTOR_T* to_vector(const gsl_vector* v_d);\n\tgsl_vector* to_vector_double(const VECTOR_T* v);\n\tVECTOR_T* to_vector(const MATRIX_T* m);\n\tMATRIX_T* to_column_matrix(const VECTOR_T* v);\n\tMATRIX_T* to_row_matrix(const VECTOR_T* v);\n\tMATRIX_T* to_matrix(const gsl_matrix* m_d);\n\tgsl_matrix* to_matrix_double(const MATRIX_T* m);\n\tVECTOR_T* to_vector(const gsl_permutation* p);\n\tgsl_permutation* to_permutation(const VECTOR_T* v);\n\t\n\t// Utility\n\tgsl_rng* get_rng();\n\tvoid seed_rng(const gsl_rng* rng, unsigned long seed);\n\tVECTOR_T* permute(const gsl_permutation* p, const VECTOR_T* v);\n\tMATRIX_T* permute_columns(const gsl_permutation* p, const MATRIX_T* m);\n\tMATRIX_T* permute_rows(const gsl_permutation* p, const MATRIX_T* m);\n}\n\n#endif\n", "meta": {"hexsha": "5f625d629f70ae90ca598e4f84046e9ed7703a9b", "size": 10340, "ext": "h", "lang": "C", "max_stars_repo_path": "matlab/matlab.h", "max_stars_repo_name": "devuci/bct-cpp", "max_stars_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_stars_repo_licenses": ["MIT"], "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.h", "max_issues_repo_name": "devuci/bct-cpp", "max_issues_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_issues_repo_licenses": ["MIT"], "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.h", "max_forks_repo_name": "devuci/bct-cpp", "max_forks_repo_head_hexsha": "bbb33f476bffbb5669e051841f00c3241f4d6f69", "max_forks_repo_licenses": ["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.1607142857, "max_line_length": 127, "alphanum_fraction": 0.7510638298, "num_tokens": 2948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883735630722, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.3866564188705512}}
{"text": "#ifndef _fim_h_included_\n#define _fim_h_included_\n\n#include <assert.h>\n#include <stdlib.h>\n#include <algorithm>\n#include <cctype>\n#include <fstream>\n#include <functional>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <set>\n#include <sstream>\n#include <vector>\n#include <sstream>\n#include <string>\n#include <boost/config.hpp>\n#include <boost/foreach.hpp>\n#include <boost/random.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_linalg.h>\n\n#include <boost/numeric/ublas/io.hpp>\n\n#include <jsc/bioinfo/gene_anno.hpp>\n#include <jsc/util/log.hpp>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\n#include \"splicing_graph.h\"\n#include \"read.h\"\n#include \"linalg.h\"\n#include \"accessible_read_starts.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::numeric;\nusing namespace jsc::bioinfo;\nusing namespace jsc::util;\n\nclass FIM {\n\tpublic:\n\t\tFIM () {\n\t\t\tofim_call_count = 0;\n\t\t}\n\n\t\tdouble get_ofim_call_count() const {\n\t\t\treturn ofim_call_count;\n\t\t};\n\n\t\tstatic double estimate_mle_variance(\n\t\t\t\tublas::matrix<double> const & I) {\n\t\t\treturn estimate_mle_variance_by_diag(I);\n\t\t}\n\n\t\tstatic double estimate_mle_variance_by_diag(\n\t\t\t\tublas::matrix<double> const & I) {\n\t\t\tunsigned long K = I.size1() + 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tsum += 1.0 / I(p,p);\n\t\t\t}\n\t\t\treturn sum;\n\t\t}\n\n\t\tstatic double estimate_mle_variance_by_inv(\n\t\t\t\tublas::matrix<double> const & I) {\n\t\t\tassert(I.size1() == I.size2());\n\t\t\tL_(debug) << I;\n\t\t\tublas::matrix<double> inv =\n\t\t\t\tublas::zero_matrix<double>(I.size1(), I.size1());\n\t\t\tlinalg::invert_matrix(I, inv);\n\n\t\t\tL_(debug) << inv;\n\n\t\t\tunsigned long K = I.size1() + 1;\n\t\t\tdouble sum = 0;\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\tsum += inv(p,q);\n\t\t\t\t}\n\t\t\t\tsum += inv(p,p);\n\t\t\t}\n\n\t\t\treturn sum;\n\t\t}\n\n\t\tstatic void print_fim_for_R(ostream & os, ublas::matrix<double> I) {\n\t\t\tunsigned long K = I.size1() + 1;\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\tos << I(p,q) << \"\\t\";\n\t\t\t\t}\n\t\t\t\tos << endl;\n\t\t\t}\n\t\t}\n\n\t\tstatic void print_fim_diag_for_R(ostream & os, ublas::matrix<double> I) {\n\t\t\tunsigned long K = I.size1() + 1;\n\t\t\tos << \"(\";\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tos << I(p,p) << \",\";\n\t\t\t}\n\t\t\tos << \")\";\n\t\t\tos << endl;\n\t\t}\n\n\t\tublas::matrix<double> bruteforce_fim(shared_ptr<Read> readp,\n\t\t\t\tvector<double> const & iso_probs) {\n\t\t\tL_(debug) << \"FIM::bruteforce_fim\";\n\t\t\treset_ofim_call_count();\n\t\t\tshared_ptr<AccessibleReadStarts> ars = readp->get_ARS();\n\t\t\tunsigned long K = ars->get_num_isoforms();\n\t\t\tublas::matrix<double> I = ublas::zero_matrix<double>(K-1, K-1);\n\n\t\t\tfor (unsigned long k = 0; k < K; ++k) {\n\t\t\t\tif (iso_probs[k] == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tublas::matrix<int> sign;\n\t\t\t\tL_(debug) << \"Possible Isoform #\" << k\n\t\t\t\t\t<< \": Generating reads with starts from 0 to \"\n\t\t\t\t\t<< ars->get_iso_ARS_total_length(k)\n\t\t\t\t\t<< \" in ARS\";\n\t\t\t\tfor (unsigned long a = 0;\n\t\t\t\t\t\ta < ars->get_iso_ARS_total_length(k);\n\t\t\t\t\t\t++a) {\n\t\t\t\t\t// generate a read starting from a in ARS\n\t\t\t\t\treadp->generate_read(k, ars->ARStart2IsoStart(k, a));\n\t\t\t\t\tdouble G = readp->prob_generated_by_iso(k);\n\t\t\t\t\tdouble log_scaler = log(G) + log(iso_probs[k]);\n\t\t\t\t\tublas::matrix<double> m = ofim(readp, iso_probs, sign);\n\t\t\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\t\t\tif (sign(p,q) > 0) {\n\t\t\t\t\t\t\t\tm(p,q) = exp(m(p,q) + log_scaler);\n\t\t\t\t\t\t\t} else if (sign(p,q) < 0) {\n\t\t\t\t\t\t\t\tm(p,q) = - exp(m(p,q) + log_scaler);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// m(p,q) must be zero, no need to perform scaling\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tassert(!isinf(m(p,q)) && !isnan(m(p,q)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tI += m;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn I;\n\t\t}\n\n\t\tublas::matrix<double> fast_fim(shared_ptr<Read> readp,\n\t\t\t\tvector<double> const & iso_probs) {\n\t\t\tL_(debug) << \"FIM::fast_fim\";\n\t\t\treset_ofim_call_count();\n\t\t\tshared_ptr<AccessibleReadStarts> ars = readp->get_ARS();\n\t\t\tunsigned long K = ars->get_num_isoforms();\n\t\t\tublas::matrix<double> I = ublas::zero_matrix<double>(K-1, K-1);\n\t\t\tfor (unsigned long k = 0; k < K; ++k) {\n\t\t\t\tif (iso_probs[k] == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tublas::matrix<int> sign;\n\t\t\t\tL_(debug) << \"Possible Isoform #\" << k\n\t\t\t\t\t<< \": Generating reads with starts from 0 to \"\n\t\t\t\t\t<< ars->get_iso_ARS_total_length(k)\n\t\t\t\t\t<< \" in ARS\";\n\n\t\t\t\tunsigned long a = 0;\n\t\t\t\twhile (a < ars->get_iso_ARS_total_length(k)) {\n\t\t\t\t\t// generate a read starting from a\n\t\t\t\t\treadp->generate_read(k, ars->ARStart2IsoStart(k, a));\n\n\t\t\t\t\tunsigned long N_overlapping_exons = readp->exon_indices.size();\n\t\t\t\t\tunsigned long N_eq_samples = min(\n\t\t\t\t\t\t\tars->exon_lengths[readp->exon_indices[0]]\n\t\t\t\t\t\t\t- readp->start_at_first_exon,\n\t\t\t\t\t\t\tars->exon_lengths[readp->exon_indices[N_overlapping_exons - 1]]\n\t\t\t\t\t\t\t- readp->end_at_last_exon + 1);\n\n\t\t\t\t\twhile ( (a + N_eq_samples - 1 >= ars->get_iso_ARS_total_length(k)) || (ars->ARStart2IsoStart(k, a + N_eq_samples - 1) != (ars->ARStart2IsoStart(k, a) + N_eq_samples - 1)) ){\n\t\t\t\t\t\tN_eq_samples--;\n\t\t\t\t\t}\n\n\t\t\t\t\tdouble G = readp->prob_generated_by_iso(k);\n\t\t\t\t\tublas::matrix<double> m = ofim(readp, iso_probs, sign);\n\t\t\t\t\tbool zero_scaler = ((G == 0) || (iso_probs[k] == 0));\n\t\t\t\t\tdouble log_scaler = log(N_eq_samples)\n\t\t\t\t\t\t+ log(G)\n\t\t\t\t\t\t+ log(iso_probs[k]);\n\t\t\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\t\t\tif (zero_scaler) {\n\t\t\t\t\t\t\t\tm(p,q) = 0;\n\t\t\t\t\t\t\t} else if (sign(p,q) > 0) {\n\t\t\t\t\t\t\t\tm(p,q) = exp(m(p,q) + log_scaler);\n\t\t\t\t\t\t\t} else if (sign(p,q) < 0) {\n\t\t\t\t\t\t\t\tm(p,q) = - exp(m(p,q) + log_scaler);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// m(p,q) must be zero, no need to perform scaling\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tassert(!isinf(m(p,q)) && !isnan(m(p,q)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tI += m;\n\t\t\t\t\ta += N_eq_samples;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn I;\n\t\t}\n\n\t\tublas::matrix<double> faster_fim(shared_ptr<Read> readp,\n\t\t\t\tvector<double> const & iso_probs) {\n\t\t\tL_(debug) << \"FIM::faster_fim\";\n\t\t\treset_ofim_call_count();\n\t\t\tshared_ptr<AccessibleReadStarts> ars = readp->get_ARS();\n\t\t\tunsigned long K = ars->get_num_isoforms();\n\t\t\tublas::matrix<double> I = ublas::zero_matrix<double>(K-1, K-1);\n\t\t\tvector<interval_list<long > > covered_sample_starts;\n\t\t\tfor (unsigned long k = 0; k < K; ++k) {\n\t\t\t\tinterval_list<long> il;\n\t\t\t\tcovered_sample_starts.push_back(il);\n\t\t\t}\n\t\t\tfor (unsigned long k = 0; k < K; ++k) {\n\t\t\t\tif (iso_probs[k] == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tunsigned long a = covered_sample_starts[k].find_min_uncovered(0);\n\t\t\t\tL_(debug) << \"Possible Isoform #\" << k\n\t\t\t\t\t<< \": Generating reads with starts from \" << a << \" to \"\n\t\t\t\t\t<< ars->get_iso_ARS_total_length(k)\n\t\t\t\t\t<< \" in ARS\";\n\t\t\t\twhile (a < ars->get_iso_ARS_total_length(k)) {\n\t\t\t\t\t// generate a read starting from a\n\t\t\t\t\treadp->generate_read(k, ars->ARStart2IsoStart(k, a));\n\n\t\t\t\t\tunsigned long N_overlapping_exons = readp->exon_indices.size();\n\t\t\t\t\tunsigned long N_eq_samples = min(\n\t\t\t\t\t\t\tars->exon_lengths[readp->exon_indices[0]]\n\t\t\t\t\t\t\t- readp->start_at_first_exon,\n\t\t\t\t\t\t\tars->exon_lengths[readp->exon_indices[N_overlapping_exons - 1]]\n\t\t\t\t\t\t\t- readp->end_at_last_exon + 1);\n\t\t\t\t\twhile ( (a + N_eq_samples - 1 >= ars->get_iso_ARS_total_length(k)) || (ars->ARStart2IsoStart(k, a + N_eq_samples - 1) != (ars->ARStart2IsoStart(k, a) + N_eq_samples - 1)) ){\n\t\t\t\t\t\tN_eq_samples--;\n\t\t\t\t\t}\n\n\t\t\t\t\tublas::matrix<int> sign;\n\t\t\t\t\tublas::matrix<double> m = ofim(readp, iso_probs, sign);\n\n\t\t\t\t\tdouble G = readp->prob_generated_by_iso(k);\n\t\t\t\t\tdouble scaler = G * N_eq_samples * iso_probs[k];\n\n\t\t\t\t\tif (covered_sample_starts[k].compute_overlap(a, a + N_eq_samples)\n\t\t\t\t\t\t\t> 0) {\n\t\t\t\t\t\tL_(debug2) << \"Cov for iso # \" << k\n\t\t\t\t\t\t\t<< \": \"\t<< covered_sample_starts[k];\n\t\t\t\t\t\tL_(error) << \"Overlap > 0!\";\n\t\t\t\t\t}\n\t\t\t\t\tcovered_sample_starts[k].add_interval(a, a + N_eq_samples);\n\t\t\t\t\tL_(debug2) << \"Adding [\" << a\n\t\t\t\t\t\t<< \",\" << (a + N_eq_samples)\n\t\t\t\t\t\t<< \") to possible isoform #\" << k;\n\t\t\t\t\tfor (unsigned long j = 0; j < K; ++j) {\n\t\t\t\t\t\tif (j == k) continue;\n\t\t\t\t\t\tlong first_matching_idx =\n\t\t\t\t\t\t\tis_connected_exons_compatible_with_isoform(\n\t\t\t\t\t\t\t\t\treadp->exon_indices,\n\t\t\t\t\t\t\t\t\tars->iso_exon_indices[j]);\n\t\t\t\t\t\tif (first_matching_idx >= 0) {\n\t\t\t\t\t\t\tdouble G_j = readp->prob_generated_by_iso(j);\n\t\t\t\t\t\t\tscaler += G_j * N_eq_samples * iso_probs[j];\n\t\t\t\t\t\t\tunsigned long a2 = readp->start_at_first_exon\n\t\t\t\t\t\t\t\t+ ars->iso_exon_total_lengths[j][first_matching_idx]\n\t\t\t\t\t\t\t\t- ars->exon_lengths[readp->exon_indices[0]];\n\t\t\t\t\t\t\ta2 = ars->IsoStart2ARStart(j, a2);\n\n\t\t\t\t\t\t\tif (covered_sample_starts[j].compute_overlap(a2, a2 + N_eq_samples)\n\t\t\t\t\t\t\t\t\t> 0) {\n\t\t\t\t\t\t\t\tL_(debug2) << \"Cov for iso # \" << j\n\t\t\t\t\t\t\t\t\t<< \": \"\t<< covered_sample_starts[j];\n\t\t\t\t\t\t\t\tL_(error) << \"Overlap > 0!\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcovered_sample_starts[j].add_interval(a2, a2 + N_eq_samples);\n\t\t\t\t\t\t\tL_(debug2) << \"Adding [\" << a2\n\t\t\t\t\t\t\t\t<< \",\" << (a2 + N_eq_samples)\n\t\t\t\t\t\t\t\t<< \") to possible isoform #\" << j;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tdouble log_scaler = log(scaler);\n\t\t\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\t\t\tif (sign(p,q) > 0) {\n\t\t\t\t\t\t\t\tm(p,q) = exp(m(p,q) + log_scaler);\n\t\t\t\t\t\t\t} else if (sign(p,q) < 0) {\n\t\t\t\t\t\t\t\tm(p,q) = - exp(m(p,q) + log_scaler);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// m(p,q) must be zero, no need to perform scaling\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tassert(!isinf(m(p,q)) && !isnan(m(p,q)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tI += m;\n\t\t\t\t\ta = covered_sample_starts[k].find_min_uncovered(0);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn I;\n\t\t}\n\tprotected:\n\t\tvoid reset_ofim_call_count() {\n\t\t\tofim_call_count = 0;\n\t\t};\n\n\t\t// \\mathfrak{I}_{s}^{(m)}(\\Theta)\n\t\tublas::matrix<double> ofim(shared_ptr<const Read> readp,\n\t\t\t\tvector<double> const & iso_probs,\n\t\t\t\tublas::matrix<int> & sign) {\n\t\t\t++ofim_call_count;\n\t\t\tshared_ptr<AccessibleReadStarts> ars = readp->get_ARS();\n\t\t\tunsigned long K = ars->get_num_isoforms();\n\t\t\tublas::matrix<double> m = ublas::zero_matrix<double>(K-1,K-1);\n\t\t\tsign = ublas::zero_matrix<int>(K-1, K-1);\n\t\t\tvector<double> v_delta_G(K, 0);\n\t\t\tfor (unsigned long k = 0; k < K; ++k) {\n\t\t\t\tif (readp->is_compatible_with_iso(k)) {\n\t\t\t\t\tv_delta_G[k] = readp->prob_generated_by_iso(k);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble sum = 0;\n\t\t\tfor (unsigned long k = 0; k < K; ++k) {\n\t\t\t\tif (v_delta_G[k] > 0 && iso_probs[k] > 0) {\n\t\t\t\t\tsum += iso_probs[k] * v_delta_G[k];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tassert(sum > 0);\n\n\t\t\tdouble log_prod = log(sum) + log(sum);\n\t\t\tfor (unsigned long p = 0; p < K - 1; ++p) {\n\t\t\t\tfor (unsigned long q = 0; q < K - 1; ++q) {\n\t\t\t\t\tm(p,q) = (v_delta_G[p] - v_delta_G[K - 1])*\n\t\t\t\t\t\t(v_delta_G[q] - v_delta_G[K - 1]);\n\t\t\t\t\tif (m(p,q) != 0) {\n\t\t\t\t\t\tsign(p,q) = m(p,q) > 0 ? 1 : -1;\n\t\t\t\t\t\tif (m(p,q) < 0) {\n\t\t\t\t\t\t\tm(p,q) = - m(p,q);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tm(p,q) = log(m(p,q)) - log_prod;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (readp->exon_indices[0] == 0\n\t\t\t\t\t&& readp->start_at_first_exon == 2730) {\n\t\t\t\tL_(info) << *readp << \" \" << m(0,0) << \" \" << sign(0,0);\n\t\t\t}\n\n\t\t\treturn m;\n\t\t}\n\n\tprivate:\n\t\tdouble ofim_call_count;\n};\n\n#endif\n", "meta": {"hexsha": "67af9c9695e3c256c206f2a9f704104cd9693d31", "size": 11080, "ext": "h", "lang": "C", "max_stars_repo_path": "common/fim.h", "max_stars_repo_name": "gersteinlab/LESSeq", "max_stars_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-06-19T21:14:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-15T03:04:41.000Z", "max_issues_repo_path": "common/fim.h", "max_issues_repo_name": "gersteinlab/LESSeq", "max_issues_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z", "max_forks_repo_path": "common/fim.h", "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_forks_repo_licenses": ["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.6256684492, "max_line_length": 178, "alphanum_fraction": 0.580866426, "num_tokens": 3685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.38630253956337884}}
{"text": "#ifndef ConditionalTest_SERIAL_H\n#define ConditionalTest_SERIAL_H\n#include <ace/core/core.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_statistics_double.h>\n#include <gsl/gsl_randist.h>\n#include \"conditionaltest.h\"\n\n\n\nclass ConditionalTest::Serial : public EAbstractAnalyticSerial\n{\n    Q_OBJECT\npublic:\n    explicit Serial(ConditionalTest* parent);\n    virtual std::unique_ptr<EAbstractAnalyticBlock> execute(const EAbstractAnalyticBlock* block) override final;\n\n    // helper functions\n    bool isEmpty(QVector<QVector<double>>& matrix);\n\n    // Statistical Tests\n    void hypergeom(\n        const QVector<QString>& amx_column,\n        const CCMatrix::Pair& ccmPair,\n        int clusterIndex,\n        int featureIndex,\n        int labelIndex,\n        double& results);\n\n    void test_proportions(\n        const QVector<QString>& amx_column,\n        const CCMatrix::Pair& ccmPair,\n        int clusterIndex,\n        int featureIndex,\n        int labelIndex,\n        double& results);\n\n    void regression(\n        const QVector<QString>& amx_column,\n        const CCMatrix::Pair& ccmPair,\n        int clusterIndex,\n        QVector<double>& results);\n\nprivate:\n    /*!\n     * Pointer to the base analytic for this object.\n     */\n    ConditionalTest* _base;\n\n    // Performs power analysis for multiple-linear regression.\n    double pwr_f2_test(int u, int v, double f2, double sig_level);\n};\n\n\n\n#endif\n", "meta": {"hexsha": "a71077385ff7e6f2eac3c42a5a2fc7c264312538", "size": 1429, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/conditionaltest_serial.h", "max_stars_repo_name": "SystemsGenetics/KINC", "max_stars_repo_head_hexsha": "afcd1cdde7e62e464561f0624dc6fa78e434e102", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-08-15T13:27:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-10T17:20:40.000Z", "max_issues_repo_path": "src/core/conditionaltest_serial.h", "max_issues_repo_name": "SystemsGenetics/KINC", "max_issues_repo_head_hexsha": "afcd1cdde7e62e464561f0624dc6fa78e434e102", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 182.0, "max_issues_repo_issues_event_min_datetime": "2016-07-31T07:15:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T01:25:41.000Z", "max_forks_repo_path": "src/core/conditionaltest_serial.h", "max_forks_repo_name": "SystemsGenetics/KINC", "max_forks_repo_head_hexsha": "afcd1cdde7e62e464561f0624dc6fa78e434e102", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-10-12T22:03:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T00:01:18.000Z", "avg_line_length": 24.6379310345, "max_line_length": 112, "alphanum_fraction": 0.6850944717, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3862674260012474}}
{"text": "#include \"std_includes.h\"\r\n\r\n#ifndef MATRIX_H\r\n#define MATRIX_H\r\n\r\n#ifdef CRANIUM_USE_MKL\r\n#define CRANIUM_USE_BLAS\r\n#include \"mkl.h\"\r\n#else\r\n#ifdef CRANIUM_USE_CBLAS\r\n#define CRANIUM_USE_BLAS\r\n#include <cblas.h>\r\n#endif\r\n#endif\r\n\r\n// represents user-supplied training data\r\ntypedef struct DataSet_ {\r\n    size_t rows;\r\n    size_t cols;\r\n    float** data;\r\n} DataSet;\r\n\r\n// represents a matrix of data in row-major order\r\ntypedef struct Matrix_ {\r\n    size_t rows;\r\n    size_t cols;\r\n    float* data;\r\n} Matrix;\r\n\r\n#ifndef RAND_MOD\r\n#define RAND_MOD 2147483647\r\n#endif\r\n\r\n// create dataset given user data\r\nstatic DataSet* createDataSet(size_t rows, size_t cols, float** data);\r\n\r\n// uses memory of the original data to split dataset into batches\r\nstatic DataSet** createBatches(DataSet* allData, int numBatches);\r\n\r\n// split a dataset into row matrices\r\nstatic Matrix** splitRows(DataSet* dataset);\r\n\r\n// destroy dataset\r\nstatic void destroyDataSet(DataSet* dataset);\r\n\r\n// convert dataset to matrix\r\nstatic Matrix* dataSetToMatrix(DataSet* dataset);\r\n\r\n// creates a matrix given data\r\nstatic Matrix* createMatrix(size_t rows, size_t cols, float* data);\r\n\r\n// creates a matrix zeroed out\r\nstatic Matrix* createMatrixZeroes(size_t rows, size_t cols);\r\n\r\n// get an element of a matrix\r\nstatic float getMatrix(Matrix* mat, size_t row, size_t col);\r\n\r\n// set an element of a matrix\r\nstatic void setMatrix(Matrix* mat, size_t row, size_t col, float val);\r\n\r\n// sets the values in $to equal to values in $from\r\nstatic void copyValuesInto(Matrix* from, Matrix* to);\r\n\r\n// prints the entries of a matrix\r\nstatic void printMatrix(Matrix* input);\r\n\r\n// sets each entry in matrix to 0\r\nstatic void zeroMatrix(Matrix* orig);\r\n\r\n// returns transpose of matrix\r\nstatic Matrix* transpose(Matrix* orig);\r\n\r\n// transposes matrix and places data into $origT\r\nstatic void transposeInto(Matrix* orig, Matrix* origT);\r\n\r\n// adds two matrices and returns result\r\nstatic Matrix* add(Matrix* A, Matrix* b);\r\n\r\n// adds $from to $to and places result in $to\r\nstatic void addTo(Matrix* from, Matrix* to);\r\n\r\n// adds $B, a row vector, to each row of $A\r\nstatic Matrix* addToEachRow(Matrix* A, Matrix* B);\r\n\r\n// multiplies every element of $orig by $C\r\nstatic void scalarMultiply(Matrix* orig, float c);\r\n\r\n// multiplies $A and $B (ordering: AB) and returns product matrix\r\nstatic Matrix* multiply(Matrix* A, Matrix* B);\r\n\r\n// multiplies $A and $B (ordering: AB) and places values into $into\r\nstatic void multiplyInto(Matrix* A, Matrix* B, Matrix* into);\r\n\r\n// element-wise multiplcation\r\nstatic Matrix* hadamard(Matrix* A, Matrix* B);\r\n\r\n// places values of hadamard product of $A and $B into $into\r\nstatic void hadamardInto(Matrix* A, Matrix* B, Matrix* into);\r\n\r\n// returns a shallow copy of input matrix\r\nstatic Matrix* copy(Matrix* orig);\r\n\r\n// returns 1 if matrices are equal, 0 otherwise\r\nstatic int equals(Matrix* A, Matrix* B);\r\n\r\n// frees a matrix and its data\r\nstatic void destroyMatrix(Matrix* matrix);\r\n\r\n\r\n/*\r\n    Begin functions.\r\n*/\r\n\r\nstatic DataSet* createDataSet(size_t rows, size_t cols, float** data){\r\n    DataSet* dataset = (DataSet*)malloc(sizeof(DataSet));\r\n    dataset->rows = rows;\r\n    dataset->cols = cols;\r\n    dataset->data = data;\r\n    return dataset;\r\n}\r\n\r\nDataSet** createBatches(DataSet* allData, int numBatches){\r\n    DataSet** batches = (DataSet**)malloc(sizeof(DataSet*) * numBatches);\r\n    int remainder = allData->rows % numBatches;\r\n    int i;\r\n    int curRow = 0;\r\n    for (i = 0; i < numBatches; i++){\r\n        size_t batchSize = allData->rows / numBatches;\r\n        if (remainder-- > 0){\r\n            batchSize++;\r\n        }\r\n        batches[i] = createDataSet(batchSize, allData->cols, allData->data + curRow);\r\n        curRow += batchSize;\r\n    }\r\n    return batches;\r\n}\r\n\r\nstatic Matrix** splitRows(DataSet* dataset){\r\n    Matrix** rows = (Matrix**)malloc(sizeof(Matrix*) * dataset->rows);\r\n    int i;\r\n    for (i = 0; i < dataset->rows; i++){\r\n        rows[i] = createMatrix(1, dataset->cols, dataset->data[i]);\r\n    }\r\n    return rows;\r\n}\r\n\r\nvoid shuffleTogether(DataSet* A, DataSet* B, std::minstd_rand &gen){\r\n    assert(A->rows == B->rows);\r\n    int i;\r\n    for (i = 0; i < A->rows - 1; i++){\r\n        size_t j = i + gen() / (RAND_MOD / (A->rows - i) + 1);\r\n        float* tmpA = A->data[j];\r\n        A->data[j] = A->data[i];\r\n        A->data[i] = tmpA;\r\n        float* tmpB = B->data[j];\r\n        B->data[j] = B->data[i];\r\n        B->data[i] = tmpB;\r\n    }\r\n}\r\n\r\nstatic void destroyDataSet(DataSet* dataset){\r\n    int i;\r\n    for (i = 0; i < dataset->rows; i++){\r\n        free(dataset->data[i]);\r\n    }\r\n    free(dataset->data);\r\n    free(dataset);\r\n}\r\n\r\nstatic Matrix* dataSetToMatrix(DataSet* dataset){\r\n    Matrix* convert = (Matrix*)malloc(sizeof(Matrix));\r\n    convert->rows = dataset->rows;\r\n    convert->cols = dataset->cols;\r\n    convert->data = (float*)malloc(sizeof(float) * dataset->rows * dataset->cols);\r\n    int i, j;\r\n    for (i = 0; i < dataset->rows; i++){\r\n        for (j = 0; j < dataset->cols; j++){\r\n            setMatrix(convert, i, j, dataset->data[i][j]);\r\n        }\r\n    }\r\n    return convert;\r\n}\r\n\r\nMatrix* createMatrix(size_t rows, size_t cols, float* data){\r\n    assert(rows > 0 && cols > 0);\r\n    Matrix* matrix = (Matrix*)malloc(sizeof(Matrix));\r\n    matrix->rows = rows;\r\n    matrix->cols = cols;\r\n    matrix->data = data;\r\n    return matrix;\r\n}\r\n\r\nMatrix* createMatrixZeroes(size_t rows, size_t cols){\r\n    assert(rows > 0 && cols > 0);\r\n    Matrix* matrix = (Matrix*)malloc(sizeof(Matrix));\r\n    matrix->rows = rows;\r\n    matrix->cols = cols;\r\n    float* data = (float*)calloc(rows * cols, sizeof(float));\r\n    matrix->data = data;\r\n    return matrix;\r\n}\r\n\r\ninline float getMatrix(Matrix* mat, size_t row, size_t col){\r\n    return mat->data[row * mat->cols + col];\r\n}\r\n\r\ninline void setMatrix(Matrix* mat, size_t row, size_t col, float val){\r\n    mat->data[row * mat->cols + col] = val;\r\n}\r\n\r\nvoid copyValuesInto(Matrix* from, Matrix* to){\r\n    assert(from->rows == to->rows && from->cols == to->cols);\r\n    memcpy(to->data, from->data, sizeof(float) * to->rows * to->cols);\r\n}\r\n\r\nvoid printMatrix(Matrix* input){\r\n    int i, j;\r\n    for (i = 0; i < input->rows; i++){\r\n        printf(\"\\n\");\r\n        for (j = 0; j < input->cols; j++){\r\n            printf(\"%.2f \", getMatrix(input, i, j));\r\n        }\r\n    }\r\n    printf(\"\\n\");\r\n}\r\n\r\nvoid zeroMatrix(Matrix* orig){\r\n    memset(orig->data, 0, orig->rows * orig->cols * sizeof(float));\r\n}\r\n\r\nMatrix* transpose(Matrix* orig){\r\n    float* data = (float*)malloc(sizeof(float) * orig->rows * orig->cols);\r\n    Matrix* transpose = createMatrix(orig->cols, orig->rows, data);\r\n    int i, j;\r\n    for (i = 0; i < orig->rows; i++){\r\n        for (j = 0; j < orig->cols; j++){\r\n            setMatrix(transpose, i, j, getMatrix(orig, i, j));\r\n        }\r\n    }\r\n    return transpose;\r\n}\r\n\r\nvoid transposeInto(Matrix* orig, Matrix* origT){\r\n    assert(orig->rows == origT->cols && orig->cols == origT->rows);\r\n    int i, j;\r\n    for (i = 0; i < orig->rows; i++){\r\n        for (j = 0; j < orig->cols; j++){\r\n            setMatrix(origT, j, i, getMatrix(orig, i, j));\r\n        }\r\n    }\r\n}\r\n\r\nMatrix* add(Matrix* A, Matrix* B){\r\n    assert(A->rows == B->rows && A->cols == B->cols);\r\n    float* data = (float*)malloc(sizeof(float) * A->rows * B->rows);\r\n    Matrix* result = createMatrix(A->rows, A->cols, data);\r\n    int i, j;\r\n    for (i = 0; i < A->rows; i++){\r\n        for (j = 0; j < A->cols; j++){\r\n            setMatrix(result, i, j, getMatrix(B, i, j) + getMatrix(A, i, j));\r\n        }\r\n    }\r\n    return result;\r\n}\r\n\r\nvoid matrix_mul_add(Matrix * to, float a, Matrix * x, float b, bool square = false) {\r\n\tassert(to->rows == x->rows && to->cols == x->cols);\r\n\tint i, j;\r\n\tfor (i = 0; i < to->rows; i++) {\r\n\t\tif (!square) {\r\n\t\t\tfor (j = 0; j < to->cols; j++)\r\n\t\t\t\tsetMatrix(to, i, j, getMatrix(to, i, j) * a + getMatrix(x, i, j) * b);\r\n\t\t}\r\n\t\telse for (j = 0; j < to->cols; j++) {\r\n\t\t\tfloat val = getMatrix(x, i, j);\r\n\t\t\tsetMatrix(to, i, j, getMatrix(to, i, j) * a + val * val * b);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid matrix_replace(Matrix * to, Matrix * x, float b) {\r\n\tassert(to->rows == x->rows && to->cols == x->cols);\r\n\tint i, j;\r\n\tfor (i = 0; i < to->rows; i++) {\r\n\t\tfor (j = 0; j < to->cols; j++)\r\n\t\t\tsetMatrix(to, i, j, getMatrix(x, i, j) * b);\r\n\t}\r\n}\r\n\r\nvoid adam_update(Matrix * to, Matrix * m, Matrix * v, float a) {\r\n\tassert(to->rows == m->rows && to->cols == m->cols);\r\n\tassert(to->rows == v->rows && to->cols == v->cols);\r\n\tint i, j;\r\n\tfor (i = 0; i < to->rows; i++) {\r\n\t\tfor (j = 0; j < to->cols; j++)\r\n\t\t\tsetMatrix(to, i, j, (getMatrix(m, i, j) * a) / (sqrt(getMatrix(v, i, j)) + 0.000000001));\r\n\t}\r\n}\r\n\r\nvoid addTo(Matrix* from, Matrix* to){\r\n    assert(from->rows == to->rows && from->cols == to->cols);\r\n    int i, j;\r\n    for (i = 0; i < from->rows; i++){\r\n        for (j = 0; j < from->cols; j++){\r\n            setMatrix(to, i, j, getMatrix(from, i, j) + getMatrix(to, i, j));\r\n        }\r\n    }\r\n}\r\n\r\n// add B to each row of A\r\nMatrix* addToEachRow(Matrix* A, Matrix* B){\r\n    assert(A->cols == B->cols && B->rows == 1);\r\n    float* data = (float*)malloc(sizeof(float) * A->rows * A->cols);\r\n    Matrix* result = createMatrix(A->rows, A->cols, data);\r\n    int i, j;\r\n    for (i = 0; i < A->rows; i++){\r\n        for (j = 0; j < A->cols; j++){\r\n            setMatrix(result, i, j, getMatrix(A, i, j) + getMatrix(B, 0, j));\r\n        }\r\n    }\r\n    return result;\r\n}\r\n\r\nvoid scalarMultiply(Matrix* orig, float c){\r\n    int i, j;\r\n    for (i = 0; i < orig->rows; i++){\r\n        for (j = 0; j < orig->cols; j++){\r\n            setMatrix(orig, i, j, getMatrix(orig, i, j) * c);\r\n        }\r\n    }\r\n}\r\n\r\nMatrix* multiply(Matrix* A, Matrix* B){\r\n    assert(A->cols == B->rows);\r\n    float* data = (float*)malloc(sizeof(float) * A->rows * B->cols);\r\n    Matrix* result = createMatrix(A->rows, B->cols, data);\r\n#ifdef CRANIUM_USE_BLAS\r\n    zeroMatrix(result);\r\n    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, A->rows, B->cols\r\n    , A->cols, 1, A->data, A->cols, B->data, B->cols, 1, result->data, result->cols);\r\n    return result;\r\n#endif\r\n    int i, j;\r\n    for (i = 0; i < A->rows; i++){\r\n        for (j = 0; j < B->cols; j++){\r\n            float sum = 0;\r\n            int k;\r\n            for (k = 0; k < B->rows; k++){\r\n                sum += getMatrix(A, i, k) * getMatrix(B, k, j);\r\n            }\r\n            setMatrix(result, i, j, sum);\r\n        }\r\n    }\r\n    return result;\r\n}\r\n\r\nvoid multiplyInto(Matrix* A, Matrix* B, Matrix* into){\r\n#ifdef CRANIUM_USE_BLAS\r\n    zeroMatrix(into);\r\n    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, A->rows, B->cols\r\n    , A->cols, 1, A->data, A->cols, B->data, B->cols, 1, into->data, into->cols);\r\n    return;\r\n#endif\r\n    assert(A->cols == B->rows);\r\n    assert(A->rows == into->rows && B->cols == into->cols);\r\n    int i, j;\r\n    for (i = 0; i < A->rows; i++){\r\n        for (j = 0; j < B->cols; j++){\r\n            float sum = 0;\r\n            int k;\r\n            for (k = 0; k < B->rows; k++){\r\n                sum += getMatrix(A, i, k) * getMatrix(B, k, j);\r\n            }\r\n            setMatrix(into, i, j, sum);\r\n        }\r\n    }\r\n}\r\n\r\nMatrix* hadamard(Matrix* A, Matrix* B){\r\n    assert(A->rows == B->rows && A->cols == B->cols);\r\n    float* data = (float*)malloc(sizeof(float) * A->rows * A->cols);\r\n    Matrix* result = createMatrix(A->rows, A->cols, data);\r\n    int i, j;\r\n    for (i = 0; i < A->rows; i++){\r\n        for (j = 0; j < A->cols; j++){\r\n            setMatrix(result, i, j, getMatrix(A, i, j) * getMatrix(B, i, j));\r\n        }\r\n    }\r\n    return result;\r\n}\r\n\r\nvoid hadamardInto(Matrix* A, Matrix* B, Matrix* into){\r\n    assert(A->rows == B->rows && A->cols == B->cols);\r\n    assert(A->rows == into->rows && A->cols == into->cols);\r\n    int i, j;\r\n    for (i = 0; i < A->rows; i++){\r\n        for (j = 0; j < A->cols; j++){\r\n            setMatrix(into, i, j, getMatrix(A, i, j) * getMatrix(B, i, j));\r\n        }\r\n    }\r\n}\r\n\r\nMatrix* copy(Matrix* orig){\r\n    float* data = (float*)malloc(sizeof(float) * orig->rows * orig->cols);\r\n    memcpy(data, orig->data, sizeof(float) * orig->cols * orig->rows);\r\n    return createMatrix(orig->rows, orig->cols, data);\r\n}\r\n\r\nint equals(Matrix* A, Matrix* B){\r\n    if (A->rows != B->rows){\r\n        return 0;\r\n    }\r\n    if (A->cols != B->cols){\r\n        return 0;\r\n    }\r\n    int i, j;\r\n    for (i = 0; i < A->rows; i++){\r\n        for (j = 0; j < A->cols; j++){\r\n            if (getMatrix(A, i, j) != getMatrix(B, i, j)){\r\n                return 0;\r\n            }\r\n        }\r\n    }\r\n    return 1;\r\n}\r\n\r\nvoid destroyMatrix(Matrix* matrix){\r\n    free(matrix->data);\r\n    free(matrix);\r\n}\r\n\r\n#endif", "meta": {"hexsha": "9ce3a18507c661ed2b77a945a9237231b0b2fee0", "size": 12707, "ext": "h", "lang": "C", "max_stars_repo_path": "cranium/src/matrix.h", "max_stars_repo_name": "ewail/DiaNN", "max_stars_repo_head_hexsha": "043090bdb60bcb77b51ebf6c56f8d19b43814eed", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2018-03-16T09:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T03:30:54.000Z", "max_issues_repo_path": "cranium/src/matrix.h", "max_issues_repo_name": "ewail/DiaNN", "max_issues_repo_head_hexsha": "043090bdb60bcb77b51ebf6c56f8d19b43814eed", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2018-04-18T03:00:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:35:58.000Z", "max_forks_repo_path": "cranium/src/matrix.h", "max_forks_repo_name": "ewail/DiaNN", "max_forks_repo_head_hexsha": "043090bdb60bcb77b51ebf6c56f8d19b43814eed", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T01:44:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T07:13:59.000Z", "avg_line_length": 29.4143518519, "max_line_length": 93, "alphanum_fraction": 0.5593767215, "num_tokens": 3703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.386036255610444}}
{"text": "/* multifit/covar.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multifit_nlin.h>\n#include <gsl/gsl_blas.h>\n\nint\ngsl_multifit_gradient (const gsl_matrix * J, const gsl_vector * f,\n                       gsl_vector * g)\n{\n  int status = gsl_blas_dgemv (CblasTrans, 1.0, J, f, 0.0, g);\n  return status;\n}\n  \n", "meta": {"hexsha": "ad04b63df3bb2eabf0d02a6d4bc0fbc10e357976", "size": 1122, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/multifit/gradient.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/multifit/gradient.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/multifit/gradient.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 33.0, "max_line_length": 72, "alphanum_fraction": 0.7121212121, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.38587959505100855}}
{"text": "/*! /file global.h\n *  /brief Declarations of global variables and functions. */\n\n\n#ifndef GLOBAL_H \n#define GLOBAL_H \n\n#ifdef COOLING_CPU\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_spline2d.h>\n#endif\n\n#if PRECISION == 1\n#ifndef FLOAT_TYPEDEF_DEFINED\ntypedef float Real;\n#endif //FLOAT_TYPEDEF_DEFINED\n#endif //PRECISION == 1\n#if PRECISION == 2\n#ifndef FLOAT_TYPEDEF_DEFINED\ntypedef double Real;\n#endif //FLOAT_TYPEDEF_DEFINED\n#endif //PRECISION == 2\n\n#define MAXLEN 100\n#define TINY_NUMBER 1.0e-20\n#define PI 3.141592653589793\n#define MP 1.672622e-24 // mass of proton, grams\n#define KB 1.380658e-16 // boltzmann constant, cgs\n//#define GN 6.67259e-8 // gravitational constant, cgs\n#define GN 4.49451e-18 // gravitational constant, kpc^3 / M_sun / kyr^2\n\n//#define TIME_UNIT 3.15569e10 // 1 kyr in s\n//#define LENGTH_UNIT 3.08567758e21 // 1 kpc in cm\n//#define MASS_UNIT 1.98855e33 // 1 solar mass in grams\n#define TIME_UNIT 60300.114856343294\n#define LENGTH_UNIT 310994529228.64191\n#define MASS_UNIT 2.6020994527238984e+18\n#define DENSITY_UNIT (MASS_UNIT/(LENGTH_UNIT*LENGTH_UNIT*LENGTH_UNIT)) \n#define VELOCITY_UNIT (LENGTH_UNIT/TIME_UNIT)\n#define ENERGY_UNIT (DENSITY_UNIT*VELOCITY_UNIT*VELOCITY_UNIT)\n#define PRESSURE_UNIT (DENSITY_UNIT*VELOCITY_UNIT*VELOCITY_UNIT)\n#define SP_ENERGY_UNIT (VELOCITY_UNIT*VELOCITY_UNIT)\n\n#ifdef SCALAR\n#define NSCALARS 1\n#endif\n\n\n#define SIGN(a) ( ((a) < 0.) ? -1. : 1. )\n\n\n\n/* Global variables */\nextern Real gama; // Ratio of specific heats\nextern Real C_cfl; // CFL number (0 - 0.5)\nextern Real t_comm;\nextern Real t_other;\n\n#ifdef COOLING_CPU\nextern gsl_interp_accel *acc;\nextern gsl_interp_accel *xacc;\nextern gsl_interp_accel *yacc;\nextern gsl_spline *highT_C_spline;\nextern gsl_spline2d *lowT_C_spline;\nextern gsl_spline2d *lowT_H_spline;\n#endif\n#ifdef COOLING_GPU\nextern float *cooling_table;\nextern float *heating_table;\n#endif\n\n/*! \\fn void Set_Gammas(Real gamma_in)\n *  \\brief Set gamma values for Riemann solver. */\nextern void Set_Gammas(Real gamma_in);\n\n/*! \\fn double get_time(void)\n *  \\brief Returns the current clock time. */ \nextern double get_time(void);\n\n/*! \\fn int sgn\n *  \\brief Mathematical sign function. Returns sign of x. */\nextern int sgn(Real x);\n\n#ifndef CUDA\n/*! \\fn Real calc_eta(Real cW[], Real gamma)\n *  \\brief Calculate the eta value for the H correction. */\nextern Real calc_eta(Real cW[], Real gamma);\n#endif\n\n\nstruct parameters\n{\n  int nx;\n  int ny;\n  int nz;\n  double tout;\n  double outstep;\n  Real gamma;\n  char init[MAXLEN];\n  int nfile;\n  int nfull;\n  Real xmin;\n  Real ymin;\n  Real zmin;\n  Real xlen;\n  Real ylen;\n  Real zlen;\n  int xl_bcnd;\n  int xu_bcnd;\n  int yl_bcnd;\n  int yu_bcnd;\n  int zl_bcnd;\n  int zu_bcnd;\n#ifdef   MPI_CHOLLA\n  int xlg_bcnd;\n  int xug_bcnd;\n  int ylg_bcnd;\n  int yug_bcnd;\n  int zlg_bcnd;\n  int zug_bcnd;\n#endif /*MPI_CHOLLA*/\n  char custom_bcnd[MAXLEN];\n  char outdir[MAXLEN];\n  Real rho;\n  Real vx;\n  Real vy;\n  Real vz;\n  Real P;\n  Real A;\n  Real rho_l;\n  Real v_l;\n  Real P_l;\n  Real rho_r;\n  Real v_r;\n  Real P_r;\n  Real diaph;\n#ifdef ROTATED_PROJECTION\n  int nxr;\n  int nzr;\n  Real delta;\n  Real theta;\n  Real phi;\n  Real Lx;\n  Real Lz;\n  int n_delta;\n  Real ddelta_dt;\n  int flag_delta;\n#endif /*ROTATED_PROJECTION*/\n  // added by TRW\n  int ncycle_out; // controls freq of output to screen\n  Real my_reals[99]; // an array to hold an additional 99 parameters\n\n};\n\n\n/*! \\fn void parse_params(char *param_file, struct parameters * parms);\n *  \\brief Reads the parameters in the given file into a structure. */\nextern void parse_params (char *param_file, struct parameters * parms);\n\n\n#endif //GLOBAL_H\n", "meta": {"hexsha": "37b546016a23f9bc66cafea5ea397c5a9b2073c5", "size": 3620, "ext": "h", "lang": "C", "max_stars_repo_path": "src/global.h", "max_stars_repo_name": "twaters/cholla", "max_stars_repo_head_hexsha": "65842e8d352635f4994ac24647e9c5abb2b72a79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/global.h", "max_issues_repo_name": "twaters/cholla", "max_issues_repo_head_hexsha": "65842e8d352635f4994ac24647e9c5abb2b72a79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/global.h", "max_forks_repo_name": "twaters/cholla", "max_forks_repo_head_hexsha": "65842e8d352635f4994ac24647e9c5abb2b72a79", "max_forks_repo_licenses": ["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.3456790123, "max_line_length": 71, "alphanum_fraction": 0.7284530387, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.38566038773005334}}
{"text": "/* ============================================================ *\n * halomodel.h\t\t\t\t\t\t\t*\n * Martin Kilbinger 2006-2009\t\t\t\t\t*\n * ============================================================ */\n\n#ifndef __HALOMODEL_H\n#define __HALOMODEL_H\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <assert.h>\n#include <string.h>\n#include <fftw3.h>\n\n\n#include <gsl/gsl_sf_erf.h>\n\n#include \"io.h\"\n#include \"errorlist.h\"\n#include \"config.h\"\n#include \"maths.h\"\n\n#include \"cosmo.h\"\n#include \"nofz.h\"\n\n#define hm_base     -1900\n#define hm_hodtype   hm_base + 1\n#define hm_Mmin      hm_base + 2\n#define hm_pofk      hm_base + 3\n#define hm_nfw       hm_base + 4\n#define hm_par       hm_base + 5\n#define hm_overflow  hm_base + 6\n#define hm_io        hm_base + 7\n#define hm_zbin      hm_base + 8\n#define hm_alpha     hm_base + 9\n#define hm_negative  hm_base + 10\n#define hm_zmean_2h  hm_base + 11\n#define hm_halo_bias hm_base + 12\n#define hm_undef     hm_base + 13\n#define hm_gsl_int   hm_base + 14\n\n/* Ranges of interpolation tables */\n#define k_max_HOD     3336.0\n\n/* Present critical density [M_sol h^2 / Mpc^3] */\n#define rho_c0  2.7754e11\n\n/* Mass limits for integration over mass functions */\n#define logMmin (3.0*log(10.0))\n#define logMmax (16.0*log(10.0))\n\n/* Number of steps for scale-factor-integration (redshift) */\n#define Na_hm 20\n\n/* Bit-coded power spectrum types */\ntypedef enum {pofk_undef=-1, pl=1, pnl=2, p1hdm=4, p2hdm=8, pthdm=16, p1hg=32, p2hg=64, pthg=128,\n\t      p1hgcs=256, p1hgss=512, pstellar=1024} pofk_t;\n\n/* Halo mass function type */\ntypedef enum {ps, st, st2, j01} massfct_t;\n#define smassfct_t(i) ( \\\n  i==ps  ? \"ps\" : \\\n  i==st  ? \"st\" : \\\n  i==st2 ? \"st2\" : \\\n  i==j01 ? \"j01\" : \\\n  \"\")\n#define Nmassfct_t 4\n\n/* Halo bias type */\ntypedef enum {halo_bias_sc, halo_bias_tinker05, halo_bias_tinker10} halo_bias_t;\n#define shalo_bias_t(i) ( \\\n   i==halo_bias_sc       ? \"halo_bias_sc\" : \\\n   i==halo_bias_tinker05 ? \"halo_bias_tinker05\" : \\\n   i==halo_bias_tinker10 ? \"halo_bias_tinker10\" : \\\n   \"\")\n#define Nhalo_bias_t 3\n\n/* HOD (Halo occupation distribution) type */\n#define Nhod_t 5\ntypedef enum {hod_none, hamana04, berwein02, berwein02_hexcl, leauthaud11} hod_t;\n#define shod_t(i) (\t\t\\\n i==hod_none  ? \"hod_none\" :\t\\\n i==hamana04  ? \"hamana04\" :\t\\\n i==berwein02 ? \"berwein02\" :\t\\\n i==berwein02_hexcl ? \"berwein02_hexcl\" :\\\n i==leauthaud11 ? \"leauthaud11\" :\t\\\n \"\")\n\n\n/* ---------------------------------------------------------------- *\n * Global variables and functions                                   *\n * ---------------------------------------------------------------- */\n\ndouble FFTLog_TMP;\n\ntypedef struct FFTLog_complex\n{\n  double re;\n  double im;\n  double amp;\n  double arg;\n}  FFTLog_complex;\n\ntypedef struct {\n  int N;\n  fftw_plan p_forward;\n  fftw_plan p_backward;\n  fftw_complex *an;\n  fftw_complex *ak;\n  fftw_complex *cm;\n  fftw_complex *um;\n  fftw_complex *cmum;\n  double min;\n  double max;\n  double q;\n  double mu;\n  double kr;\n} FFTLog_config;\n\n\n\ntypedef struct {\n  \n  cosmo *cosmo;\n  redshift_t *redshift;\n  double zmin, zmax;\n  \n  /* Dark matter halo profile                                                      */\n  double c0;\t\t\t/* concentration parameter                         */\n  double alpha_NFW;\t\t/* density slope                                   */\n  double beta_NFW;\t\t/* concentration slope as fct of mass              */\n  massfct_t massfct;            /* halo mass function\t\t\t\t   */\n  halo_bias_t halo_bias;        /* Halo bias                                       */\n  \n  /* Mass function parameters (Sheth&Torman). Do not set manually, they are set    *\n   * in set_massfct() according to enum massfct.\t\t\t\t   */\n  double nmz_a;                 /* Called q in CS02                                */\n  double nmz_p;                 /* a=1, p=1/2 is Press-Schechter mass fct.         */\n  \n  /* HOD (halo occupation distribution) parameters\t\t\t\t   */\n  hod_t hod;                    /* HOD type                                        */\n  double M1, M0, sigma_log_M;\n  double M_min;\n  double alpha;\n  double pi_max;  \n  double eta;                   /* central galaxy proportion                       */\n\n  /* galaxy-galaxy lensing and wp(rp) */\n  double log10Mhalo;\n  double coord_phys;\n\n  /* For Leauthaud11 model                                                         */\n  double beta,delta,gamma,Mstar0;\n  double beta_sat,B_sat,beta_cut,B_cut;\n  double x;                     /* any parameter to propagate if needed            */\n  double Mstellar_min, Mstellar_max;\n  double fcen1, fcen2;\n  \n  /* Precomputed stuff */\n  double A;\t\t\t/* Mass function normalisation                     */\n  double Mstar;                 /* M_*(a=1.0)\t\t\t\t\t   */\n  interTable2D *Pthdm;\n  interTable *xir;\n  interTable *xi_dm;\n  interTable2D *rhohat;\n  splineTable* sigRsqr;\n  double a_xir;\n\n  /* FFTLOG flag - OBSOLETE */\n  int FFTLog;\n\n} cosmo_hm;\n\n\ntypedef struct {\n  \n  cosmo    *cosmo;\n  cosmo_hm *model;\n  double   a, r, k, ng, ngp, eps, c;\n  double  logMlim, bias_fac, Mh, Mstellar, Mstellar_min, Mstellar_max;\n  double  M, r_vir, *kk;\n  error    **err;\n  \n  double   logrmin, logrmax, rp, xi;\n  gsl_interp_accel *acc;\n  gsl_spline *spline;\n  \n  int i, j, type, asymptotic, logintegrate;\n  \n  double   (*bias_func)(double, void *);\n} cosmo_hm_params;\n\n\n\ntypedef struct gsl_int_params\n{\n  void *params;\n  funcwithpars func;\n  error **err;\n\n} gsl_int_params;\n\n\n\ntypedef struct { \n  double *z;\n  double *fac;\n  double *ypn; /* for spline interpolation */\n  double zm;   /* average weighted redshift*/ \n  int nbins;\n} nz_t;\n\ncosmo_hm* init_parameters_hm(double OMEGAM, double OMEGADE, double W0_DE, double W1_DE,\n\t\t\t     double *W_POLY_DE, int N_POLY_DE,\n\t\t\t     double H100, double OMEGAB, double OMEGANUMASS, \n\t\t\t     double NEFFNUMASS, double NORM, double NSPEC,\n\t\t\t     int Nzbin, const int *Nnz, const nofz_t *nofz, double *par_nz,\n\t\t\t     double zmin, double zmax,\n\t\t\t     nonlinear_t NONLINEAR, transfer_t TRANSFER, growth_t GROWTH,\n\t\t\t     de_param_t DEPARAM, norm_t normmode,\n\t\t\t     double C0, double ALPHANFW, double BETANFW, massfct_t MASSFCT, halo_bias_t HALO_BIAS,\n\t\t\t     double M_min, double M1, double M0, double sigma_log_M, double alpha,\n\t\t\t     double Mstar0, double beta, double delta, double gamma, double B_cut, double B_sat, \n\t\t\t     double beta_cut, double beta_sat, double Mstellar_min, double Mstellar_max, double eta,\n\t\t\t     double fcen1, double fcen2,\n\t\t\t     hod_t HOD, double pi_max, error **err);\n\ncosmo_hm* copy_parameters_hm_only(cosmo_hm* source, error **err);\ncosmo_hm *copy_parameters_hm(cosmo_hm *source, error **err);\nvoid read_cosmological_parameters_hm(cosmo_hm **model, FILE *F, error **err);\ncosmo_hm *set_cosmological_parameters_to_default_hm(error **err);\nvoid free_parameters_hm(cosmo_hm** model);\n\nvoid set_massfct(massfct_t massfct, double *nmz_a, double *nmz_p, error **err);\nvoid dump_param_only_hm(cosmo_hm* model, FILE *F);\nvoid dump_param_hm(cosmo_hm* model, FILE *F, error **err);\n\ndouble sm2_rtbis(double (*func)(double, void *, error **), double x1, double x2,\n\t\t double xacc, void *param, error **err);\n\n/* From nrcomplex.h,c */\n#ifndef _DCOMPLEX_DECLARE_T_\ntypedef struct DCOMPLEX {double r,i;} dcomplex;\n#define _DCOMPLEX_DECLARE_T_\n#endif /* _DCOMPLEX_DECLARE_T_ */\ndcomplex Complex(double re, double im);\ndcomplex Cadd(dcomplex a, dcomplex b);\ndcomplex Cmul(dcomplex a, dcomplex b);\ndcomplex Cdiv(dcomplex a, dcomplex b);\ndcomplex RCmul(double x, dcomplex a);\nvoid sm2_cisi(double x, double *ci, double *si, error **err);\n\n\ndouble delta_c(cosmo *model, double a, error **err);\ndouble bis_Mstar(double logM, void *param, error **err);\ndouble bis_Mstar_a(double logM, void *param, error **err);\ndouble Mstar(cosmo_hm *model, error **err);\ndouble Mstar_a(cosmo_hm *model, double a, error **err);\ndouble concentration(cosmo_hm *model, double Mh, double a, error **err);\ndouble Delta_vir(cosmo_hm *model, double a);\ndouble dsigma_R_sqr_dR(cosmo_hm *model, double R, error **err);\ndouble nufnu(cosmo_hm *model, double nu, int asymptotic, error **err);\ndouble nufnu_j01(double x);\ndouble sigma_R_sqr(cosmo_hm *model, double R, error **err);\ndouble sigmasqr_M(cosmo_hm *model, double M, error **err);\n\ndouble dsigma_m1_dlnM(cosmo_hm *model, double M, error **err);\ndouble dnu_dlnM(cosmo_hm *model, double M, double a, error **err);\ndouble dn_dlnM_lnM(double logM, void *intpar, error **err);\ndouble dn_dlnM_uf(double M, cosmo_hm *model, double a, error **err);\ndouble dn_dlnM(double M, void *intpar, error **err);\n\ndouble r_vir(cosmo_hm *model, double M, double a, error **err);\ndouble M_vir(cosmo_hm *model, double r_vir, double a, error **err);\ndouble Delta_h(cosmo_hm *model, double a, error **err);\ndouble rho_crit(cosmo_hm *model, double a, error **err);\ndouble rho_crit_halo(cosmo_hm *model, double a, error **err);\ndouble Omega_m_halo(cosmo_hm *model, double a, error **err);\ndouble rho_halo(cosmo_hm *model, double r, double a, double Mh, double c, error **err);\n\ndouble DeltaSigma_WB2000(cosmo_hm *model, double r, const double a, const double M,  double c,  double Delta, error **err);\ndouble g_inf(double x, error **err);\ndouble g_sup(double x, error **err);\n\ndouble int_for_rhohat(double, void *, error **err);\ndouble rhohat_halo(cosmo_hm *model, double k, double M, double a, double c, error **err);\n\n\ndouble halo_bias(cosmo_hm *model, double M, double a, int k, error **err);\ndouble bias(cosmo_hm *model, double M, double a, int k, error **err);\ndouble bias_tinker(cosmo_hm *model, double M, double a, error **err);\ndouble bias_tinker10(cosmo_hm *model, double M, double a, error **err);\ndouble int_for_bias_norm(double logM, void *intpar, error **err);\ndouble bias_norm(cosmo_hm *model, double a, error **err);\n\ndouble int_for_M_ij(double, void *, error **);\ndouble M_ij(cosmo_hm *model, int i, int j, double a, const double *k, error **err);\ndouble P1h_dm(cosmo_hm *model, double a, double k, error **err);\ndouble P2h_dm(cosmo_hm *model, double a, double k, error **err);\n\ndouble xi_dm_NL_OBSOLETE(cosmo_hm *model, double a, double r, error **err);  // non-linear DM xi\ndouble int_for_xi_dm_NL_OBSOLETE(double k, void *intpar,  error **err);  // non-linear DM xi\n\n#define CHANGE(fct) int change_##fct(cosmo_hm*, cosmo_hm*)\n\n/* ---------------------------------------------------------------- *\n * Utils                                                            *\n * ---------------------------------------------------------------- */\n\ndouble int_gsl(funcwithpars func,void *params, double a, double b, double eps, error **err);\ndouble integrand_gsl(double x,void *p);\n\nCHANGE(massfct);\nCHANGE(massfct_params);\nCHANGE(halo_bias);\nCHANGE(sigma_R_sqr);\nCHANGE(Mstar);\nCHANGE(rhohat_halo);\nCHANGE(Pth);\n\n#undef CHANGE\n\n\n#endif\n\n", "meta": {"hexsha": "d2add04fcf6646f471973cc0fdaf3ac0bad48ce3", "size": 10747, "ext": "h", "lang": "C", "max_stars_repo_path": "src/nicaea_2.5/halomodel/include/halomodel.h", "max_stars_repo_name": "danielgruen/ccv", "max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z", "max_issues_repo_path": "src/nicaea_2.5/halomodel/include/halomodel.h", "max_issues_repo_name": "danielgruen/ccv", "max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nicaea_2.5/halomodel/include/halomodel.h", "max_forks_repo_name": "danielgruen/ccv", "max_forks_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_forks_repo_licenses": ["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.8654434251, "max_line_length": 123, "alphanum_fraction": 0.6379454732, "num_tokens": 3151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7772998560157663, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3856136622180558}}
{"text": "/** \n * Simple and fast kmeans-implementation making use of multithreading.\n *\n * Author: Anders Bennehag\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Anders Bennehag\n *\n */\n#ifndef FASTKMEANS_H_\n#define FASTKMEANS_H_\n\n#include <gsl/gsl_matrix.h>\n\nint fkm_kmeans(const gsl_matrix* points, gsl_matrix* clusters,\n               size_t max_iter, int num_threads);\n\ngsl_matrix* fkm_matrix_load(FILE* fout);\nint fkm_matrix_save(FILE* fout, gsl_matrix* mat);\n\n#define WHERESTR  \"[%s:%d]: \"\n#define WHEREARG  __FILE__, __LINE__\n#define DEBUGPRINT2(...)       fprintf(stderr, __VA_ARGS__)\n\n#define FKM_LOGFMT(_fmt, ...)  DEBUGPRINT2(WHERESTR _fmt \"\\n\", WHEREARG, __VA_ARGS__)\n#define FKM_LOG(_s) DEBUGPRINT2(WHERESTR \"%s\\n\", WHEREARG, _s)\n#define FKM_LOGTYPE(_tp, _s)  DEBUGPRINT2(WHERESTR \"%s: %s\" \"\\n\", WHEREARG, _tp, _s)\n#define FKM_LOGTYPEFMT(_tp, _fmt, ...)  DEBUGPRINT2(WHERESTR \"%s: \" _fmt \"\\n\", WHEREARG, _tp, __VA_ARGS__)\n\n#if (ISDEBUG + 0)\n    #define FKM_DEBUGFMT(_fmt, ...)  FKM_LOGTYPEFMT(\"DEBUG\", _fmt, __VA_ARGS__)\n    #define FKM_DEBUG(_s)  FKM_LOGTYPE(\"DEBUG\", _s)\n#else\n    #define FKM_DEBUGFMT(...)\n    #define FKM_DEBUG(...)\n#endif\n#define FKM_INFOFMT(_fmt, ...)   FKM_LOGTYPEFMT(\"INFO\", _fmt, __VA_ARGS__)\n#define FKM_WARNFMT(_fmt, ...)   FKM_LOGTYPEFMT(\"WARN\", _fmt, __VA_ARGS__)\n#define FKM_ERRORFMT(_fmt, ...)  FKM_LOGTYPEFMT(\"ERROR\", _fmt, __VA_ARGS__)\n\n#define FKM_INFO(_s)   FKM_LOGTYPE(\"INFO\", _s)\n#define FKM_WARN(_s)   FKM_LOGTYPE(\"WARN\", _s)\n#define FKM_ERROR(_s)  FKM_LOGTYPE(\"ERROR\", _s)\n\n\n#endif\n", "meta": {"hexsha": "8d7b7bafd0d6c441be58d444e0797e2dfe427c17", "size": 1530, "ext": "h", "lang": "C", "max_stars_repo_path": "include/fastkmeans/fastkmeans.h", "max_stars_repo_name": "PureW/fast-kmeans", "max_stars_repo_head_hexsha": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/fastkmeans/fastkmeans.h", "max_issues_repo_name": "PureW/fast-kmeans", "max_issues_repo_head_hexsha": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/fastkmeans/fastkmeans.h", "max_forks_repo_name": "PureW/fast-kmeans", "max_forks_repo_head_hexsha": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd", "max_forks_repo_licenses": ["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.875, "max_line_length": 106, "alphanum_fraction": 0.7013071895, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.38524084905321404}}
{"text": "#include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h\"\n#include <gsl/gsl_sf.h>\nint main(int argc, const char * argv[]) {\nunsigned long int hexdouble;\nint a;\na = atoi(argv[1]);\nint b;\nb = atoi(argv[2]);\nint c;\nc = atoi(argv[3]);\nint d;\nd = atoi(argv[4]);\nint e;\ne = atoi(argv[5]);\nint f;\nf = atoi(argv[6]);\ndouble result = gsl_sf_coupling_6j(a, b, c, d, e, f);\n//printf(\"%.15f\\n\", result);\nVALGRIND_PRINT_ERROR(\"result\", &result);\nreturn 0;\n}", "meta": {"hexsha": "0243eebe16e740398d6a7f257587751215dea4d7", "size": 504, "ext": "c", "lang": "C", "max_stars_repo_path": "others_ori/gsl_sf_coupling_6j.c", "max_stars_repo_name": "floatfeather/FpGenetic", "max_stars_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "others_ori/gsl_sf_coupling_6j.c", "max_issues_repo_name": "floatfeather/FpGenetic", "max_issues_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others_ori/gsl_sf_coupling_6j.c", "max_forks_repo_name": "floatfeather/FpGenetic", "max_forks_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_forks_repo_licenses": ["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.9130434783, "max_line_length": 78, "alphanum_fraction": 0.6607142857, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3852408316827809}}
{"text": "/**\n *\n * @file core_claset.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @date 2010-11-15\n * @generated c Tue Jan  7 11:44:48 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex32_t\n *\n *  CORE_claset - Sets the elements of the matrix A on the diagonal\n *  to beta and on the off-diagonals to alpha\n *\n *******************************************************************************\n *\n * @param[in] uplo\n *          Specifies which elements of the matrix are to be set\n *          = PlasmaUpper: Upper part of A is set;\n *          = PlasmaLower: Lower part of A is set;\n *          = PlasmaUpperLower: ALL elements of A are set.\n *\n * @param[in] M\n *          The number of rows of the matrix A.  M >= 0.\n *\n * @param[in] N\n *         The number of columns of the matrix A.  N >= 0.\n *\n * @param[in] alpha\n *         The constant to which the off-diagonal elements are to be set.\n *\n * @param[in] beta\n *         The constant to which the diagonal elements are to be set.\n *\n * @param[in,out] A\n *         On entry, the M-by-N tile A.\n *         On exit, A has been set accordingly.\n *\n * @param[in] LDA\n *         The leading dimension of the array A.  LDA >= max(1,M).\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_claset = PCORE_claset\n#define CORE_claset PCORE_claset\n#endif\nvoid CORE_claset(PLASMA_enum uplo, int M, int N,\n                 PLASMA_Complex32_t alpha, PLASMA_Complex32_t beta,\n                 PLASMA_Complex32_t *A, int LDA)\n{\n    LAPACKE_claset_work(\n        LAPACK_COL_MAJOR,\n        lapack_const(uplo),\n        M, N, alpha, beta, A, LDA);\n}\n\n", "meta": {"hexsha": "afc9bb42b936c552217303d89d1d79c4eb09c7e0", "size": 1859, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_claset.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_claset.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_claset.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.7462686567, "max_line_length": 80, "alphanum_fraction": 0.5685852609, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.3851656462815392}}
{"text": "/**\n *\n * @file dsungesv.c\n *\n *  PLASMA computational routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Emmanuel Agullo\n * @date 2010-11-15\n * @generated ds Tue Jan  7 11:45:09 2014\n *\n **/\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <lapacke.h>\n#include \"common.h\"\n\n#define PLASMA_dlag2s(_descA, _descSB)                \\\n  plasma_parallel_call_4(plasma_pdlag2s,              \\\n                         PLASMA_desc,      (_descA),  \\\n                         PLASMA_desc,      (_descSB), \\\n                         PLASMA_sequence*, sequence,  \\\n                         PLASMA_request*,  request)\n\n#define PLASMA_slag2d(_descSA, _descB)                \\\n  plasma_parallel_call_4(plasma_pslag2d,              \\\n                         PLASMA_desc,      (_descSA), \\\n                         PLASMA_desc,      (_descB),  \\\n                         PLASMA_sequence*, sequence,  \\\n                         PLASMA_request*,  request)\n\n#define PLASMA_dlange(_norm, _descA, _result, _work)   \\\n  _result = 0;                                         \\\n  plasma_parallel_call_6(plasma_pdlange,               \\\n                         PLASMA_enum,      (_norm),    \\\n                         PLASMA_desc,      (_descA),   \\\n                         double*,          (_work),    \\\n                         double*,          &(_result), \\\n                         PLASMA_sequence*, sequence,   \\\n                         PLASMA_request*,  request);\n\n#define PLASMA_dlacpy(_descA, _descB)                        \\\n  plasma_parallel_call_5(plasma_pdlacpy,                     \\\n                         PLASMA_enum,      PlasmaUpperLower, \\\n                         PLASMA_desc,      (_descA),         \\\n                         PLASMA_desc,      (_descB),         \\\n                         PLASMA_sequence*, sequence,         \\\n                         PLASMA_request*,  request)\n\n#define PLASMA_dgeadd(_alpha, _descA, _descB)                 \\\n  plasma_parallel_call_5(plasma_pdgeadd,                      \\\n                         double, (_alpha),        \\\n                         PLASMA_desc,        (_descA),        \\\n                         PLASMA_desc,        (_descB),        \\\n                         PLASMA_sequence*,   sequence,        \\\n                         PLASMA_request*,    request)\n\n/***************************************************************************//**\n *\n * @ingroup double\n *\n *  PLASMA_dsungesv - Solves overdetermined or underdetermined linear systems involving an M-by-N\n *  matrix A using the QR or the LQ factorization of A.  It is assumed that A has full rank.\n *  The following options are provided:\n *\n *  # trans = PlasmaNoTrans and M >= N: find the least squares solution of an overdetermined\n *    system, i.e., solve the least squares problem: minimize || B - A*X ||.\n *\n *  # trans = PlasmaNoTrans and M < N:  find the minimum norm solution of an underdetermined\n *    system A * X = B.\n *\n *  Several right hand side vectors B and solution vectors X can be handled in a single call;\n *  they are stored as the columns of the M-by-NRHS right hand side matrix B and the N-by-NRHS\n *  solution matrix X.\n *\n *  PLASMA_dsungesv first attempts to factorize the matrix in COMPLEX and use this\n *  factorization within an iterative refinement procedure to produce a\n *  solution with COMPLEX*16 normwise backward error quality (see below).\n *  If the approach fails the method switches to a COMPLEX*16\n *  factorization and solve.\n *\n *  The iterative refinement is not going to be a winning strategy if\n *  the ratio COMPLEX performance over COMPLEX*16 performance is too\n *  small. A reasonable strategy should take the number of right-hand\n *  sides and the size of the matrix into account. This might be done\n *  with a call to ILAENV in the future. Up to now, we always try\n *  iterative refinement.\n *\n *  The iterative refinement process is stopped if ITER > ITERMAX or\n *  for all the RHS we have: RNRM < N*XNRM*ANRM*EPS*BWDMAX\n *  where:\n *\n *  - ITER is the number of the current iteration in the iterative refinement process\n *  - RNRM is the infinity-norm of the residual\n *  - XNRM is the infinity-norm of the solution\n *  - ANRM is the infinity-operator-norm of the matrix A\n *  - EPS is the machine epsilon returned by DLAMCH('Epsilon').\n *\n *  Actually, in its current state (PLASMA 2.1.0), the test is slightly relaxed.\n *\n *  The values ITERMAX and BWDMAX are fixed to 30 and 1.0D+00 respectively.\n *\n *  We follow Bjorck's algorithm proposed in \"Iterative Refinement of Linear\n *  Least Squares solutions I\", BIT, 7:257-278, 1967.4\n *\n *******************************************************************************\n *\n * @param[in] trans\n *          Intended usage:\n *          = PlasmaNoTrans:   the linear system involves A;\n *          = PlasmaTrans: the linear system involves A**H.\n *          Currently only PlasmaNoTrans is supported.\n *\n * @param[in] N\n *          The number of columns of the matrix A. N >= 0.\n *\n * @param[in] NRHS\n *          The number of right hand sides, i.e., the number of columns of the matrices B and X.\n *          NRHS >= 0.\n *\n * @param[in] A\n  *          The M-by-N matrix A. This matrix is not modified.\n *\n * @param[in] LDA\n *          The leading dimension of the array A. LDA >= max(1,M).\n *\n * @param[in] B\n *          The M-by-NRHS matrix B of right hand side vectors, stored columnwise. Not modified.\n *\n * @param[in] LDB\n *          The leading dimension of the array B. LDB >= MAX(1,M,N).\n *\n * @param[out] X\n *          If return value = 0, the solution vectors, stored columnwise.\n *          if M >= N, rows 1 to N of B contain the least squares solution vectors; the residual\n *          sum of squares for the solution in each column is given by the sum of squares of the\n *          modulus of elements N+1 to M in that column;\n *          if M < N, rows 1 to N of B contain the minimum norm solution vectors;\n *\n * @param[in] LDX\n *          The leading dimension of the array B. LDB >= MAX(1,M,N).\n *\n * @param[out] ITER\n *          The number of the current iteration in the iterative refinement process\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *          \\retval <0 if -i, the i-th argument had an illegal value\n *\n *******************************************************************************\n *\n * @sa PLASMA_dsungesv_Tile\n * @sa PLASMA_dsungesv_Tile_Async\n * @sa PLASMA_dsungesv\n * @sa PLASMA_dgels\n *\n ******************************************************************************/\nint PLASMA_dsungesv(PLASMA_enum trans, int N, int NRHS,\n                    double *A, int LDA,\n                    double *B, int LDB,\n                    double *X, int LDX, int *ITER)\n{\n    int NB;\n    int status;\n    PLASMA_desc  descA;\n    PLASMA_desc  descB;\n    PLASMA_desc *descT;\n    PLASMA_desc  descX;\n    plasma_context_t *plasma;\n    PLASMA_sequence *sequence = NULL;\n    PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_dsungesv\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n\n    *ITER = 0;\n\n    /* Check input arguments */\n    if (trans != PlasmaNoTrans   && \n        trans != PlasmaTrans &&\n        trans != PlasmaTrans ) \n    {\n        plasma_error(\"PLASMA_dsungesv\", \"illegal value of trans\");\n        return -1;\n    }\n    if (trans != PlasmaNoTrans) {\n        plasma_error(\"PLASMA_dsungesv\", \"only PlasmaNoTrans supported\");\n        return PLASMA_ERR_NOT_SUPPORTED;\n    }\n    if (N < 0) {\n        plasma_error(\"PLASMA_dsungesv\", \"illegal value of N\");\n        return -2;\n    }\n    if (NRHS < 0) {\n        plasma_error(\"PLASMA_dsungesv\", \"illegal value of NRHS\");\n        return -3;\n    }\n    if (LDA < max(1, N)) {\n        plasma_error(\"PLASMA_dsungesv\", \"illegal value of LDA\");\n        return -5;\n    }\n    if (LDB < max(1, N)) {\n        plasma_error(\"PLASMA_dsungesv\", \"illegal value of LDB\");\n        return -7;\n    }\n    if (LDX < max(1, N)) {\n        plasma_error(\"PLASMA_dsungesv\", \"illegal value of LDX\");\n        return -9;\n    }\n\n    /* Quick return */\n    if ( N == 0 )\n        return PLASMA_SUCCESS;\n\n    /* Tune NB & IB depending on M, N & NRHS; Set NBNB */\n    status = plasma_tune(PLASMA_FUNC_DSGELS, N, N, NRHS);\n    if (status != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_dsungesv\", \"plasma_tune() failed\");\n        return status;\n    }\n\n    NB = PLASMA_NB;\n\n    plasma_sequence_create(plasma, &sequence);\n\n    /* DOUBLE PRECISION INITIALIZATION */\n    if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n        plasma_dooplap2tile( descA, A, NB, NB, LDA, N,    0, 0, N, N,    sequence, &request,\n                             plasma_desc_mat_free(&(descA)) );\n        plasma_dooplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS, sequence, &request,\n                             plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB)) );\n        plasma_ddesc_alloc(  descX, NB, NB, N, NRHS, 0, 0, N, NRHS, plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB)); plasma_desc_mat_free(&(descX)) );\n    } else {\n        plasma_diplap2tile( descA, A, NB, NB, LDA, N,    0, 0, N, N,   \n                            sequence, &request);\n        plasma_diplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS,\n                            sequence, &request);\n\n        descX = plasma_desc_init(\n            PlasmaRealDouble, NB, NB, (NB*NB), \n            LDX, NRHS, 0, 0, N, NRHS);\n        descX.mat = X;\n    }\n\n    /* Allocate workspace */\n    PLASMA_Alloc_Workspace_dgels_Tile(N, N, &descT);\n\n    /* Call the native interface */\n    status = PLASMA_dsungesv_Tile_Async(PlasmaNoTrans, &descA, descT, &descB, &descX, ITER,\n                                        sequence, &request);\n\n    if (status == PLASMA_SUCCESS) {\n        if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n            plasma_dooptile2lap( descX, X, NB, NB, LDX, NRHS,  sequence, &request);\n            plasma_dynamic_sync();\n            plasma_desc_mat_free(&descA);\n            plasma_desc_mat_free(&descB);\n            plasma_desc_mat_free(&descX);\n        } else {\n            plasma_diptile2lap( descA, A, NB, NB, LDA, N,     sequence, &request);\n            plasma_diptile2lap( descB, B, NB, NB, LDB, NRHS,  sequence, &request);\n            plasma_diptile2lap( descX, X, NB, NB, LDX, NRHS,  sequence, &request);\n            plasma_dynamic_sync();\n        }\n    }\n\n    PLASMA_Dealloc_Handle_Tile(&descT);\n    plasma_sequence_destroy(plasma, sequence);\n    return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup double_Tile\n *\n *  PLASMA_dsungesv_Tile - Solves symmetric linear system of equations using the tile QR\n *  or the tile LQ factorization and mixed-precision iterative refinement.\n *  Tile equivalent of PLASMA_dsungesv().\n *  Operates on matrices stored by tiles.\n *  All matrices are passed through descriptors.\n *  All dimensions are taken from the descriptors.\n *\n *******************************************************************************\n *\n * @param[in] trans\n *          Intended usage:\n *          = PlasmaNoTrans:   the linear system involves A;\n *          = PlasmaTrans: the linear system involves A**H.\n *          Currently only PlasmaNoTrans is supported.\n *\n * @param[in,out] A\n *          - If the iterative refinement converged, A is not modified;\n *          - otherwise, it fell back to double precision solution, and\n *          on exit the M-by-N matrix A contains:\n *          if M >= N, A is overwritten by details of its QR factorization as returned by\n *                     PLASMA_dgeqrf;\n *          if M < N, A is overwritten by details of its LQ factorization as returned by\n *                      PLASMA_dgelqf.\n *\n * @param[out] T\n *          On exit:\n *          - if the iterative refinement converged, T is not modified;\n *          - otherwise, it fell back to double precision solution,\n *          and then T is an auxiliary factorization data.\n *\n * @param[in,out] B\n *          On entry, the M-by-NRHS matrix B of right hand side vectors, stored columnwise;\n * @param[in] B\n *          The N-by-NRHS matrix of right hand side matrix B.\n *\n * @param[out] X\n *          If return value = 0, X is the solution vectors, stored columnwise:\n *          if M >= N, rows 1 to N of X contain the least squares solution vectors; the residual\n *          sum of squares for the solution in each column is given by the sum of squares of the\n *          modulus of elements N+1 to M in that column;\n *          if M < N, rows 1 to N of X contain the minimum norm solution vectors;\n *\n * @param[out] ITER\n *          The number of the current iteration in the iterative refinement process\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *\n *******************************************************************************\n *\n * @sa PLASMA_dsungesv\n * @sa PLASMA_dsungesv_Tile_Async\n * @sa PLASMA_dsungesv_Tile\n * @sa PLASMA_dgels_Tile\n *\n ******************************************************************************/\nint PLASMA_dsungesv_Tile(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T,\n                         PLASMA_desc *B, PLASMA_desc *X, int *ITER)\n{\n    plasma_context_t *plasma;\n    PLASMA_sequence *sequence = NULL;\n    PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n    int status;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_dsungesv_Tile\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n    plasma_sequence_create(plasma, &sequence);\n    status = PLASMA_dsungesv_Tile_Async(trans, A, T, B, X, ITER, sequence, &request);\n    if (status != PLASMA_SUCCESS)\n        return status;\n    plasma_dynamic_sync();\n    status = sequence->status;\n    plasma_sequence_destroy(plasma, sequence);\n    return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup double_Tile_Async\n *\n *  PLASMA_dsungesv_Tile_Async - Solves symmetric linear system of equations using\n *  the tile QR or the tile LQ factorization and mixed-precision iterative refinement.\n *  Non-blocking equivalent of PLASMA_dsungesv_Tile().\n *  May return before the computation is finished.\n *  Allows for pipelining of operations at runtime.\n *\n *******************************************************************************\n *\n * @param[in] sequence\n *          Identifies the sequence of function calls that this call belongs to\n *          (for completion checks and exception handling purposes).\n *\n * @param[out] request\n *          Identifies this function call (for exception handling purposes).\n *\n *******************************************************************************\n *\n * @sa PLASMA_dsungesv\n * @sa PLASMA_dsungesv_Tile\n * @sa PLASMA_dsungesv_Tile_Async\n * @sa PLASMA_dgels_Tile_Async\n *\n ******************************************************************************/\nint PLASMA_dsungesv_Tile_Async(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T,\n                               PLASMA_desc *B, PLASMA_desc *X, int *ITER,\n                               PLASMA_sequence *sequence, PLASMA_request *request)\n{\n    int N, NB, IB;\n    PLASMA_desc descA;\n    PLASMA_desc descT;\n    PLASMA_desc descB;\n    PLASMA_desc descX;\n    PLASMA_desc descR, descSA, descST, descSX;\n    plasma_context_t *plasma;\n    double *work;\n\n    const int    itermax = 30;\n    const double bwdmax  = 1.0;\n    const double negone = -1.0;\n    const double one = 1.0;\n    int iiter;\n    double Anorm, cte, eps, Rnorm, Xnorm;\n    *ITER=0;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_dsungesv_Tile\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n    if (sequence == NULL) {\n        plasma_fatal_error(\"PLASMA_dsungesv_Tile\", \"NULL sequence\");\n        return PLASMA_ERR_UNALLOCATED;\n    }\n    if (request == NULL) {\n        plasma_fatal_error(\"PLASMA_dsungesv_Tile\", \"NULL request\");\n        return PLASMA_ERR_UNALLOCATED;\n    }\n    /* Check sequence status */\n    if (sequence->status == PLASMA_SUCCESS)\n        request->status = PLASMA_SUCCESS;\n    else\n        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n    /* Check descriptors for correctness */\n    if (plasma_desc_check(A) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_dsungesv_Tile\", \"invalid first descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descA = *A;\n    }\n    if (plasma_desc_check(T) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_dsungesv_Tile\", \"invalid second descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descT = *T;\n    }\n    if (plasma_desc_check(B) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_dsungesv_Tile\", \"invalid third descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descB = *B;\n    }\n    if (plasma_desc_check(X) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_dsungesv_Tile\", \"invalid fourth descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descX = *X;\n    }\n    /* Check input arguments */\n    if ( (descA.nb != descA.mb) || (descB.nb != descB.mb) || (descX.nb != descX.mb) ||\n         (descA.mb != descB.mb) || (descB.mb != descX.mb) ) {\n        plasma_error(\"PLASMA_dsungesv_Tile\", \"only square tiles of same size are supported\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    }\n    if (trans != PlasmaNoTrans) {\n        plasma_error(\"PLASMA_dsungesv_Tile\", \"only PlasmaNoTrans supported\");\n        return PLASMA_ERR_NOT_SUPPORTED;\n    }\n\n    /* Set N, NRHS, NB */\n    N  = descA.m;\n    NB = descA.nb;\n    IB = descT.mb;\n\n    work = (double *)plasma_shared_alloc(plasma, PLASMA_SIZE, PlasmaRealDouble);\n    if (work == NULL) {\n        plasma_error(\"PLASMA_dsungesv\", \"plasma_shared_alloc() failed\");\n        plasma_shared_free(plasma, work);\n        return PLASMA_ERR_OUT_OF_RESOURCES;\n    }\n\n    plasma_ddesc_alloc( descR,  NB, NB, descB.m, descB.n, 0, 0, descB.m, descB.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR) );\n    plasma_sdesc_alloc( descSA, NB, NB, descA.m, descA.n, 0, 0, descA.m, descA.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA) );\n    plasma_sdesc_alloc( descST, IB, NB, descT.m, descT.n, 0, 0, descT.m, descT.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descST) );\n    plasma_sdesc_alloc( descSX, NB, NB, descX.m, descX.n, 0, 0, descX.m, descX.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descST); plasma_desc_mat_free(&descSX) );\n\n    /* Compute some constants */\n    PLASMA_dlange(PlasmaInfNorm, descA, Anorm, work);\n    eps = LAPACKE_dlamch_work('e');\n\n    /* Convert B from double precision to single precision and store\n       the result in SX. */\n    PLASMA_dlag2s(descB, descSX);\n    if (sequence->status != PLASMA_SUCCESS)\n        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n\n    /* Convert A from double precision to single precision and store\n       the result in SA. */\n    PLASMA_dlag2s(descA, descSA);\n    if (sequence->status != PLASMA_SUCCESS)\n        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n\n    /* Compute the QR factorization of SA */\n    plasma_parallel_call_4(plasma_psgeqrf,\n        PLASMA_desc, descSA,\n        PLASMA_desc, descST,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    /* Compute the solve in simple */\n    plasma_parallel_call_7(plasma_psormqr,\n        PLASMA_enum, PlasmaLeft,\n        PLASMA_enum, PlasmaTrans,\n        PLASMA_desc, descSA,\n        PLASMA_desc, descSX,\n        PLASMA_desc, descST,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    plasma_parallel_call_9(plasma_pstrsm,\n        PLASMA_enum, PlasmaLeft,\n        PLASMA_enum, PlasmaUpper,\n        PLASMA_enum, PlasmaNoTrans,\n        PLASMA_enum, PlasmaNonUnit,\n        float, 1.0,\n        PLASMA_desc, descSA,\n        PLASMA_desc, descSX,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    /* Convert SX back to double precision */\n    PLASMA_slag2d(descSX, descX);\n\n    /* Compute R = B - AX. */\n    PLASMA_dlacpy(descB, descR);\n\n    plasma_parallel_call_9(plasma_pdgemm,\n        PLASMA_enum, PlasmaNoTrans,\n        PLASMA_enum, PlasmaNoTrans,\n        double, negone,\n        PLASMA_desc, descA,\n        PLASMA_desc, descX,\n        double, one,\n        PLASMA_desc, descR,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    /* Check whether the NRHS normwise backward error satisfies the\n       stopping criterion. If yes return. Note that ITER=0 (already set). */\n    PLASMA_dlange(PlasmaInfNorm, descX, Xnorm, work);\n    PLASMA_dlange(PlasmaInfNorm, descR, Rnorm, work);\n\n    /* Wait for the end of Anorm, Xnorm and Bnorm computations */\n    plasma_dynamic_sync();\n\n    cte = Anorm*eps*((double) N)*bwdmax;\n    if (Rnorm < Xnorm * cte){\n        /* The NRHS normwise backward errors satisfy the\n           stopping criterion. We are good to exit. */\n        plasma_desc_mat_free(&descSA);\n        plasma_desc_mat_free(&descST);\n        plasma_desc_mat_free(&descSX);\n        plasma_desc_mat_free(&descR);\n        plasma_shared_free(plasma, work);\n        return PLASMA_SUCCESS;\n    }\n\n    /* Iterative refinement */\n    for (iiter = 0; iiter < itermax; iiter++){\n\n        /* Convert R from double precision to single precision\n           and store the result in SX. */\n        PLASMA_dlag2s(descR, descSX);\n\n        plasma_parallel_call_7(plasma_psormqr,\n            PLASMA_enum, PlasmaLeft,\n            PLASMA_enum, PlasmaTrans,\n            PLASMA_desc, descSA,\n            PLASMA_desc, descSX,\n            PLASMA_desc, descST,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        plasma_parallel_call_9(plasma_pstrsm,\n            PLASMA_enum, PlasmaLeft,\n            PLASMA_enum, PlasmaUpper,\n            PLASMA_enum, PlasmaNoTrans,\n            PLASMA_enum, PlasmaNonUnit,\n            float, (float)1.0,\n            PLASMA_desc, descSA,\n            PLASMA_desc, descSX,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        /* Convert SX back to double precision and update the current\n           iterate. */\n        PLASMA_slag2d(descSX, descR);\n        PLASMA_dgeadd(one, descR, descX);\n\n        /* Compute R = B - AX. */\n        PLASMA_dlacpy(descB,descR);\n        plasma_parallel_call_9(plasma_pdgemm,\n            PLASMA_enum, PlasmaNoTrans,\n            PLASMA_enum, PlasmaNoTrans,\n            double, negone,\n            PLASMA_desc, descA,\n            PLASMA_desc, descX,\n            double, one,\n            PLASMA_desc, descR,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        /* Check whether the NRHS normwise backward errors satisfy the\n           stopping criterion. If yes, set ITER=IITER>0 and return. */\n        PLASMA_dlange(PlasmaInfNorm, descX, Xnorm, work);\n        PLASMA_dlange(PlasmaInfNorm, descR, Rnorm, work);\n\n        /* Wait for the end of Xnorm and Bnorm computations */\n        plasma_dynamic_sync();\n\n        if (Rnorm < Xnorm * cte){\n            /* The NRHS normwise backward errors satisfy the\n               stopping criterion. We are good to exit. */\n            *ITER = iiter;\n\n            plasma_desc_mat_free(&descSA);\n            plasma_desc_mat_free(&descST);\n            plasma_desc_mat_free(&descSX);\n            plasma_desc_mat_free(&descR);\n            plasma_shared_free(plasma, work);\n            return PLASMA_SUCCESS;\n        }\n    }\n\n    /* We have performed ITER=itermax iterations and never satisified\n       the stopping criterion, set up the ITER flag accordingly and\n       follow up on double precision routine. */\n    *ITER = -itermax - 1;\n\n    plasma_desc_mat_free(&descSA);\n    plasma_desc_mat_free(&descST);\n    plasma_desc_mat_free(&descSX);\n    plasma_desc_mat_free(&descR);\n    plasma_shared_free(plasma, work);\n\n    /* Single-precision iterative refinement failed to converge to a\n       satisfactory solution, so we restart to double precision. */\n    PLASMA_dlacpy(descB, descX);\n\n    plasma_parallel_call_4(plasma_pdgeqrf,\n        PLASMA_desc, descA,\n        PLASMA_desc, descT,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    plasma_parallel_call_7(plasma_pdormqr,\n        PLASMA_enum, PlasmaLeft,\n        PLASMA_enum, PlasmaTrans,\n        PLASMA_desc, descA,\n        PLASMA_desc, descX,\n        PLASMA_desc, descT,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    plasma_parallel_call_9(plasma_pdtrsm,\n        PLASMA_enum, PlasmaLeft,\n        PLASMA_enum, PlasmaUpper,\n        PLASMA_enum, PlasmaNoTrans,\n        PLASMA_enum, PlasmaNonUnit,\n        double, (double)1.0,\n        PLASMA_desc, descA,\n        PLASMA_desc, descX,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "c19684a62d0b3922f431660a42a703fc17aa434f", "size": 25527, "ext": "c", "lang": "C", "max_stars_repo_path": "compute/dsungesv.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/dsungesv.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/dsungesv.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.8177777778, "max_line_length": 242, "alphanum_fraction": 0.5925490657, "num_tokens": 6609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3850578851851527}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_matrix.h>\n#include \"bstrlib/bstrlib.h\"\n#include \"paths.h\"\n#include \"ParseSCF.h\"\n#include \"HTightBinding.h\"\n#include \"BandEnergy.h\"\n#include \"SpinOrbit.h\"\n\nint main(int argc, char *argv[]) {\n    if (argc < 8) {\n        printf(\"SOC-induced anisotropy calculation -- invoke with:\\n\");\n        printf(\"anisotropy.out (system_name) (na) (nb) (nc) (soc_strength) (theta1) (phi1) (theta2) (phi2)\\n\");\n        return 1;\n    }\n    char *system_name = argv[1];\n    int na = atoi(argv[2]);\n    int nb = atoi(argv[3]);\n    int nc = atoi(argv[4]);\n    double soc_strength = atof(argv[5]);\n    double theta1 = atof(argv[6]);\n    double phi1 = atof(argv[7]);\n    double theta2 = atof(argv[8]);\n    double phi2 = atof(argv[9]);\n    \n    char *scf_path = cwannier_data_path(system_name, \"wannier\", \"\\0\", \"scf.out\");\n    double num_electrons, alat;\n    gsl_matrix *R = gsl_matrix_alloc(3, 3);\n\n    int err = ParseSCF(scf_path, &num_electrons, &alat, R);\n    if (err != CWANNIER_PARSESCF_OK) {\n        printf(\"Error code = %d returned from ParseSCF\\n\", err);\n        return err;\n    }\n    bcstrfree(scf_path);\n\n    char *hr_up_path = cwannier_data_path(system_name, \"wannier\", system_name, \"_up_hr.dat\");\n    HTightBinding *Hrs_up = ExtractHTightBinding(hr_up_path);\n    bcstrfree(hr_up_path);\n\n    char *hr_dn_path = cwannier_data_path(system_name, \"wannier\", system_name, \"_dn_hr.dat\");\n    HTightBinding *Hrs_dn = ExtractHTightBinding(hr_dn_path);\n    bcstrfree(hr_dn_path);\n\n    printf(\"Hamiltonian loaded.\\n\");\n\n    HTightBinding *Hrs_soc_1 = HamiltonianWithSOC(soc_strength, theta1, phi1, Hrs_up, Hrs_dn);\n    HTightBinding *Hrs_soc_2 = HamiltonianWithSOC(soc_strength, theta2, phi2, Hrs_up, Hrs_dn);\n\n    bool use_cache = true;\n    double E_Fermi_1 = 0.0;\n    double E_Fermi_2 = 0.0;\n\n    double energy1 = BandEnergy(&E_Fermi_1, Hrs_soc_1, R, num_electrons, na, nb, nc, use_cache);\n    printf(\"Got energy1 = %f\\n\", energy1);\n\n    double energy2 = BandEnergy(&E_Fermi_2, Hrs_soc_2, R, num_electrons, na, nb, nc, use_cache);\n    printf(\"Got energy2 = %f\\n\", energy2);\n\n    printf(\"energy1 - energy2 = %e\\n\", energy1 - energy2);\n\n    FreeHTightBinding(Hrs_up);\n    FreeHTightBinding(Hrs_dn);\n    FreeHTightBinding(Hrs_soc_1);\n    FreeHTightBinding(Hrs_soc_2);\n    return 0;\n}\n", "meta": {"hexsha": "21c12a3ed32aa39577027a2bebe5627073c18963", "size": 2298, "ext": "c", "lang": "C", "max_stars_repo_path": "Anisotropy.c", "max_stars_repo_name": "tflovorn/cwannier", "max_stars_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Anisotropy.c", "max_issues_repo_name": "tflovorn/cwannier", "max_issues_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Anisotropy.c", "max_forks_repo_name": "tflovorn/cwannier", "max_forks_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8", "max_forks_repo_licenses": ["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.7941176471, "max_line_length": 111, "alphanum_fraction": 0.6662315057, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.38501462771632444}}
{"text": "/**\n * @file convolution.h\n * @brief Block convolution realization of an LTI system with the FFT.Time delay estimation\n * @author John McDonough\n */\n\n#ifndef CONVOLUTION_H\n#define CONVOLUTION_H\n\n#include <stdio.h>\n#include <assert.h>\n\n#include <gsl/gsl_block.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include \"common/jexception.h\"\n\n#include \"stream/stream.h\"\n#include \"feature/feature.h\"\n\n// ----- definition for class `OverlapAdd' -----\n//\nclass OverlapAdd : public VectorFloatFeatureStream {\n public:\n  OverlapAdd(VectorFloatFeatureStreamPtr& samp,\n             const gsl_vector* impulseResponse = NULL, unsigned fftLen = 0,\n             const String& nm = \"OverlapAdd\");\n\n  ~OverlapAdd();\n\n  virtual const gsl_vector_float* next(int frame_no = -5);\n\n  virtual void reset();\n\n private:\n  void set_impulse_response_(const gsl_vector* impulseResponse);\n  unsigned check_fftLen_(unsigned sectionLen, unsigned irLen, unsigned fftLen);\n\n  const VectorFloatFeatureStreamPtr\t\t\tsamp_;\n  const unsigned\t\t\t\t\tL_;\n  const unsigned\t\t\t\t\tP_;\n  const unsigned\t\t\t\t\tN_;\n  const unsigned\t\t\t\t\tN2_;\n\n  double*\t\t\t\t\t\tsection_;\n  gsl_vector_complex*\t\t\t\t\tfrequencyResponse_;\n  gsl_vector_float*\t\t\t\t\tbuffer_;\n};\n\ntypedef Inherit<OverlapAdd, VectorFloatFeatureStreamPtr> OverlapAddPtr;\n\n\n// ----- definition for class `OverlapSave' -----\n//\nclass OverlapSave : public VectorFloatFeatureStream {\n public:\n  OverlapSave(VectorFloatFeatureStreamPtr& samp,\n              const gsl_vector* impulseResponse = NULL, const String& nm = \"OverlapSave\");\n\n  ~OverlapSave();\n\n  virtual const gsl_vector_float* next(int frame_no = -5);\n\n  virtual void reset();\n\n  void update(const gsl_vector_complex* delta);\n\n private:\n  void set_impulse_response_(const gsl_vector* impulseResponse);\n  unsigned check_output_size_(unsigned irLen, unsigned sampLen);\n  unsigned check_L_(unsigned irLen, unsigned sampLen);\n\n  const VectorFloatFeatureStreamPtr\t\t\tsamp_;\n  const unsigned\t\t\t\t\tL_;\n  const unsigned\t\t\t\t\tL2_;\n  const unsigned\t\t\t\t\tP_;\n\n  double*\t\t\t\t\t\tsection_;\n  gsl_vector_complex*\t\t\t\t\tfrequencyResponse_;\n};\n\ntypedef Inherit<OverlapSave, VectorFloatFeatureStreamPtr> OverlapSavePtr;\n\n#endif // CONVOLUTION_H\n", "meta": {"hexsha": "79692c8e7fa40adeb60fe86db9f058d21fcd4ac9", "size": 2246, "ext": "h", "lang": "C", "max_stars_repo_path": "btk20_src/convolution/convolution.h", "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_issues_repo_path": "btk20_src/convolution/convolution.h", "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_forks_repo_path": "btk20_src/convolution/convolution.h", "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "avg_line_length": 25.816091954, "max_line_length": 91, "alphanum_fraction": 0.731522707, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.38490046147434215}}
{"text": "#ifndef KEYPOINTS_H_CFNIGHAG\n#define KEYPOINTS_H_CFNIGHAG\n\n#include <boost/histogram.hpp>\n#include <gsl/gsl>\n#include <opencv2/core/persistence.hpp>\n#include <opencv2/core/types.hpp>\n#include <sens_loc/analysis/distance.h>\n\nnamespace sens_loc::analysis {\n\n/// Analyze the distribution and characteristics of detected keypoints.\nclass keypoints {\n  public:\n    /// Use a regular grid with no transformation, no overflow and an axis\n    /// title.\n    using axis_t = distance::axis_t;\n    /// Histogram type for the 2D distribution of keypoints in the dataset.\n    using distribution_histo_t =\n        decltype(boost::histogram::make_histogram(axis_t{}, axis_t{}));\n    /// Histogram type for 'size' and 'response' of the keypoints.\n    using histo_t = decltype(boost::histogram::make_histogram(axis_t{}));\n\n    keypoints() = default;\n    keypoints(unsigned int img_width, unsigned int img_height)\n        : _img_width{img_width}\n        , _img_height{img_height} {}\n\n    void configure_image_dimension(unsigned int img_width,\n                                   unsigned int img_height) noexcept {\n        _img_width  = img_width;\n        _img_height = img_height;\n    }\n\n    void configure_size(unsigned int bins) noexcept { _size_bins = bins; }\n    void configure_size(std::string axis_title) noexcept {\n        _size_title = std::move(axis_title);\n    }\n    void configure_size(unsigned int bins, std::string axis_title) noexcept {\n        _size_bins  = bins;\n        _size_title = std::move(axis_title);\n    }\n    void enable_size_histo(bool enabled) noexcept {\n        _size_histo_enabled = enabled;\n    }\n\n\n    void configure_response(unsigned int bins) noexcept {\n        _response_bins = bins;\n    }\n    void configure_response(std::string axis_title) noexcept {\n        _response_title = std::move(axis_title);\n    }\n    void configure_response(unsigned int bins,\n                            std::string  axis_title) noexcept {\n        _response_bins  = bins;\n        _response_title = std::move(axis_title);\n    }\n    void enable_response_histo(bool enabled) noexcept {\n        _response_histo_enabled = enabled;\n    }\n\n\n    void configure_distribution(unsigned int both_bins) noexcept {\n        _dist_width_bins  = both_bins;\n        _dist_height_bins = both_bins;\n    }\n    void configure_distribution(unsigned int w_bins,\n                                unsigned int h_bins) noexcept {\n        _dist_width_bins  = w_bins;\n        _dist_height_bins = h_bins;\n    }\n    void configure_distribution(std::string w_axis_title,\n                                std::string h_axis_title) noexcept {\n        _dist_w_title = std::move(w_axis_title);\n        _dist_h_title = std::move(h_axis_title);\n    }\n\n    /// Analyze the properties of a set of keypoints. The booleans are toggles\n    /// to deactivate analysis for the specified quantity to save some\n    /// computations.\n    void analyze(gsl::span<const cv::KeyPoint> points,\n                 bool                          distribution = true,\n                 bool                          size         = true,\n                 bool                          response     = true) noexcept;\n\n    [[nodiscard]] const distribution_histo_t& distribution() const noexcept {\n        return _distribution;\n    }\n    [[nodiscard]] const histo_t& size_histo() const noexcept {\n        return _size_histo;\n    }\n    [[nodiscard]] const histo_t& response_histo() const noexcept {\n        return _response_histo;\n    }\n\n    [[nodiscard]] const statistic& size() const noexcept { return _size; }\n    [[nodiscard]] const statistic& response() const noexcept {\n        return _response;\n    }\n\n  private:\n    unsigned int _img_width  = 0U;\n    unsigned int _img_height = 0U;\n\n    bool         _size_histo_enabled = true;\n    statistic    _size;\n    histo_t      _size_histo;\n    unsigned int _size_bins  = 50U;\n    std::string  _size_title = \"size of keypoints\";\n\n    bool         _response_histo_enabled = true;\n    statistic    _response;\n    histo_t      _response_histo;\n    unsigned int _response_bins  = 50U;\n    std::string  _response_title = \"response of keypoints\";\n\n    distribution_histo_t _distribution;\n    unsigned int         _dist_width_bins  = 50U;\n    unsigned int         _dist_height_bins = 50U;\n    std::string          _dist_w_title = \"width - distribution of keypoints\";\n    std::string          _dist_h_title = \"height - distribution of keypoints\";\n};\n\n/// Write the statistics for the keypoint distribution in a file with OpenCVs\n/// FileStorage API.\nvoid write(cv::FileStorage& fs, const std::string& name, const keypoints& kp);\n\n}  // namespace sens_loc::analysis\n\n#endif /* end of include guard: KEYPOINTS_H_CFNIGHAG */\n", "meta": {"hexsha": "7673dca6f0f62af4df960ed7d163bfbf0677bd93", "size": 4691, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/sens_loc/analysis/keypoints.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/include/sens_loc/analysis/keypoints.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/sens_loc/analysis/keypoints.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5378787879, "max_line_length": 78, "alphanum_fraction": 0.6503943722, "num_tokens": 1033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3849004547987014}}
{"text": "#include <gsl/blas/cblas.h>\n\n/**\n\tAll the methods below are obtained directly from the ATLAS implementation of BLAS, available at: http://www.netlib.org/clapack/cblas/\n*/\n\n#include \"f2c.h\"\n\ndoublereal ddot(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy){\n\n    /* System generated locals */\n    integer i__1;\n    doublereal ret_val;\n\n    /* Local variables */\n    static integer i, m;\n    static doublereal dtemp;\n    static integer ix, iy, mp1;\n\n\n/*     forms the dot product of two vectors.   \n       uses unrolled loops for increments equal to one.   \n       jack dongarra, linpack, 3/11/78.   \n       modified 12/3/93, array(1) declarations changed to array(*)   \n\n   Parameter adjustments   \n       Function Body */\n#define DY(I) dy[(I)-1]\n#define DX(I) dx[(I)-1]\n\n\n    ret_val = 0.;\n    dtemp = 0.;\n    if (*n <= 0) {\n\treturn ret_val;\n    }\n    if (*incx == 1 && *incy == 1) {\n\tgoto L20;\n    }\n\n/*        code for unequal increments or equal increments   \n            not equal to 1 */\n\n    ix = 1;\n    iy = 1;\n    if (*incx < 0) {\n\tix = (-(*n) + 1) * *incx + 1;\n    }\n    if (*incy < 0) {\n\tiy = (-(*n) + 1) * *incy + 1;\n    }\n    i__1 = *n;\n    for (i = 1; i <= *n; ++i) {\n\tdtemp += DX(ix) * DY(iy);\n\tix += *incx;\n\tiy += *incy;\n/* L10: */\n    }\n    ret_val = dtemp;\n    return ret_val;\n\n/*        code for both increments equal to 1   \n\n\n          clean-up loop */\n\nL20:\n    m = *n % 5;\n    if (m == 0) {\n\tgoto L40;\n    }\n    i__1 = m;\n    for (i = 1; i <= m; ++i) {\n\tdtemp += DX(i) * DY(i);\n/* L30: */\n    }\n    if (*n < 5) {\n\tgoto L60;\n    }\nL40:\n    mp1 = m + 1;\n    i__1 = *n;\n    for (i = mp1; i <= *n; i += 5) {\n\tdtemp = dtemp + DX(i) * DY(i) + DX(i + 1) * DY(i + 1) + DX(i + 2) * \n\t\tDY(i + 2) + DX(i + 3) * DY(i + 3) + DX(i + 4) * DY(i + 4);\n/* L50: */\n    }\nL60:\n    ret_val = dtemp;\n    return ret_val;\n} /* ddot_ */\n\n\n\ndoublereal dnrm2(integer *n, doublereal *x, integer *incx)\n{\n    /* System generated locals */\n    integer i__1, i__2;\n    doublereal ret_val, d__1;\n\n    /* Builtin functions */\n    double sqrt(doublereal);\n\n    /* Local variables */\n    static doublereal norm, scale, absxi;\n    static integer ix;\n    static doublereal ssq;\n\n\n/*  DNRM2 returns the euclidean norm of a vector via the function   \n    name, so that   \n\n       DNRM2 := sqrt( x'*x )   \n\n\n\n    -- This version written on 25-October-1982.   \n       Modified on 14-October-1993 to inline the call to DLASSQ.   \n       Sven Hammarling, Nag Ltd.   \n\n\n    \n   Parameter adjustments   \n       Function Body */\n#define X(I) x[(I)-1]\n\n\n    if (*n < 1 || *incx < 1) {\n\tnorm = 0.;\n    } else if (*n == 1) {\n\tnorm = abs(X(1));\n    } else {\n\tscale = 0.;\n\tssq = 1.;\n/*        The following loop is equivalent to this call to the LAPACK \n  \n          auxiliary routine:   \n          CALL DLASSQ( N, X, INCX, SCALE, SSQ ) */\n\n\ti__1 = (*n - 1) * *incx + 1;\n\ti__2 = *incx;\n\tfor (ix = 1; *incx < 0 ? ix >= (*n-1)**incx+1 : ix <= (*n-1)**incx+1; ix += *incx) {\n\t    if (X(ix) != 0.) {\n\t\tabsxi = (d__1 = X(ix), abs(d__1));\n\t\tif (scale < absxi) {\n/* Computing 2nd power */\n\t\t    d__1 = scale / absxi;\n\t\t    ssq = ssq * (d__1 * d__1) + 1.;\n\t\t    scale = absxi;\n\t\t} else {\n/* Computing 2nd power */\n\t\t    d__1 = absxi / scale;\n\t\t    ssq += d__1 * d__1;\n\t\t}\n\t    }\n/* L10: */\n\t}\n\tnorm = scale * sqrt(ssq);\n    }\n\n    ret_val = norm;\n    return ret_val;\n\n/*     End of DNRM2. */\n\n} /* dnrm2_ */\n\nint dswap(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy)\n{\n\n\n    /* System generated locals */\n    integer i__1;\n\n    /* Local variables */\n    static integer i, m;\n    static doublereal dtemp;\n    static integer ix, iy, mp1;\n\n\n/*     interchanges two vectors.   \n       uses unrolled loops for increments equal one.   \n       jack dongarra, linpack, 3/11/78.   \n       modified 12/3/93, array(1) declarations changed to array(*)   \n\n\n    \n   Parameter adjustments   \n       Function Body */\n#define DY(I) dy[(I)-1]\n#define DX(I) dx[(I)-1]\n\n\n    if (*n <= 0) {\n\treturn 0;\n    }\n    if (*incx == 1 && *incy == 1) {\n\tgoto L20;\n    }\n\n/*       code for unequal increments or equal increments not equal   \n           to 1 */\n\n    ix = 1;\n    iy = 1;\n    if (*incx < 0) {\n\tix = (-(*n) + 1) * *incx + 1;\n    }\n    if (*incy < 0) {\n\tiy = (-(*n) + 1) * *incy + 1;\n    }\n    i__1 = *n;\n    for (i = 1; i <= *n; ++i) {\n\tdtemp = DX(ix);\n\tDX(ix) = DY(iy);\n\tDY(iy) = dtemp;\n\tix += *incx;\n\tiy += *incy;\n/* L10: */\n    }\n    return 0;\n\n/*       code for both increments equal to 1   \n\n\n         clean-up loop */\n\nL20:\n    m = *n % 3;\n    if (m == 0) {\n\tgoto L40;\n    }\n    i__1 = m;\n    for (i = 1; i <= m; ++i) {\n\tdtemp = DX(i);\n\tDX(i) = DY(i);\n\tDY(i) = dtemp;\n/* L30: */\n    }\n    if (*n < 3) {\n\treturn 0;\n    }\nL40:\n    mp1 = m + 1;\n    i__1 = *n;\n    for (i = mp1; i <= *n; i += 3) {\n\tdtemp = DX(i);\n\tDX(i) = DY(i);\n\tDY(i) = dtemp;\n\tdtemp = DX(i + 1);\n\tDX(i + 1) = DY(i + 1);\n\tDY(i + 1) = dtemp;\n\tdtemp = DX(i + 2);\n\tDX(i + 2) = DY(i + 2);\n\tDY(i + 2) = dtemp;\n/* L50: */\n    }\n    return 0;\n} /* dswap_ */\n\n\n\n\n\nint dcopy(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy)\n{\n\n\n    /* System generated locals */\n    integer i__1;\n\n    /* Local variables */\n    static integer i, m, ix, iy, mp1;\n\n\n/*     copies a vector, x, to a vector, y.   \n       uses unrolled loops for increments equal to one.   \n       jack dongarra, linpack, 3/11/78.   \n       modified 12/3/93, array(1) declarations changed to array(*)   \n\n\n    \n   Parameter adjustments   \n       Function Body */\n#define DY(I) dy[(I)-1]\n#define DX(I) dx[(I)-1]\n\n\n    if (*n <= 0) {\n\treturn 0;\n    }\n    if (*incx == 1 && *incy == 1) {\n\tgoto L20;\n    }\n\n/*        code for unequal increments or equal increments   \n            not equal to 1 */\n\n    ix = 1;\n    iy = 1;\n    if (*incx < 0) {\n\tix = (-(*n) + 1) * *incx + 1;\n    }\n    if (*incy < 0) {\n\tiy = (-(*n) + 1) * *incy + 1;\n    }\n    i__1 = *n;\n    for (i = 1; i <= *n; ++i) {\n\tDY(iy) = DX(ix);\n\tix += *incx;\n\tiy += *incy;\n/* L10: */\n    }\n    return 0;\n\n/*        code for both increments equal to 1   \n\n\n          clean-up loop */\n\nL20:\n    m = *n % 7;\n    if (m == 0) {\n\tgoto L40;\n    }\n    i__1 = m;\n    for (i = 1; i <= m; ++i) {\n\tDY(i) = DX(i);\n/* L30: */\n    }\n    if (*n < 7) {\n\treturn 0;\n    }\nL40:\n    mp1 = m + 1;\n    i__1 = *n;\n    for (i = mp1; i <= *n; i += 7) {\n\tDY(i) = DX(i);\n\tDY(i + 1) = DX(i + 1);\n\tDY(i + 2) = DX(i + 2);\n\tDY(i + 3) = DX(i + 3);\n\tDY(i + 4) = DX(i + 4);\n\tDY(i + 5) = DX(i + 5);\n\tDY(i + 6) = DX(i + 6);\n/* L50: */\n    }\n    return 0;\n} /* dcopy_ */\n\n\nint dgemm(char *transa, char *transb, integer *m, integer *\tn, integer *k, doublereal *alpha, doublereal *a, integer *lda, doublereal *b, integer *ldb, doublereal *beta, doublereal *c, integer *ldc)\n{\n\n    /* System generated locals */\n    integer a_dim1, a_offset, b_dim1, b_offset, c_dim1, c_offset, i__1, i__2, \n\t    i__3;\n\n    /* Local variables */\n    static integer info;\n    static logical nota, notb;\n    static doublereal temp;\n    static integer i, j, l, ncola;\n    extern logical lsame_(char *, char *);\n    static integer nrowa, nrowb;\n    extern /* Subroutine */ int xerbla_(char *, integer *);\n\n\n/*  Purpose   \n    =======   \n\n    DGEMM  performs one of the matrix-matrix operations   \n\n       C := alpha*op( A )*op( B ) + beta*C,   \n\n    where  op( X ) is one of   \n\n       op( X ) = X   or   op( X ) = X',   \n\n    alpha and beta are scalars, and A, B and C are matrices, with op( A ) \n  \n    an m by k matrix,  op( B )  a  k by n matrix and  C an m by n matrix. \n  \n\n    Parameters   \n    ==========   \n\n    TRANSA - CHARACTER*1.   \n             On entry, TRANSA specifies the form of op( A ) to be used in \n  \n             the matrix multiplication as follows:   \n\n                TRANSA = 'N' or 'n',  op( A ) = A.   \n\n                TRANSA = 'T' or 't',  op( A ) = A'.   \n\n                TRANSA = 'C' or 'c',  op( A ) = A'.   \n\n             Unchanged on exit.   \n\n    TRANSB - CHARACTER*1.   \n             On entry, TRANSB specifies the form of op( B ) to be used in \n  \n             the matrix multiplication as follows:   \n\n                TRANSB = 'N' or 'n',  op( B ) = B.   \n\n                TRANSB = 'T' or 't',  op( B ) = B'.   \n\n                TRANSB = 'C' or 'c',  op( B ) = B'.   \n\n             Unchanged on exit.   \n\n    M      - INTEGER.   \n             On entry,  M  specifies  the number  of rows  of the  matrix \n  \n             op( A )  and of the  matrix  C.  M  must  be at least  zero. \n  \n             Unchanged on exit.   \n\n    N      - INTEGER.   \n             On entry,  N  specifies the number  of columns of the matrix \n  \n             op( B ) and the number of columns of the matrix C. N must be \n  \n             at least zero.   \n             Unchanged on exit.   \n\n    K      - INTEGER.   \n             On entry,  K  specifies  the number of columns of the matrix \n  \n             op( A ) and the number of rows of the matrix op( B ). K must \n  \n             be at least  zero.   \n             Unchanged on exit.   \n\n    ALPHA  - DOUBLE PRECISION.   \n             On entry, ALPHA specifies the scalar alpha.   \n             Unchanged on exit.   \n\n    A      - DOUBLE PRECISION array of DIMENSION ( LDA, ka ), where ka is \n  \n             k  when  TRANSA = 'N' or 'n',  and is  m  otherwise.   \n             Before entry with  TRANSA = 'N' or 'n',  the leading  m by k \n  \n             part of the array  A  must contain the matrix  A,  otherwise \n  \n             the leading  k by m  part of the array  A  must contain  the \n  \n             matrix A.   \n             Unchanged on exit.   \n\n    LDA    - INTEGER.   \n             On entry, LDA specifies the first dimension of A as declared \n  \n             in the calling (sub) program. When  TRANSA = 'N' or 'n' then \n  \n             LDA must be at least  max( 1, m ), otherwise  LDA must be at \n  \n             least  max( 1, k ).   \n             Unchanged on exit.   \n\n    B      - DOUBLE PRECISION array of DIMENSION ( LDB, kb ), where kb is \n  \n             n  when  TRANSB = 'N' or 'n',  and is  k  otherwise.   \n             Before entry with  TRANSB = 'N' or 'n',  the leading  k by n \n  \n             part of the array  B  must contain the matrix  B,  otherwise \n  \n             the leading  n by k  part of the array  B  must contain  the \n  \n             matrix B.   \n             Unchanged on exit.   \n\n    LDB    - INTEGER.   \n             On entry, LDB specifies the first dimension of B as declared \n  \n             in the calling (sub) program. When  TRANSB = 'N' or 'n' then \n  \n             LDB must be at least  max( 1, k ), otherwise  LDB must be at \n  \n             least  max( 1, n ).   \n             Unchanged on exit.   \n\n    BETA   - DOUBLE PRECISION.   \n             On entry,  BETA  specifies the scalar  beta.  When  BETA  is \n  \n             supplied as zero then C need not be set on input.   \n             Unchanged on exit.   \n\n    C      - DOUBLE PRECISION array of DIMENSION ( LDC, n ).   \n             Before entry, the leading  m by n  part of the array  C must \n  \n             contain the matrix  C,  except when  beta  is zero, in which \n  \n             case C need not be set on entry.   \n             On exit, the array  C  is overwritten by the  m by n  matrix \n  \n             ( alpha*op( A )*op( B ) + beta*C ).   \n\n    LDC    - INTEGER.   \n             On entry, LDC specifies the first dimension of C as declared \n  \n             in  the  calling  (sub)  program.   LDC  must  be  at  least \n  \n             max( 1, m ).   \n             Unchanged on exit.   \n\n\n    Level 3 Blas routine.   \n\n    -- Written on 8-February-1989.   \n       Jack Dongarra, Argonne National Laboratory.   \n       Iain Duff, AERE Harwell.   \n       Jeremy Du Croz, Numerical Algorithms Group Ltd.   \n       Sven Hammarling, Numerical Algorithms Group Ltd.   \n\n\n\n       Set  NOTA  and  NOTB  as  true if  A  and  B  respectively are not \n  \n       transposed and set  NROWA, NCOLA and  NROWB  as the number of rows \n  \n       and  columns of  A  and the  number of  rows  of  B  respectively. \n  \n\n    \n   Parameter adjustments   \n       Function Body */\n\n#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]\n#define B(I,J) b[(I)-1 + ((J)-1)* ( *ldb)]\n#define C(I,J) c[(I)-1 + ((J)-1)* ( *ldc)]\n\n    nota = lsame_(transa, \"N\");\n    notb = lsame_(transb, \"N\");\n    if (nota) {\n\tnrowa = *m;\n\tncola = *k;\n    } else {\n\tnrowa = *k;\n\tncola = *m;\n    }\n    if (notb) {\n\tnrowb = *k;\n    } else {\n\tnrowb = *n;\n    }\n\n/*     Test the input parameters. */\n\n    info = 0;\n    if (! nota && ! lsame_(transa, \"C\") && ! lsame_(transa, \"T\")) {\n\tinfo = 1;\n    } else if (! notb && ! lsame_(transb, \"C\") && ! lsame_(transb, \n\t    \"T\")) {\n\tinfo = 2;\n    } else if (*m < 0) {\n\tinfo = 3;\n    } else if (*n < 0) {\n\tinfo = 4;\n    } else if (*k < 0) {\n\tinfo = 5;\n    } else if (*lda < max(1,nrowa)) {\n\tinfo = 8;\n    } else if (*ldb < max(1,nrowb)) {\n\tinfo = 10;\n    } else if (*ldc < max(1,*m)) {\n\tinfo = 13;\n    }\n    if (info != 0) {\n\txerbla_(\"DGEMM \", &info);\n\treturn 0;\n    }\n\n/*     Quick return if possible. */\n\n    if (*m == 0 || *n == 0 || (*alpha == 0. || *k == 0) && *beta == 1.) {\n\treturn 0;\n    }\n\n/*     And if  alpha.eq.zero. */\n\n    if (*alpha == 0.) {\n\tif (*beta == 0.) {\n\t    i__1 = *n;\n\t    for (j = 1; j <= *n; ++j) {\n\t\ti__2 = *m;\n\t\tfor (i = 1; i <= *m; ++i) {\n\t\t    C(i,j) = 0.;\n/* L10: */\n\t\t}\n/* L20: */\n\t    }\n\t} else {\n\t    i__1 = *n;\n\t    for (j = 1; j <= *n; ++j) {\n\t\ti__2 = *m;\n\t\tfor (i = 1; i <= *m; ++i) {\n\t\t    C(i,j) = *beta * C(i,j);\n/* L30: */\n\t\t}\n/* L40: */\n\t    }\n\t}\n\treturn 0;\n    }\n\n/*     Start the operations. */\n\n    if (notb) {\n\tif (nota) {\n\n/*           Form  C := alpha*A*B + beta*C. */\n\n\t    i__1 = *n;\n\t    for (j = 1; j <= *n; ++j) {\n\t\tif (*beta == 0.) {\n\t\t    i__2 = *m;\n\t\t    for (i = 1; i <= *m; ++i) {\n\t\t\tC(i,j) = 0.;\n/* L50: */\n\t\t    }\n\t\t} else if (*beta != 1.) {\n\t\t    i__2 = *m;\n\t\t    for (i = 1; i <= *m; ++i) {\n\t\t\tC(i,j) = *beta * C(i,j);\n/* L60: */\n\t\t    }\n\t\t}\n\t\ti__2 = *k;\n\t\tfor (l = 1; l <= *k; ++l) {\n\t\t    if (B(l,j) != 0.) {\n\t\t\ttemp = *alpha * B(l,j);\n\t\t\ti__3 = *m;\n\t\t\tfor (i = 1; i <= *m; ++i) {\n\t\t\t    C(i,j) += temp * A(i,l);\n/* L70: */\n\t\t\t}\n\t\t    }\n/* L80: */\n\t\t}\n/* L90: */\n\t    }\n\t} else {\n\n/*           Form  C := alpha*A'*B + beta*C */\n\n\t    i__1 = *n;\n\t    for (j = 1; j <= *n; ++j) {\n\t\ti__2 = *m;\n\t\tfor (i = 1; i <= *m; ++i) {\n\t\t    temp = 0.;\n\t\t    i__3 = *k;\n\t\t    for (l = 1; l <= *k; ++l) {\n\t\t\ttemp += A(l,i) * B(l,j);\n/* L100: */\n\t\t    }\n\t\t    if (*beta == 0.) {\n\t\t\tC(i,j) = *alpha * temp;\n\t\t    } else {\n\t\t\tC(i,j) = *alpha * temp + *beta * C(i,j);\n\t\t    }\n/* L110: */\n\t\t}\n/* L120: */\n\t    }\n\t}\n    } else {\n\tif (nota) {\n\n/*           Form  C := alpha*A*B' + beta*C */\n\n\t    i__1 = *n;\n\t    for (j = 1; j <= *n; ++j) {\n\t\tif (*beta == 0.) {\n\t\t    i__2 = *m;\n\t\t    for (i = 1; i <= *m; ++i) {\n\t\t\tC(i,j) = 0.;\n/* L130: */\n\t\t    }\n\t\t} else if (*beta != 1.) {\n\t\t    i__2 = *m;\n\t\t    for (i = 1; i <= *m; ++i) {\n\t\t\tC(i,j) = *beta * C(i,j);\n/* L140: */\n\t\t    }\n\t\t}\n\t\ti__2 = *k;\n\t\tfor (l = 1; l <= *k; ++l) {\n\t\t    if (B(j,l) != 0.) {\n\t\t\ttemp = *alpha * B(j,l);\n\t\t\ti__3 = *m;\n\t\t\tfor (i = 1; i <= *m; ++i) {\n\t\t\t    C(i,j) += temp * A(i,l);\n/* L150: */\n\t\t\t}\n\t\t    }\n/* L160: */\n\t\t}\n/* L170: */\n\t    }\n\t} else {\n\n/*           Form  C := alpha*A'*B' + beta*C */\n\n\t    i__1 = *n;\n\t    for (j = 1; j <= *n; ++j) {\n\t\ti__2 = *m;\n\t\tfor (i = 1; i <= *m; ++i) {\n\t\t    temp = 0.;\n\t\t    i__3 = *k;\n\t\t    for (l = 1; l <= *k; ++l) {\n\t\t\ttemp += A(l,i) * B(j,l);\n/* L180: */\n\t\t    }\n\t\t    if (*beta == 0.) {\n\t\t\tC(i,j) = *alpha * temp;\n\t\t    } else {\n\t\t\tC(i,j) = *alpha * temp + *beta * C(i,j);\n\t\t    }\n/* L190: */\n\t\t}\n/* L200: */\n\t    }\n\t}\n    }\n\n    return 0;\n\n/*     End of DGEMM . */\n\n} /* dgemm_ */\n\n\n\n\n\n\nint dgemv(char *trans, integer *m, integer *n, doublereal *\talpha, doublereal *a, integer *lda, doublereal *x, integer *incx, doublereal *beta, doublereal *y, integer *incy)\n{\n\n\n    /* System generated locals */\n    integer a_dim1, a_offset, i__1, i__2;\n\n    /* Local variables */\n    static integer info;\n    static doublereal temp;\n    static integer lenx, leny, i, j;\n    extern logical lsame_(char *, char *);\n    static integer ix, iy, jx, jy, kx, ky;\n    extern /* Subroutine */ int xerbla_(char *, integer *);\n\n\n/*  Purpose   \n    =======   \n\n    DGEMV  performs one of the matrix-vector operations   \n\n       y := alpha*A*x + beta*y,   or   y := alpha*A'*x + beta*y,   \n\n    where alpha and beta are scalars, x and y are vectors and A is an   \n    m by n matrix.   \n\n    Parameters   \n    ==========   \n\n    TRANS  - CHARACTER*1.   \n             On entry, TRANS specifies the operation to be performed as   \n             follows:   \n\n                TRANS = 'N' or 'n'   y := alpha*A*x + beta*y.   \n\n                TRANS = 'T' or 't'   y := alpha*A'*x + beta*y.   \n\n                TRANS = 'C' or 'c'   y := alpha*A'*x + beta*y.   \n\n             Unchanged on exit.   \n\n    M      - INTEGER.   \n             On entry, M specifies the number of rows of the matrix A.   \n             M must be at least zero.   \n             Unchanged on exit.   \n\n    N      - INTEGER.   \n             On entry, N specifies the number of columns of the matrix A. \n  \n             N must be at least zero.   \n             Unchanged on exit.   \n\n    ALPHA  - DOUBLE PRECISION.   \n             On entry, ALPHA specifies the scalar alpha.   \n             Unchanged on exit.   \n\n    A      - DOUBLE PRECISION array of DIMENSION ( LDA, n ).   \n             Before entry, the leading m by n part of the array A must   \n             contain the matrix of coefficients.   \n             Unchanged on exit.   \n\n    LDA    - INTEGER.   \n             On entry, LDA specifies the first dimension of A as declared \n  \n             in the calling (sub) program. LDA must be at least   \n             max( 1, m ).   \n             Unchanged on exit.   \n\n    X      - DOUBLE PRECISION array of DIMENSION at least   \n             ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n'   \n             and at least   \n             ( 1 + ( m - 1 )*abs( INCX ) ) otherwise.   \n             Before entry, the incremented array X must contain the   \n             vector x.   \n             Unchanged on exit.   \n\n    INCX   - INTEGER.   \n             On entry, INCX specifies the increment for the elements of   \n             X. INCX must not be zero.   \n             Unchanged on exit.   \n\n    BETA   - DOUBLE PRECISION.   \n             On entry, BETA specifies the scalar beta. When BETA is   \n             supplied as zero then Y need not be set on input.   \n             Unchanged on exit.   \n\n    Y      - DOUBLE PRECISION array of DIMENSION at least   \n             ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n'   \n             and at least   \n             ( 1 + ( n - 1 )*abs( INCY ) ) otherwise.   \n             Before entry with BETA non-zero, the incremented array Y   \n             must contain the vector y. On exit, Y is overwritten by the \n  \n             updated vector y.   \n\n    INCY   - INTEGER.   \n             On entry, INCY specifies the increment for the elements of   \n             Y. INCY must not be zero.   \n             Unchanged on exit.   \n\n\n    Level 2 Blas routine.   \n\n    -- Written on 22-October-1986.   \n       Jack Dongarra, Argonne National Lab.   \n       Jeremy Du Croz, Nag Central Office.   \n       Sven Hammarling, Nag Central Office.   \n       Richard Hanson, Sandia National Labs.   \n\n\n\n       Test the input parameters.   \n\n    \n   Parameter adjustments   \n       Function Body */\n#define X(I) x[(I)-1]\n#define Y(I) y[(I)-1]\n\n#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]\n\n    info = 0;\n    if (! lsame_(trans, \"N\") && ! lsame_(trans, \"T\") && ! \n\t    lsame_(trans, \"C\")) {\n\tinfo = 1;\n    } else if (*m < 0) {\n\tinfo = 2;\n    } else if (*n < 0) {\n\tinfo = 3;\n    } else if (*lda < max(1,*m)) {\n\tinfo = 6;\n    } else if (*incx == 0) {\n\tinfo = 8;\n    } else if (*incy == 0) {\n\tinfo = 11;\n    }\n    if (info != 0) {\n\txerbla_(\"DGEMV \", &info);\n\treturn 0;\n    }\n\n/*     Quick return if possible. */\n\n    if (*m == 0 || *n == 0 || *alpha == 0. && *beta == 1.) {\n\treturn 0;\n    }\n\n/*     Set  LENX  and  LENY, the lengths of the vectors x and y, and set \n  \n       up the start points in  X  and  Y. */\n\n    if (lsame_(trans, \"N\")) {\n\tlenx = *n;\n\tleny = *m;\n    } else {\n\tlenx = *m;\n\tleny = *n;\n    }\n    if (*incx > 0) {\n\tkx = 1;\n    } else {\n\tkx = 1 - (lenx - 1) * *incx;\n    }\n    if (*incy > 0) {\n\tky = 1;\n    } else {\n\tky = 1 - (leny - 1) * *incy;\n    }\n\n/*     Start the operations. In this version the elements of A are   \n       accessed sequentially with one pass through A.   \n\n       First form  y := beta*y. */\n\n    if (*beta != 1.) {\n\tif (*incy == 1) {\n\t    if (*beta == 0.) {\n\t\ti__1 = leny;\n\t\tfor (i = 1; i <= leny; ++i) {\n\t\t    Y(i) = 0.;\n/* L10: */\n\t\t}\n\t    } else {\n\t\ti__1 = leny;\n\t\tfor (i = 1; i <= leny; ++i) {\n\t\t    Y(i) = *beta * Y(i);\n/* L20: */\n\t\t}\n\t    }\n\t} else {\n\t    iy = ky;\n\t    if (*beta == 0.) {\n\t\ti__1 = leny;\n\t\tfor (i = 1; i <= leny; ++i) {\n\t\t    Y(iy) = 0.;\n\t\t    iy += *incy;\n/* L30: */\n\t\t}\n\t    } else {\n\t\ti__1 = leny;\n\t\tfor (i = 1; i <= leny; ++i) {\n\t\t    Y(iy) = *beta * Y(iy);\n\t\t    iy += *incy;\n/* L40: */\n\t\t}\n\t    }\n\t}\n    }\n    if (*alpha == 0.) {\n\treturn 0;\n    }\n    if (lsame_(trans, \"N\")) {\n\n/*        Form  y := alpha*A*x + y. */\n\n\tjx = kx;\n\tif (*incy == 1) {\n\t    i__1 = *n;\n\t    for (j = 1; j <= *n; ++j) {\n\t\tif (X(jx) != 0.) {\n\t\t    temp = *alpha * X(jx);\n\t\t    i__2 = *m;\n\t\t    for (i = 1; i <= *m; ++i) {\n\t\t\tY(i) += temp * A(i,j);\n/* L50: */\n\t\t    }\n\t\t}\n\t\tjx += *incx;\n/* L60: */\n\t    }\n\t} else {\n\t    i__1 = *n;\n\t    for (j = 1; j <= *n; ++j) {\n\t\tif (X(jx) != 0.) {\n\t\t    temp = *alpha * X(jx);\n\t\t    iy = ky;\n\t\t    i__2 = *m;\n\t\t    for (i = 1; i <= *m; ++i) {\n\t\t\tY(iy) += temp * A(i,j);\n\t\t\tiy += *incy;\n/* L70: */\n\t\t    }\n\t\t}\n\t\tjx += *incx;\n/* L80: */\n\t    }\n\t}\n    } else {\n\n/*        Form  y := alpha*A'*x + y. */\n\n\tjy = ky;\n\tif (*incx == 1) {\n\t    i__1 = *n;\n\t    for (j = 1; j <= *n; ++j) {\n\t\ttemp = 0.;\n\t\ti__2 = *m;\n\t\tfor (i = 1; i <= *m; ++i) {\n\t\t    temp += A(i,j) * X(i);\n/* L90: */\n\t\t}\n\t\tY(jy) += *alpha * temp;\n\t\tjy += *incy;\n/* L100: */\n\t    }\n\t} else {\n\t    i__1 = *n;\n\t    for (j = 1; j <= *n; ++j) {\n\t\ttemp = 0.;\n\t\tix = kx;\n\t\ti__2 = *m;\n\t\tfor (i = 1; i <= *m; ++i) {\n\t\t    temp += A(i,j) * X(ix);\n\t\t    ix += *incx;\n/* L110: */\n\t\t}\n\t\tY(jy) += *alpha * temp;\n\t\tjy += *incy;\n/* L120: */\n\t    }\n\t}\n    }\n\n    return 0;\n\n/*     End of DGEMV . */\n\n} /* dgemv_ */\n\nlogical lsame_(char *ca, char *cb)\n{\n\n\n    /* System generated locals */\n    logical ret_val;\n\n    /* Local variables */\n    static integer inta, intb, zcode;\n\n\n/*  -- LAPACK auxiliary routine (version 2.0) --   \n       Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,   \n       Courant Institute, Argonne National Lab, and Rice University   \n       January 31, 1994   \n\n\n    Purpose   \n    =======   \n\n    LSAME returns .TRUE. if CA is the same letter as CB regardless of   \n    case.   \n\n    Arguments   \n    =========   \n\n    CA      (input) CHARACTER*1   \n    CB      (input) CHARACTER*1   \n            CA and CB specify the single characters to be compared.   \n\n   ===================================================================== \n  \n\n\n       Test if the characters are equal */\n\n    ret_val = *(unsigned char *)ca == *(unsigned char *)cb;\n    if (ret_val) {\n\treturn ret_val;\n    }\n\n/*     Now test for equivalence if both characters are alphabetic. */\n\n    zcode = 'Z';\n\n/*     Use 'Z' rather than 'A' so that ASCII can be detected on Prime   \n       machines, on which ICHAR returns a value with bit 8 set.   \n       ICHAR('A') on Prime machines returns 193 which is the same as   \n       ICHAR('A') on an EBCDIC machine. */\n\n    inta = *(unsigned char *)ca;\n    intb = *(unsigned char *)cb;\n\n    if (zcode == 90 || zcode == 122) {\n\n/*        ASCII is assumed - ZCODE is the ASCII code of either lower o\nr   \n          upper case 'Z'. */\n\n\tif (inta >= 97 && inta <= 122) {\n\t    inta += -32;\n\t}\n\tif (intb >= 97 && intb <= 122) {\n\t    intb += -32;\n\t}\n\n    } else if (zcode == 233 || zcode == 169) {\n\n/*        EBCDIC is assumed - ZCODE is the EBCDIC code of either lower\n or   \n          upper case 'Z'. */\n\n\tif (inta >= 129 && inta <= 137 || inta >= 145 && inta <= 153 || inta \n\t\t>= 162 && inta <= 169) {\n\t    inta += 64;\n\t}\n\tif (intb >= 129 && intb <= 137 || intb >= 145 && intb <= 153 || intb \n\t\t>= 162 && intb <= 169) {\n\t    intb += 64;\n\t}\n\n    } else if (zcode == 218 || zcode == 250) {\n\n/*        ASCII is assumed, on Prime machines - ZCODE is the ASCII cod\ne   \n          plus 128 of either lower or upper case 'Z'. */\n\n\tif (inta >= 225 && inta <= 250) {\n\t    inta += -32;\n\t}\n\tif (intb >= 225 && intb <= 250) {\n\t    intb += -32;\n\t}\n    }\n    ret_val = inta == intb;\n\n/*     RETURN   \n\n       End of LSAME */\n\n    return ret_val;\n} /* lsame_ */\nint xerbla_(char *srname, integer *info)\n{\n/*  -- LAPACK auxiliary routine (version 2.0) --   \n       Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,   \n       Courant Institute, Argonne National Lab, and Rice University   \n       September 30, 1994   \n\n\n    Purpose   \n    =======   \n\n    XERBLA  is an error handler for the LAPACK routines.   \n    It is called by an LAPACK routine if an input parameter has an   \n    invalid value.  A message is printed and execution stops.   \n\n    Installers may consider modifying the STOP statement in order to   \n    call system-specific exception-handling facilities.   \n\n    Arguments   \n    =========   \n\n    SRNAME  (input) CHARACTER*6   \n            The name of the routine which called XERBLA.   \n\n    INFO    (input) INTEGER   \n            The position of the invalid parameter in the parameter list   \n\n            of the calling routine.   \n\n   ===================================================================== \n*/\n\n    printf(\"** On entry to %6s, parameter number %2i had an illegal value\\n\",\n\t\tsrname, *info);\n\n/*     End of XERBLA */\n\n    return 0;\n} /* xerbla_ */\n\n\n\n\n", "meta": {"hexsha": "822c008379b52d3daaf761dbf15833f329872df9", "size": 25919, "ext": "c", "lang": "C", "max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/cblas.c", "max_stars_repo_name": "MontyThibault/centre-of-mass-awareness", "max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/cblas.c", "max_issues_repo_name": "MontyThibault/centre-of-mass-awareness", "max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/blas/cblas.c", "max_forks_repo_name": "MontyThibault/centre-of-mass-awareness", "max_forks_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d", "max_forks_repo_licenses": ["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.0963341858, "max_line_length": 198, "alphanum_fraction": 0.4696168834, "num_tokens": 8572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.3847231841737933}}
{"text": "#ifndef CHEVALIER_H\n#define CHEVALIER_H\n\n#include <math.h>\n#include <gsl/gsl_roots.h>\n#include <gsl/gsl_multiroots.h>\n\n#define parsec_in_cm 3.085678e+18 //parsec in cm\n#define parsec_in_km 3.085678e+13 //parsec in km\n#define msun_in_g    1.988920e+33 //msun in g\n#define year_in_sec  3.155760e+07 //year in s\n\n\ntypedef struct Chevalier\n{\n    double M_dot;               //mass input rate\n    double E_dot;               //energy input rate\n    double R;                   //limit of mass and energy input\n    double gamma;               //adiabatic index\n    double V;                   //Volume of input area\n    double q;                   //M_dot / V\n    double Q;                   //E_dot / V\n    gsl_root_fsolver *grsolve;  //GSL root solver\n} Chevalier;\n\n// Function declarations for Chevalier struct\nvoid SetChevalier(Chevalier *c, double M_dot, double E_dot, double gamma, double R);\ndouble MachNumber(Chevalier *c, double r);      //mach number vs. radius\ndouble MomentumDensity(Chevalier *c, double r); //momentum density vs. radius in Msun/pc^3 * km/s\ndouble Pressure(Chevalier *c, double r);        //Pressure in dyn cm^-2\ndouble Density(Chevalier *c, double r);         //density in g cm^-3\ndouble Density_Msunpc3(Chevalier *c, double r); //density in Msun/pc3\ndouble WindVelocity(Chevalier *c, double r);    //wind velocity in km/s\ndouble EnergyIntegral(Chevalier *c, double r);  //msun/yr (km/s)^2 / pc^3\ndouble u_star(Chevalier *c, double r);          //normalized wind velocity\ndouble rho_star(Chevalier *c, double r);        //normalized density\ndouble P_star(Chevalier *c, double r);          //normalized pressure\n\ndouble mach_crossing_A(double M, void *fp);     //functions for Mach number root finding\ndouble mach_crossing_B(double M, void *fp);\n\n// Function definitions\nvoid SetChevalier(Chevalier *c, double M_dot, double E_dot, double gamma, double R) {\n    // M_dot = Mass input in Msun/yr\n    // E_dot = Energy input in erg / s\n    // gamma = Adiabatic index\n    // R     = Radius of the wind region in parsec\n    \n    //Set model parameters\n    c->M_dot = M_dot;\n    c->E_dot = E_dot;\n    c->gamma = gamma;\n    c->R     = R;\n    c->V     = (4.*M_PI/3. * R*R*R); //volume in pc^3\n    //compute input density rate (msun / yr / pc^3)\n    c->q     = c->M_dot / c->V; \n    //compute input energy density rate (msun/yr (km/s)^2 / pc^3)\n    c->Q     = (c->E_dot/msun_in_g*year_in_sec / 1.0e10) / c->V;\n    //define the GSL root solver to use\n    const gsl_root_fsolver_type *grsolve_T = gsl_root_fsolver_brent;\n    c->grsolve = gsl_root_fsolver_alloc(grsolve_T);\n}\n\n\ndouble u_star(Chevalier *c, double r) {\n    // Returns dimensionless wind velocity\n    double u = WindVelocity(c, r);\n    double u_prime = sqrt(c->E_dot)/sqrt(c->M_dot*msun_in_g/year_in_sec)/1.0e5;\n    return u/u_prime;\n}\n\n\ndouble rho_star(Chevalier *c, double r) {\n    // Returns dimensionless density\n    double rho = Density(c,r); //g cm^-3\n    double M_dot_prime = c->M_dot * msun_in_g/year_in_sec; // g/s\n    double R_prime = c->R * parsec_in_cm; //cm\n    double rho_prime = pow(M_dot_prime,1.5)/(sqrt(c->E_dot)*R_prime*R_prime);\n    return rho/rho_prime;\n}\n\n\ndouble P_star(Chevalier *c, double r) {\n    // Returns dimensionless pressure\n    double P = Pressure(c,r); //dyn cm^-2\n    double M_dot_prime = c->M_dot * msun_in_g/year_in_sec; // g/s\n    double R_prime = c->R * parsec_in_cm; //cm\n    double P_prime = sqrt(M_dot_prime)*sqrt(c->E_dot)/(R_prime*R_prime);\n    return P/P_prime;\n}\n\n\ndouble Pressure(Chevalier *c, double r) {\n    // Returns pressure in dyn cm^-2\n    double Mach = MachNumber(c,r);          //mach number\n    double u    = WindVelocity(c,r);        //km/s\n    double cs   = u/Mach * 1.0e5;           //sound speed in cm/s\n    u *= year_in_sec / parsec_in_km;        //to pc/yr\n    double rho  = MomentumDensity(c,r)/u;   //Msun / pc^3\n    rho *= msun_in_g;                       //g / pc^3\n    rho /= pow(parsec_in_cm, 3);            //g / cm^3\n    double P = cs*cs*rho/c->gamma;          //pressure in cgs\n    return P;                               //in dyn cm^-2\n}\n\n\ndouble Density(Chevalier *c, double r) {\n    // Returns density in g cm^-3\n    double rho = Density_Msunpc3(c, r);     //Msun/pc^3\n    rho *= msun_in_g;                       //g / pc^3\n    rho /= pow(parsec_in_cm, 3);            //g / cm^3\n    return rho;                             // in g/cm^3\n}\n\n\ndouble Density_Msunpc3(Chevalier *c, double r) {\n    // Returns density in g cm^-3\n    double u = WindVelocity(c, r);          //km/s\n    u *= year_in_sec / parsec_in_km;        //to pc/yr\n    return MomentumDensity(c,r)/u;          //Msun/pc^3;\n}\n\n\ndouble WindVelocity(Chevalier *c, double r) {\n    // Returns wind velocity in km/s\n\n    //First, find integrated energy input density\n    double Qint = EnergyIntegral(c, r);     //msun/yr (km/s)^2 / pc^3\n    //Second, find momentum density\n    double rhou = MomentumDensity(c, r);     //msun/yr/pc^2\n    //find sq of velocity (modulo gamma + Mach correction)\n    double usq = Qint/rhou;                 //1/2 u^2 + (gamma/(gamma-1))*P/rho\n                                            //1/2 u^2 + c^2 / (gamma-1)\n                                            //1/2 u^2 + u^2 / (M^2 (gamma-1))\n                                            //u^2 * ( 1/2 + 1/(M^2 (gamma-1)) )\n    //get the mach number\n    double Mach = MachNumber(c,r);\n    //find the adjustment factor\n    double fac = (0.5 + 1./(Mach*Mach*(c->gamma-1.)));\n    return sqrt(usq/fac);\t//km/s\n}\n\n\ndouble EnergyIntegral(Chevalier *c, double r) {\n    double Qint = r<c->R ? 1./3.*c->Q*r : 1./3.*c->Q*c->R*c->R*c->R/(r*r);\n    return Qint;    //msun/yr (km/s)^2 / pc^3\n}\n\n\ndouble MomentumDensity(Chevalier *c, double r) {\n    double rhou = r<c->R ? 1./3.*c->q*r : 1./3.*c->q*c->R*c->R*c->R/(r*r) ;\n    return rhou;    // in Msun/yr/pc^2\n}\n\n\ndouble MachNumber(Chevalier *c, double r) {\n    \n    int    status, iter=0, max_iter=100;\n    double M_lo = 1.0e-5, M_hi = 5.;\n    double Mx, answer = 0;\n    double x = r/c->R;\n    gsl_function func;\n    double fp[2] = {c->gamma, x};\n\n    //choose which solution to use\n    if(x<=1.0) {\n        M_lo = 1.0e-5;\n        M_hi = 1.0;\n        func.function = &mach_crossing_A;\n    }\n    else {\n        M_lo = 1.0;\n        M_hi = 10000.0;\n        func.function = &mach_crossing_B;\n    }\n    func.params   = &fp[0];\n\n    gsl_root_fsolver_set(c->grsolve, &func, M_lo, M_hi);\n\n    while(++iter<max_iter){\n        status = gsl_root_fsolver_iterate(c->grsolve);\n        Mx = gsl_root_fsolver_root(c->grsolve);\n        M_lo = gsl_root_fsolver_x_lower(c->grsolve);\n        M_hi = gsl_root_fsolver_x_upper(c->grsolve);\n        status = gsl_root_test_interval(M_lo,M_hi,0,1.0e-5);\n        if(status==GSL_SUCCESS) {answer = Mx; break;}\n    }\n\n    return answer;\n}\n\n\ndouble mach_crossing_A(double M, void *fp) {\n    double *g     = (double *) fp;\n    double gamma  = g[0];\n    double x      = g[1];\n    double alpha  = -1.*(3.*gamma+1.)/(5.*gamma+1.);\n    double beta   = (gamma+1.)/(2.*(5.*gamma+1.));\n    double A      = pow( (3.*gamma + 1./(M*M))/(1.+3.*gamma), alpha);\n    double B      = pow( (gamma-1.+2./(M*M))/(1.+gamma), beta);\n    return A*B - x;\n}\n\n\ndouble mach_crossing_B(double M, void *fp) {\n    double *g     = (double *) fp;\n    double gamma = g[0];\n    double x     = g[1];\n    double alpha = 2./(gamma-1.);\n    double beta  = (gamma+1.)/(2.*(gamma-1.));\n    double A     = pow( M, alpha);\n    double B     = pow( (gamma-1.+2./(M*M))/(1.+gamma), beta);\n    return A*B - x*x;\n}\n\n#endif //CHEVALIER_H", "meta": {"hexsha": "0beb79112041ef564d4ac2a3b38a1393bd1d2208", "size": 7534, "ext": "h", "lang": "C", "max_stars_repo_path": "galpy/potential/potential_c_ext/Chevalier.h", "max_stars_repo_name": "editeodoro/galpy", "max_stars_repo_head_hexsha": "b550ea71473a4db8d110bf56c03889806358aea1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "galpy/potential/potential_c_ext/Chevalier.h", "max_issues_repo_name": "editeodoro/galpy", "max_issues_repo_head_hexsha": "b550ea71473a4db8d110bf56c03889806358aea1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "galpy/potential/potential_c_ext/Chevalier.h", "max_forks_repo_name": "editeodoro/galpy", "max_forks_repo_head_hexsha": "b550ea71473a4db8d110bf56c03889806358aea1", "max_forks_repo_licenses": ["BSD-3-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.8796296296, "max_line_length": 97, "alphanum_fraction": 0.5793735068, "num_tokens": 2406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5, "lm_q1q2_score": 0.38454011853536413}}
{"text": "#ifndef __DESIGN_H\n#define __DESIGN_H\n\n#include <gsl/gsl_matrix.h>\n\n//function prototypes\ndouble distance(double *x,double *y,int D,double p);\ndouble cost(gsl_matrix *data,int Npoints,int D,double p,double lambda);\ndouble diagonalCost(int Npoints,double lambda);\ndouble swap(gsl_matrix *data,int Npoints,int D,double p,double lambda,int i1,int i2, int d);\nvoid swapBack(gsl_matrix *data,int i1,int i2,int d);\n\n//main design sampler prototype\ndouble sample(int Npoints,int D,double p,double lambda,int seed,int maxIterations,gsl_matrix *data,double *costValues);\n\n#endif", "meta": {"hexsha": "6bfb535890720c6c28e8e496a9ad3c75a57ce00c", "size": 569, "ext": "h", "lang": "C", "max_stars_repo_path": "lenstools/extern/design.h", "max_stars_repo_name": "asabyr/LensTools", "max_stars_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-27T02:03:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T02:03:11.000Z", "max_issues_repo_path": "lenstools/extern/design.h", "max_issues_repo_name": "asabyr/LensTools", "max_issues_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lenstools/extern/design.h", "max_forks_repo_name": "asabyr/LensTools", "max_forks_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c", "max_forks_repo_licenses": ["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.5625, "max_line_length": 119, "alphanum_fraction": 0.7855887522, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3845187302845595}}
{"text": "/* multirobust.c\n * \n * Copyright (C) 2013 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * This module contains routines related to robust linear least squares. The\n * algorithm used closely follows the publications:\n *\n * [1] DuMouchel, W. and F. O'Brien (1989), \"Integrating a robust\n * option into a multiple regression computing environment,\"\n * Computer Science and Statistics:  Proceedings of the 21st\n * Symposium on the Interface, American Statistical Association\n *\n * [2] Street, J.O., R.J. Carroll, and D. Ruppert (1988), \"A note on\n * computing robust regression estimates via iteratively\n * reweighted least squares,\" The American Statistician, v. 42, \n * pp. 152-154.\n */\n\n//#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_statistics.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_sort_vector.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_linalg.h>\n\n#include \"linear_common.c\"\n\nstatic int robust_test_convergence(const gsl_vector *c_prev, const gsl_vector *c,\n                                   const double tol);\nstatic double robust_madsigma(const gsl_vector *x, gsl_multifit_robust_workspace *w);\nstatic double robust_robsigma(const gsl_vector *r, const double s,\n                              const double tune, gsl_multifit_robust_workspace *w);\nstatic double robust_sigma(const double s_ols, const double s_rob,\n                           gsl_multifit_robust_workspace *w);\nstatic int robust_covariance(const double sigma, gsl_matrix *cov,\n                             gsl_multifit_robust_workspace *w);\n\n/*\ngsl_multifit_robust_alloc\n  Allocate a robust workspace\n\nInputs: T - robust weighting algorithm\n        n - number of observations\n        p - number of model parameters\n\nReturn: pointer to workspace\n*/\n\ngsl_multifit_robust_workspace *\ngsl_multifit_robust_alloc(const gsl_multifit_robust_type *T,\n                          const size_t n, const size_t p)\n{\n  gsl_multifit_robust_workspace *w;\n\n  if (n < p)\n    {\n      GSL_ERROR_VAL(\"observations n must be >= p\", GSL_EINVAL, 0);\n    }\n\n  w = calloc(1, sizeof(gsl_multifit_robust_workspace));\n  if (w == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for multifit_robust struct\",\n                    GSL_ENOMEM, 0);\n    }\n\n  w->n = n;\n  w->p = p;\n  w->type = T;\n  /* bdavis */\n  //w->maxiter = 100; /* maximum iterations */\n  w->maxiter = 5; /* maximum iterations */\n  /* bdavis */\n  w->tune = w->type->tuning_default;\n\n  w->multifit_p = gsl_multifit_linear_alloc(n, p);\n  if (w->multifit_p == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for multifit_linear struct\",\n                    GSL_ENOMEM, 0);\n    }\n\n  w->r = gsl_vector_alloc(n);\n  if (w->r == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for residuals\",\n                    GSL_ENOMEM, 0);\n    }\n\n  w->weights = gsl_vector_alloc(n);\n  if (w->weights == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for weights\", GSL_ENOMEM, 0);\n    }\n\n  w->c_prev = gsl_vector_alloc(p);\n  if (w->c_prev == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for c_prev\", GSL_ENOMEM, 0);\n    }\n\n  w->resfac = gsl_vector_alloc(n);\n  if (w->resfac == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for residual factors\",\n                    GSL_ENOMEM, 0);\n    }\n\n  w->psi = gsl_vector_alloc(n);\n  if (w->psi == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for psi\", GSL_ENOMEM, 0);\n    }\n\n  w->dpsi = gsl_vector_alloc(n);\n  if (w->dpsi == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for dpsi\", GSL_ENOMEM, 0);\n    }\n\n  w->QSI = gsl_matrix_alloc(p, p);\n  if (w->QSI == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for QSI\", GSL_ENOMEM, 0);\n    }\n\n  w->D = gsl_vector_alloc(p);\n  if (w->D == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for D\", GSL_ENOMEM, 0);\n    }\n\n  w->workn = gsl_vector_alloc(n);\n  if (w->workn == 0)\n    {\n      GSL_ERROR_VAL(\"failed to allocate space for workn\", GSL_ENOMEM, 0);\n    }\n\n  w->stats.sigma_ols = 0.0;\n  w->stats.sigma_mad = 0.0;\n  w->stats.sigma_rob = 0.0;\n  w->stats.sigma = 0.0;\n  w->stats.Rsq = 0.0;\n  w->stats.adj_Rsq = 0.0;\n  w->stats.rmse = 0.0;\n  w->stats.sse = 0.0;\n  w->stats.dof = n - p;\n  w->stats.weights = w->weights;\n  w->stats.r = w->r;\n\n  return w;\n} /* gsl_multifit_robust_alloc() */\n\n/*\ngsl_multifit_robust_free()\n  Free memory associated with robust workspace\n*/\n\nvoid\ngsl_multifit_robust_free(gsl_multifit_robust_workspace *w)\n{\n  if (w->multifit_p)\n    gsl_multifit_linear_free(w->multifit_p);\n\n  if (w->r)\n    gsl_vector_free(w->r);\n\n  if (w->weights)\n    gsl_vector_free(w->weights);\n\n  if (w->c_prev)\n    gsl_vector_free(w->c_prev);\n\n  if (w->resfac)\n    gsl_vector_free(w->resfac);\n\n  if (w->psi)\n    gsl_vector_free(w->psi);\n\n  if (w->dpsi)\n    gsl_vector_free(w->dpsi);\n\n  if (w->QSI)\n    gsl_matrix_free(w->QSI);\n\n  if (w->D)\n    gsl_vector_free(w->D);\n\n  if (w->workn)\n    gsl_vector_free(w->workn);\n\n  free(w);\n} /* gsl_multifit_robust_free() */\n\nint\ngsl_multifit_robust_tune(const double tune, gsl_multifit_robust_workspace *w)\n{\n  w->tune = tune;\n  return GSL_SUCCESS;\n}\n\nconst char *\ngsl_multifit_robust_name(const gsl_multifit_robust_workspace *w)\n{\n  return w->type->name;\n}\n\ngsl_multifit_robust_stats\ngsl_multifit_robust_statistics(const gsl_multifit_robust_workspace *w)\n{\n  return w->stats;\n}\n\n/*\ngsl_multifit_robust()\n  Perform robust iteratively reweighted linear least squares\nfit\n\nInputs: X     - design matrix of basis functions\n        y     - right hand side vector\n        c     - (output) model coefficients\n        cov   - (output) covariance matrix\n        w     - workspace\n*/\n\nint\ngsl_multifit_robust(const gsl_matrix * X,\n                    const gsl_vector * y,\n                    gsl_vector * c,\n                    gsl_matrix * cov,\n                    gsl_multifit_robust_workspace *w)\n{\n  /* check matrix and vector sizes */\n  if (X->size1 != y->size)\n    {\n      GSL_ERROR\n        (\"number of observations in y does not match rows of matrix X\",\n         GSL_EBADLEN);\n    }\n  else if (X->size2 != c->size)\n    {\n      GSL_ERROR (\"number of parameters c does not match columns of matrix X\",\n                 GSL_EBADLEN);\n    }\n  else if (cov->size1 != cov->size2)\n    {\n      GSL_ERROR (\"covariance matrix is not square\", GSL_ENOTSQR);\n    }\n  else if (c->size != cov->size1)\n    {\n      GSL_ERROR\n        (\"number of parameters does not match size of covariance matrix\",\n         GSL_EBADLEN);\n    }\n  else if (X->size1 != w->n || X->size2 != w->p)\n    {\n      GSL_ERROR\n        (\"size of workspace does not match size of observation matrix\",\n         GSL_EBADLEN);\n    }\n  else\n    {\n      int s;\n      double chisq;\n      const double tol = GSL_SQRT_DBL_EPSILON;\n      int converged = 0;\n      size_t numit = 0;\n      const size_t n = y->size;\n      double sigy = gsl_stats_sd(y->data, y->stride, n);\n      double sig_lower;\n      size_t i;\n\n      /*\n       * if the initial fit is very good, then finding outliers by comparing\n       * them to the residual standard deviation is difficult. Therefore we\n       * set a lower bound on the standard deviation estimate that is a small\n       * fraction of the standard deviation of the data values\n       */\n      sig_lower = 1.0e-6 * sigy;\n      if (sig_lower == 0.0)\n        sig_lower = 1.0;\n\n      /* compute initial estimates using ordinary least squares */\n      s = gsl_multifit_linear(X, y, c, cov, &chisq, w->multifit_p);\n      if (s)\n        return s;\n\n      /* save Q S^{-1} of original matrix */\n      gsl_matrix_memcpy(w->QSI, w->multifit_p->QSI);\n      gsl_vector_memcpy(w->D, w->multifit_p->D);\n\n      /* compute statistical leverage of each data point */\n      s = gsl_linalg_SV_leverage(w->multifit_p->A, w->resfac);\n      if (s)\n        return s;\n\n      /* correct residuals with factor 1 / sqrt(1 - h) */\n      for (i = 0; i < n; ++i)\n        {\n          double h = gsl_vector_get(w->resfac, i);\n\n          if (h > 0.9999)\n            h = 0.9999;\n\n          gsl_vector_set(w->resfac, i, 1.0 / sqrt(1.0 - h));\n        }\n\n      /* compute residuals from OLS fit r = y - X c */\n      s = gsl_multifit_linear_residuals(X, y, c, w->r);\n      if (s)\n        return s;\n\n      /* compute estimate of sigma from ordinary least squares */\n      w->stats.sigma_ols = gsl_blas_dnrm2(w->r) / sqrt((double) w->stats.dof);\n\n      while (!converged && ++numit <= w->maxiter)\n        {\n          double sig;\n\n          /* adjust residuals by statistical leverage (see DuMouchel and O'Brien) */\n          s = gsl_vector_mul(w->r, w->resfac);\n          if (s)\n            return s;\n\n          /* compute estimate of standard deviation using MAD */\n          sig = robust_madsigma(w->r, w);\n\n          /* scale residuals by standard deviation and tuning parameter */\n          gsl_vector_scale(w->r, 1.0 / (GSL_MAX(sig, sig_lower) * w->tune));\n\n          /* compute weights using these residuals */\n          s = w->type->wfun(w->r, w->weights);\n          if (s)\n            return s;\n\n          gsl_vector_memcpy(w->c_prev, c);\n\n          /* solve weighted least squares with new weights */\n          s = gsl_multifit_wlinear(X, w->weights, y, c, cov, &chisq, w->multifit_p);\n          if (s)\n            return s;\n\n          /* compute new residuals r = y - X c */\n          s = gsl_multifit_linear_residuals(X, y, c, w->r);\n          if (s)\n            return s;\n\n          converged = robust_test_convergence(w->c_prev, c, tol);\n        }\n\n      /* compute final MAD sigma */\n      w->stats.sigma_mad = robust_madsigma(w->r, w);\n\n      /* compute robust estimate of sigma */\n      w->stats.sigma_rob = robust_robsigma(w->r, w->stats.sigma_mad, w->tune, w);\n\n      /* compute final estimate of sigma */\n      w->stats.sigma = robust_sigma(w->stats.sigma_ols, w->stats.sigma_rob, w);\n\n      /* store number of iterations */\n      w->stats.numit = numit;\n\n      {\n        double dof = (double) w->stats.dof;\n        double rnorm = w->stats.sigma * sqrt(dof); /* see DuMouchel, sec 4.2 */\n        double ss_err = rnorm * rnorm;\n        double ss_tot = gsl_stats_tss(y->data, y->stride, n);\n\n        /* compute R^2 */\n        w->stats.Rsq = 1.0 - ss_err / ss_tot;\n\n        /* compute adjusted R^2 */\n        w->stats.adj_Rsq = 1.0 - (1.0 - w->stats.Rsq) * (n - 1.0) / dof;\n\n        /* compute rmse */\n        w->stats.rmse = sqrt(ss_err / dof);\n\n        /* store SSE */\n        w->stats.sse = ss_err;\n      }\n\n      /* calculate covariance matrix = sigma^2 (X^T X)^{-1} */\n      s = robust_covariance(w->stats.sigma, cov, w);\n      if (s)\n        return s;\n\n      /* raise an error if not converged */\n/* bdavis */\n      /* Eliminating this check is to avoid an error when iterations */\n      /* exceed 5.  A better solution is probably recommended, such as */\n      /* reverting to default of 100 if an input specification is not */\n      /* enabled and defined. */\n      /* bdavis@usgs.gov */\n      /*\n      if (numit > w->maxiter)\n        {\n          GSL_ERROR(\"maximum iterations exceeded\", GSL_EMAXITER);\n        }\n      */\n/* bdavis */\n\n      return s;\n    }\n} /* gsl_multifit_robust() */\n\n/* Estimation of values for given x */\nint\ngsl_multifit_robust_est(const gsl_vector * x, const gsl_vector * c,\n                        const gsl_matrix * cov, double *y, double *y_err)\n{\n  int s = gsl_multifit_linear_est(x, c, cov, y, y_err);\n\n  return s;\n}\n\n/***********************************\n * INTERNAL ROUTINES               *\n ***********************************/\n\n/*\nrobust_test_convergence()\n  Test for convergence in robust least squares\n\nConvergence criteria:\n\n|c_i^(k) - c_i^(k-1)| <= tol * max(|c_i^(k)|, |c_i^(k-1)|)\n\nfor all i. k refers to iteration number.\n\nInputs: c_prev - coefficients from previous iteration\n        c      - coefficients from current iteration\n        tol    - tolerance\n\nReturn: 1 if converged, 0 if not\n*/\n\nstatic int\nrobust_test_convergence(const gsl_vector *c_prev, const gsl_vector *c,\n                        const double tol)\n{\n  size_t p = c->size;\n  size_t i;\n\n  for (i = 0; i < p; ++i)\n    {\n      double ai = gsl_vector_get(c_prev, i);\n      double bi = gsl_vector_get(c, i);\n\n      if (fabs(bi - ai) > tol * GSL_MAX(fabs(ai), fabs(bi)))\n        return 0; /* not yet converged */\n    }\n\n  /* converged */\n  return 1;\n} /* robust_test_convergence() */\n\n/*\nrobust_madsigma()\n  Estimate the standard deviation of the residuals using\nthe Median-Absolute-Deviation (MAD) of the residuals,\nthrowing away the smallest p residuals.\n\nSee: Street et al, 1988\n\nInputs: r - vector of residuals\n        w - workspace\n*/\n\nstatic double\nrobust_madsigma(const gsl_vector *r, gsl_multifit_robust_workspace *w)\n{\n  gsl_vector_view v;\n  double sigma;\n  size_t n = r->size;\n  const size_t p = w->p;\n  size_t i;\n\n  /* copy |r| into workn */\n  for (i = 0; i < n; ++i)\n    {\n      gsl_vector_set(w->workn, i, fabs(gsl_vector_get(r, i)));\n    }\n\n  gsl_sort_vector(w->workn);\n\n  /*\n   * ignore the smallest p residuals when computing the median\n   * (see Street et al 1988)\n   */\n  v = gsl_vector_subvector(w->workn, p - 1, n - p + 1);\n  sigma = gsl_stats_median_from_sorted_data(v.vector.data, v.vector.stride, v.vector.size) / 0.6745;\n\n  return sigma;\n} /* robust_madsigma() */\n\n/*\nrobust_robsigma()\n  Compute robust estimate of sigma so that\nsigma^2 * inv(X' * X) is a reasonable estimate of\nthe covariance for robust regression. Based heavily\non the equations of Street et al, 1988.\n\nInputs: r    - vector of residuals y - X c\n        s    - sigma estimate using MAD\n        tune - tuning constant\n        w    - workspace\n*/\n\nstatic double\nrobust_robsigma(const gsl_vector *r, const double s,\n                const double tune, gsl_multifit_robust_workspace *w)\n{\n  double sigma;\n  size_t i;\n  const size_t n = w->n;\n  const size_t p = w->p;\n  const double st = s * tune;\n  double a, b, lambda;\n\n  /* compute u = r / sqrt(1 - h) / st */\n  gsl_vector_memcpy(w->workn, r);\n  gsl_vector_mul(w->workn, w->resfac);\n  gsl_vector_scale(w->workn, 1.0 / st);\n\n  /* compute w(u) and psi'(u) */\n  w->type->wfun(w->workn, w->psi);\n  w->type->psi_deriv(w->workn, w->dpsi);\n\n  /* compute psi(u) = u*w(u) */\n  gsl_vector_mul(w->psi, w->workn);\n\n  /* Street et al, Eq (3) */\n  a = gsl_stats_mean(w->dpsi->data, w->dpsi->stride, n);\n\n  /* Street et al, Eq (5) */\n  b = 0.0;\n  for (i = 0; i < n; ++i)\n    {\n      double psi_i = gsl_vector_get(w->psi, i);\n      double resfac = gsl_vector_get(w->resfac, i);\n      double fac = 1.0 / (resfac*resfac); /* 1 - h */\n\n      b += fac * psi_i * psi_i;\n    }\n  b /= (double) (n - p);\n\n  /* Street et al, Eq (5) */\n  lambda = 1.0 + ((double)p)/((double)n) * (1.0 - a) / a;\n\n  sigma = lambda * sqrt(b) * st / a;\n\n  return sigma;\n} /* robust_robsigma() */\n\n/*\nrobust_sigma()\n  Compute final estimate of residual standard deviation, using\nthe OLS and robust sigma estimates.\n\nThis equation is taken from DuMouchel and O'Brien, sec 4.1:\n\\hat{\\sigma_R}\n\nInputs: s_ols - OLS sigma\n        s_rob - robust sigma\n        w     - workspace\n\nReturn: final estimate of sigma\n*/\n\nstatic double\nrobust_sigma(const double s_ols, const double s_rob,\n             gsl_multifit_robust_workspace *w)\n{\n  double sigma;\n  const size_t p = w->p;\n  const size_t n = w->n;\n\n  /* see DuMouchel and O'Brien, sec 4.1 */\n  sigma = GSL_MAX(s_rob,\n                  sqrt((s_ols*s_ols*p*p + s_rob*s_rob*n) /\n                       (p*p + n)));\n\n  return sigma;\n} /* robust_sigma() */\n\n/*\nrobust_covariance()\n  Calculate final covariance matrix, defined as:\n\n  sigma * (X^T X)^{-1}\n\nInputs: sigma - residual standard deviation\n        cov   - (output) covariance matrix\n        w     - workspace\n*/\n\nstatic int\nrobust_covariance(const double sigma, gsl_matrix *cov,\n                  gsl_multifit_robust_workspace *w)\n{\n  int s = 0;\n  const size_t p = w->p;\n  const double s2 = sigma * sigma;\n  size_t i, j;\n  gsl_matrix *QSI = w->QSI;\n  gsl_vector *D = w->D;\n\n  /* Form variance-covariance matrix cov = s2 * (Q S^-1) (Q S^-1)^T */\n\n  for (i = 0; i < p; i++)\n    {\n      gsl_vector_view row_i = gsl_matrix_row (QSI, i);\n      double d_i = gsl_vector_get (D, i);\n\n      for (j = i; j < p; j++)\n        {\n          gsl_vector_view row_j = gsl_matrix_row (QSI, j);\n          double d_j = gsl_vector_get (D, j);\n          double s;\n\n          gsl_blas_ddot (&row_i.vector, &row_j.vector, &s);\n\n          gsl_matrix_set (cov, i, j, s * s2 / (d_i * d_j));\n          gsl_matrix_set (cov, j, i, s * s2 / (d_i * d_j));\n        }\n    }\n\n  return s;\n} /* robust_covariance() */\n", "meta": {"hexsha": "594feb5c068ebe2c34bb0ef4adbe20c3128695f4", "size": 17233, "ext": "c", "lang": "C", "max_stars_repo_path": "C/AFMapTSComposite/multirobust.c", "max_stars_repo_name": "agroimpacts/imager", "max_stars_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T18:48:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T18:48:12.000Z", "max_issues_repo_path": "C/AFMapTSComposite/multirobust.c", "max_issues_repo_name": "agroimpacts/imager", "max_issues_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "max_issues_repo_licenses": ["Apache-2.0"], "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/AFMapTSComposite/multirobust.c", "max_forks_repo_name": "agroimpacts/imager", "max_forks_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42", "max_forks_repo_licenses": ["Apache-2.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.5941358025, "max_line_length": 100, "alphanum_fraction": 0.6053502002, "num_tokens": 4978, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.384502174363668}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_matrix.h>\n#include \"globals.h\"\n#include \"SimulationSteps.h\"\n\n\n//#define WDON\n\nint P;\nint Np;\ngsl_matrix *LIFT;\ngsl_matrix *VolMat;\ngsl_matrix *MassMatrix;\n\nint main(int argc, char **argv)\n{\n\tif (argc != 2)\n\t{\n\t\tprintf(\"Usage: ./Simulation 'Fort.14'\\n\");\n\t\tprintf(\"Fort.14: Mesh for the channel\\n\");\n\t\texit(EXIT_FAILURE);\n\n\t}\n\t\n\tchar *Mesh = argv[1];\n\t\n\t//printf(\"Enter the polynomial approximation order:\\n\");\n\t//scanf(\"%d\", &P);\n\n\tP = 1;\n\tNp = P+1;\n\n\n\tstore_mesh(Mesh);\n\n/*\tfor (int i = 0; i < NumEl; i++)\n\t{\n\t\tfor (int j = 0; j < Np; j++)\n\t\t\tprintf(\"x = %lf \\t z = %lf \\t S0 = %3.18lf\\n\", NodalX[i*Np+j] , Nodalz[i*Np+j], dz[i*Np+j]);\n\t}\n\n\texit(1);\n*/\t// Create VolMat, LIFT and MassMatrix\n\tcalculateLIFTVolMat(P, Np, &LIFT, &VolMat, &MassMatrix);\n\n\tdouble FinalTime;\n\n\tprintf(\"Enter the time you would like to run the simulation till:\\n\");\n\tscanf(\"%lf\", &FinalTime);\n\t\n\n\tinitialize();\n\n\t/* Impose boundary conditions and couple the channels to the junction */\n\tboundary_conditions();\n\n\t/* Step through time */\n\n\ttime_evolution(FinalTime);\n\n\treturn(0);\n\n}\n\n\n \n\t\n\t\n", "meta": {"hexsha": "efcb8923722a5869ac6e7d51bb97e588bd9aa0b5", "size": 1143, "ext": "c", "lang": "C", "max_stars_repo_path": "1DCode/main.c", "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_issues_repo_path": "1DCode/main.c", "max_issues_repo_name": "evalseth/DG-RAIN", "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1DCode/main.c", "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "avg_line_length": 16.0985915493, "max_line_length": 95, "alphanum_fraction": 0.6307961505, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3844277324436496}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_multimin.h>\n#include <gsl/gsl_sf.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_cdf.h>\n#include <gsl/gsl_linalg.h>\n#include <getopt.h>\n#include <string.h>\n\n#include \"libhdr\"\n#include \"Library_DFE_v1.8.h\"\n\n\n/*\n  version 1.7.3: \n  -added: constant population support\n  -added: generate gamma distribution deviates\n  -added: generate beta distribution deviates\n  -added: generate gamma+beta distribution deviates\n\n  to compile:\n\n  gcc -O3 -o bin/Multi_DFE_gen_v1.8 Multi_DFE_gen_v1.8.c Library_DFE_v1.8.c tmatrix_routines.c genlib.c nrlib.c nrutil.c  -lm -lgsl -lgslcblas -w\n\n\n  example run:\n\n  GSL_RNG_SEED=1 ~/Multi_DFE_est/source/bin/Multi_DFE_gen_v1.8 -N1 100 -N2 100 -nalleles 20 -t 100 -f0 0.9 -neutral 1000000 -selected 1000000 -mode 9 -conpop 1 -exp_mean 0.05 -file 1.out\n\n  #-gamma_alpha 10 -gamma_beta 0.5\n  #-exp_mean 0.02 -beta_alpha 10 -beta_beta 1\n  #-exp_mean 0.02 -gamma_alpha 1000 -gamma_beta 50\n  #-gamma_alpha 70 -gamma_beta 0.07 -gamma2_alpha 1000 -gamma2_beta 50\n  #-exp_mean 0.05\n\n*/\n\n\n/*Global variable declaration*/\nint selmode=0;\nint  n_sfs=0;\nint nspikes=1;//default a single spike\n\nint N1,N2=100;\nint max_n2d=2000;\ndouble saveresults[100];\nint n2_step=0, conpop=0, output_egf_mode=0;\n\n/*Function list*/\ndouble load_FV(int n1,int n2,int t2,double s,double f0,double *mean_FV);\n\n/******************************************************************************/\ndouble load_FV(int n1,int n2,int t2,double s,double f0,double *mean_FV)\n{\n  \n  static double egf_vec1_lower[maxnd+1], egf_vec2_lower[maxnd+1], \n    egf_vec1_upper[maxnd+1], egf_vec2_upper[maxnd+1],\n    egf_vec1[maxnd+1], egf_vec2[maxnd+1],egf_vec[maxnd+1];\n\n  double *gamma_density_vec;\n\n  int i=0,j=0,file_size_bytes=0;\n  int t2_upper=0;\n  int t2_real=t2;\n  int n1d=2*n1;\n  int n2d=2*n2;\n\n\n  char *buffer_p1_t2_lower, *buffer_p2_t2_lower,\n    *buffer_p1_t2_upper, *buffer_p2_t2_upper, *buffer_const_pop;\n  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n  if (!conpop)\n    {\n      get_upper_lower_int(t2_real, &t2_lower, &t2_upper, n_t2_evaluated, t2_evaluated_vec);\n      if ((t2_lower==undefined_int)||(t2_upper==undefined_int))\n\t{\n\t  return undefined;\n\t}\n      //printf(\"\\n%d\",t2_lower);\n      //printf(\"\\n%f\",s);\n      file_size_bytes=compute_file_size_bytes(n2);\n      //Read buffers\n      ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n      buffer_p1_t2_lower = (char*) malloc (file_size_bytes);\n      buffer_p1_t2_upper = (char*) malloc (file_size_bytes);\n\n      buffer_p2_t2_lower = (char*) malloc (file_size_bytes);\n      buffer_p2_t2_upper = (char*) malloc (file_size_bytes);\n\n      read_phase1_phase2_file_into_buffer(n1,1, n2, t2_lower,\n\t\t\t\t\t  buffer_p1_t2_lower, file_size_bytes);\n      read_phase1_phase2_file_into_buffer(n1,1, n2, t2_upper,\n\t\t\t\t\t  buffer_p1_t2_upper, file_size_bytes);\n\n      read_phase1_phase2_file_into_buffer(n1,2, n2, t2_lower,\n\t\t\t\t\t  buffer_p2_t2_lower, file_size_bytes);\n      read_phase1_phase2_file_into_buffer(n1,2, n2, t2_upper,\n\t\t\t\t\t  buffer_p2_t2_upper, file_size_bytes);\n\n      get_binary_egf_vec(buffer_p1_t2_lower, n2, t2_lower, s, egf_vec1_lower);\n      get_binary_egf_vec(buffer_p1_t2_upper, n2, t2_upper, s, egf_vec1_upper);\n\n\n      get_binary_egf_vec(buffer_p2_t2_lower, n2, t2_lower, s, egf_vec2_lower);\n      get_binary_egf_vec(buffer_p2_t2_upper, n2, t2_upper, s, egf_vec2_upper);\n      //End reading buffers\n      ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n      //Averaging vectors w(s) and x(s)\n\n      compute_weighted_average_egf_vec(t2_real, t2_lower, t2_upper,\n\t\t\t\t       egf_vec1_lower, egf_vec1_upper, egf_vec1, n2d);\n      compute_weighted_average_egf_vec(t2_real, t2_lower, t2_upper,\n\t\t\t\t       egf_vec2_lower, egf_vec2_upper, egf_vec2, n2d);\n      ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n      //dumpvector(egf_vec1,0,210,\"egf_vec1\"); \n      //printf(\"\\n%d\\t%d\",t2_lower, t2_upper);\n      //dumpvector(egf_vec2,0,210,\"egf_vec2\"); \n      compute_weighted_average( mean_FV, egf_vec1, egf_vec2, n1d, n2d);\n\n\n      free(buffer_p1_t2_lower);\n      free(buffer_p2_t2_lower);\n      free(buffer_p1_t2_upper);\n      free(buffer_p2_t2_upper);\n    }   \n  else//constant population\n    {\n      if (2*n1 > max_n2d)\n\t{\n\t  printf(\"ERROR: Value of 2*n1 %d exceeds max_n2d %d\\n\", n1, max_n2d);\n\t  gabort(\"Program terminating\", 0);\n\t}\n      file_size_bytes = compute_file_size_bytes(n1);\n      //      printf(\"const pop: file_size_bytes %d\\n\", file_size_bytes); monitorinput();\n      buffer_const_pop = (char*) malloc (file_size_bytes);\n\n      read_const_pop_file_into_buffer(n1, buffer_const_pop, file_size_bytes);\n      get_const_pop_egf_vec(s, n1, mean_FV, buffer_const_pop, 1);\n\n\n      free(buffer_const_pop);\n    } \n\n\n  return (1);\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\nstatic int verbose_flag;\nmain(argc,argv)\nint argc; char **argv;\n{\n  int i=0,j=0;\n  int nalleles=0;\n  double f0=0;\n  int t=0;\n  int nspikes=0;\n  int sampleS=0,sampleN=0;\n\n  double beta_alpha=0,beta_beta=0,gamma_alpha=0, gamma_beta=0,gamma2_alpha=0,gamma2_beta=0,exp_mean=0,exp_mean2=0,\n    sel_coeff1=0,sel_coeff2=0,sel_coeff3=0,prob1=0,prob2=0,prob3=0;\n  char *sfs_filename;\n\n  /*\n    location parameters measured\n    Mean,squared mean,harmonic mean\n  */\n  double MEAN_S=0,MEAN_S2=0,MEAN_H=0,fix_prob=0;\n\n  int c;\n     \n  while (1)\n    {\n      static struct option long_options[] =\n\t{\n\t  /* These options set a flag. */\n\t  // {\"verbose\", no_argument,       &verbose_flag, 1},\n\t  // {\"brief\",   no_argument,       &verbose_flag, 0},\n\t  /* These options don't set a flag.\n\t     We distinguish them by their indices. */\n\t  {\"N1\",     required_argument,0, 'a'},\n\t  {\"N2\",  required_argument,0, 'b'},\n\t  {\"nalleles\",  required_argument, 0, 'c'},\n\t  {\"t\",  required_argument, 0, 'd'},\n\t  {\"f0\",    required_argument, 0, 'e'},\n\t  {\"neutral\",    required_argument, 0, 'f'},\n\t  {\"selected\",    required_argument, 0, 'g'},\n\t  {\"mode\",    required_argument, 0, 'h'},\n\t  {\"nspikes\",    required_argument, 0, 'i'},\n\t  {\"gamma_alpha\",    required_argument, 0, 'j'},\n\t  {\"gamma_beta\",    required_argument, 0, 'k'},\n\t  {\"beta_alpha\",    required_argument, 0, 'l'},\n\t  {\"beta_beta\",    required_argument, 0, 'm'},\n\t  {\"gamma2_alpha\",    required_argument, 0, 'n'},\n\t  {\"gamma2_beta\",    required_argument, 0, 'o'},\n\t  {\"exp_mean\",    required_argument, 0, 'p'},\n\t  {\"conpop\",    required_argument, 0, 'q'},\n\t  {\"file\",    required_argument, 0, 'r'},\n\t  {\"exp_mean2\",    required_argument, 0, 's'},\n\t  {\"s1\",    required_argument, 0, 't'},\t  \n\t  {\"s2\",    required_argument, 0, 'u'},\n\t  {\"s3\",    required_argument, 0, 'v'},\t  \n\t  {\"p1\",    required_argument, 0, 'w'},\n\t  {\"p2\",    required_argument, 0, 'x'},\n\t  {\"p3\",    required_argument, 0, 'y'},\n\t  {0, 0, 0, 0}\n\t};\n      /* getopt_long stores the option index here. */\n      int option_index = 0;\n     \n      c = getopt_long_only (argc, argv, \"\",\n                            long_options, &option_index);\n     \n      /* Detect the end of the options. */\n      if (c == -1)\n\tbreak;\n     \n      switch (c)\n\t{\n\tcase 0:\n\t  /* If this option set a flag, do nothing else now. */\n\t  if (long_options[option_index].flag != 0)\n\t    break;\n\t  printf (\"option %s\", long_options[option_index].name);\n\t  if (optarg)\n\t    printf (\" with arg %s\", optarg);\n\t  printf (\"\\nalleles\");\n\t  break;\n\n\tcase 'a':\n\t  N1=atoi(optarg);\n\t  break;   \n\tcase 'b':\n\t  N2=atoi(optarg);\n\t  break;     \n\tcase 'c':\n\t  nalleles=atoi(optarg);\n\t  break;     \n\tcase 'd':\n\t  t=atof(optarg);\n\t  break;     \n\tcase 'e':\n\t  f0=atof(optarg);\n\t  break;\n\tcase 'f':\n\t  sampleS=atoi(optarg);\n\t  break;\n\tcase 'g':\n\t  sampleN=atoi(optarg);\n\t  break;\n\tcase 'h':\n\t  selmode=atoi(optarg);\n\t  break;\n\tcase 'i':\n\t  nspikes=atoi(optarg);\n\t  break;\n\tcase 'j':\n\t  gamma_alpha=atof(optarg);\n\t  break;\n\tcase 'k':\n\t  gamma_beta=atof(optarg);\n\t  break;\n\tcase 'l':\n\t  beta_alpha=atof(optarg);\n\t  break;\n\tcase 'm':\n\t  beta_beta=atof(optarg);\n\t  break;\n\tcase 'n':\n\t  gamma2_alpha=atof(optarg);\n\t  break;\n\tcase 'o':\n\t  gamma2_beta=atof(optarg);\n\t  break;\n\tcase 'p':\n\t  exp_mean=atof(optarg);\n\t  break;\n\tcase 'q':\n\t  conpop=atoi(optarg);\n\t  break;\n\tcase 'r':\n\t  sfs_filename=optarg;\n\t  break;     \n\tcase 's':\n\t  exp_mean2=atof(optarg);\n\t  break;  \n\tcase 't':\n\t  sel_coeff1=atof(optarg);\n\t  break; \n\tcase 'u':\n\t  sel_coeff2=atof(optarg);\n\t  break; \n\tcase 'v':\n\t  sel_coeff3=atof(optarg);\n\t  break; \n\tcase 'w':\n\t  prob1=atof(optarg);\n\t  break; \n\tcase 'x':\n\t  prob2=atof(optarg);\n\t  break; \n\tcase 'y':\n\t  prob3=atof(optarg);\n\t  break; \t     \n\tcase '?':\n\t  /* getopt_long already printed an error message. */\n\t  break;\n     \n\tdefault:\n\t  abort ();\n\t}\n    }\n\n  /* Print any remaining command line arguments (not options). */\n  if (optind < argc)\n    {\n      printf (\"non-option ARGV-elements: \");\n      while (optind < argc)\n\tprintf (\"%s \", argv[optind++]);\n      putchar ('\\n');\n    }\n\n\n  double n1d=2*N1;\n  double n2d=2*N2;\n  /*find n_e*/\n  double prop[4],n_es=0;\n  double n_e=calculate_ne(N1,N2,t);   \n\n  /*Set up Spikes*/ \n  double * spikes_vec = (double*) calloc (nspikes+1, sizeof(double));\n  double * prob_vec = (double*) calloc (nspikes+1, sizeof(double));\n\n  for(i = 1; i <= nspikes; i++){\n    printf(\"Give s for spike %d:\\n\", i);\n    scanf(\"%lf\",&spikes_vec[i]);\n  }\n  spikes_vec[0]=0;\n\n  double sum_prob=0;\n  for(i = 1; i <= nspikes-1; i++){\n    printf(\"Give probability of Spike %d:\\n\", i);\n    scanf(\"%lf\",&prob_vec[i]);\n    sum_prob+=prob_vec[i];\n  }\n  prob_vec[nspikes]=1-sum_prob;\n  prob_vec[0]=0;\n\n  double **FVSX= calloc(maxnd+1, sizeof(double *));\n\n  for(i = 1; i <= nspikes; i++){\n    FVSX[i] = calloc(maxnd+1,  sizeof(double));\n  }\n  double * FV0 = (double*) calloc (maxnd+1, sizeof(double));\n\n  /*Set up Tables*/\n\n  get_data_path(data_path);\n  set_up_file_name(N1, s_evaluated_vec_file_const, s_evaluated_vec_file);\n  set_up_file_name(N1, s_range_file_const, s_range_file);\n  get_s_evaluated_vec(s_evaluated_vec, &n_s_evaluated, &n_s_evaluated_file, \n\t\t      s_evaluated_vec_file);\n  get_s_ranges();\n\n  if (!conpop)\n    {\n      set_up_file_name(N1, n2_evaluated_vec_file_const, n2_evaluated_vec_file);\n      set_up_file_name(N1, t2_evaluated_vec_file_const, t2_evaluated_vec_file);\n      set_up_file_name(N1, phase_1_dir_const, phase_1_dir);\n      set_up_file_name(N1, phase_2_dir_const, phase_2_dir);\n\n      get_int_evaluated_vec(t2_evaluated_vec,&n_t2_evaluated, &t2_lower,\n\t\t\t    &t2_step,&t2_evaluated_vec_file);\n      get_int_evaluated_vec(n2_evaluated_vec,&n_n2_evaluated, &n2_lower,\n\t\t\t    &n2_step,&n2_evaluated_vec_file);\n    }\n  else\n    {\n      set_up_file_name(N1, \"\", const_pop_dir);\n    }\n \n  /* calculate neutral frequency vector*/ \n  load_FV(N1,N2,t,0.0,f0,FV0);\n\n  /*Sampling of sites*/\n  int * discrete0 = (int*) calloc (nalleles+2, sizeof(int));\n  int * discrete1 = (int*) calloc (nalleles+2, sizeof(int));\n\n  const gsl_rng_type * T;\n  double selcoeff=0,uniform=0;\n\n  gsl_rng_env_setup();\n  T = gsl_rng_taus;\n  gsl_rng  *rgen =gsl_rng_alloc(T);\n  \n  printf(\"%f,%f\\n\",gamma_alpha,gamma_beta);\n  i=1;\n  while (i<=sampleN)\n    {// loop for sampling starts here\n      i++;\n      uniform=gsl_rng_uniform (rgen);\n      double * FVS = (double*) calloc (maxnd+1, sizeof(double));\n      selcoeff=0;\n      switch(selmode)\n\t{\n\tcase 0:case 1:\n\t  break;\n\tcase 2:\n\t  selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);\n\t  break;\n\tcase 3:\n\t  selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);\n\t  break;\n\tcase 4:\n\t  if (uniform<=0.2) {selcoeff=gsl_ran_exponential(rgen,exp_mean);}\n\t  if (uniform>0.2) {selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);}\n\t  break;\n\tcase 5:\n\t  if (uniform<=0.5) {selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);}\n\t  if (uniform>0.5) {selcoeff=gsl_ran_gamma (rgen, gamma2_beta, 1/gamma2_alpha);}\n\t  break;\n\tcase 6:\n\t  if (uniform<=0.5) {selcoeff=gsl_ran_exponential(rgen, exp_mean);}\n\t  if (uniform>0.5) {selcoeff=gsl_ran_exponential (rgen, exp_mean2);}\n\t  break;\n\tcase 7:\n\t  if (uniform<=0.5) {selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);}\n\t  if (uniform>0.5) {selcoeff=gsl_ran_exponential (rgen, exp_mean);}\n\t  break; \n\tcase 8:\n\t  if (uniform<=0.8) {selcoeff=gsl_ran_exponential(rgen,exp_mean);}\n\t  if (uniform>0.8) {selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);}\n\t  break;\n\tcase 9:\n          selcoeff=gsl_ran_exponential(rgen,exp_mean);\n\t  break;\n\tcase 10:\n          if (uniform<=0.5) {selcoeff=0.0;}\n          if (uniform>0.5) {selcoeff=0.05;}\n\t  break;\n\tcase 11:\n          if (uniform<=(0.3)) {selcoeff=0.0;}\n          if (uniform>0.33&&uniform<=0.67) {selcoeff=0.05;}\n          if (uniform>0.67) {selcoeff=0.5;}\n\t  break;\n    case 12:\n          if (uniform<=0.3) {selcoeff=0;}//gsl_ran_gaussian (rgen,1e-5);}\n          if (uniform>0.3&&uniform<=0.4) {selcoeff=-0.05;}//gsl_ran_gaussian (rgen,1e-5);selcoeff+=0.005;}\n          if (uniform>0.4&&uniform<=0.6) {selcoeff=-0.5;}//gsl_ran_gaussian (rgen,1e-5);selcoeff+=0.05;}\n          if (uniform>0.6) {selcoeff=-5;} //gsl_ran_gaussian (rgen,1e-5);selcoeff+=0.5;}\n\t  break;\n\tcase 13:\n          selcoeff=uniform;\n\t  break;\n    case 14:\n\t  if (uniform<=0.5) {selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);}\n\t  if (uniform>0.5) {selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);}\n\t  break;\n    case 15:\n\t  if (uniform<=0.2) {selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);}\n\t  if (uniform>0.2) {selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);}\n\t  break;\n    case 16:\n\t  if (uniform<=0.8) {selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);}\n\t  if (uniform>0.8) {selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);}\n\t  break;\n \tcase 17:\n          if (uniform<=(0.3)) {selcoeff=0.0;}\n          if (uniform>0.33&&uniform<=0.67) {selcoeff=0.03;}\n          if (uniform>0.67) {selcoeff=0.06;}\n\t  break;\t\n\tcase 18:\n          if (uniform<=0.2) {selcoeff=sel_coeff1;}\n          if (uniform>0.2&&uniform<=0.8) {selcoeff=sel_coeff2;}\n          if (uniform>0.8) {selcoeff=sel_coeff3;}\n\t  break;\n\tcase 19:\n          if (uniform<=0.3) {selcoeff=0;}\n          if (uniform>0.3) {selcoeff=0.05;}\n\t  break;\n\tcase 20:\n          if (uniform<=0.2) {selcoeff=0;}\n          if (uniform>0.2&&uniform<=0.4) {selcoeff=0.05;}\n          if (uniform>0.4) {selcoeff=0.5;}\n\t  break;\n\tcase 21:\n          if (uniform<=0.2) {selcoeff=0;}\n          if (uniform>0.2&&uniform<=0.4) {selcoeff=0.02;}\n          if (uniform>0.4&&uniform<=0.6) {selcoeff=0.05;}\n          if (uniform>0.6) {selcoeff=0.1;}\n          break;\n    case 22:\n\t  selcoeff=exp_mean;\n\t  break;\n    case 23:\n\t  selcoeff=gsl_ran_lognormal (rgen, gamma_alpha, gamma_beta);\n\t  break;\n\tcase 24:\n          if (uniform<=0.2) {selcoeff=sel_coeff1;}\n          if (uniform>0.2) {selcoeff=sel_coeff2;}\n\t  break;\t\n    case 25:\n          if (uniform<=0.5) {selcoeff=sel_coeff1;}\n          if (uniform>0.5) {selcoeff=sel_coeff2;}\n\t  break;\t\n\tcase 26:\n          if (uniform<=prob1) {selcoeff=sel_coeff1;}\n          if (uniform>prob1) {selcoeff=sel_coeff2;}\n\t  break;\n\tcase 27:\n          if (uniform<=prob1) {selcoeff=sel_coeff1;}\n          if (uniform>=prob1) {selcoeff=sel_coeff1;}\n          if (uniform>prob1) {selcoeff=sel_coeff2;}\n\t  break;\n\t}//end switch\n\n      //monitorinput(); \n      if(selcoeff>0){selcoeff=-selcoeff;}\n      if (selcoeff<-100) {selcoeff=-100;}//free(FVS);continue;}//free(FVS);continue;\n      //printf(\"%f\\n\",selcoeff);\n      MEAN_S+=selcoeff;\n      MEAN_S2+=-pow(selcoeff,2);\n      MEAN_H+=1/selcoeff;\n      \n\n      if (selcoeff== 0)\n        {\n\t  fix_prob += 0.5/n_e;\n\t}\n      else\n\t{\n\t  fix_prob += kimura_fixation_prob(selcoeff, n_e);\n\t}       \n      \n      \n      /*calculate relative proportions*/\n      n_es=-n_e*selcoeff;\n      if (n_es<=0.1){prop[0]++;}\n      if (n_es<=1.0){prop[1]++;}\n      if (n_es<=10.0){prop[2]++;}\n      if (n_es<100.0){prop[3]++;}\n      \n      load_FV(N1,N2,t,selcoeff,f0,FVS);\n     \n      egf_scaling(N2,f0,FV0,FVS);\n      gsl_ran_discrete_t *r= gsl_ran_discrete_preproc (n2d,FVS);\n      double s1=gsl_ran_discrete (rgen, r);\n      double prob=(double)(s1)/n2d;\n\n      int success=gsl_ran_binomial(rgen,prob,nalleles);\n      if (success==nalleles){discrete1[0]++;}else{\n\tdiscrete1[success]++;\n      }\n      free(FVS);\n      gsl_ran_discrete_free(r);\n      \n    }//end sampling\n\n  MEAN_S/=sampleN;\n  MEAN_S2/=sampleN;\n  MEAN_H/=sampleN;\n  MEAN_H=1/MEAN_H;//Reciprocal of the mean of the reciprocals\n  fix_prob/=sampleN;\n\n  fix_prob *=2*n_e;\n\n  prop[3]=(prop[3]-prop[2])/sampleN;\n  prop[2]=(prop[2]-prop[1])/sampleN;\n  prop[1]=(prop[1]-prop[0])/sampleN;\n  prop[0]=prop[0]/sampleN;\n\n  egf_scaling(N2,f0,FV0,FV0);\n  binomial_sampling(N2,nalleles,sampleS,FV0,discrete0);//neutral\n\n  /*Print Output*/\n\n  printf(\"%f\\t%f\\t%f\\n\",MEAN_S,MEAN_S2,MEAN_H);\n  //output_sfs_to_file_thanasis_format(nalleles,discrete0,discrete1,sfs_filename);\n  output_sfs_to_file_peter_format2(nalleles,sampleS,sampleN,discrete1,discrete0,sfs_filename);\n\n  FILE *file1= fopen(strcat(sfs_filename,\".mean\"), \"w\" );\n  fprintf(file1,\"%0.16E %0.16E %0.16E \",MEAN_S,MEAN_S2,MEAN_H);\n  \n  for(i = 0; i <= 3; i++){\n    fprintf(file1,\"%0.16E \",prop[i]);\n  }\n  fprintf(file1,\"%0.16E \",fix_prob);\n  fclose(file1);\n  ////////////////////////////////////////////////////////////////////////////////\n  \n  free(FV0);\n  gsl_rng_free (rgen);\n\n  free(discrete0);\n  free(discrete1);\n\n  for(i = 1; i <= nspikes; i++){\n    free(FVSX[i]);\n  }\n  free(FVSX);\n\n  return 0;\n}\n", "meta": {"hexsha": "5d9211fa95927de958d8d36386ee48eeb2cdda3c", "size": 18238, "ext": "c", "lang": "C", "max_stars_repo_path": "Multi_DFE_gen_v1.8.c", "max_stars_repo_name": "kousathanas/simsfs_fast", "max_stars_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Multi_DFE_gen_v1.8.c", "max_issues_repo_name": "kousathanas/simsfs_fast", "max_issues_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Multi_DFE_gen_v1.8.c", "max_forks_repo_name": "kousathanas/simsfs_fast", "max_forks_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_forks_repo_licenses": ["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.7035830619, "max_line_length": 186, "alphanum_fraction": 0.5971597763, "num_tokens": 5836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.38433960419684876}}
{"text": "/** @file */\n\n#ifndef __CCL_F3D_H_INCLUDED__\n#define __CCL_F3D_H_INCLUDED__\n\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_interp2d.h>\n#include <gsl/gsl_spline2d.h>\n\nCCL_BEGIN_DECLS\n\n/**\n * Struct for accelerated linear interpolation.\n */\ntypedef struct {\n  int ia_last; /**< Last index found */\n  double amin; /**< Minimum a-value within range */\n  double amax; /**< Maximum a-value within range */\n  int na; /**< Number of a-values held */\n  double *a_arr; /**< Array of a-values */\n} ccl_a_finder;\n\n/**\n * Creates a new ccl_a_finder structure from an array\n * of scale factors.\n * @param na Number of elements held by a_arr\n * @param a_arr array of scale factors over which linear interpolation will be carried out.\n */\nccl_a_finder *ccl_a_finder_new(int na, double *a_arr);\n\n/**\n * ccl_a_finder destructor.\n */\nvoid ccl_a_finder_free(ccl_a_finder *finda);\n\n/**\n * Find index corresponding to scale factor value a\n * such that finda->a_arr[index]<a<finda->a_arr[index+1].\n * @param finda ccl_a_finder.\n * @param a scale factor value.\n */\nint ccl_find_a_index(ccl_a_finder *finda, double a);\n\n\n/**\n * Struct containing a 3D trispectrum\n */\ntypedef struct {\n  double lkmin,lkmax; /**< Edges in log(k)*/\n  int na; /**< Number of a values */\n  double *a_arr; /**< Array of a values at which this is sampled */\n  int is_product; /**< Is this factorizable as f(k1,a)*g(k2,a)? */\n  int extrap_order_lok; /**< Order of extrapolating polynomial in log(k) for low k (0, 1 or 2)*/\n  int extrap_order_hik; /**< Order of extrapolating polynomial in log(k) for high k (0, 1 or 2)*/\n  ccl_f2d_extrap_growth_t extrap_linear_growth;  /**< Extrapolation type at high redshifts*/\n  int is_log; /**< Do I hold the values of log(f(k,a))?*/\n  double growth_factor_0; /**< Constant extrapolating growth factor*/\n  int growth_exponent; /**< Power to which growth should be exponentiated*/\n  ccl_f2d_t *fka_1; /**< If is_product=True, then this holds the first factor f(k,a) */\n  ccl_f2d_t *fka_2; /**< If is_product=True, then this holds the second factor g(k,a) */\n  gsl_spline2d **tkka; /**< Array of 2D (k1,k2) splines (one for each value of a). */\n} ccl_f3d_t;\n\n/**\n * Create a ccl_f3d_t structure.\n * @param na number of elements in a_arr.\n * @param a_arr array of scale factor values at which the function is defined. The array should be ordered.\n * @param nk number of elements of lk_arr.\n * @param lk_arr array of logarithmic wavenumbers at which the function is defined (i.e. this array contains ln(k), NOT k). The array should be ordered.\n * @param tkka_arr array of size na * nk * nk containing the 3D function. The 3D ordering is such that fka_arr[ik1+nk*(ik2+nk*ia)] = f(k1=exp(lk_arr[ik1]),k2=exp(lk_arr[ik2],a=a_arr[ia]).\n * @param fka1_arr array of size nk * na containing the first factor f1 making up the total function if it's factorizable such that f(k1,k2,a) = f1(k1,a)*f2(k2,a). The 2D ordering of this array should be such that fka1_arr[ik+nk*ia] = f1(k=exp(lk_arr[ik]),a=a_arr[ia]). Only relevant if is_product is true.\n * @param fka2_arr same as fka1_arr for the second factor.\n * @param is_product if not 0, fka1_arr and fka2_arr will be used as 2-D arrays to construct a factorizable 3D function f(k1,k1,a) = f1(k1,a)*f2(k2,a).\n * @param extrap_order_lok Order of the polynomial that extrapolates on wavenumbers smaller than the minimum of lk_arr. Allowed values: 0 (constant) and 1 (linear extrapolation). Extrapolation happens in ln(k).\n * @param extrap_order_hik Order of the polynomial that extrapolates on wavenumbers larger than the maximum of lk_arr. Allowed values: 0 (constant) and 1 (linear extrapolation). Extrapolation happens in ln(k).\n * @param extrap_linear_growth: ccl_f2d_extrap_growth_t value defining how the function with scale factors below the interpolation range. Allowed values: ccl_f2d_cclgrowth (scale with the CCL linear growth factor), ccl_f2d_constantgrowth (scale by multiplying the function at the earliest available scale factor by a constant number, defined by `growth_factor_0`), ccl_f2d_no_extrapol (throw an error if the function is ever evaluated outside the interpolation range in a). Note that, above the interpolation range (i.e. for low redshifts), the function will be assumed constant.\n * @param is_tkka_log: if not zero, `tkka_arr` contains ln(f(k1,k2,a)) instead of f(k1,k2,a) (and likewise for fka1_arr and fka2_arr).\n * @param growth_factor_0: growth factor outside the range of scale factors held by a_arr. Irrelevant if extrap_linear_growth!=ccl_f2d_constantgrowth.\n * @param growth_exponent: power to which the extrapolating growth factor should be exponentiated when extrapolating (e.g. usually 4 for trispectra).\n * @param interp_type: 2D interpolation method in k1,k2 space. Currently only ccl_f2d_3 is implemented (bicubic interpolation). Note that linear interpolation is used between values of the scale factor.\n * @param status Status flag. 0 if there are no errors, nonzero otherwise.\n */\nccl_f3d_t *ccl_f3d_t_new(int na,double *a_arr,\n\t\t\t int nk,double *lk_arr,\n                         double *tkka_arr,\n\t\t\t double *fka1_arr,\n\t\t\t double *fka2_arr,\n\t\t\t int is_product,\n\t\t\t int extrap_order_lok,\n\t\t\t int extrap_order_hik,\n\t\t\t ccl_f2d_extrap_growth_t extrap_linear_growth,\n\t\t\t int is_tkka_log,\n\t\t\t double growth_factor_0,\n\t\t\t int growth_exponent,\n\t\t\t ccl_f2d_interp_t interp_type,\n\t\t\t int *status);\n\n/**\n * Evaluate 3D function of k1, k2 and a defined by ccl_f3d_t structure.\n * @param f3d ccl_f3d_t structure defining f(k1,k2,a).\n * @param lk1 Natural logarithm of the wavenumber.\n * @param lk2 Natural logarithm of the wavenumber.\n * @param a Scale factor.\n * @param finda Helper structure used to accelerate the scale factor interpolation.\n * @param cosmo ccl_cosmology structure, only needed if evaluating f(k1,k2,a) at small scale factors outside the interpolation range, and if fka was initialized with extrap_linear_growth = ccl_f2d_cclgrowth.\n * @param status Status flag. 0 if there are no errors, nonzero otherwise.\n */\ndouble ccl_f3d_t_eval(ccl_f3d_t *f3d,double lk1,double lk2,double a,ccl_a_finder *finda,\n                      void *cosmo, int *status);\n\n/**\n * F3D structure destructor.\n * Frees up all memory associated with a f3d structure.\n * @param f3d Structure to be freed.\n */\nvoid ccl_f3d_t_free(ccl_f3d_t *f3d);\n\n/**\n * Make a copy of a ccl_f3d_t structure.\n * @param f3d_o old ccl_f3d_t structure.\n * @param status Status flag. 0 if there are no errors, nonzero otherwise.\n */\nccl_f3d_t *ccl_f3d_t_copy(ccl_f3d_t *f3d_o, int *status);\n\n/**\n * Create a ccl_a_finder from the array of scale factors held\n * by a ccl_f3d_t structure.\n * @param f3d ccl_f3d_t structure.\n */\nccl_a_finder *ccl_a_finder_new_from_f3d(ccl_f3d_t *f3d);\n\nCCL_END_DECLS\n\n#endif\n", "meta": {"hexsha": "17d5457ec26955a63fc1f9c5b3eebbf0fd723f35", "size": 6738, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ccl_f3d.h", "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_issues_repo_path": "include/ccl_f3d.h", "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 703.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_forks_repo_path": "include/ccl_f3d.h", "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "avg_line_length": 49.9111111111, "max_line_length": 579, "alphanum_fraction": 0.7387948946, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3842715212855457}}
{"text": "#include <stdlib.h>\n#include <utility>\n#include <gsl/gsl_multiroots.h>\n#include <gsl/gsl_sf.h>\n#include <string>\n#include <random>\n#include <array>\n\nusing namespace std;\nstruct mass_eff_scalar_density_params\n{\n    vector<double> scalar_coeff;\n    vector<double> scalar_exp;\n    double number_density;\n    double nucleon_mass;\n    double degeneracy;\n    double temperature;\n    vector<double> vec_coeff;\n    vector<double> vec_exp;\n};\n//struct for the parameters for root solving for the coupling constants\nstruct coeff_params\n{\n    double saturation_densitiy;\n    double nucleon_mass;\n    double binding_energy;\n    double degeneracy;\n    vector<double> scalar_exp;\n    vector<double> vec_exp;\n    unsigned int* terms;\n};\n//struct for the parameters for finding the critical point\nstruct crit_params\n{\n    vector<double> scalar_coeff;\n    vector<double> scalar_exp;\n    vector<double> vec_coeff;\n    vector<double> vec_exp;\n    double nucleon_mass;\n    double degeneracy;\n};\n//struct for the parameters for finding the interaction terms for 1 CP\nstruct interaction_params\n{\n    double nucleon_mass;\n    double degeneracy;\n    double saturation_density;\n    double binding_energy;\n    double critical_temperature;\n    double critical_density;\n    unsigned int* terms;\n};\n//struct for the parameters for finding the interaction terms for 2 CPs\nstruct interaction_params_2crit\n{\n    double nucleon_mass;\n    double degeneracy;\n    double saturation_density;\n    double binding_energy;\n    double critical_temperature_lg;\n    double critical_density_lg;\n    double critical_temperature_qgp;\n    double critical_density_qgp;\n    double spinodial_l_density;\n    double spinodial_r_density;\n    unsigned int* terms;\n};\nint mass_eff_scalar_density_root(const gsl_vector * x, void *params, gsl_vector * f);\nint print_state_mass_eff_scalar_density (size_t iter, gsl_multiroot_fsolver * s);\npair<double, double> get_mass_eff_scalar_density(double degeneracy, double nucleon_mass,vector<double> scalar_coeff ,vector<double>  scalar_exp,double number_density,bool print);\nint T_mass_eff_mu_eff_scalar_density_root(const gsl_vector * x, void *params, gsl_vector * f);\nint print_state_T_mass_eff_mu_eff_scalar_density (size_t iter, gsl_multiroot_fsolver * s);\ntuple<double, double,double,bool> get_T_mass_eff_mu_eff_scalar_density(vector<double> scalar_coeff, vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double nucleon_mass,double number_density, double temperature, double degeneracy, bool print);\nint coeff_root(const gsl_vector * x, void *params, gsl_vector * f);\nint print_state_coeff (size_t iter, gsl_multiroot_fsolver * s);\npair<double, double> get_coeff(double nucleon_mass, double saturation_density, double binding_energy, double degeneracy, vector<double> scalar_exp, vector<double> vec_exp, bool print, unsigned int terms[2], bool * success=NULL);\nint crit_root(const gsl_vector * x, void *params, gsl_vector * f);\npair<double, double> get_crit(double nucleon_mass,double saturation_density, double binding_energy, double degeneracy, vector<double> scalar_exp, vector<double> vec_exp, bool print, double crit_T=19.09, double crit_density=540000, vector<double> scalar_coeff={0.0}, vector<double> vec_coeff={0.0});\nint interaction_root(const gsl_vector * x, void *params, gsl_vector * f);\nint print_state_interaction (size_t iter, gsl_multiroot_fsolver * s);\ntuple<double, double,double,double, double, bool> get_interaction_4D(void * p, bool print,vector<double> init_exp={2.05,2.05},vector<double> init_coeff={10*4*M_PI/pow(550,2.0),10*4*M_PI/pow(783,2.0)});\nint interaction_root_2crit(const gsl_vector * x, void *params, gsl_vector * f);\nint print_state_interaction_2crit (size_t iter, gsl_multiroot_fsolver * s);\ntuple<double, vector<double>, vector<double>, bool> get_interaction_2crit(void * p, bool print,vector<double> init_exp={2.05,2.05,3,3},vector<double> init_coeff={10*4*M_PI/pow(550,2.0),10*4*M_PI/pow(783,2.0),0,0});\ndouble energy_pp_minus_mass_solv(double degeneracy, double nucleon_mass,double number_density, vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp);\ndouble energy_pp_minus_mass_dn_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp);\ndouble press_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp);\ndouble press_dn_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp);\ndouble incsolv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp,double delta=1);\ndouble T_press_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature);\ndouble  T_press_dmu_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature, double delta=1.);\ndouble  T_press_dT_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature, double delta=1e-2);\ndouble  T_press_dn_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature, double delta=1e3);\ndouble  T_press_dn2_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp,double temperature, double delta=1e3);\npair<double, double> T_press_dn12_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature, double delta=1e3);\ndouble T_eps_solv(double degeneracy, double nucleon_mass,double number_density,vector<double> scalar_coeff,vector<double> scalar_exp, vector<double> vec_coeff, vector<double> vec_exp, double temperature);\nvoid gsl_handler (const char * reason, const char * file, int line, int gsl_errno);\nbool validate_interaction(double error, vector<double> coeff_guess, vector<double> exp_guess,vector<double> coeff, vector<double> exp, string filename, int timestamp, void* params);\nvoid interaction_4D_grid(double nucleon_mass,double critical_temperature, double critical_density, double binding_energy, double saturation_density, double degeneracy, double boundaries  [4][3], unsigned int terms [2], string filename, bool print, int num_sol=0);\nvoid interaction_4D_crit_grid(double nucleon_mass, double binding_energy, double saturation_density, double degeneracy, double boundaries_model  [4][3], double boundaries_crit [2][3], unsigned int terms [2], string filename, bool print, int num_sol);\ndouble round_to_n_digits(double x, int n);\n", "meta": {"hexsha": "5aef5306dae9f9e01710e6804799b3c1ea147efb", "size": 7332, "ext": "h", "lang": "C", "max_stars_repo_path": "src/wsolvers.h", "max_stars_repo_name": "NGoetz/CWalecka", "max_stars_repo_head_hexsha": "44c03dee180ab10dc83ea6eb4e5be4911dc20445", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wsolvers.h", "max_issues_repo_name": "NGoetz/CWalecka", "max_issues_repo_head_hexsha": "44c03dee180ab10dc83ea6eb4e5be4911dc20445", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wsolvers.h", "max_forks_repo_name": "NGoetz/CWalecka", "max_forks_repo_head_hexsha": "44c03dee180ab10dc83ea6eb4e5be4911dc20445", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 71.8823529412, "max_line_length": 298, "alphanum_fraction": 0.8029187125, "num_tokens": 1705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.38416472747513797}}
{"text": "/* Copyright (c) 2011-2012, J\u00e9r\u00e9my Fix. All rights reserved. */\n\n/* Redistribution and use in source and binary forms, with or without */\n/* modification, are permitted provided that the following conditions are met: */\n\n/* * Redistributions of source code must retain the above copyright notice, */\n/* this list of conditions and the following disclaimer. */\n/* * Redistributions in binary form must reproduce the above copyright notice, */\n/* this list of conditions and the following disclaimer in the documentation */\n/* and/or other materials provided with the distribution. */\n/* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */\n\n/* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND */\n/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */\n/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */\n/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */\n/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */\n/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */\n/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */\n/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */\n/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */\n/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */\n\n#ifndef UKF_NDIM_STATE_H\n#define UKF_NDIM_STATE_H\n\n#include <gsl/gsl_linalg.h> // For the Cholesky decomposition\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_blas.h>\n\n#include \"ukf_types.h\"\n\nnamespace ukf\n{\n\n  /**\n   * @short UKF for state estimation, additive noise case\n   * The notations follow \"Sigma-Point Kalman Filters for Probabilistic Inference in Dynamic State-Space Models\",p108, PhD, van Der Merwe\n   */\n  namespace state\n  {\n    /**\n     * @short Allocation of the vectors/matrices and initialization\n     *\n     */\n    void ukf_init(ukf_param &p, ukf_state &s)\n    {\n      // Parameters for the sigma points of the process equation\n      p.nbSamples = 2 * p.n + 1;\n      p.lambda = p.alpha * p.alpha * (p.n + p.kpa) - p.n;\n      p.gamma = sqrt(p.n + p.lambda);\n\n      // Parameters for the sigma points of the observation equation\n      p.nbSamplesMeasure = 4 * p.n + 1;\n      p.lambda_aug = p.alpha * p.alpha * (2*p.n + p.kpa) - 2*p.n;\n      p.gamma_aug = sqrt(2*p.n + p.lambda_aug);\n\n      // Init the matrices used to iterate\n      s.xi = gsl_vector_alloc(p.n);\n      gsl_vector_set_zero(s.xi);\n\n      s.xi_prediction = gsl_matrix_alloc(p.n, p.nbSamples);\n      gsl_matrix_set_zero(s.xi_prediction);\n\n      s.xi_mean = gsl_vector_alloc(p.n);\n      gsl_vector_set_zero(s.xi_mean);\n\n      s.Pxxi = gsl_matrix_alloc(p.n,p.n);\n      gsl_matrix_set_identity(s.Pxxi);\n      gsl_matrix_scale(s.Pxxi, p.prior_x);\n\n      s.cholPxxi = gsl_matrix_alloc(p.n,p.n);\n      gsl_matrix_set_zero(s.cholPxxi);\n\n      s.Pvvi = gsl_matrix_alloc(p.n,p.n);\n      s.cholPvvi = gsl_matrix_alloc(p.n,p.n);\n      p.evolution_noise->init(p,s);\n\n      s.yi_prediction = gsl_matrix_alloc(p.no, p.nbSamplesMeasure);\n      gsl_matrix_set_zero(s.yi_prediction);\n\n      s.yi_mean = gsl_vector_alloc(p.no);\n      gsl_vector_set_zero(s.yi_mean);\n\n      s.ino_yi = gsl_vector_alloc(p.no);\n      gsl_vector_set_zero(s.ino_yi);\n\n      s.Pyyi = gsl_matrix_alloc(p.no, p.no);\n      gsl_matrix_set_zero(s.Pyyi);\n\n      s.Pnni = gsl_matrix_alloc(p.no,p.no);\n      gsl_matrix_set_identity(s.Pnni);\n      gsl_matrix_scale(s.Pnni, p.measurement_noise);\n\n      s.Pxyi = gsl_matrix_alloc(p.n, p.no);\n      gsl_matrix_set_zero(s.Pxyi);\n\n      s.sigmaPoint = gsl_vector_alloc(p.n);\n      gsl_vector_set_zero(s.sigmaPoint);\n\n      s.sigmaPoints = gsl_matrix_alloc(p.n, p.nbSamples);\n      gsl_matrix_set_zero(s.sigmaPoints);\n\n      s.sigmaPointMeasure = gsl_vector_alloc(p.n);\n      gsl_vector_set_zero(s.sigmaPoint);\n\n      s.sigmaPointsMeasure = gsl_matrix_alloc(p.n, p.nbSamplesMeasure);\n      gsl_matrix_set_zero(s.sigmaPointsMeasure);\n\n      // Weights used to update the statistics\n      s.wm_j  = gsl_vector_alloc(p.nbSamples); // Weights used to compute the mean of the sigma points images\n      s.wc_j = gsl_vector_alloc(p.nbSamples); // Weights used to update the covariance matrices\n\n      // Set the weights\n      gsl_vector_set(s.wm_j, 0, p.lambda / (p.n + p.lambda));\n      gsl_vector_set(s.wc_j, 0, p.lambda / (p.n + p.lambda) + (1.0 - p.alpha*p.alpha + p.beta));\n      for(int j = 1 ; j < p.nbSamples; j ++)\n\t{\n\t  gsl_vector_set(s.wm_j, j, 1.0 / (2.0 * (p.n + p.lambda)));\n\t  gsl_vector_set(s.wc_j, j, 1.0 / (2.0 * (p.n + p.lambda)));\n\t}\n\n      // Set the weights\n      s.wm_aug_j  = gsl_vector_alloc(p.nbSamplesMeasure); // Weights used to compute the mean of the sigma points images\n      s.wc_aug_j = gsl_vector_alloc(p.nbSamplesMeasure); // Weights used to update the covariance matrices\n      gsl_vector_set(s.wm_aug_j, 0, p.lambda_aug / (2*p.n + p.lambda_aug));\n      gsl_vector_set(s.wc_aug_j, 0, p.lambda_aug / (2*p.n + p.lambda_aug) + (1.0 - p.alpha*p.alpha + p.beta));\n      for(int j = 1 ; j < p.nbSamplesMeasure; j ++)\n\t{\n\t  gsl_vector_set(s.wm_aug_j, j, 1.0 / (2.0 * (2*p.n + p.lambda_aug)));\n\t  gsl_vector_set(s.wc_aug_j, j, 1.0 / (2.0 * (2*p.n + p.lambda_aug)));\n\t}\n\n      s.Ki = gsl_matrix_alloc(p.n, p.no);\n      s.Ki_T = gsl_matrix_alloc(p.no, p.n);\n\n      // Allocate temporary matrices\n      s.temp_n = gsl_vector_alloc(p.n);\n\n      s.temp_n_1 = gsl_matrix_alloc(p.n,1);\n      s.temp_1_n = gsl_matrix_alloc(1,p.n);\n      s.temp_n_n = gsl_matrix_alloc(p.n, p.n);\n      s.temp_n_no = gsl_matrix_alloc(p.n, p.no);\n      s.temp_no_1 = gsl_matrix_alloc(p.no,1);\n      s.temp_1_no = gsl_matrix_alloc(1,p.no);\n      s.temp_no_no = gsl_matrix_alloc(p.no, p.no);\n    }\n\n    /**\n     * @short Free of memory allocation\n     *\n     */\n    void ukf_free(ukf_param &p, ukf_state &s)\n    {\n      gsl_vector_free(s.xi);\n      gsl_matrix_free(s.xi_prediction);\n      gsl_vector_free(s.xi_mean);\n      gsl_matrix_free(s.Pxxi);\n      gsl_matrix_free(s.cholPxxi);\n      gsl_matrix_free(s.Pvvi);\n      gsl_matrix_free(s.cholPvvi);\n\n      gsl_matrix_free(s.yi_prediction);\n      gsl_vector_free(s.yi_mean);\n      gsl_vector_free(s.ino_yi);\n      gsl_matrix_free(s.Pyyi);\n      gsl_matrix_free(s.Pnni);\n\n      gsl_matrix_free(s.Pxyi);\n\n      gsl_vector_free(s.sigmaPoint);\n      gsl_matrix_free(s.sigmaPoints);\n\n      gsl_vector_free(s.sigmaPointMeasure);\n      gsl_matrix_free(s.sigmaPointsMeasure);\n\n      gsl_vector_free(s.wm_j);\n      gsl_vector_free(s.wc_j);\n\n      gsl_vector_free(s.wm_aug_j);\n      gsl_vector_free(s.wc_aug_j);\n\n      gsl_matrix_free(s.Ki);\n      gsl_matrix_free(s.Ki_T);\n\n      gsl_vector_free(s.temp_n);\n      gsl_matrix_free(s.temp_n_1);\n      gsl_matrix_free(s.temp_1_n);\n      gsl_matrix_free(s.temp_n_n);\n\n      gsl_matrix_free(s.temp_n_no);\n      gsl_matrix_free(s.temp_no_1);\n      gsl_matrix_free(s.temp_1_no);\n      gsl_matrix_free(s.temp_no_no);\n    }\n\n    /**\n     * @short UKF-additive (zero-mean) noise case, \"Kalman Filtering and Neural Networks\", p.233\n     *\n     */\n    template<typename FFUNC, \n      typename HFUNC>\n    void ukf_iterate(ukf_param &p, ukf_state &s, \n\t\t     FFUNC f,\n\t\t     HFUNC h, \n\t\t     gsl_vector* yi)\n    {\n      int i,j,k;\n\n      // ************************************************** //\n      // ************ Compute the sigma points ************ //\n      // ************************************************** //\n\n      // 0 - Compute the Cholesky decomposition of s.Pxxi\n      gsl_matrix_memcpy(s.cholPxxi, s.Pxxi);\n      gsl_linalg_cholesky_decomp(s.cholPxxi);\n      // Set all the elements of cholPvvi strictly above the diagonal to zero\n      for(j = 0 ; j < p.n ; j++)\n\tfor(k = j+1 ; k < p.n ; k++)\n\t  gsl_matrix_set(s.cholPxxi,j,k,0.0);\n\n      // 1- Compute the sigma points,\n      // Equation (3.170)\n      // sigmapoint_j = x_(i-1)\n      // sigmapoint_j = x_(i-1) + gamma * sqrt(P_i-1)_j for 1 <= j <= n\n      // sigmapoint_j = x_(i-1) - gamma * sqrt(P_i-1)_(j-(n+1)) for n+1 <= j <= 2n\n      gsl_matrix_set_col(s.sigmaPoints, 0, s.xi);\n      for(j = 1 ; j < p.n+1 ; ++j)\n\tfor(i = 0 ; i < p.n ; ++i)\n\t  {\n\t    gsl_matrix_set(s.sigmaPoints,i,j, s.xi->data[i] + p.gamma * gsl_matrix_get(s.cholPxxi, i, j-1));\n\t    gsl_matrix_set(s.sigmaPoints,i,j+p.n, s.xi->data[i] - p.gamma * gsl_matrix_get(s.cholPxxi, i, j-1));\n\t  }\n\n      /**********************************/\n      /***** Time update equations  *****/\n      /**********************************/\n\n      // Time update equations\n      // 0 - Compute the image of the sigma points and the mean of these images\n      gsl_vector_set_zero(s.xi_mean);\n      gsl_vector_view vec_view;\n      for(j = 0 ; j < p.nbSamples ; ++j)\n\t{\n\t  gsl_matrix_get_col(s.sigmaPoint, s.sigmaPoints, j);\n\t  vec_view = gsl_matrix_column(s.xi_prediction,j);\n\t  f(s.params, s.sigmaPoint, &vec_view.vector);\n\n\t  // Update the mean, Eq (3.172)\n\t  for(i = 0 ; i < p.n ; ++i)\n\t    s.xi_mean->data[i] += s.wm_j->data[j] * gsl_matrix_get(s.xi_prediction,i,j);\n\t}\n\n      // 1 - Compute the covariance of the images and add the process noise,\n      // Equation (3.173)\n      // Warning, s.Pxxi will now hold P_xk^-\n      gsl_matrix_set_zero(s.Pxxi);\n      for(j = 0 ; j < p.nbSamples ; ++j)\n\t{\n\t  for(i = 0 ; i < p.n ; ++i)\n\t    s.temp_n_1->data[i] = gsl_matrix_get(s.xi_prediction,i,j) - s.xi_mean->data[i];\n\n\t  gsl_blas_dgemm(CblasNoTrans, CblasTrans, s.wc_j->data[j] , s.temp_n_1, s.temp_n_1, 0, s.temp_n_n);\n\t  gsl_matrix_add(s.Pxxi, s.temp_n_n);\n\t}\n      // Add the covariance of the evolution noise\n      gsl_matrix_add(s.Pxxi, s.Pvvi);\n\n      // Augment sigma points\n      // Equation 3.174\n      // First put the images of the initial sigma points\n      gsl_matrix_view mat_view;\n      mat_view = gsl_matrix_submatrix(s.sigmaPointsMeasure, 0, 0, p.n, p.nbSamples);\n      gsl_matrix_memcpy(&mat_view.matrix, s.xi_prediction);\n      // And add the additional sigma points eq. (7.56)\n      for(j = 0 ; j < p.n ; ++j)\n\t{\n\t  for(i = 0 ; i < p.n ; ++i)\n\t    {\n\t      gsl_matrix_set(s.sigmaPointsMeasure, i, j+p.nbSamples, gsl_matrix_get(s.xi_prediction,i,0)+p.gamma_aug*gsl_matrix_get(s.cholPvvi,i,j));\n\t      gsl_matrix_set(s.sigmaPointsMeasure, i, j+p.nbSamples+p.n, gsl_matrix_get(s.xi_prediction,i,0)-p.gamma_aug*gsl_matrix_get(s.cholPvvi,i,j));\n\t    }\n\t}\n\n      // Compute the image of the sigma points through the observation equation\n      // eq (3.175)\n      gsl_vector_set_zero(s.yi_mean);\n      for(j = 0 ; j < p.nbSamplesMeasure ; ++j)\n\t{\n\t  gsl_matrix_get_col(s.sigmaPointMeasure, s.sigmaPointsMeasure, j);\n\t  vec_view = gsl_matrix_column(s.yi_prediction,j);\n\t  h(s.sigmaPointMeasure, &vec_view.vector);\n\n\t  // Update the mean , eq (3.176)\n\t  for(i = 0 ; i < p.no ; ++i)\n\t    s.yi_mean->data[i] += s.wm_aug_j->data[j] * gsl_matrix_get(s.yi_prediction,i,j);\n\t}\n\n      /*****************************************/\n      /***** Measurement update equations  *****/\n      /*****************************************/\n\n      // Compute the covariance of the observations\n      // Eq. (3.177)\n      // Initialize with the observation noise covariance\n      gsl_matrix_memcpy(s.Pyyi, s.Pnni);\n      for(j = 0 ; j < p.nbSamplesMeasure ; ++j)\n\t{\n\t  for(i = 0 ; i < p.no ; ++i)\n\t    s.temp_no_1->data[i] = gsl_matrix_get(s.yi_prediction,i,j) - s.yi_mean->data[i];\n\n\t  gsl_blas_dgemm(CblasNoTrans, CblasTrans, s.wc_aug_j->data[j] , s.temp_no_1, s.temp_no_1, 0, s.temp_no_no);\n\t  gsl_matrix_add(s.Pyyi, s.temp_no_no);\n\t}\n\n      // Compute the state/observation covariance\n      // Eq (3.178)\n      gsl_matrix_set_zero(s.Pxyi);\n      for(j = 0 ; j < p.nbSamplesMeasure ; ++j)\n\t{\n\t  for(i = 0 ; i < p.n ; ++i)\n\t    s.temp_n_1->data[i] = gsl_matrix_get(s.sigmaPointsMeasure,i,j) - s.xi_mean->data[i];\n\n\t  for(i = 0 ; i < p.no ; ++i)\n\t    s.temp_1_no->data[i] = gsl_matrix_get(s.yi_prediction,i,j) - s.yi_mean->data[i];\n\n\t  gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, s.wc_aug_j->data[j] , s.temp_n_1, s.temp_1_no, 0, s.temp_n_no);\n\t  gsl_matrix_add(s.Pxyi, s.temp_n_no);\n\t}\n\n      // Compute the Kalman gain, eq (3.179)\n      // 0- Compute the inverse of Pyyi\n      gsl_matrix_memcpy(s.temp_no_no, s.Pyyi);\n      gsl_linalg_cholesky_decomp(s.temp_no_no);\n      gsl_linalg_cholesky_invert(s.temp_no_no);\n\n      // 1- Compute the Kalman gain\n      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Pxyi, s.temp_no_no, 0, s.Ki);\n\n      // Correction : correct the estimation of the state\n      // Eq. 3.180\n      // Compute the innovations\n      for(i = 0 ; i < p.no ; ++i)\n\ts.ino_yi->data[i] = gsl_vector_get(yi, i) - gsl_vector_get(s.yi_mean, i);\n      gsl_vector_memcpy(s.xi, s.xi_mean);\n      gsl_blas_dgemv(CblasNoTrans, 1.0 , s.Ki, s.ino_yi, 1.0, s.xi);\n\n      // Correction : Update the covariance matrix Pk\n      // Eq. 3.181\n      gsl_matrix_transpose_memcpy(s.Ki_T, s.Ki);\n      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Ki, s.Pyyi, 0, s.temp_n_no);\n      gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0 , s.temp_n_no, s.Ki_T, 1.0, s.Pxxi);\n\n      // Update of the process noise\n      p.evolution_noise->updateEvolutionNoise(p,s);\n      //            switch(p.process_noise_type)\n      //            {\n      //            case ukf::UKF_PROCESS_FIXED:\n      //                //nothing to do\n      //                break;\n      //            case ukf::UKF_PROCESS_RLS:\n      //                gsl_matrix_memcpy(s.Pvvi, s.Pxxi);\n      //                gsl_matrix_scale(s.Pvvi, 1.0/p.process_noise-1.0);\n      //                gsl_matrix_memcpy(s.cholPvvi, s.Pvvi);\n      //                gsl_linalg_cholesky_decomp(s.cholPvvi);\n      //                for(j = 0 ; j < p.n ; j++)\n      //                    for(k = j+1 ; k < p.n ; k++)\n      //                        gsl_matrix_set(s.cholPvvi,j,k,0.0);\n      //                break;\n      //            default:\n      //                printf(\"Warning : Unrecognized process noise type\\n\");\n      //            }\n\n\n    }\n\n    /**\n     * @short Evaluation of the output from the sigma points\n     *\n     */\n    void ukf_evaluate(ukf_param &p, ukf_state &s, \n\t\t      void (*f)(gsl_vector*, gsl_vector *, gsl_vector *), \n\t\t      void (*h)(gsl_vector*, gsl_vector *), gsl_vector* yi)\n    {\n\n      int i,j,k;\n      gsl_matrix_view mat_view;\n      gsl_vector_view vec_view;\n      // ************************************************** //\n      // ************ Compute the sigma points ************ //\n      // ************************************************** //\n\n      // 0 - Compute the Cholesky decomposition of s.Pxxi\n      gsl_matrix_memcpy(s.cholPxxi, s.Pxxi);\n      gsl_linalg_cholesky_decomp(s.cholPxxi);\n      // Set all the elements of cholPvvi strictly above the diagonal to zero\n      for(j = 0 ; j < p.n ; j++)\n\tfor(k = j+1 ; k < p.n ; k++)\n\t  gsl_matrix_set(s.cholPxxi,j,k,0.0);\n\n      // 1- Compute the sigma points,\n      // Equation (3.170)\n      // sigmapoint_j = x_(i-1)\n      // sigmapoint_j = x_(i-1) + gamma * sqrt(P_i-1)_j for 1 <= j <= n\n      // sigmapoint_j = x_(i-1) - gamma * sqrt(P_i-1)_(j-(n+1)) for n+1 <= j <= 2n\n      gsl_matrix_set_col(s.sigmaPoints, 0, s.xi);\n      for(j = 1 ; j < p.n+1 ; ++j)\n\tfor(i = 0 ; i < p.n ; ++i)\n\t  {\n\t    gsl_matrix_set(s.sigmaPoints,i,j, s.xi->data[i] + p.gamma * gsl_matrix_get(s.cholPxxi, i, j-1));\n\t    gsl_matrix_set(s.sigmaPoints,i,j+p.n, s.xi->data[i] - p.gamma * gsl_matrix_get(s.cholPxxi, i, j-1));\n\t  }\n\n      /**********************************/\n      /***** Time update equations  *****/\n      /**********************************/\n\n      // Time update equations\n      // 0 - Compute the image of the sigma points and the mean of these images\n      gsl_vector_set_zero(s.xi_mean);\n      for(j = 0 ; j < p.nbSamples ; ++j)\n\t{\n\t  gsl_matrix_get_col(s.sigmaPoint, s.sigmaPoints, j);\n\t  vec_view = gsl_matrix_column(s.xi_prediction,j);\n\t  f(s.params, s.sigmaPoint, &vec_view.vector);\n\n\t  // Update the mean, Eq (3.172)\n\t  for(i = 0 ; i < p.n ; ++i)\n\t    s.xi_mean->data[i] += s.wm_j->data[j] * gsl_matrix_get(s.xi_prediction,i,j);\n\t}\n\n      // 1 - Compute the covariance of the images and add the process noise,\n      // Equation (3.173)\n      // Warning, s.Pxxi will now hold P_xk^-\n      gsl_matrix_set_zero(s.Pxxi);\n      for(j = 0 ; j < p.nbSamples ; ++j)\n\t{\n\t  for(i = 0 ; i < p.n ; ++i)\n\t    s.temp_n_1->data[i] = gsl_matrix_get(s.xi_prediction,i,j) - s.xi_mean->data[i];\n\n\t  gsl_blas_dgemm(CblasNoTrans, CblasTrans, s.wc_j->data[j] , s.temp_n_1, s.temp_n_1, 0, s.temp_n_n);\n\t  gsl_matrix_add(s.Pxxi, s.temp_n_n);\n\t}\n      // Add the covariance of the evolution noise\n      gsl_matrix_add(s.Pxxi, s.Pvvi);\n\n      // Augment sigma points\n      // Equation 3.174\n      // First put the images of the initial sigma points\n      mat_view = gsl_matrix_submatrix(s.sigmaPointsMeasure, 0, 0, p.n, p.nbSamples);\n      gsl_matrix_memcpy(&mat_view.matrix, s.xi_prediction);\n      // And add the additional sigma points eq. (7.56)\n      for(j = 0 ; j < p.n ; ++j)\n\t{\n\t  for(i = 0 ; i < p.n ; ++i)\n\t    {\n\t      gsl_matrix_set(s.sigmaPointsMeasure, i, j+p.nbSamples, gsl_matrix_get(s.xi_prediction,i,0)+p.gamma_aug*gsl_matrix_get(s.cholPvvi,i,j));\n\t      gsl_matrix_set(s.sigmaPointsMeasure, i, j+p.nbSamples+p.n, gsl_matrix_get(s.xi_prediction,i,0)-p.gamma_aug*gsl_matrix_get(s.cholPvvi,i,j));\n\t    }\n\t}\n\n      // Compute the image of the sigma points through the observation equation\n      // eq (3.175)\n      gsl_vector_set_zero(yi);\n      for(j = 0 ; j < p.nbSamplesMeasure ; ++j)\n\t{\n\t  gsl_matrix_get_col(s.sigmaPointMeasure, s.sigmaPointsMeasure, j);\n\t  vec_view = gsl_matrix_column(s.yi_prediction,j);\n\t  h(s.sigmaPointMeasure, &vec_view.vector);\n\n\t  // Update the mean , eq (3.176)\n\t  for(i = 0 ; i < p.no ; ++i)\n\t    yi->data[i] += s.wm_aug_j->data[j] * gsl_matrix_get(s.yi_prediction,i,j);\n\t}\n    }\n  } // state\n} // ukf\n\n\n#endif // UKF_NDIM_STATE_H\n", "meta": {"hexsha": "d31b4dce61828d2e12ea5fa0fadee177c83af6aa", "size": 18002, "ext": "h", "lang": "C", "max_stars_repo_path": "src/ukf_state_ndim.h", "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_issues_repo_path": "src/ukf_state_ndim.h", "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_forks_repo_path": "src/ukf_state_ndim.h", "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 52.0, "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "avg_line_length": 37.4261954262, "max_line_length": 158, "alphanum_fraction": 0.6097100322, "num_tokens": 5284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3838812031229763}}
{"text": "/* fit/gsl_fit.h\n * \n * Copyright (C) 2000 Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#ifndef __GSL_FIT_H__\n#define __GSL_FIT_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nint gsl_fit_linear (const double * x, const size_t xstride,\n                    const double * y, const size_t ystride,\n                    const size_t n,\n                    double * c0, double * c1, \n                    double * cov00, double * cov01, double * cov11, \n                    double * sumsq);\n\n\nint gsl_fit_wlinear (const double * x, const size_t xstride,\n                     const double * w, const size_t wstride,\n                     const double * y, const size_t ystride,\n                     const size_t n,\n                     double * c0, double * c1, \n                     double * cov00, double * cov01, double * cov11, \n                     double * chisq);\n\nint\ngsl_fit_linear_est (const double x, \n                    const double c0, const double c1, \n                    const double c00, const double c01, const double c11,\n                    double *y, double *y_err);\n\n\nint gsl_fit_mul (const double * x, const size_t xstride,\n                 const double * y, const size_t ystride,\n                 const size_t n,\n                 double * c1, \n                 double * cov11, \n                 double * sumsq);\n\nint gsl_fit_wmul (const double * x, const size_t xstride,\n                  const double * w, const size_t wstride,\n                  const double * y, const size_t ystride,\n                  const size_t n,\n                  double * c1, \n                  double * cov11, \n                  double * sumsq);\n\n\nint\ngsl_fit_mul_est (const double x, \n                 const double c1, \n                 const double c11,\n                 double *y, double *y_err);\n\n\n/* choose better names!! */\n\nint gsl_fit_poly (const double * x, \n                  const double * w,\n                  const double * y, \n                  size_t n,\n                  double * c, size_t m,\n                  double * chisq);\n\nint gsl_fit_fns (const double * A, \n                 const double * w,\n                 const double * y, \n                 size_t n,\n                 double * c, size_t m,\n                 double * chisq);\n\nint gsl_fit_linear_nd (double * m, double * y, double * w);\n\n\n__END_DECLS\n\n#endif /* __GSL_FIT_H__ */\n", "meta": {"hexsha": "a906585eb94a1cd5ac47529056cf9f1429008cbf", "size": 3243, "ext": "h", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/fit/gsl_fit.h", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/fit/gsl_fit.h", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/fit/gsl_fit.h", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 30.5943396226, "max_line_length": 73, "alphanum_fraction": 0.5646006784, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3837221625460602}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C code for the implementation of the Fourier-domain overlaps, likelihoods.\n *\n */\n\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"splinecoeffs.h\"\n#include \"fresnel.h\"\n#include \"likelihood.h\"\n\n#include \"wip.h\"\n\n#include <time.h> /* for testing */\n\n\n/* Number of points to be used in linear integration - hardcoded for now */\n#define nbptsintdefault 32768 /* Default number of points to use for linear overlaps */\n\n\n/********************************* Utilities ****************************************/\n\n/* Function to evaluate a Noise function  */\nvoid EvaluateNoise(\n  gsl_vector* noisevalues,                         /* Output: vector of the noise values */\n  gsl_vector* freq,                                /* Input: vector of frequencies on which to evaluate */\n  ObjectFunction * Snoise,                  /* Noise function */\n  double fLow,                                     /* Lower bound of the frequency window for the detector */\n  double fHigh)                                    /* Upper bound of the frequency window for the detector */\n{\n  int nbpts = (int) freq->size;\n\n  /* Checking the length */\n  if( freq->size != noisevalues->size) {\n    printf(\"Error: incompatible sizes in EvaluateNoise.\\n\");\n    exit(1);\n  }\n\n  /* Checking the boundary frequencies */\n  if( gsl_vector_get(freq, 0) - fLow < -1e-15 || gsl_vector_get(freq, nbpts-1) > fHigh + 1e-15 ) {\n    printf(\"Error: incompatible frequency range in EvaluateNoise.\\n\");\n    printf(\"freq[0]=%g vs fLow=%g, freq[max]=%g vs fHigh=%g\\n\",gsl_vector_get(freq, 0), fLow, gsl_vector_get(freq, nbpts-1), fHigh);\n    printf(\" %i, %i\\n\",gsl_vector_get(freq, 0) < fLow , gsl_vector_get(freq, nbpts-1) > fHigh);\n    printf(\"%g\\n\",gsl_vector_get(freq, 0) - fLow);\n    exit(1);\n  }\n\n  for(int i=0; i<nbpts; i++) {\n    gsl_vector_set(noisevalues, i, ObjectFunctionCall(Snoise,gsl_vector_get(freq, i)));\n  }\n}\n\n/* Function building a frequency vector with linear or logarithmic sampling */\nvoid SetLinearFrequencies(\n  gsl_vector* freqvector,    /* Output pointer to gsl_vector, already allocated */\n  const double fmin,         /* Lower bound of the frequency interval */\n  const double fmax,         /* Upper bound of the frequency interval */\n  const int nbpts)           /* Number of points */\n{\n  /* Vector of frequencies with logarithmic spacing */\n  double stepf = (fmax-fmin)/(nbpts-1.);\n  for(int i=0; i<nbpts; i++) {\n    gsl_vector_set(freqvector, i, fmin + i * stepf);\n  }\n}\nvoid SetLogFrequencies(\n  gsl_vector* freqvector,    /* Output pointer to gsl_vector, already allocated */\n  const double fmin,         /* Lower bound of the frequency interval */\n  const double fmax,         /* Upper bound of the frequency interval */\n  const int nbpts)           /* Number of points */\n{\n  /* Vector of frequencies with logarithmic spacing */\n  double lnratio = log(fmax/fmin);\n  double lnfmin = log(fmin);\n  for(int i=0; i<nbpts; i++) {\n    gsl_vector_set(freqvector, i, exp(lnfmin + (double) i/(nbpts-1.) * lnratio));\n  }\n}\n\n/* Function determining logarithmically spaced frequencies from a waveform given as a list of modes, a minimal frequency and a number of points */\nvoid ListmodesSetFrequencies(\n  struct tagListmodesCAmpPhaseFrequencySeries *list,     /* Waveform, list of modes in amplitude/phase form */\n  double fLow,                                           /* Additional lower frequency limit */\n  double fHigh,                                          /* Additional upper frequency limit */\n  int nbpts,                                             /* Number of frequency samples */\n  int tagsampling,                                       /* Tag for linear (0) or logarithmic (1) sampling */\n  gsl_vector* freqvector)                                /* Output: vector of frequencies, already allocated with nbpts */\n{\n  /* Checking the length */\n  if((int) freqvector->size != nbpts) {\n    printf(\"Error: incompatible sizes in ListmodesSetFrequencies.\\n\");\n    exit(1);\n  }\n\n  /* Determining the frequency interval - from the lowest frequency of the 22 mode to the highest frequency covered by at least one mode */\n  double minf, maxf;\n  ListmodesCAmpPhaseFrequencySeries* listelementmode22 = ListmodesCAmpPhaseFrequencySeries_GetMode(list, 2, 2);\n  minf = gsl_vector_get(listelementmode22->freqseries->freq, 0);\n  maxf = gsl_vector_get(list->freqseries->freq, (int) list->freqseries->freq->size - 1);\n  ListmodesCAmpPhaseFrequencySeries* listelement = list;\n  while(listelement) {\n    maxf = fmax(maxf, gsl_vector_get(listelement->freqseries->freq, (int) listelement->freqseries->freq->size - 1));\n    listelement = listelement->next;\n  }\n\n  /* Checking that the waveform covers the fLow */\n  if(fLow < minf) printf(\"Warning: in ListmodesSetFrequencies, fLow not covered by the wave data.\\n\");\n\n  /* Actual boundaries of the frequency vector - cuts what is below fLow and above fHigh */\n  minf = fmax(minf, fLow);\n  maxf = fmin(maxf, fHigh);\n\n  /* Setting values of the vector of frequencies, linear or logarithmic sampling */\n  if(tagsampling==0) SetLinearFrequencies(freqvector, minf, maxf, nbpts);\n  else if(tagsampling==1) SetLogFrequencies(freqvector, minf, maxf, nbpts);\n  else {\n    printf(\"Error: incorrect tagsampling in ListmodesSetFrequencies.\");\n    exit(1);\n  }\n}\n\n/* Function computing a simple trapeze integration for real data */\nstatic double TrapezeIntegrate(const gsl_vector* x, const gsl_vector* y)\n{\n  if(x->size!=y->size) {\n    printf(\"Error: trying to apply TrapezeIntegrate on vectors of different lengths.\\n\");\n    exit(1);\n  }\n  int N = ((int) x->size) - 1;\n  double result = 0.;\n  for(int i=0; i<N; i++){\n    result += (gsl_vector_get(x, i+1) - gsl_vector_get(x, i)) * (gsl_vector_get(y, i) + gsl_vector_get(y, i+1))/2.;\n  }\n  return result;\n}\n\n/***************************** Functions for overlaps using linear integration ******************************/\n\n/* Function computing the overlap (h1|h2) between two given modes, for a given noise function - uses simple trapeze integration on logarithmically sampled frequencies  */\ndouble FDSinglemodeLogLinearOverlap(\n  struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */\n  struct tagCAmpPhaseFrequencySeries *freqseries2, /* Second mode h2, in amplitude/phase form */\n  ObjectFunction * Snoise,                  /* Noise function */\n  double fLow,                                     /* Lower bound of the frequency window for the detector */\n  double fHigh)                                    /* Upper bound of the frequency window for the detector */\n{\n  double res;\n  int size1 = (int) freqseries1->freq->size;\n  int size2 = (int) freqseries2->freq->size;\n  int nbpts = nbptsintdefault;\n\n  /* Minimal, maximal frequencies */\n  double fmin1 = gsl_vector_get(freqseries1->freq, 0);\n  double fmin2 = gsl_vector_get(freqseries2->freq, 0);\n  double fmax1 = gsl_vector_get(freqseries1->freq, size1 - 1);\n  double fmax2 = gsl_vector_get(freqseries2->freq, size2 - 1);\n  double fmin0 = fmax(fLow, fmax(fmin1, fmin2));\n  double fmax0 = fmin(fHigh, fmin(fmax1, fmax2));\n\n  /* Vector of frequencies with logarithmic spacing */\n  gsl_vector* freqvector = gsl_vector_alloc(nbpts);\n  SetLogFrequencies(freqvector, fmin0, fmax0, nbpts);\n\n  /* Initializing the splines */\n  /* Note: since this must also apply to mode contribution after processing, real and imaginary parts of the amplitude are present - but since they should differ for LLV detectors by a constant factor, they can be interpolated */\n  gsl_interp_accel* accel_amp1real = gsl_interp_accel_alloc();\n  gsl_interp_accel* accel_amp2real = gsl_interp_accel_alloc();\n  gsl_interp_accel* accel_amp1imag = gsl_interp_accel_alloc();\n  gsl_interp_accel* accel_amp2imag = gsl_interp_accel_alloc();\n  gsl_interp_accel* accel_phase1 = gsl_interp_accel_alloc();\n  gsl_interp_accel* accel_phase2 = gsl_interp_accel_alloc();\n  gsl_spline* amp1real = gsl_spline_alloc(gsl_interp_cspline, size1);\n  gsl_spline* amp2real = gsl_spline_alloc(gsl_interp_cspline, size2);\n  gsl_spline* amp1imag = gsl_spline_alloc(gsl_interp_cspline, size1);\n  gsl_spline* amp2imag = gsl_spline_alloc(gsl_interp_cspline, size2);\n  gsl_spline* phase1 = gsl_spline_alloc(gsl_interp_cspline, size1);\n  gsl_spline* phase2 = gsl_spline_alloc(gsl_interp_cspline, size2);\n  gsl_vector* valuesvector = gsl_vector_alloc(nbpts);\n  gsl_spline_init(amp1real, gsl_vector_const_ptr(freqseries1->freq,0), gsl_vector_const_ptr(freqseries1->amp_real,0), size1);\n  gsl_spline_init(amp1imag, gsl_vector_const_ptr(freqseries1->freq,0), gsl_vector_const_ptr(freqseries1->amp_imag,0), size1);\n  gsl_spline_init(amp2real, gsl_vector_const_ptr(freqseries2->freq,0), gsl_vector_const_ptr(freqseries2->amp_real,0), size2);\n  gsl_spline_init(amp2imag, gsl_vector_const_ptr(freqseries2->freq,0), gsl_vector_const_ptr(freqseries2->amp_imag,0), size2);\n  gsl_spline_init(phase1, gsl_vector_const_ptr(freqseries1->freq,0), gsl_vector_const_ptr(freqseries1->phase,0), size1);\n  gsl_spline_init(phase2, gsl_vector_const_ptr(freqseries2->freq,0), gsl_vector_const_ptr(freqseries2->phase,0), size2);\n\n  /* Main loop - vector of values to be evaluated */\n  double f, phi1, phi2, Sn;\n  double complex A1;\n  double complex A2;\n  double* freqvectordata = freqvector->data;\n  double* valuesvectordata = valuesvector->data;\n  int i=0;\n  for(i=0; i<nbpts; i++){\n    if(i==0) {f = fmax(freqvectordata[i], fmin0);}\n    else if(i==nbpts-1) {f = fmin(freqvectordata[i], fmax0);}\n    else {f = freqvectordata[i];}\n    A1 = gsl_spline_eval(amp1real, f, accel_amp1real) + I*gsl_spline_eval(amp1imag, f, accel_amp1imag);\n    A2 = gsl_spline_eval(amp2real, f, accel_amp2real) + I*gsl_spline_eval(amp2imag, f, accel_amp2imag);\n    phi1 = gsl_spline_eval(phase1, f, accel_phase1);\n    phi2 = gsl_spline_eval(phase2, f, accel_phase2);\n    Sn = ObjectFunctionCall(Snoise,f);\n    valuesvectordata[i] = 4.*creal(A1*conj(A2)*cexp(I*(phi1-phi2))/Sn);\n  }\n\n  /* Trapeze integration */\n  res = TrapezeIntegrate(freqvector, valuesvector);\n\n  /* Clean up */\n  gsl_vector_free(freqvector);\n  gsl_vector_free(valuesvector);\n  gsl_interp_accel_free(accel_amp1real);\n  gsl_interp_accel_free(accel_amp2real);\n  gsl_interp_accel_free(accel_amp1imag);\n  gsl_interp_accel_free(accel_amp2imag);\n  gsl_interp_accel_free(accel_phase1);\n  gsl_interp_accel_free(accel_phase2);\n  gsl_spline_free(amp1real);\n  gsl_spline_free(amp2real);\n  gsl_spline_free(amp1imag);\n  gsl_spline_free(amp2imag);\n  gsl_spline_free(phase1);\n  gsl_spline_free(phase2);\n\n  return res;\n}\n\n/* Function computing the overlap (h1|h2) between two waveforms given as lists of mode contributions (factos sYlm already included), for a given noise function - uses simple trapeze integration on logarithmically sampled frequencies - generates the frequency series in Re/Im form by summing the mode contributions first, then computes the overlap */\ndouble FDListmodesLogLinearOverlap(\n  struct tagListmodesCAmpPhaseFrequencySeries *list1,    /* First waveform, list of modes in amplitude/phase form */\n  struct tagListmodesCAmpPhaseFrequencySeries *list2,    /* Second waveform, list of modes in amplitude/phase form */\n  ObjectFunction * Snoise,                        /* Noise function */\n  double fLow,                                           /* Lower bound of the frequency window for the detector */\n  double fHigh,                                          /* Upper bound of the frequency window for the detector */\n  double fstartobs1,                                     /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */\n  double fstartobs2)                                     /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n{\n  /* Number of points to use in the trapeze integration */\n  int nbpts = nbptsintdefault;\n\n  /* Determining the frequency interval - from the lowest frequency of the 22 mode to the highest frequency covered by at least one mode */\n  double minf1, maxf1, minf2, maxf2, minf, maxf;\n  ListmodesCAmpPhaseFrequencySeries* listelement1mode22 = ListmodesCAmpPhaseFrequencySeries_GetMode(list1, 2, 2);\n  ListmodesCAmpPhaseFrequencySeries* listelement2mode22 = ListmodesCAmpPhaseFrequencySeries_GetMode(list2, 2, 2);\n  minf1 = gsl_vector_get(listelement1mode22->freqseries->freq, 0);\n  minf2 = gsl_vector_get(listelement2mode22->freqseries->freq, 0);\n  maxf1 = ListmodesCAmpPhaseFrequencySeries_maxf(list1);\n  maxf2 = ListmodesCAmpPhaseFrequencySeries_maxf(list2);\n  /* Taking into account fLow, fHigh -- fstartobs, determined from 22 mode, is also used as a fLow */\n  if(!(fHigh==0.)) {\n    maxf1 = fmin(maxf1, fHigh);\n    maxf2 = fmin(maxf2, fHigh);\n  }\n  if(!(fLow==0.)) {\n    minf1 = fmax(minf1, fLow);\n    minf2 = fmax(minf2, fLow);\n  }\n  if(!(fstartobs1==0.)) minf1 = fmax(minf1, fstartobs1);\n  if(!(fstartobs2==0.)) minf1 = fmax(minf2, fstartobs2);\n  /* Actual boundaries to be used in the overlap - intersection of freqs covered by wf 1 and 2 */\n  minf = fmax(minf1, minf2);\n  maxf = fmin(maxf1, maxf2);\n\n  /* Vector of frequencies used for the overlap */\n  gsl_vector* freqoverlap = gsl_vector_alloc(nbpts);\n  SetLogFrequencies(freqoverlap, minf, maxf, nbpts);\n\n  /* Evaluating each frequency series by interpolating and summing the mode contributions */\n  ReImFrequencySeries* freqseries1 = NULL;\n  ReImFrequencySeries_Init(&freqseries1, nbpts);\n  ReImFrequencySeries_SumListmodesCAmpPhaseFrequencySeries(freqseries1, list1, freqoverlap, fLow, fHigh, fstartobs1);\n  ReImFrequencySeries* freqseries2 = NULL;\n  ReImFrequencySeries_Init(&freqseries2, nbpts);\n  ReImFrequencySeries_SumListmodesCAmpPhaseFrequencySeries(freqseries2, list2, freqoverlap, fLow, fHigh, fstartobs2);\n\n  /* Compute the integrand */\n  gsl_vector* valuesoverlap = gsl_vector_alloc(nbpts);\n  double* hreal1data = freqseries1->h_real->data;\n  double* himag1data = freqseries1->h_imag->data;\n  double* hreal2data = freqseries2->h_real->data;\n  double* himag2data = freqseries2->h_imag->data;\n  double* freqdata = freqoverlap->data;\n  for(int i=0; i<nbpts; i++) {\n    gsl_vector_set(valuesoverlap, i, 4.*creal( (hreal1data[i] + I*himag1data[i]) * (hreal2data[i] - I*himag2data[i]) / ObjectFunctionCall(Snoise,freqdata[i])));\n  }\n\n  /* Final trapeze integration */\n  double overlap = TrapezeIntegrate(freqoverlap, valuesoverlap);\n\n  /* Clean up */\n  ReImFrequencySeries_Cleanup(freqseries1);\n  ReImFrequencySeries_Cleanup(freqseries2);\n  gsl_vector_free(freqoverlap);\n  gsl_vector_free(valuesoverlap);\n\n  return overlap;\n}\n\n/* Function computing the overlap (h1|h2) between h1 given in Re/Im form and h2 given as a list of mode contributions (factors sYlm already included), for a given vector of noise values - uses simple trapeze integration - generates the frequency series of h2 in Re/Im form by summing the mode contributions first, then computes the overlap */\ndouble FDOverlapReImvsListmodesCAmpPhase(\n  struct tagReImFrequencySeries *freqseries1,            /* First waveform, in Re/Im form */\n  struct tagListmodesCAmpPhaseFrequencySeries *list2,    /* Second waveform, list of modes in amplitude/phase form */\n  gsl_vector* noisevalues,                               /* Vector for the noise values on the freq of h1 */\n  double fLow,                                           /* Minimal frequency - set to 0 to ignore */\n  double fHigh,                                          /* Maximal frequency - set to 0 to ignore */\n  double fstartobs2)                                     /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n{\n  /* Check the lengths */\n  if(freqseries1->freq->size != noisevalues->size) {\n    printf(\"Error: inconsistent lengths in FDOverlapReImvsListmodesCAmpPhase.\\n\");\n    exit(1);\n  }\n\n  /* Frequencies used for the overlap */\n  int nbpts = (int) freqseries1->freq->size;\n  gsl_vector* freqoverlap = freqseries1->freq;\n\n  /* Evaluating frequency series 2 by interpolating and summing the mode contributions */\n  ReImFrequencySeries* freqseries2 = NULL;\n  ReImFrequencySeries_Init(&freqseries2, nbpts);\n  ReImFrequencySeries_SumListmodesCAmpPhaseFrequencySeries(freqseries2, list2, freqoverlap, fLow, fHigh, fstartobs2);\n\n  /* Compute the integrand */\n  gsl_vector* valuesoverlap = gsl_vector_alloc(nbpts);\n  double* hreal1data = freqseries1->h_real->data;\n  double* himag1data = freqseries1->h_imag->data;\n  double* hreal2data = freqseries2->h_real->data;\n  double* himag2data = freqseries2->h_imag->data;\n  double* noisedata = noisevalues->data;\n  for(int i=0; i<nbpts; i++) {\n    gsl_vector_set(valuesoverlap, i, 4.*creal( (hreal1data[i] + I*himag1data[i]) * (hreal2data[i] - I*himag2data[i]) / noisedata[i]));\n  }\n\n  /* Final trapeze integration */\n  double overlap = TrapezeIntegrate(freqoverlap, valuesoverlap);\n\n  /* Clean up */\n  ReImFrequencySeries_Cleanup(freqseries2);\n  gsl_vector_free(valuesoverlap);\n\n  return overlap;\n}\n\n/* Function computing the overlap (h1|h2) between two waveforms given as Re/Im frequency series (common freq values assumed), for a given vector of noise values - uses simple trapeze integration */\ndouble FDOverlapReImvsReIm(\n  struct tagReImFrequencySeries *freqseries1,  /* First waveform, frequency series in Re/Im form */\n  struct tagReImFrequencySeries *freqseries2,  /* Second waveform, frequency series in Re/Im form */\n  gsl_vector* noisevalues)                     /* Vector for the noise values on common freq of the freqseries */\n{\n  /* Check the lengths */\n  if(freqseries1->freq->size != noisevalues->size || freqseries2->freq->size != noisevalues->size) {\n    printf(\"Error: inconsistent lengths in FDOverlapReImvsReIm.\\n\");\n    exit(1);\n  }\n\n  /* Frequency vector - assuming they match beyond their mere lengths */\n  gsl_vector* freqoverlap = freqseries1->freq;\n  int nbpts = (int) freqoverlap->size;\n\n  /* Compute the integrand */\n  gsl_vector* valuesoverlap = gsl_vector_alloc((int) freqoverlap->size);\n  double* hreal1data = freqseries1->h_real->data;\n  double* himag1data = freqseries1->h_imag->data;\n  double* hreal2data = freqseries2->h_real->data;\n  double* himag2data = freqseries2->h_imag->data;\n  double* noisedata = noisevalues->data;\n  for(int i=0; i<nbpts; i++) {\n    gsl_vector_set(valuesoverlap, i, 4.*creal( (hreal1data[i] + I*himag1data[i]) * (hreal2data[i] - I*himag2data[i]) / noisedata[i]));\n  }\n\n  /* Final trapeze integration */\n  double overlap = TrapezeIntegrate(freqoverlap, valuesoverlap);\n\n  /* Clean up */\n  gsl_vector_free(valuesoverlap);\n\n  return overlap;\n}\n\n/***************************** Functions for overlaps using amplitude/phase (wip) ******************************/\n\n/* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form, for a given noise function - uses the amplitude/phase representation (wip) */\ndouble FDSinglemodeWIPOverlap(\n  struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */\n  struct tagCAmpPhaseFrequencySeries *freqseries2, /* Second mode h2, in amplitude/phase form */\n  ObjectFunction * Snoise,                  /* Noise function */\n  double fLow,                                     /* Lower bound of the frequency window for the detector */\n  double fHigh)                                    /* Upper bound of the frequency window for the detector */\n{\n  /* Should add some error checking */\n  CAmpPhaseFrequencySeries* h1 = freqseries1;\n  CAmpPhaseFrequencySeries* h2 = freqseries2;\n\n  double *f1 = h1->freq->data;\n  int n1 = h1->freq->size;\n  double *h1Ar = h1->amp_real->data;\n  double *h1Ai = h1->amp_imag->data;\n  double *h1p = h1->phase->data;\n\n  double *f2 = h2->freq->data;\n  int n2 = h2->freq->size;\n  double *h2Ar = h2->amp_real->data;\n  double *h2Ai = h2->amp_imag->data;\n  double *h2p = h2->phase->data;\n\n  /* fLow or fHigh <= 0 means use intersection of signal domains  */\n  /* NOTE: factor 4 was previously missing */\n  double overlap = 4.*wip_phase(f1, n1, f2, n2, h1Ar, h1Ai, h1p, h2Ar, h2Ai, h2p, Snoise, 1.0, fLow, fHigh);\n  return overlap;\n}\n\n/* Function computing the overlap (h1|h2) between two waveforms given as list of modes, for a given noise function - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */\ndouble FDListmodesWIPOverlap(\n  struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First waveform, list of modes in amplitude/phase form */\n  struct tagListmodesCAmpPhaseFrequencySeries *listh2, /* Second waveform, list of modes in amplitude/phase form */\n  ObjectFunction * Snoise,                  /* Noise function */\n  double fLow,                                         /* Lower bound of the frequency window for the detector */\n  double fHigh,                                        /* Upper bound of the frequency window for the detector */\n  double fstartobs1,                                   /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */\n  double fstartobs2)                                   /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n{\n  double overlap = 0;\n\n  /* Main loop over the modes - goes through all the modes present */\n  ListmodesCAmpPhaseFrequencySeries* listelementh1 = listh1;\n  while(listelementh1) {\n    ListmodesCAmpPhaseFrequencySeries* listelementh2 = listh2;\n    while(listelementh2) {\n      /* Scaling fstartobs1/2 with the appropriate factor of m (for the 21 mode we use m=2) - setting fmin in the overlap accordingly */\n      int mmax1 = max(2, listelementh1->m);\n      int mmax2 = max(2, listelementh2->m);\n      double fcutLow = fmax(fLow, fmax(((double) mmax1)/2. * fstartobs1, ((double) mmax2)/2. * fstartobs2));\n      overlap += FDSinglemodeWIPOverlap(listelementh1->freqseries, listelementh2->freqseries, Snoise, fcutLow, fHigh);\n\n      listelementh2 = listelementh2->next;\n    }\n    listelementh1 = listelementh1->next;\n  }\n  return overlap;\n}\n\n/************** Functions for overlap/likelihood allowing to switch between wip and loglinear integration *****************/\n\n/* Wrapping of FDListmodesWIPOverlap or FDListmodesLogLinearOverlap according to tagint */\ndouble FDListmodesOverlap(\n  struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First mode h1, list of modes in amplitude/phase form */\n  struct tagListmodesCAmpPhaseFrequencySeries *listh2, /* Second mode h2, list of modes in amplitude/phase form */\n  ObjectFunction * Snoise,                  /* Noise function */\n  double fLow,                                         /* Lower bound of the frequency window for the detector */\n  double fHigh,                                        /* Upper bound of the frequency window for the detector */\n  double fstartobs1,                                   /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */\n  double fstartobs2,                                   /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n  int tagint)                                          /* Tag choosing the integrator: 0 for wip, 1 for log linear integration */\n{\n  double overlap;\n  if(tagint==0) {\n    overlap = FDListmodesWIPOverlap(listh1, listh2, Snoise, fLow, fHigh, fstartobs1, fstartobs2);\n  }\n  else if(tagint==1) {\n    overlap = FDListmodesLogLinearOverlap(listh1, listh2, Snoise, fLow, fHigh, fstartobs1, fstartobs2);\n  }\n  return overlap;\n}\n\n/* Function computing the log likelihood (h|s) - 1/2 (h|h) - 1/2 (s|s), with s the signal, h the template, and where we keep the constant term (s|s) - passed to the function as a parameter - all the cross-products between modes are taken into account - two additionals parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */\ndouble FDLogLikelihood(\n  struct tagListmodesCAmpPhaseFrequencySeries *lists,  /* Input: list of modes for the signal s, in Frequency-domain amplitude and phase form */\n  struct tagListmodesCAmpPhaseFrequencySeries *listh,  /* Input: list of modes for the template, in Frequency-domain amplitude and phase form */\n  ObjectFunction * Snoise,                      /* Noise function */\n  double fLow,                                         /* Lower bound of the frequency window for the detector */\n  double fHigh,                                        /* Upper bound of the frequency window for the detector */\n  double ss,                                           /* Inner product (s|s), constant to be computed elsewhere and passed as an argument */\n  double hh,                                           /* Inner product (h|h), constant to be computed elsewhere and passed as an argument */\n  double fstartobss,                                   /* Starting frequency for the 22 mode of s - as determined from a limited duration of the observation - set to 0 to ignore */\n  double fstartobsh,                                   /* Starting frequency for the 22 mode of h - as determined from a limited duration of the observation - set to 0 to ignore */\n  int tagint)                                          /* Tag choosing the integrator: 0 for wip, 1 for log linear integration */\n{\n  double lnL;\n  if(tagint==0) {\n    lnL = FDListmodesWIPOverlap(lists, listh, Snoise, fLow, fHigh, fstartobss, fstartobsh) - 1./2 * hh - 1./2 * ss;\n  }\n  else if(tagint==1) {\n    lnL = FDListmodesLogLinearOverlap(lists, listh, Snoise, fLow, fHigh, fstartobss, fstartobsh) - 1./2 * hh - 1./2 * ss;\n  }\n  return lnL;\n}\n\n/************** Functions for overlap/likelihood specific to loglinear integration *****************/\n\n/* Function computing the log likelihood -1/2(h-s|h-s), with s the signal, h the template (both given as frequency series in Re/Im form) - h, s assumed to be given on the same set of frequencies - same for the vector of noise values - fstartobs for s, h has already been taken into account */\ndouble FDLogLikelihoodReIm(\n  struct tagReImFrequencySeries *s,    /* First waveform (injection), frequency series in Re/Im form */\n  struct tagReImFrequencySeries *h,    /* Second waveform (template), frequency series in Re/Im form */\n  gsl_vector* noisevalues)             /* Vector for the noise values on common freq of the freqseries */\n{\n  /* Check the lengths */\n  if(s->freq->size != noisevalues->size || h->freq->size != noisevalues->size) {\n    printf(\"Error: inconsistent lengths in FDLogLikelihoodReIm.\\n\");\n    exit(1);\n  }\n\n  /* Taking the difference between the frequency series: diff = h-s */\n  int nbpts = (int) s->freq->size;\n  ReImFrequencySeries* diff = NULL;\n  ReImFrequencySeries_Init(&diff, nbpts);\n  gsl_vector_memcpy(diff->freq, s->freq);\n  gsl_vector_memcpy(diff->h_real, h->h_real);\n  gsl_vector_memcpy(diff->h_imag, h->h_imag);\n  gsl_vector_sub(diff->h_real, s->h_real);\n  gsl_vector_sub(diff->h_imag, s->h_imag);\n\n  /* Likelihood lnL = -1/2(h-s|h-s) */\n  double lnL;\n  lnL = -1./2 * FDOverlapReImvsReIm(diff, diff, noisevalues);\n\n  /* Clean up */\n  ReImFrequencySeries_Cleanup(diff);\n\n  return lnL;\n}\n\n/***************************** Functions for overlaps using amplitude/phase (Fresnel) ******************************/\n\n/*  Moved these to splinecoeffs.c\n \n// Note: for the spines in matrix form, the first column contains the x values, so the coeffs start at 1 \nstatic double EvalCubic(\n  gsl_vector* coeffs,  \n  double eps,          \n  double eps2,         \n  double eps3)         \n{\n  double p0 = gsl_vector_get(coeffs, 1);\n  double p1 = gsl_vector_get(coeffs, 2);\n  double p2 = gsl_vector_get(coeffs, 3);\n  double p3 = gsl_vector_get(coeffs, 4);\n  return p0 + p1*eps + p2*eps2 + p3*eps3;\n}\nstatic double EvalQuad(\n  gsl_vector* coeffs,  \n  double eps,          \n  double eps2)         \n{\n  double p0 = gsl_vector_get(coeffs, 1);\n  double p1 = gsl_vector_get(coeffs, 2);\n  double p2 = gsl_vector_get(coeffs, 3);\n  return p0 + p1*eps + p2*eps2;\n}\n*/\n\n/* Quadratic Legendre approximation to compute values at minf and maxf when they do not fall on the grid of a freqseries, using the two first/last intervals */\nstatic double EstimateBoundaryLegendreQuad(\n  gsl_vector* vectx,   /**/\n  gsl_vector* vecty,   /**/\n  int j,               /**/\n  double xvalue)       /**/\n{\n  double x0 = 0;\n  double x1 = gsl_vector_get(vectx, j+1) - gsl_vector_get(vectx, j);\n  double x2 = gsl_vector_get(vectx, j+2) - gsl_vector_get(vectx, j);\n  double x = xvalue - gsl_vector_get(vectx, j);\n  double y0 = gsl_vector_get(vecty, j);\n  double y1 = gsl_vector_get(vecty, j+1);\n  double y2 = gsl_vector_get(vecty, j+2);\n  if(!(x>=x0 && x<=x2)) {\n    printf(\"Error: value out of bounds in EstimateBoundaryLegendreQuad.\\n\");\n    exit(1);\n  }\n  return y0*(x-x1)*(x-x2)/(x0-x1)/(x0-x2) + y1*(x-x0)*(x-x2)/(x1-x0)/(x1-x2) + y2*(x-x0)*(x-x1)/(x2-x0)/(x2-x1);\n}\n\n/* Function computing the integrand values */\nvoid ComputeIntegrandValues(\n  CAmpPhaseFrequencySeries** integrand,     /* Output: values of the integrand on common frequencies (initialized in the function) */\n  CAmpPhaseFrequencySeries* freqseries1,    /* Input: frequency series for wf 1 */\n  CAmpPhaseSpline* splines2,                /* Input: splines in matrix form for wf 2 */\n  ObjectFunction * Snoise,           /* Noise function */\n  double fLow,                              /* Lower bound of the frequency - 0 to ignore */\n  double fHigh)                             /* Upper bound of the frequency - 0 to ignore */\n{\n  gsl_set_error_handler(&Err_Handler);\n\n  /* Determining the boundaries of indices */\n  gsl_vector* freq1 = freqseries1->freq;\n  int imin1 = 0;\n  int imax1 = freq1->size - 1;\n  double* f1 = freq1->data;\n  double f2min = gsl_matrix_get(splines2->quadspline_phase, 0, 0);\n  double f2max = gsl_matrix_get(splines2->quadspline_phase, splines2->quadspline_phase->size1 - 1, 0);\n  if((fLow>0 && (f1[imax1]<=fLow || f2max<=fLow)) || (fHigh>0 && (f1[imin1]>=fHigh || f2min>=fHigh))) {\n    printf(\"Error: range of frequencies incompatible with fLow, fHigh in IntegrandValues.\\n\");\n    printf(\"need one of {%g, %g} <= %g and one of {%g, %g}>=%g\\n\",f1[imax1],f2max,fLow,f1[imin1],f2min,fHigh);\n    exit(1);\n  }\n  /* If starting outside, move the ends of the frequency series to be just outside the final minf and maxf */\n  double minf = fmax(f1[imin1], f2min);\n  double maxf = fmin(f1[imax1], f2max);\n  if(fLow>0) {minf = fmax(fLow, minf);}\n  if(fHigh>0) {maxf = fmin(fHigh, maxf);}\n  while(f1[imin1+1]<=minf) imin1++;\n  while(f1[imax1-1]>=maxf) imax1--;\n  /* Estimate locally values for freqseries1 at the boundaries */\n  double areal1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1->amp_real, imin1, minf);\n  double aimag1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1->amp_imag, imin1, minf);\n  double phi1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1->phase, imin1, minf);\n  double areal1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1->amp_real, imax1-2, maxf); /* Note the imax1-2 */\n  double aimag1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1->amp_imag, imax1-2, maxf); /* Note the imax1-2 */\n  double phi1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1->phase, imax1-2, maxf); /* Note the imax1-2 */\n\n\n  /* Initializing output structure */\n  int nbpts = imax1 + 1 - imin1;\n  CAmpPhaseFrequencySeries_Init(integrand, nbpts);\n\n  /* Loop computing integrand values */\n  gsl_vector* freq = (*integrand)->freq;\n  gsl_vector* ampreal = (*integrand)->amp_real;\n  gsl_vector* ampimag = (*integrand)->amp_imag;\n  gsl_vector* phase = (*integrand)->phase;\n  double f, eps, eps2, eps3, ampreal1, ampimag1, phase1, ampreal2, ampimag2, phase2, invSn;\n  double complex camp;\n  double* areal1 = freqseries1->amp_real->data;\n  double* aimag1 = freqseries1->amp_imag->data;\n  double* phi1 = freqseries1->phase->data;\n  gsl_matrix* splineAreal2 = splines2->spline_amp_real;\n  gsl_matrix* splineAimag2 = splines2->spline_amp_imag;\n  gsl_matrix* quadsplinephase2 = splines2->quadspline_phase;\n  int i2 = 0; int j = 0;\n  for(int i=imin1; i<=imax1; i++) {\n    /* Distinguish the case where we are at minf or maxf */\n    if(i==imin1) {\n      f = minf;\n      ampreal1 = areal1minf;\n      ampimag1 = aimag1minf;\n      phase1 = phi1minf;\n    }\n    else if(i==imax1) {\n      f = maxf;\n      ampreal1 = areal1maxf;\n      ampimag1 = aimag1maxf;\n      phase1 = phi1maxf;\n    }\n    else {\n      f = gsl_vector_get(freq1, i);\n      ampreal1 = areal1[i];\n      ampimag1 = aimag1[i];\n      phase1 = phi1[i];\n    }\n    /* Adjust the index in the spline if necessary and compute */\n    while(gsl_matrix_get(splines2->quadspline_phase, i2+1, 0)<f) i2++;\n    eps = f - gsl_matrix_get(splines2->quadspline_phase, i2, 0);\n    eps2 = eps*eps;\n    eps3 = eps2*eps;\n    gsl_vector_view coeffsampreal2 = gsl_matrix_row(splineAreal2, i2);\n    gsl_vector_view coeffsampimag2 = gsl_matrix_row(splineAimag2, i2);\n    gsl_vector_view coeffsphase2 = gsl_matrix_row(quadsplinephase2, i2);\n    ampreal2 = EvalCubic(&coeffsampreal2.vector, eps, eps2, eps3);\n    ampimag2 = EvalCubic(&coeffsampimag2.vector, eps, eps2, eps3);\n    phase2 = EvalQuad(&coeffsphase2.vector, eps, eps2);\n    invSn = 1./ObjectFunctionCall(Snoise,f);\n    camp = invSn * (ampreal1 + I*ampimag1) * (ampreal2 - I*ampimag2);\n    gsl_vector_set(freq, j, f);\n    gsl_vector_set(ampreal, j, creal(camp));\n    gsl_vector_set(ampimag, j, cimag(camp));\n    gsl_vector_set(phase, j, phase1 - phase2);\n    j++;\n  }\n}\n\n/* Function computing the integrand values, combining three non-correlated channels */\nint ComputeIntegrandValues3Chan(\n  CAmpPhaseFrequencySeries** integrand,     /* Output: values of the integrand on common frequencies (initialized in the function) */\n  CAmpPhaseFrequencySeries* freqseries1chan1,    /* Input: frequency series for wf 1, channel 1 */\n  CAmpPhaseFrequencySeries* freqseries1chan2,    /* Input: frequency series for wf 1, channel 2 */\n  CAmpPhaseFrequencySeries* freqseries1chan3,    /* Input: frequency series for wf 1, channel 3 */\n  CAmpPhaseSpline* splines2chan1,                /* Input: splines in matrix form for wf 2, channel 1 */\n  CAmpPhaseSpline* splines2chan2,                /* Input: splines in matrix form for wf 2, channel 2 */\n  CAmpPhaseSpline* splines2chan3,                /* Input: splines in matrix form for wf 2, channel 3 */\n  ObjectFunction * Snoise1,                /* Noise function */\n  ObjectFunction * Snoise2,                /* Noise function */\n  ObjectFunction * Snoise3,                /* Noise function */\n  double fLow,                              /* Lower bound of the frequency - 0 to ignore */\n  double fHigh)                             /* Upper bound of the frequency - 0 to ignore */\n{\n  gsl_set_error_handler(&Err_Handler);\n\n  /* Determining the boundaries of indices - frequency vectors assumed to be the same for channels 1,2,3 */\n  gsl_vector* freq1 = freqseries1chan1->freq;\n  int imin1 = 0;\n  int imax1 = freq1->size - 1;\n  double* f1 = freq1->data;\n  double f2min = gsl_matrix_get(splines2chan1->quadspline_phase, 0, 0);\n  double f2max = gsl_matrix_get(splines2chan1->quadspline_phase, splines2chan1->quadspline_phase->size1 - 1, 0);\n  if((fLow>0 && (f1[imax1]<=fLow || f2max<=fLow)) || (fHigh>0 && (f1[imin1]>=fHigh || f2min>=fHigh))) {\n    //printf(\"Error: range of frequencies incompatible with fLow, fHigh in IntegrandValues.\\n\");\n    //printf(\"need both {%g, %g} > %g and both {%g, %g} < %g\\n\",f1[imax1],f2max,fLow,f1[imin1],f2min,fHigh);\n    return -1;\n  }\n  /* If starting outside, move the ends of the frequency series to be just outside the final minf and maxf */\n  double minf = fmax(f1[imin1], f2min);\n  double maxf = fmin(f1[imax1], f2max);\n  if(fLow>0) {minf = fmax(fLow, minf);}\n  if(fHigh>0) {maxf = fmin(fHigh, maxf);}\n  while(f1[imin1+1]<=minf) imin1++;\n  while(f1[imax1-1]>=maxf) imax1--;\n  //printf(\"imin=%i, imax=%i\\n\",imin1,imax1);\n  int nbpts = imax1 + 1 - imin1;\n  //printf(\"nbpts=%i\\n\",nbpts);\n  if(nbpts<4)return -1;\n  /* Estimate locally values for freqseries1 at the boundaries - phase vectors assumed to be the same for channels 1,2,3 - this is still true now that the response-processed phase includes the signal phase + R-delay phase, which is the same for all channels */\n  double areal1chan1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->amp_real, imin1, minf);\n  double aimag1chan1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->amp_imag, imin1, minf);\n  double areal1chan2minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan2->amp_real, imin1, minf);\n  double aimag1chan2minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan2->amp_imag, imin1, minf);\n  double areal1chan3minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan3->amp_real, imin1, minf);\n  double aimag1chan3minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan3->amp_imag, imin1, minf);\n  double phi1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->phase, imin1, minf);\n  double areal1chan1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->amp_real, imax1-2, maxf); /* Note the imax1-2 */\n  double aimag1chan1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->amp_imag, imax1-2, maxf); /* Note the imax1-2 */\n  double areal1chan2maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan2->amp_real, imax1-2, maxf); /* Note the imax1-2 */\n  double aimag1chan2maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan2->amp_imag, imax1-2, maxf); /* Note the imax1-2 */\n  double areal1chan3maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan3->amp_real, imax1-2, maxf); /* Note the imax1-2 */\n  double aimag1chan3maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan3->amp_imag, imax1-2, maxf); /* Note the imax1-2 */\n  double phi1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->phase, imax1-2, maxf); /* Note the imax1-2 */\n\n  /* Initializing output structure */\n  CAmpPhaseFrequencySeries_Init(integrand, nbpts);\n\n  /* Loop computing integrand values - phases are the same for chan1, chan2 and chan3 */\n  gsl_vector* freq = (*integrand)->freq;\n  gsl_vector* ampreal = (*integrand)->amp_real;\n  gsl_vector* ampimag = (*integrand)->amp_imag;\n  gsl_vector* phase = (*integrand)->phase;\n  double f, eps, eps2, eps3, ampreal1chan1, ampimag1chan1, ampreal1chan2, ampimag1chan2, ampreal1chan3, ampimag1chan3, phase1, ampreal2chan1, ampimag2chan1, ampreal2chan2, ampimag2chan2, ampreal2chan3, ampimag2chan3, phase2, invSnchan1, invSnchan2, invSnchan3;\n  double complex camp;\n  double* areal1chan1 = freqseries1chan1->amp_real->data;\n  double* aimag1chan1 = freqseries1chan1->amp_imag->data;\n  double* areal1chan2 = freqseries1chan2->amp_real->data;\n  double* aimag1chan2 = freqseries1chan2->amp_imag->data;\n  double* areal1chan3 = freqseries1chan3->amp_real->data;\n  double* aimag1chan3 = freqseries1chan3->amp_imag->data;\n  double* phi1 = freqseries1chan1->phase->data;\n  gsl_matrix* splinechan1real2chan1 = splines2chan1->spline_amp_real;\n  gsl_matrix* splinechan1imag2chan1 = splines2chan1->spline_amp_imag;\n  gsl_matrix* splinechan1real2chan2 = splines2chan2->spline_amp_real;\n  gsl_matrix* splinechan1imag2chan2 = splines2chan2->spline_amp_imag;\n  gsl_matrix* splinechan1real2chan3 = splines2chan3->spline_amp_real;\n  gsl_matrix* splinechan1imag2chan3 = splines2chan3->spline_amp_imag;\n  gsl_matrix* quadsplinephase2 = splines2chan1->quadspline_phase;\n  int i2 = 0; int j = 0;\n  for(int i=imin1; i<=imax1; i++) {\n    /* Distinguish the case where we are at minf or maxf */\n    if(i==imin1) {\n      f = minf;\n      ampreal1chan1 = areal1chan1minf;\n      ampimag1chan1 = aimag1chan1minf;\n      ampreal1chan2 = areal1chan2minf;\n      ampimag1chan2 = aimag1chan2minf;\n      ampreal1chan3 = areal1chan3minf;\n      ampimag1chan3 = aimag1chan3minf;\n      phase1 = phi1minf;\n    }\n    else if(i==imax1) {\n      f = maxf;\n      ampreal1chan1 = areal1chan1maxf;\n      ampimag1chan1 = aimag1chan1maxf;\n      ampreal1chan2 = areal1chan2maxf;\n      ampimag1chan2 = aimag1chan2maxf;\n      ampreal1chan3 = areal1chan3maxf;\n      ampimag1chan3 = aimag1chan3maxf;\n      phase1 = phi1maxf;\n    }\n    else {\n      f = gsl_vector_get(freq1, i);\n      ampreal1chan1 = areal1chan1[i];\n      ampimag1chan1 = aimag1chan1[i];\n      ampreal1chan2 = areal1chan2[i];\n      ampimag1chan2 = aimag1chan2[i];\n      ampreal1chan3 = areal1chan3[i];\n      ampimag1chan3 = aimag1chan3[i];\n      phase1 = phi1[i];\n    }\n    /* Adjust the index in the spline if necessary and compute */\n    while(gsl_matrix_get(splines2chan1->quadspline_phase, i2+1, 0)<f) i2++;\n    eps = f - gsl_matrix_get(splines2chan1->quadspline_phase, i2, 0);\n    eps2 = eps*eps;\n    eps3 = eps2*eps;\n    gsl_vector_view coeffsampreal2chan1 = gsl_matrix_row(splinechan1real2chan1, i2);\n    gsl_vector_view coeffsampimag2chan1 = gsl_matrix_row(splinechan1imag2chan1, i2);\n    gsl_vector_view coeffsampreal2chan2 = gsl_matrix_row(splinechan1real2chan2, i2);\n    gsl_vector_view coeffsampimag2chan2 = gsl_matrix_row(splinechan1imag2chan2, i2);\n    gsl_vector_view coeffsampreal2chan3 = gsl_matrix_row(splinechan1real2chan3, i2);\n    gsl_vector_view coeffsampimag2chan3 = gsl_matrix_row(splinechan1imag2chan3, i2);\n    gsl_vector_view coeffsphase2 = gsl_matrix_row(quadsplinephase2, i2);\n    ampreal2chan1 = EvalCubic(&coeffsampreal2chan1.vector, eps, eps2, eps3);\n    ampimag2chan1 = EvalCubic(&coeffsampimag2chan1.vector, eps, eps2, eps3);\n    ampreal2chan2 = EvalCubic(&coeffsampreal2chan2.vector, eps, eps2, eps3);\n    ampimag2chan2 = EvalCubic(&coeffsampimag2chan2.vector, eps, eps2, eps3);\n    ampreal2chan3 = EvalCubic(&coeffsampreal2chan3.vector, eps, eps2, eps3);\n    ampimag2chan3 = EvalCubic(&coeffsampimag2chan3.vector, eps, eps2, eps3);\n    phase2 = EvalQuad(&coeffsphase2.vector, eps, eps2);\n    invSnchan1 = 1./ObjectFunctionCall(Snoise1,f);\n    invSnchan2 = 1./ObjectFunctionCall(Snoise2,f);\n    invSnchan3 = 1./ObjectFunctionCall(Snoise3,f);\n\n    camp = invSnchan1 * (ampreal1chan1 + I*ampimag1chan1) * (ampreal2chan1 - I*ampimag2chan1) + invSnchan2 * (ampreal1chan2 + I*ampimag1chan2) * (ampreal2chan2 - I*ampimag2chan2) + invSnchan3 * (ampreal1chan3 + I*ampimag1chan3) * (ampreal2chan3 - I*ampimag2chan3);\n    //dump\n    /*\n    printf(\"j=%i, im=%g\\n a11=(%g,%g),  a12=(%g,%g),  a13=(%g,%g)\\n a11=(%g,%g),  a12=(%g,%g),  a13=(%g,%g)\\n\",j,cimag(camp),\n\t   ampreal1chan1,ampimag1chan1,ampreal1chan2,ampimag1chan2,ampreal1chan3,ampimag1chan3,\n\t   ampreal2chan1,ampimag2chan1,ampreal2chan2,ampimag2chan2,ampreal2chan3,ampimag2chan3);\n    printf(\"in1=%g, in2=%g, in3=%g\\n\",invSnchan1,invSnchan2,invSnchan3);\n    */\n    \n    gsl_vector_set(freq, j, f);\n    gsl_vector_set(ampreal, j, creal(camp));\n    gsl_vector_set(ampimag, j, cimag(camp));\n    gsl_vector_set(phase, j, phase1 - phase2);\n    j++;\n  }\n  return 0;\n}\n\n/* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form, one being already interpolated, for a given noise function - uses the amplitude/phase representation (Fresnel) */\ndouble FDSinglemodeFresnelOverlap(\n  struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */\n  struct tagCAmpPhaseSpline *splines2,             /* Second mode h2, already interpolated in matrix form */\n  ObjectFunction * Snoise,                  /* Noise function */\n  double fLow,                                     /* Lower bound of the frequency window for the detector */\n  double fHigh)                                    /* Upper bound of the frequency window for the detector */\n{\n  /* Computing the integrand values, on the frequency grid of h1 */\n  CAmpPhaseFrequencySeries* integrand = NULL;\n  ComputeIntegrandValues(&integrand, freqseries1, splines2, Snoise, fLow, fHigh);\n\n  /* Rescaling the integrand */\n  double scaling = 10./gsl_vector_get(integrand->freq, integrand->freq->size-1);\n  gsl_vector_scale(integrand->freq, scaling);\n  gsl_vector_scale(integrand->amp_real, 1./scaling);\n  gsl_vector_scale(integrand->amp_imag, 1./scaling);\n\n  /* Interpolating the integrand */\n  CAmpPhaseSpline* integrandspline = NULL;\n  BuildSplineCoeffs(&integrandspline, integrand);\n\n  /* Computing the integral - including here the factor 4 and the real part */\n  double overlap = 4.*creal(ComputeInt(integrandspline->spline_amp_real, integrandspline->spline_amp_imag, integrandspline->quadspline_phase));\n\n  /* Clean up */\n  CAmpPhaseSpline_Cleanup(integrandspline);\n  CAmpPhaseFrequencySeries_Cleanup(integrand);\n\n  return overlap;\n}\n\n/* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form for each non-correlated channel 1,2,3, one being already interpolated, for a given noise function - uses the amplitude/phase representation (Fresnel) */\ndouble FDSinglemodeFresnelOverlap3Chan(\n  struct tagCAmpPhaseFrequencySeries *freqseries1chan1, /* First mode h1 for channel 1, in amplitude/phase form */\n  struct tagCAmpPhaseFrequencySeries *freqseries1chan2, /* First mode h1 for channel 2, in amplitude/phase form */\n  struct tagCAmpPhaseFrequencySeries *freqseries1chan3, /* First mode h1 for channel 3, in amplitude/phase form */\n  struct tagCAmpPhaseSpline *splines2chan1,             /* Second mode h2 for channel 1, already interpolated in matrix form */\n  struct tagCAmpPhaseSpline *splines2chan2,             /* Second mode h2 for channel 2, already interpolated in matrix form */\n  struct tagCAmpPhaseSpline *splines2chan3,             /* Second mode h2 for channel 3, already interpolated in matrix form */\n  ObjectFunction * Snoisechan1,                  /* Noise function */\n  ObjectFunction * Snoisechan2,                  /* Noise function */\n  ObjectFunction * Snoisechan3,                  /* Noise function */\n  double fLow,                                      /* Lower bound of the frequency window for the detector */\n  double fHigh)                                     /* Upper bound of the frequency window for the detector */\n{\n  /* Computing the integrand values, on the frequency grid of h1 */\n  CAmpPhaseFrequencySeries* integrand = NULL;\n  if(0>ComputeIntegrandValues3Chan(&integrand, freqseries1chan1, freqseries1chan2, freqseries1chan3, splines2chan1, splines2chan2, splines2chan3, Snoisechan1, Snoisechan2, Snoisechan3, fLow, fHigh))return 0;//if allowed freq range does not exist, return 0 for overlap\n\n  /* Rescaling the integrand */\n  double scaling = 10./gsl_vector_get(integrand->freq, integrand->freq->size-1);\n\n//TEST\n//scaling = 1.;\n\n  gsl_vector_scale(integrand->freq, scaling);\n  gsl_vector_scale(integrand->amp_real, 1./scaling);\n  gsl_vector_scale(integrand->amp_imag, 1./scaling);\n\n  //dump\n  /*\n  for(int ii=0;ii<integrand->freq->size;ii++)\n    printf(\"ii=%i, f=%g, integrand = ( %g, %g, %g )\\n\",ii,gsl_vector_get(integrand->freq,ii),gsl_vector_get(integrand->amp_real,ii),gsl_vector_get(integrand->amp_imag,ii),gsl_vector_get(integrand->phase,ii));\n  */\n  \n  /* Interpolating the integrand */\n  CAmpPhaseSpline* integrandspline = NULL;\n  BuildSplineCoeffs(&integrandspline, integrand);\n\n  /* Computing the integral - including here the factor 4 and the real part */\n  double overlap = 4.*creal(ComputeInt(integrandspline->spline_amp_real, integrandspline->spline_amp_imag, integrandspline->quadspline_phase));\n\n  /* Clean up */\n  CAmpPhaseSpline_Cleanup(integrandspline);\n  CAmpPhaseFrequencySeries_Cleanup(integrand);\n\n  return overlap;\n}\n\n\n/* Function computing the overlap (h1|h2) between two waveforms given as list of modes, one being already interpolated, for a given noise function - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */\ndouble FDListmodesFresnelOverlap(\n  struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First waveform, list of modes in amplitude/phase form */\n  struct tagListmodesCAmpPhaseSpline *listsplines2,    /* Second waveform, list of modes already interpolated in matrix form */\n  ObjectFunction * Snoise,                  /* Noise function */\n  double fLow,                                         /* Lower bound of the frequency window for the detector */\n  double fHigh,                                        /* Upper bound of the frequency window for the detector */\n  double fstartobs1,                                   /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */\n  double fstartobs2)                                   /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n{\n  double overlap = 0;\n\n  /* Main loop over the modes - goes through all the modes present */\n  ListmodesCAmpPhaseFrequencySeries* listelementh1 = listh1;\n  while(listelementh1) {\n    ListmodesCAmpPhaseSpline* listelementsplines2 = listsplines2;\n    while(listelementsplines2) {\n      /* Scaling fstartobs1/2 with the appropriate factor of m (for the 21 mode we use m=2) - setting fmin in the overlap accordingly */\n      int mmax1 = max(2, listelementh1->m);\n      int mmax2 = max(2, listelementsplines2->m);\n      double fcutLow = fmax(fLow, fmax(((double) mmax1)/2. * fstartobs1, ((double) mmax2)/2. * fstartobs2));\n      overlap += FDSinglemodeFresnelOverlap(listelementh1->freqseries, listelementsplines2->splines, Snoise, fcutLow, fHigh);\n\n      listelementsplines2 = listelementsplines2->next;\n    }\n    listelementh1 = listelementh1->next;\n  }\n  return overlap;\n}\n\n/* Function computing the overlap (h1|h2) between two waveforms given as list of modes for each non-correlated channel 1,2,3, one being already interpolated, for a given noise function - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */\ndouble FDListmodesFresnelOverlap3Chan(\n  struct tagListmodesCAmpPhaseFrequencySeries *listh1chan1, /* First waveform channel channel 1, list of modes in amplitude/phase form */\n  struct tagListmodesCAmpPhaseFrequencySeries *listh1chan2, /* First waveform channel channel 2, list of modes in amplitude/phase form */\n  struct tagListmodesCAmpPhaseFrequencySeries *listh1chan3, /* First waveform channel channel 3, list of modes in amplitude/phase form */\n  struct tagListmodesCAmpPhaseSpline *listsplines2chan1,    /* Second waveform channel channel 1, list of modes already interpolated in matrix form */\n  struct tagListmodesCAmpPhaseSpline *listsplines2chan2,    /* Second waveform channel channel 2, list of modes already interpolated in matrix form */\n  struct tagListmodesCAmpPhaseSpline *listsplines2chan3,    /* Second waveform channel channel 3, list of modes already interpolated in matrix form */\n  ObjectFunction * Snoise1,                          /* Noise function for channel 1 */\n  ObjectFunction * Snoise2,                          /* Noise function for channel 1 */\n  ObjectFunction * Snoise3,                          /* Noise function for channel 1 */\n  double fLow,                                          /* Lower bound of the frequency window for the detector */\n  double fHigh,                                         /* Upper bound of the frequency window for the detector */\n  double fstartobs1,                                    /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */\n  double fstartobs2)                                    /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */\n{\n  double overlap = 0;\n\n  /* Main loop over the modes - goes through all the modes present, the same for all three channels 1,2,3 */\n  ListmodesCAmpPhaseFrequencySeries* listelementh1chan1 = listh1chan1;\n  while(listelementh1chan1) { /* We use the structure for channel 1 to loop through modes */\n    ListmodesCAmpPhaseFrequencySeries* listelementh1chan2 = ListmodesCAmpPhaseFrequencySeries_GetMode(listh1chan2, listelementh1chan1->l, listelementh1chan1->m);\n    ListmodesCAmpPhaseFrequencySeries* listelementh1chan3 = ListmodesCAmpPhaseFrequencySeries_GetMode(listh1chan3, listelementh1chan1->l, listelementh1chan1->m);\n    ListmodesCAmpPhaseSpline* listelementsplines2chan1 = listsplines2chan1;\n    while(listelementsplines2chan1) { /* We use the structure for channel 1 to loop through modes */\n      ListmodesCAmpPhaseSpline* listelementsplines2chan2 = ListmodesCAmpPhaseSpline_GetMode(listsplines2chan2, listelementsplines2chan1->l, listelementsplines2chan1->m);\n      ListmodesCAmpPhaseSpline* listelementsplines2chan3 = ListmodesCAmpPhaseSpline_GetMode(listsplines2chan3, listelementsplines2chan1->l, listelementsplines2chan1->m);\n      /* Scaling fstartobs1/2 with the appropriate factor of m (for the 21 mode we use m=2) - setting fmin in the overlap accordingly */\n      int mmax1 = max(2, listelementh1chan1->m);\n      int mmax2 = max(2, listelementsplines2chan1->m);\n      double fcutLow = fmax(fLow, fmax(((double) mmax1)/2. * fstartobs1, ((double) mmax2)/2. * fstartobs2));\n      double overlapmode = FDSinglemodeFresnelOverlap3Chan(listelementh1chan1->freqseries, listelementh1chan2->freqseries, listelementh1chan3->freqseries, listelementsplines2chan1->splines, listelementsplines2chan2->splines, listelementsplines2chan3->splines, Snoise1, Snoise2, Snoise3, fcutLow, fHigh);\n      overlap += overlapmode;\n      listelementsplines2chan1 = listelementsplines2chan1->next;\n    }\n    listelementh1chan1 = listelementh1chan1->next;\n  }\n\n  return overlap;\n}\n\n", "meta": {"hexsha": "dbc86d28bfd8fc72f4c1ae6a5bfc5918e8caf17f", "size": 54307, "ext": "c", "lang": "C", "max_stars_repo_path": "tools/likelihood.c", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "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/likelihood.c", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "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/likelihood.c", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.1445663011, "max_line_length": 405, "alphanum_fraction": 0.69663211, "num_tokens": 15247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.38339675635411263}}
{"text": "#ifndef SurrogateHeatFluidDriver_h\n#define SurrogateHeatFluidDriver_h\n\n#include <memory>\n#include <vector>\n\n#include \"Teuchos_ParameterList.hpp\"\n#include \"Teuchos_RCP.hpp\"\n\n#include <gsl/gsl>\n\n#include \"Assembly_Model.h\"\n#include \"Single_Pin_Subchannel.h\"\n#include \"Single_Pin_Conduction.h\"\n\nnamespace enrico {\n\n//! Driver for coupled subchannel/heat conduction simulations. This driver\n//! decouples the fluid and solid phase in an explicit manner (i.e. no\n//! iteration between the convective heat transfer linking the phases within\n//! a single solve), which is sufficient given that this project targets\n//! steady-state simulations via fixed point iteration.\nclass SurrogateHeatFluidDriver {\npublic:\n  //@{\n  //! Typedefs\n  using SP_Assembly = std::shared_ptr<Assembly_Model>;\n  using RCP_PL = Teuchos::RCP<Teuchos::ParameterList>;\n  //@}\n\n  //! solve the thermal-hydraulic problem for the fluid and solid phases\n  //! for a given power distribution\n  void solve(const std::vector<double>& powers);\n\n  //! fluid temperature\n  virtual std::vector<double> fluid_temperature() const { return d_pin_temps; }\n\n  //! fluid density\n  virtual std::vector<double> density() const { return d_pin_densities; }\n\n  //! solid temperature\n  virtual std::vector<double> solid_temperature() const { return d_solid_temps; }\n\n  double pressure_bc_; //! System pressure in [MPa]\n\nprivate:\n  // >>> DATA\n  SP_Assembly d_assembly;\n\n  // Note that for channel-centered equations, Nx and Ny are one greater\n  //  than number of pins in each direction.\n  int d_Nx, d_Ny, d_Nz;\n\n  // Cross sectional area of each channel\n  std::vector<double> d_areas;\n\n  // Mass flow rate (kg/s) in each channel\n  std::vector<double> d_mdots;\n\n  //! subchannel solver for a single channel\n  std::unique_ptr<Single_Pin_Subchannel> d_pin_subchannel;\n\n  //! heat conduction solver for a single rod\n  std::unique_ptr<Single_Pin_Conduction> d_pin_conduction;\n\n  //! coolant temperature in [K] for each channel, of total length given by the\n  //! product of the number of pins by the number of axial cells\n  std::vector<double> d_pin_temps;\n\n  //! coolant density in [g/cm^3] for each channel, of total length given by the\n  //! product of the number of pins by the number of axial cells\n  std::vector<double> d_pin_densities;\n\n  //! solid temperature in [K]\n  std::vector<double> d_solid_temps;\n\npublic:\n  // Constructor\n  SurrogateHeatFluidDriver(SP_Assembly assembly,\n                       RCP_PL subchannel_params,\n                       RCP_PL conduction_params,\n                       const std::vector<double>& dz);\n\n  //! heat source\n  std::vector<double> d_pin_powers;\n\nprivate:\n  //! Set up the sizes of solution arrays\n  void generate_arrays();\n\n  int channel_index(int ix, int iy) const\n  {\n    Expects(ix < d_Nx);\n    Expects(iy < d_Ny);\n    return ix + d_Nx * iy;\n  }\n\n  // Solve the fluid flow equations\n  void solve_fluid(const std::vector<double>& power);\n\n  // Solve the solid equations\n  void solve_heat(const std::vector<double>& power,\n    const std::vector<double>& channel_temp, std::vector<double>& fuel_temp);\n};\n\n//---------------------------------------------------------------------------//\n} // end namespace enrico\n\n//---------------------------------------------------------------------------//\n#endif // SurrogateHeatFluidDriver_h\n\n//---------------------------------------------------------------------------//\n// end of SurrogateHeatFluidDriver.h\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "f7d8355ba4fb251fcd2d83006e447117d0ba3c7f", "size": 3519, "ext": "h", "lang": "C", "max_stars_repo_path": "include/smrt/surrogate_heat_fluid_driver.h", "max_stars_repo_name": "sphamil/enrico", "max_stars_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smrt/surrogate_heat_fluid_driver.h", "max_issues_repo_name": "sphamil/enrico", "max_issues_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smrt/surrogate_heat_fluid_driver.h", "max_forks_repo_name": "sphamil/enrico", "max_forks_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_forks_repo_licenses": ["BSD-3-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.6, "max_line_length": 81, "alphanum_fraction": 0.6527422563, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.383354781253436}}
{"text": "\n/*\n (rho v, u) = ( v , div(C : grad(u)) ) + (v,F)\n \n where (v,F) = (v, Mp delta_1) + (v, -div(-Ms delta_2 ))\n \n (rho v, u) = -(grad(v) , C : grad(u)) + (v, sigma.n)_ds\n              + (v, Mp delta_1) + (grad(v), Ms delta_2 ) - (v, (Ms delta_2 ).n)_ds\n\n            = -(grad(v) , C : grad(u))\n              +(v, Mp delta_1 ) + (grad(v), Ms delta_2 )\n              + (v, sigma.n)_ds\n              - (v, (-Ms delta_2 ).n)_ds  ==> which will be dropped as we assume the source does not intersect with the boundary\n \n \n \n*/\n\n#include <petsc.h>\n#include <petsctime.h>\n#include <petscksp.h>\n#include <petscdm.h>\n#include <petscdmda.h>\n\n#include \"rupture.h\"\n\ntypedef enum { TENS2D_XX=0, TENS2D_YY=1, TENS2D_XY=2 } VoigtTensor2d;\n\ntypedef struct _p_SpecFECtx *SpecFECtx;\n\ntypedef struct {\n  PetscInt region;\n  PetscReal lambda,mu;\n  PetscReal rho;\n} QPntIsotropicElastic;\n\nstruct _p_SpecFECtx {\n  PetscMPIInt rank,size;\n  PetscInt basisorder;\n  PetscInt mx,my,mz;\n  PetscInt mx_g,my_g,mz_g,nx_g,ny_g,nz_g;\n  //PetscReal dx,dy,dz;\n  PetscInt dim;\n  PetscInt dofs;\n  DM dm;\n  PetscInt npe,npe_1d,ne,ne_g;\n  PetscInt *element;\n  PetscReal *xi1d,*w1d,*w;\n  PetscReal *elbuf_coor,*elbuf_field,*elbuf_field2;\n  PetscInt  *elbuf_dofs;\n  PetscInt nqp;\n  QPntIsotropicElastic *cell_data;\n  PetscReal **dN_dxi,**dN_deta;\n  PetscReal **dN_dx,**dN_dy;\n  //PetscInt  source_implementation; /* DR */\n  \n  /* DR */\n  PetscReal delta;         /* fault thickness */\n  PetscReal *elbuf_field3; /* additional element buffer (will hold velocity) */\n  DRVar     *dr_qp_data;   /* stores data like slip, slip-rate */\n  PetscReal mu_s,mu_d,D_c; /* linear slip weakening parameters */\n};\n\n\ntypedef struct {\n  PetscReal xi[2];\n  PetscInt  nbasis;\n  PetscInt  *element_indices;\n  PetscReal *element_values;\n  PetscReal *buffer;\n} PointwiseContext;\n\n\n\n\n/**\n * Function to calculate weighting for the traction\n*/ \nPetscErrorCode PetscTanHWeighting(PetscReal *Result, PetscReal ValueTrial, PetscReal CritValue,  PetscReal phi, PetscReal Amplitude, PetscReal Offset)\n{\n  PetscReal weight;\n\n  weight = 0.5 * PetscTanhReal((PetscAbsReal(phi)-Offset) * Amplitude)  + 0.5;\n\n  Result[0] =  CritValue * (1.0 - weight)  + ValueTrial * weight ;\n  PetscFunctionReturn(0);\n}\n\n/**\n * Function to calculate the new KV timestep following Galvez (2014) eq 27.\n * dT_KV = (sqrt(1+(eta*eta)/(dT*dT))-eta/dT)\n*/ \nvoid GetStableTimeStep(double dT, double eta, double * dT_KV)\n{\n  dT_KV[0] = (sqrt(1 + (eta/dT) * (eta/dT)) - eta / dT)*dT;\n} \n\n/*\n warp for dr mesh\n \n get ymax\n \n plot (exp(4*x)-1)/exp(4),x\n \n s = y / ymax\n s' = (exp(4*s)-1)/exp(4)\n \n*/\nPetscErrorCode warp_y_exp(SpecFECtx c,PetscReal factor)\n{\n  PetscInt i,N;\n  PetscReal ymax = -1.0e32,s[2],sp[2];\n  Vec coor;\n  PetscScalar *_coor;\n  PetscErrorCode ierr;\n  \n  DMGetCoordinates(c->dm,&coor);\n  VecGetSize(coor,&N);\n  N = N / 2;\n  VecGetArray(coor,&_coor);\n  for (i=0; i<N; i++) {\n    ymax = PetscMax(ymax,_coor[2*i+1]);\n  }\n\n  for (i=0; i<N; i++) {\n    s[0] = _coor[2*i+0];\n    s[1] = _coor[2*i+1];\n\n    // normalize to 1\n    s[1] = s[1] / ymax;\n\n    sp[0] = s[0];\n    sp[1] = s[1];\n    if (s[1] >= 0.0) {\n      sp[1] = (PetscExpReal(factor * s[1]) - 1.0)/PetscExpReal(factor);\n    } else {\n      PetscReal _s = PetscAbsReal(s[1]);\n      \n      sp[1] = -(PetscExpReal(factor * _s) - 1.0)/PetscExpReal(factor);\n    }\n\n    sp[1] *= ymax;\n   \n    _coor[2*i+0] = sp[0];\n    _coor[2*i+1] = sp[1];\n  }\n  \n  VecRestoreArray(coor,&_coor);\n  \n  PetscFunctionReturn(0);\n}\n\n\n/* N = polynomial order */\nPetscErrorCode CreateGLLCoordsWeights(PetscInt N,PetscInt *_npoints,PetscReal **_xi,PetscReal **_w)\n{\n  PetscInt N1;\n  PetscReal *xold,*x,*w,*P;\n  PetscReal eps,res;\n  PetscInt i,j,k;\n  PetscErrorCode ierr;\n  \n  \n  // Truncation + 1\n  N1 = N + 1;\n  \n  ierr = PetscMalloc(sizeof(PetscReal)*N1,&xold);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*N1,&x);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*N1,&w);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*N1*N1,&P);CHKERRQ(ierr);\n  \n  // Use the Chebyshev-Gauss-Lobatto nodes as the first guess\n  for (i=0; i<N1; i++) {\n    x[i]=PetscCosReal(PETSC_PI*i/(PetscReal)N);\n  }\n  \n  // The Legendre Vandermonde Matrix\n  for (i=0; i<N1; i++) {\n    for (j=0; j<N1; j++) {\n      P[i+j*N1] = 0.0;\n    }\n  }\n  \n  // Compute P_(N) using the recursion relation\n  // Compute its first and second derivatives and\n  // update x using the Newton-Raphson method.\n  for (i=0; i<N1; i++) {\n    xold[i]=2.0;\n  }\n  \n  res = 1.0;\n  eps = 1.0e-12;\n  while (res > eps) {\n    \n    //xold=x;\n    for (i=0; i<N1; i++) {\n      xold[i] = x[i];\n    }\n    \n    //P(:,1)=1;    P(:,2)=x;\n    for (i=0; i<N1; i++) {\n      for (j=0; j<N1; j++) {\n        P[i+0*N1] = 1.0;\n        P[i+1*N1] = x[i];\n      }\n    }\n    \n    //for k=2:N\n    //    P(:,k+1)=( (2*k-1)*x.*P(:,k)-(k-1)*P(:,k-1) )/k;\n    //end\n    for (i=0; i<N1; i++) {\n      for (k=1; k<N; k++) {\n        P[i+(k+1)*N1] = ( (2.0*(k+1)-1.0)*x[i] * P[i+k*N1] - (k+1.0-1.0) * P[i+(k-1)*N1] ) / (PetscReal)(k+1.0);\n      }\n    }\n    \n    //x=xold-( x.*P(:,N1)-P(:,N) )./( N1*P(:,N1) );\n    for (i=0; i<N1; i++) {\n      x[i] = xold[i] - (x[i] * P[i+(N1-1)*N1] - P[i+(N-1)*N1]) / ( N1 * P[i+(N1-1)*N1] );\n    }\n    \n    res = 0.0;\n    for (i=0; i<N1; i++) {\n      res += (x[i] - xold[i])*(x[i] - xold[i]);\n    }\n    res = PetscSqrtReal(res);\n  }\n  \n  // w=2./(N*N1*P(:,N1).^2);\n  for (i=0; i<N1; i++) {\n    PetscReal pp = P[i+(N1-1)*N1];\n    w[i] = 2.0 / (N*N1*pp*pp);\n  }\n  \n  if (_xi) {\n    /* flip order so they are ordered from -1 to 1 */\n    for (i=0; i<N1/2; i++) {\n      PetscReal tmp;\n      \n      tmp = x[i];\n      x[i] = x[N1-1-i];\n      x[N1-1-i] = tmp;\n    }\n    *_xi = x;\n  } else {\n    ierr = PetscFree(x);CHKERRQ(ierr);\n  }\n  \n  if (_npoints) {\n    *_npoints = N1;\n  }\n  if (_w) {\n    *_w = w;\n  } else {\n    ierr = PetscFree(w);CHKERRQ(ierr);\n  }\n  ierr = PetscFree(xold);CHKERRQ(ierr);\n  ierr = PetscFree(P);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode MatComputeConditionNumber(Mat A,PetscReal *cond)\n{\n  PetscReal *realpt,*complexpt,*nrmeigs;\n  PetscInt rank,i;\n  KSP kspV;\n  PC pc;\n  Vec x,y;\n  PetscErrorCode ierr;\n  \n  ierr = MatCreateVecs(A,&y,&x);CHKERRQ(ierr);\n  ierr = VecSet(y,1.0);CHKERRQ(ierr);\n  \n  ierr = KSPCreate(PETSC_COMM_SELF,&kspV);CHKERRQ(ierr);\n  ierr = KSPSetOperators(kspV,A,A);CHKERRQ(ierr);\n  ierr = KSPSetType(kspV,KSPPREONLY);CHKERRQ(ierr);\n  ierr = KSPGetPC(kspV,&pc);CHKERRQ(ierr);\n  ierr = PCSetType(pc,PCNONE);CHKERRQ(ierr);\n  ierr = KSPSolve(kspV,y,x);CHKERRQ(ierr);\n  \n  ierr = MatGetSize(A,&rank,0);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*rank,&realpt);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*rank,&complexpt);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*rank,&nrmeigs);CHKERRQ(ierr);\n  \n  ierr = KSPComputeEigenvaluesExplicitly(kspV,rank,realpt,complexpt);CHKERRQ(ierr);\n  for (i=0; i<rank; i++) {\n    nrmeigs[i] = PetscSqrtReal( realpt[i]*realpt[i] + complexpt[i]*complexpt[i]);\n  }\n  ierr = PetscSortReal(rank,nrmeigs);CHKERRQ(ierr);\n  \n  *cond = nrmeigs[rank-1]/nrmeigs[0];\n  \n  ierr = PetscFree(nrmeigs);CHKERRQ(ierr);\n  ierr = PetscFree(realpt);CHKERRQ(ierr);\n  ierr = PetscFree(complexpt);CHKERRQ(ierr);\n  ierr = VecDestroy(&y);CHKERRQ(ierr);\n  ierr = VecDestroy(&x);CHKERRQ(ierr);\n  ierr = KSPDestroy(&kspV);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TabulateBasis1d_CLEGENDRE(PetscInt npoints,PetscReal xi[],PetscInt order,PetscInt *_nbasis,PetscReal ***_Ni)\n{\n  PetscErrorCode ierr;\n  PetscReal **Ni,*xilocal,**basis_coeff, *monomials;\n  PetscInt i,j,k,p;\n  PetscInt nbasis,cnt;\n  Mat A;\n  Vec x,y;\n  KSP ksp;\n  PC pc;\n  \n  \n  ierr = CreateGLLCoordsWeights(order,&nbasis,&xilocal,NULL);CHKERRQ(ierr);\n  \n  ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&monomials);CHKERRQ(ierr);\n  \n  ierr = PetscMalloc(sizeof(PetscReal*)*npoints,&Ni);CHKERRQ(ierr);\n  for (i=0; i<npoints; i++) {\n    ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&Ni[i]);CHKERRQ(ierr);\n  }\n  \n  ierr = PetscMalloc(sizeof(PetscReal*)*nbasis,&basis_coeff);CHKERRQ(ierr);\n  for (i=0; i<nbasis; i++) {\n    ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&basis_coeff[i]);CHKERRQ(ierr);\n  }\n  \n  /* generate all the basis coefficients */\n  ierr = MatCreateSeqDense(PETSC_COMM_SELF,nbasis,nbasis,NULL,&A);CHKERRQ(ierr);\n  for (k=0; k<nbasis; k++) {\n    PetscReal xil,Aij;\n    \n    xil  = xilocal[k];\n    \n    cnt = 0;\n    for (i=0; i<nbasis; i++) {\n      Aij = PetscPowReal(xil,(PetscReal)i);\n      ierr = MatSetValue(A,k,cnt,Aij,INSERT_VALUES);CHKERRQ(ierr);\n      cnt++;\n    }\n  }\n  ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n  ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n  \n  {\n    PetscReal cond;\n    PetscBool compute_vandermonde_condition = PETSC_FALSE;\n    \n    ierr = PetscOptionsGetBool(NULL,NULL,\"-compute_vandermonde_condition\",&compute_vandermonde_condition,NULL);CHKERRQ(ierr);\n    if (compute_vandermonde_condition) {\n      \n      PetscPrintf(PETSC_COMM_WORLD,\"Computing condition number of Vandermonde matrix\\n\");\n      ierr = MatComputeConditionNumber(A,&cond);CHKERRQ(ierr);\n      PetscPrintf(PETSC_COMM_WORLD,\"cond(V) = %1.6e \\n\",cond);\n    }\n  }\n  \n  ierr = MatCreateVecs(A,&x,&y);CHKERRQ(ierr);\n  \n  ierr = KSPCreate(PETSC_COMM_SELF,&ksp);CHKERRQ(ierr);\n  ierr = KSPSetOptionsPrefix(ksp,\"basis_\");CHKERRQ(ierr);\n  ierr = KSPSetOperators(ksp,A,A);CHKERRQ(ierr);\n  ierr = KSPSetType(ksp,KSPPREONLY);CHKERRQ(ierr);\n  ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr);\n  ierr = PCSetType(pc,PCLU);CHKERRQ(ierr);\n  ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr);\n  \n  for (k=0; k<nbasis; k++) {\n    const PetscScalar *LA_x;\n    \n    ierr = VecZeroEntries(y);CHKERRQ(ierr);\n    ierr = VecSetValue(y,k,1.0,INSERT_VALUES);CHKERRQ(ierr);\n    ierr = VecAssemblyBegin(y);CHKERRQ(ierr);\n    ierr = VecAssemblyEnd(y);CHKERRQ(ierr);\n    \n    ierr = KSPSolve(ksp,y,x);CHKERRQ(ierr);\n    \n    ierr = VecGetArrayRead(x,&LA_x);CHKERRQ(ierr);\n    for (i=0; i<nbasis; i++) {\n      basis_coeff[k][i] = LA_x[i];\n    }\n    ierr = VecRestoreArrayRead(x,&LA_x);CHKERRQ(ierr);\n  }\n  \n  /* evaluate basis at each xi[] */\n  for (p=0; p<npoints; p++) {\n    \n    /* generate all monomials for point, p */\n    cnt = 0;\n    for (i=0; i<nbasis; i++) {\n      monomials[cnt] = PetscPowReal((PetscReal)xi[p],(PetscReal)i);\n      cnt++;\n    }\n    \n    for (i=0; i<nbasis; i++) {\n      Ni[p][i] = 0.0;\n      \n      for (j=0; j<nbasis; j++) {\n        Ni[p][i] += basis_coeff[i][j] * monomials[j];\n      }\n      if (PetscAbsReal(Ni[p][i]) < 1.0e-12) {\n        Ni[p][i] = 0.0;\n      }\n    }\n    \n    /*\n     printf(\"p = %d (xi = %+1.4e) N = [\",p,xi[p]);\n     for (i=0; i<nbasis; i++) {\n     printf(\" %+1.4e \",Ni[p][i]);\n     }\n     printf(\"]\\n\");\n     */\n  }\n  \n  //for (p=0; p<npoints; p++) {\n  //  ierr = PetscFree(Ni[p]);CHKERRQ(ierr);\n  //}\n  //ierr = PetscFree(Ni);CHKERRQ(ierr);\n  *_Ni = Ni;\n  *_nbasis = nbasis;\n  \n  ierr = PetscFree(monomials);CHKERRQ(ierr);\n  for (i=0; i<nbasis; i++) {\n    ierr = PetscFree(basis_coeff[i]);CHKERRQ(ierr);\n  }\n  ierr = PetscFree(basis_coeff);CHKERRQ(ierr);\n  ierr = PetscFree(xilocal);CHKERRQ(ierr);\n  ierr = MatDestroy(&A);CHKERRQ(ierr);\n  ierr = VecDestroy(&x);CHKERRQ(ierr);\n  ierr = VecDestroy(&y);CHKERRQ(ierr);\n  ierr = KSPDestroy(&ksp);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TabulateBasisDerivatives1d_CLEGENDRE(PetscInt npoints,PetscReal xi[],PetscInt order,PetscInt *_nbasis,PetscReal ***_GNix)\n{\n  PetscErrorCode ierr;\n  PetscReal **GNix,*xilocal,**basis_coeff, *monomials;\n  PetscInt i,j,k,p;\n  PetscInt nbasis,cnt;\n  Mat A;\n  Vec x,y;\n  KSP ksp;\n  PC pc;\n  \n  \n  ierr = CreateGLLCoordsWeights(order,&nbasis,&xilocal,NULL);CHKERRQ(ierr);\n  \n  ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&monomials);CHKERRQ(ierr);\n  \n  ierr = PetscMalloc(sizeof(PetscReal*)*npoints,&GNix);CHKERRQ(ierr);\n  for (i=0; i<npoints; i++) {\n    ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&GNix[i]);CHKERRQ(ierr);\n  }\n  \n  ierr = PetscMalloc(sizeof(PetscReal*)*nbasis,&basis_coeff);CHKERRQ(ierr);\n  for (i=0; i<nbasis; i++) {\n    ierr = PetscMalloc(sizeof(PetscReal)*nbasis,&basis_coeff[i]);CHKERRQ(ierr);\n  }\n  \n  /* generate all the basis coefficients */\n  ierr = MatCreateSeqDense(PETSC_COMM_SELF,nbasis,nbasis,NULL,&A);CHKERRQ(ierr);\n  for (k=0; k<nbasis; k++) {\n    PetscReal xil,Aij;\n    \n    xil  = xilocal[k];\n    \n    cnt = 0;\n    for (i=0; i<nbasis; i++) {\n      Aij = PetscPowReal(xil,(PetscReal)i);\n      ierr = MatSetValue(A,k,cnt,Aij,INSERT_VALUES);CHKERRQ(ierr);\n      cnt++;\n    }\n  }\n  ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n  ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);\n  \n  {\n    PetscReal cond;\n    PetscBool compute_vandermonde_condition = PETSC_FALSE;\n    \n    ierr = PetscOptionsGetBool(NULL,NULL,\"-compute_vandermonde_condition\",&compute_vandermonde_condition,NULL);CHKERRQ(ierr);\n    if (compute_vandermonde_condition) {\n      \n      PetscPrintf(PETSC_COMM_WORLD,\"Computing condition number of Vandermonde matrix\\n\");\n      ierr = MatComputeConditionNumber(A,&cond);CHKERRQ(ierr);\n      PetscPrintf(PETSC_COMM_WORLD,\"cond(V) = %1.6e \\n\",cond);\n    }\n  }\n  \n  ierr = MatCreateVecs(A,&x,&y);CHKERRQ(ierr);\n  \n  ierr = KSPCreate(PETSC_COMM_SELF,&ksp);CHKERRQ(ierr);\n  ierr = KSPSetOptionsPrefix(ksp,\"basis_\");CHKERRQ(ierr);\n  ierr = KSPSetOperators(ksp,A,A);CHKERRQ(ierr);\n  ierr = KSPSetType(ksp,KSPPREONLY);CHKERRQ(ierr);\n  ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr);\n  ierr = PCSetType(pc,PCLU);CHKERRQ(ierr);\n  ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr);\n  \n  for (k=0; k<nbasis; k++) {\n    const PetscScalar *LA_x;\n    \n    ierr = VecZeroEntries(y);CHKERRQ(ierr);\n    ierr = VecSetValue(y,k,1.0,INSERT_VALUES);CHKERRQ(ierr);\n    ierr = VecAssemblyBegin(y);CHKERRQ(ierr);\n    ierr = VecAssemblyEnd(y);CHKERRQ(ierr);\n    \n    ierr = KSPSolve(ksp,y,x);CHKERRQ(ierr);\n    \n    ierr = VecGetArrayRead(x,&LA_x);CHKERRQ(ierr);\n    for (i=0; i<nbasis; i++) {\n      basis_coeff[k][i] = LA_x[i];\n    }\n    ierr = VecRestoreArrayRead(x,&LA_x);CHKERRQ(ierr);\n  }\n  \n  /* evaluate basis at each xi[] */\n  for (p=0; p<npoints; p++) {\n    \n    /* generate all monomials for point, p */\n    cnt = 0;\n    for (i=0; i<nbasis; i++) {\n      PetscReal dm_dx;\n      \n      if (i == 0) {\n        dm_dx = 0.0;\n        } else {\n          dm_dx = ((PetscReal)i)*PetscPowReal((PetscReal)xi[p],(PetscReal)(i-1));\n        }\n      \n      monomials[cnt] = dm_dx;\n      cnt++;\n    }\n    \n    for (i=0; i<nbasis; i++) {\n      GNix[p][i] = 0.0;\n      \n      for (j=0; j<nbasis; j++) {\n        GNix[p][i] += basis_coeff[i][j] * monomials[j];\n      }\n      if (PetscAbsReal(GNix[p][i]) < 1.0e-12) {\n        GNix[p][i] = 0.0;\n      }\n    }\n    \n    /*\n     printf(\"p = %d (xi = %+1.4e) dN_dx = [\",p,xi[p]);\n     for (i=0; i<nbasis; i++) {\n     printf(\" %+1.4e \",GNix[p][i]);\n     }\n     printf(\"]\\n\");\n     */\n  }\n  \n  ierr = PetscFree(monomials);CHKERRQ(ierr);\n  for (i=0; i<nbasis; i++) {\n    ierr = PetscFree(basis_coeff[i]);CHKERRQ(ierr);\n  }\n  ierr = PetscFree(basis_coeff);CHKERRQ(ierr);\n  ierr = PetscFree(xilocal);CHKERRQ(ierr);\n  ierr = MatDestroy(&A);CHKERRQ(ierr);\n  ierr = VecDestroy(&x);CHKERRQ(ierr);\n  ierr = VecDestroy(&y);CHKERRQ(ierr);\n  ierr = KSPDestroy(&ksp);CHKERRQ(ierr);\n  \n  *_nbasis = nbasis;\n  *_GNix = GNix;\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TabulateBasisDerivativesTensorProduct2d(PetscInt order,PetscReal ***_dN_dxi,PetscReal ***_dN_deta)\n{\n  PetscErrorCode ierr;\n  PetscReal *xiq,**dphi_xi,**dN_dxi,**dN_deta;\n  PetscInt qpoint,k,i,j,qi,qj,nqp,nbasis;\n  \n  ierr = CreateGLLCoordsWeights(order,&nqp,&xiq,NULL);CHKERRQ(ierr);\n  ierr = TabulateBasisDerivatives1d_CLEGENDRE(nqp,xiq,order,&nbasis,&dphi_xi);CHKERRQ(ierr);\n  \n  ierr = PetscMalloc(sizeof(PetscReal*)*nqp*nqp,&dN_dxi);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal*)*nqp*nqp,&dN_deta);CHKERRQ(ierr);\n  for (i=0; i<nqp*nqp; i++) {\n    ierr = PetscMalloc(sizeof(PetscReal)*nbasis*nbasis,&dN_dxi[i]);CHKERRQ(ierr);\n    ierr = PetscMalloc(sizeof(PetscReal)*nbasis*nbasis,&dN_deta[i]);CHKERRQ(ierr);\n  }\n  \n  qpoint = 0;\n  for (qj=0; qj<nqp; qj++) {\n    for (qi=0; qi<nqp; qi++) {\n      \n      k = 0;\n      for (j=0; j<nbasis; j++) {\n        for (i=0; i<nbasis; i++) {\n          PetscReal phi_xi,phi_eta;\n          \n          phi_xi = 0.0;\n          if (qi == i) phi_xi = 1.0;\n          \n          phi_eta = 0.0;\n          if (qj == j) phi_eta = 1.0;\n          \n          dN_dxi[qpoint][k]  = dphi_xi[qi][i] * phi_eta;\n          dN_deta[qpoint][k] = phi_xi * dphi_xi[qj][j];\n          \n          k++;\n        }}\n      qpoint++;\n    }}\n  \n  /* viewer */\n  /*\n   for (k=0; k<nqp*nqp; k++) {\n   printf(\"qp[%d]: dNdxi  = [ \",k);\n   for (j=0; j<nbasis*nbasis; j++) {\n   printf(\" %+1.4e \",dN_dxi[k][j]);\n   } printf(\"]\\n\");\n   \n   printf(\"qp[%d]: dNdeta = [ \",k);\n   for (j=0; j<nbasis*nbasis; j++) {\n   printf(\" %+1.4e \",dN_deta[k][j]);\n   } printf(\"]\\n\");\n   }\n   */\n  \n  /* free up mempry */\n  ierr = PetscFree(xiq);CHKERRQ(ierr);\n  for (k=0; k<nqp; k++) {\n    ierr = PetscFree(dphi_xi[k]);CHKERRQ(ierr);\n  }\n  ierr = PetscFree(dphi_xi);CHKERRQ(ierr);\n  \n  if (_dN_dxi) { *_dN_dxi = dN_dxi; }\n  else {\n    for (k=0; k<nqp*nqp; k++) {\n      ierr = PetscFree(dN_dxi[k]);CHKERRQ(ierr);\n    }\n    ierr = PetscFree(dN_dxi);CHKERRQ(ierr);\n  }\n  \n  if (_dN_deta) { *_dN_deta = dN_deta; }\n  else {\n    for (k=0; k<nqp*nqp; k++) {\n      ierr = PetscFree(dN_deta[k]);CHKERRQ(ierr);\n    }\n    ierr = PetscFree(dN_deta);CHKERRQ(ierr);\n  }\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TabulateBasisDerivativesAtPointTensorProduct2d(PetscReal xiq[],PetscInt order,PetscReal ***_dN_dxi,PetscReal ***_dN_deta)\n{\n  PetscErrorCode ierr;\n  PetscReal **dphi_xi,**Ni_xi,**dphi_eta,**Ni_eta,**dN_dxi,**dN_deta;\n  PetscInt qpoint,k,i,j,q,nqp,nbasis;\n  \n  nqp = 1;\n  ierr = TabulateBasisDerivatives1d_CLEGENDRE(nqp,&xiq[0],order,&nbasis,&dphi_xi);CHKERRQ(ierr);\n  ierr = TabulateBasis1d_CLEGENDRE(nqp,&xiq[0],order,&nbasis,&Ni_xi);CHKERRQ(ierr);\n  \n  ierr = TabulateBasisDerivatives1d_CLEGENDRE(nqp,&xiq[1],order,&nbasis,&dphi_eta);CHKERRQ(ierr);\n  ierr = TabulateBasis1d_CLEGENDRE(nqp,&xiq[1],order,&nbasis,&Ni_eta);CHKERRQ(ierr);\n  \n  ierr = PetscMalloc(sizeof(PetscReal*)*nqp,&dN_dxi);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal*)*nqp,&dN_deta);CHKERRQ(ierr);\n  for (i=0; i<nqp; i++) {\n    ierr = PetscMalloc(sizeof(PetscReal)*nbasis*nbasis,&dN_dxi[i]);CHKERRQ(ierr);\n    ierr = PetscMalloc(sizeof(PetscReal)*nbasis*nbasis,&dN_deta[i]);CHKERRQ(ierr);\n  }\n  \n  qpoint = 0;\n  for (q=0; q<nqp; q++) {\n    \n    k = 0;\n    for (j=0; j<nbasis; j++) {\n      for (i=0; i<nbasis; i++) {\n        PetscReal phi_xi,phi_eta;\n        \n        phi_xi = Ni_xi[q][i];\n        phi_eta = Ni_eta[q][j];\n        \n        dN_dxi[qpoint][k]  = dphi_xi[q][i] * phi_eta;\n        dN_deta[qpoint][k] = phi_xi * dphi_eta[q][j];\n        k++;\n      }}\n    qpoint++;\n  }\n  \n  /* viewer */\n  /*\n   for (k=0; k<nqp; k++) {\n   printf(\"qp[%d]: dNdxi  = [ \",k);\n   for (j=0; j<nbasis*nbasis; j++) {\n   printf(\" %+1.4e \",dN_dxi[k][j]);\n   } printf(\"]\\n\");\n   \n   printf(\"qp[%d]: dNdeta = [ \",k);\n   for (j=0; j<nbasis*nbasis; j++) {\n   printf(\" %+1.4e \",dN_deta[k][j]);\n   } printf(\"]\\n\");\n   }\n   */\n  \n  /* free up mempry */\n  for (k=0; k<nqp; k++) {\n    ierr = PetscFree(dphi_xi[k]);CHKERRQ(ierr);\n    ierr = PetscFree(dphi_eta[k]);CHKERRQ(ierr);\n  }\n  ierr = PetscFree(dphi_xi);CHKERRQ(ierr);\n  ierr = PetscFree(dphi_eta);CHKERRQ(ierr);\n  \n  for (k=0; k<nqp; k++) {\n    ierr = PetscFree(Ni_xi[k]);CHKERRQ(ierr);\n    ierr = PetscFree(Ni_eta[k]);CHKERRQ(ierr);\n  }\n  ierr = PetscFree(Ni_xi);CHKERRQ(ierr);\n  ierr = PetscFree(Ni_eta);CHKERRQ(ierr);\n  \n  if (_dN_dxi) { *_dN_dxi = dN_dxi; }\n  else {\n    for (k=0; k<nqp*nqp; k++) {\n      ierr = PetscFree(dN_dxi[k]);CHKERRQ(ierr);\n    }\n    ierr = PetscFree(dN_dxi);CHKERRQ(ierr);\n  }\n  \n  if (_dN_deta) { *_dN_deta = dN_deta; }\n  else {\n    for (k=0; k<nqp*nqp; k++) {\n      ierr = PetscFree(dN_deta[k]);CHKERRQ(ierr);\n    }\n    ierr = PetscFree(dN_deta);CHKERRQ(ierr);\n  }\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxCreate(SpecFECtx *c)\n{\n  SpecFECtx ctx;\n  PetscErrorCode ierr;\n  \n  ierr = PetscMalloc(sizeof(struct _p_SpecFECtx),&ctx);CHKERRQ(ierr);\n  ierr = PetscMemzero(ctx,sizeof(struct _p_SpecFECtx));CHKERRQ(ierr);\n  ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&ctx->rank);CHKERRQ(ierr);\n  ierr = MPI_Comm_size(PETSC_COMM_WORLD,&ctx->size);CHKERRQ(ierr);\n  *c = ctx;\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxCreateENMap2d_SEQ(SpecFECtx c)\n{\n  PetscErrorCode ierr;\n  PetscInt ni0,nj0,i,j,ei,ej,ecnt,*emap,nid;\n  \n  ierr = PetscMalloc(sizeof(PetscInt)*c->ne*c->npe,&c->element);CHKERRQ(ierr);\n  ierr = PetscMemzero(c->element,sizeof(PetscInt)*c->ne*c->npe);CHKERRQ(ierr);\n  \n  ecnt = 0;\n  for (ej=0; ej<c->my; ej++) {\n    nj0 = ej*(c->npe_1d-1);\n    \n    for (ei=0; ei<c->mx; ei++) {\n      ni0 = ei*(c->npe_1d-1);\n      \n      emap = &c->element[c->npe*ecnt];\n      \n      for (j=0; j<c->npe_1d; j++) {\n        for (i=0; i<c->npe_1d; i++) {\n          \n          nid = (ni0 + i) + (nj0 + j) * c->nx_g;\n          emap[i+j*c->npe_1d] = nid;\n        }\n      }\n      \n      ecnt++;\n    }\n  }\n  \n  PetscFunctionReturn(0);\n}\n\n/* Creates domain over [0,1]^d - scale later */\nPetscErrorCode SpecFECtxCreateMeshCoords2d_SEQ(SpecFECtx c)\n{\n  PetscErrorCode ierr;\n  Vec coor;\n  DM cdm;\n  DMDACoor2d **LA_coor2d;\n  PetscInt ei,ej,i,j,ni0,nj0;\n  PetscReal dx,dy,x0,y0;\n  \n  ierr = DMDASetUniformCoordinates(c->dm,0.0,1.0,0.0,1.0,0,0);CHKERRQ(ierr);\n  ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr);\n  ierr = DMGetCoordinateDM(c->dm,&cdm);CHKERRQ(ierr);\n  \n  dx = 1.0/((PetscReal)c->mx_g);\n  dy = 1.0/((PetscReal)c->my_g);\n  ierr = DMDAVecGetArray(cdm,coor,&LA_coor2d);CHKERRQ(ierr);\n  for (ej=0; ej<c->my; ej++) {\n    \n    for (ei=0; ei<c->mx; ei++) {\n      x0 = 0.0 + ei*dx;\n      y0 = 0.0 + ej*dy;\n      \n      ni0 = ei*(c->npe_1d-1);\n      nj0 = ej*(c->npe_1d-1);\n      \n      for (j=0; j<c->npe_1d; j++) {\n        for (i=0; i<c->npe_1d; i++) {\n          LA_coor2d[nj0+j][ni0+i].x = 0.5*(c->xi1d[i]+1.0)*dx + x0;\n          LA_coor2d[nj0+j][ni0+i].y = 0.5*(c->xi1d[j]+1.0)*dy + y0;\n          \n          //if ((ej==0) && (j==0)) {\n          //  printf(\"[e %d,i %d] xc %+1.4e\\n\",ei,i,LA_coor2d[nj0+j][ni0+i].x*4.0e3-2.0e3);\n          //}\n          \n        }\n      }\n    }\n  }\n  ierr = DMDAVecRestoreArray(cdm,coor,&LA_coor2d);CHKERRQ(ierr);\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxScaleMeshCoords(SpecFECtx c,PetscReal scale[],PetscReal shift[])\n{\n  PetscErrorCode ierr;\n  Vec coor,lcoor;\n  DM cdm;\n  \n  ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr);\n  \n  if (scale) {\n    if (c->dim >= 1) ierr = VecStrideScale(coor,0,scale[0]);CHKERRQ(ierr);\n    if (c->dim >= 2) ierr = VecStrideScale(coor,1,scale[1]);CHKERRQ(ierr);\n    if (c->dim == 3) ierr = VecStrideScale(coor,2,scale[2]);CHKERRQ(ierr);\n  }\n  if (shift) {\n    Vec ss;\n    \n    ierr = VecDuplicate(coor,&ss);CHKERRQ(ierr);\n    \n    if (c->dim >= 1) {\n      ierr = VecZeroEntries(ss);CHKERRQ(ierr);\n      ierr = VecStrideSet(ss,0,shift[0]);CHKERRQ(ierr);\n      ierr = VecAXPY(coor,1.0,ss);CHKERRQ(ierr);\n    }\n    if (c->dim >= 2) {\n      ierr = VecZeroEntries(ss);CHKERRQ(ierr);\n      ierr = VecStrideSet(ss,1,shift[1]);CHKERRQ(ierr);\n      ierr = VecAXPY(coor,1.0,ss);CHKERRQ(ierr);\n    }\n    if (c->dim >= 3) {\n      ierr = VecZeroEntries(ss);CHKERRQ(ierr);\n      ierr = VecStrideSet(ss,2,shift[2]);CHKERRQ(ierr);\n      ierr = VecAXPY(coor,1.0,ss);CHKERRQ(ierr);\n    }\n    ierr = VecDestroy(&ss);CHKERRQ(ierr);\n  }\n  \n  ierr = DMGetCoordinateDM(c->dm,&cdm);CHKERRQ(ierr);\n  ierr = DMGetCoordinatesLocal(c->dm,&lcoor);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalBegin(c->dm,coor,INSERT_VALUES,lcoor);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(c->dm,coor,INSERT_VALUES,lcoor);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxCreateMesh_SEQ(SpecFECtx c,PetscInt dim,PetscInt mx,PetscInt my,PetscInt mz,PetscInt basisorder,PetscInt ndofs)\n{\n  PetscErrorCode ierr;\n  PetscInt stencil_width,i,j;\n  \n  c->dim = dim;\n  c->mx = mx;\n  c->my = my;\n  c->mz = mz;\n  c->mx_g = mx;\n  c->my_g = my;\n  c->mz_g = mz;\n  c->basisorder = basisorder;\n  c->dofs = ndofs;\n  \n  c->nx_g = basisorder*mx + 1;\n  c->ny_g = basisorder*my + 1;\n  c->nz_g = basisorder*mz + 1;\n  \n  ierr = CreateGLLCoordsWeights(basisorder,&c->npe_1d,&c->xi1d,&c->w1d);CHKERRQ(ierr);\n  \n  stencil_width = 1;\n  switch (dim) {\n    case 2:\n    c->npe = c->npe_1d * c->npe_1d;\n    c->ne = mx * my;\n    c->ne_g = mx * my;\n    \n    ierr = DMDACreate2d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_BOX,\n                        c->nx_g,c->ny_g,PETSC_DECIDE,PETSC_DECIDE,ndofs,stencil_width,NULL,NULL,&c->dm);CHKERRQ(ierr);\n    ierr = DMSetUp(c->dm);CHKERRQ(ierr);\n    ierr = SpecFECtxCreateENMap2d_SEQ(c);CHKERRQ(ierr);\n    ierr = SpecFECtxCreateMeshCoords2d_SEQ(c);CHKERRQ(ierr);\n    \n    /* tensor product for weights */\n    ierr = PetscMalloc(sizeof(PetscReal)*c->npe,&c->w);CHKERRQ(ierr);\n    for (j=0; j<c->npe_1d; j++) {\n      for (i=0; i<c->npe_1d; i++) {\n        c->w[i+j*c->npe_1d] = c->w1d[i] * c->w1d[j];\n      }\n    }\n    \n    ierr = TabulateBasisDerivativesTensorProduct2d(basisorder,&c->dN_dxi,&c->dN_deta);CHKERRQ(ierr);\n    ierr = TabulateBasisDerivativesTensorProduct2d(basisorder,&c->dN_dx,&c->dN_dy);CHKERRQ(ierr);\n    \n    break;\n  }\n  \n  c->nqp = c->npe;\n  \n  ierr = PetscMalloc(sizeof(QPntIsotropicElastic)*c->ne,&c->cell_data);CHKERRQ(ierr);\n  ierr = PetscMemzero(c->cell_data,sizeof(QPntIsotropicElastic)*c->ne);CHKERRQ(ierr);\n\n  ierr = PetscMalloc1(c->ne * c->nqp,&c->dr_qp_data);CHKERRQ(ierr);\n  ierr = PetscMemzero(c->dr_qp_data,sizeof(DRVar)*c->ne*c->nqp);CHKERRQ(ierr);\n  \n  ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dim,&c->elbuf_coor);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field2);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field3);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscInt)*c->npe*c->dofs,&c->elbuf_dofs);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\n/*\n Degree 4 has 5 basis in each direction\n |           |\n 0--1--2--3--4\n*/\nPetscErrorCode SpecFECtxGetCornerBasis_MPI(SpecFECtx c,PetscInt *si,PetscInt *si_g,PetscInt *sj,PetscInt *sj_g)\n{\n  PetscInt gi,gj,m,n,k;\n  PetscErrorCode ierr;\n\n  ierr = DMDAGetGhostCorners(c->dm,&gi,&gj,NULL,&m,&n,NULL);CHKERRQ(ierr);\n  /*printf(\"rank %d: gi,gj %d %d  npe %d\\n\",c->rank,gi,gj,c->npe_1d);*/\n  for (k=0; k<m; k++) {\n    if (((gi+k) % (c->npe_1d-1)) == 0) {\n      *si = k;\n      *si_g = gi+k;\n      break;\n    }\n  }\n  for (k=0; k<n; k++) {\n    if (((gj+k) % (c->npe_1d-1)) == 0) {\n      *sj = k;\n      *sj_g = gj+k;\n      break;\n    }\n  }\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxGetLocalBoundingBox(SpecFECtx c,PetscReal gmin[],PetscReal gmax[])\n{\n  PetscErrorCode ierr;\n  PetscInt si[]={0,0},si_g[]={0,0},m,n,ii,jj;\n  const PetscReal *LA_coor;\n  Vec coor;\n  \n  ierr = SpecFECtxGetCornerBasis_MPI(c,&si[0],&si_g[0],&si[1],&si_g[1]);CHKERRQ(ierr);\n  ierr = DMDAGetGhostCorners(c->dm,NULL,NULL,NULL,&m,&n,NULL);CHKERRQ(ierr);\n  ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  ii = si[0];\n  jj = si[1];\n  gmin[0] = LA_coor[2*(ii + jj*m)+0];\n  gmin[1] = LA_coor[2*(ii + jj*m)+1];\n  ii = si[0] + c->mx * c->basisorder;\n  jj = si[1] + c->my * c->basisorder;\n  gmax[0] = LA_coor[2*(ii + jj*m)+0];\n  gmax[1] = LA_coor[2*(ii + jj*m)+1];\n  ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxCreateENMap2d_MPI(SpecFECtx c)\n{\n  PetscErrorCode ierr;\n  PetscInt ni0,nj0,i,j,ei,ej,ecnt,*emap,nid;\n  PetscInt si,si_g,sj,sj_g,nx_local;\n  \n  \n  ierr = PetscMalloc(sizeof(PetscInt)*c->ne*c->npe,&c->element);CHKERRQ(ierr);\n  ierr = PetscMemzero(c->element,sizeof(PetscInt)*c->ne*c->npe);CHKERRQ(ierr);\n  \n  ierr = SpecFECtxGetCornerBasis_MPI(c,&si,&si_g,&sj,&sj_g);CHKERRQ(ierr);\n  ierr = DMDAGetGhostCorners(c->dm,NULL,NULL,NULL,&nx_local,NULL,NULL);CHKERRQ(ierr);\n  /*printf(\"rank %d : %d %d x %d %d\\n\",c->rank,si,si_g,sj,sj_g);*/\n  \n  ecnt = 0;\n  for (ej=0; ej<c->my; ej++) {\n    nj0 = sj + ej*(c->npe_1d-1);\n    \n    for (ei=0; ei<c->mx; ei++) {\n      ni0 = si + ei*(c->npe_1d-1);\n      \n      emap = &c->element[c->npe*ecnt];\n      \n      for (j=0; j<c->npe_1d; j++) {\n        for (i=0; i<c->npe_1d; i++) {\n          \n          nid = (ni0 + i) + (nj0 + j) * nx_local;\n          emap[i+j*c->npe_1d] = nid;\n          //if (c->rank == 0) {\n          //  printf(\"e %d : %d [max %d]\\n\",ecnt,nid,c->ne*c->npe);\n          //}\n        }\n      }\n      \n      ecnt++;\n    }\n  }\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxCreateMeshCoords2d_MPI(SpecFECtx c)\n{\n  PetscErrorCode ierr;\n  Vec coor,gcoor;\n  DM cdm;\n  PetscInt ei,ej,i,j,ni0,nj0,si,si_g,sj,sj_g,gi,gj,m,n;\n  PetscReal dx,dy,x0,y0;\n  PetscReal *LA_coor;\n  \n  ierr = DMDASetUniformCoordinates(c->dm,0.0,1.0,0.0,1.0,0,0);CHKERRQ(ierr);\n  ierr = DMGetCoordinateDM(c->dm,&cdm);CHKERRQ(ierr);\n  ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr);\n\n  ierr = DMGetCoordinates(c->dm,&gcoor);CHKERRQ(ierr);\n  ierr = VecZeroEntries(gcoor);CHKERRQ(ierr);\n  \n  ierr = SpecFECtxGetCornerBasis_MPI(c,&si,&si_g,&sj,&sj_g);CHKERRQ(ierr);\n  ierr = DMDAGetGhostCorners(c->dm,&gi,&gj,NULL,&m,&n,NULL);CHKERRQ(ierr);\n\n  dx = 1.0/((PetscReal)c->mx_g);\n  dy = 1.0/((PetscReal)c->my_g);\n  ierr = VecGetArray(coor,&LA_coor);CHKERRQ(ierr);\n  for (ej=0; ej<c->my; ej++) {\n    \n    for (ei=0; ei<c->mx; ei++) {\n      if ( si >= m*n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,\"Out of range-si\");\n      if ( sj >= m*n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,\"Out of range-sj\");\n\n      x0 = LA_coor[2*(si + sj*m)+0] + ei*dx;\n      y0 = LA_coor[2*(si + sj*m)+1] + ej*dy;\n\n      ni0 = si + ei*(c->npe_1d-1);\n      nj0 = sj + ej*(c->npe_1d-1);\n      \n      //printf(\"rank %d : (%d,%d) -> %d %d  %+1.4e %+1.4e\\n\",c->rank,ei,ej,ni0,nj0,x0,y0);\n      \n      for (j=0; j<c->npe_1d; j++) {\n        for (i=0; i<c->npe_1d; i++) {\n          if ( (ni0+i)+(nj0+j)*m >= m*n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,\"Local index out of range\");\n\n          LA_coor[2*((ni0+i) + (nj0+j)*m)+0] = x0 + 0.5*(c->xi1d[i]+1.0)*dx;\n          LA_coor[2*((ni0+i) + (nj0+j)*m)+1] = y0 + 0.5*(c->xi1d[j]+1.0)*dy;\n          \n          ierr = VecSetValueLocal(gcoor,2*((ni0+i) + (nj0+j)*m)+0,x0 + 0.5*(c->xi1d[i]+1.0)*dx,INSERT_VALUES);CHKERRQ(ierr);\n          ierr = VecSetValueLocal(gcoor,2*((ni0+i) + (nj0+j)*m)+1,y0 + 0.5*(c->xi1d[j]+1.0)*dy,INSERT_VALUES);CHKERRQ(ierr);\n        }\n      }\n    }\n  }\n  ierr = VecRestoreArray(coor,&LA_coor);CHKERRQ(ierr);\n  ierr = VecAssemblyBegin(gcoor);CHKERRQ(ierr);\n  ierr = VecAssemblyEnd(gcoor);CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxCreateMesh_MPI(SpecFECtx c,PetscInt dim,PetscInt mx,PetscInt my,PetscInt mz,PetscInt basisorder,PetscInt ndofs)\n{\n  PetscErrorCode ierr;\n  PetscInt stencil_width,i,j;\n  DM dm_ref;\n  PetscInt ranks[3];\n  PetscInt r,*lx,*ly;\n  const PetscInt *lx_ref,*ly_ref;\n  DMDALocalInfo info;\n  \n  c->dim = dim;\n  c->mx_g = mx;\n  c->my_g = my;\n  c->mz_g = mz;\n  c->basisorder = basisorder;\n  c->dofs = ndofs;\n  \n  c->nx_g = basisorder*mx + 1;\n  c->ny_g = basisorder*my + 1;\n  c->nz_g = basisorder*mz + 1;\n  \n  ierr = CreateGLLCoordsWeights(basisorder,&c->npe_1d,&c->xi1d,&c->w1d);CHKERRQ(ierr);\n  \n  stencil_width = 1;\n  switch (dim) {\n    case 2:\n    c->npe = c->npe_1d * c->npe_1d;\n    c->ne_g = mx * my;\n\n    ierr = DMDACreate2d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_BOX,\n                        c->mx_g,c->my_g,PETSC_DECIDE,PETSC_DECIDE,1,0,NULL,NULL,&dm_ref);CHKERRQ(ierr);\n    ierr = DMSetUp(dm_ref);CHKERRQ(ierr);\n    /*ierr = DMView(dm_ref,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); */\n\n    ierr = DMDAGetInfo(dm_ref,NULL,NULL,NULL,NULL,&ranks[0],&ranks[1],NULL,NULL,NULL,NULL,NULL,NULL,NULL);CHKERRQ(ierr);\n    ierr = DMDAGetOwnershipRanges(dm_ref,&lx_ref,&ly_ref,NULL);CHKERRQ(ierr);\n    ierr = DMDAGetLocalInfo(dm_ref,&info);CHKERRQ(ierr);\n    \n    c->mx = info.xm;\n    c->my = info.ym;\n    c->ne = c->mx * c->my;\n    \n    ierr = PetscMalloc1(ranks[0],&lx);CHKERRQ(ierr);\n    ierr = PetscMalloc1(ranks[1],&ly);CHKERRQ(ierr);\n    for (r=0; r<ranks[0]; r++) {\n      lx[r] = lx_ref[r] * (c->npe_1d - 1);\n    }\n    lx[ranks[0]-1]++;\n\n    /*for (r=0; r<ranks[0]; r++)  PetscPrintf(PETSC_COMM_WORLD,\"npoints-i[%D] %D \\n\",r,lx[r]);*/\n    \n    for (r=0; r<ranks[1]; r++) {\n      ly[r] = ly_ref[r] * (c->npe_1d - 1);\n    }\n    ly[ranks[1]-1]++;\n    \n    /*for (r=0; r<ranks[1]; r++)  PetscPrintf(PETSC_COMM_WORLD,\"npoints-j[%D] %D \\n\",r,ly[r]);*/\n    \n    ierr = DMDACreate2d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_BOX,\n                        c->nx_g,c->ny_g,ranks[0],ranks[1],ndofs,stencil_width,lx,ly,&c->dm);CHKERRQ(ierr);\n    ierr = DMSetUp(c->dm);CHKERRQ(ierr);\n    /*ierr = DMView(c->dm,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); */\n\n    ierr = SpecFECtxCreateENMap2d_MPI(c);CHKERRQ(ierr);\n    ierr = SpecFECtxCreateMeshCoords2d_MPI(c);CHKERRQ(ierr);\n    \n    /* tensor product for weights */\n    ierr = PetscMalloc(sizeof(PetscReal)*c->npe,&c->w);CHKERRQ(ierr);\n    for (j=0; j<c->npe_1d; j++) {\n      for (i=0; i<c->npe_1d; i++) {\n        c->w[i+j*c->npe_1d] = c->w1d[i] * c->w1d[j];\n      }\n    }\n    \n    ierr = TabulateBasisDerivativesTensorProduct2d(basisorder,&c->dN_dxi,&c->dN_deta);CHKERRQ(ierr);\n    ierr = TabulateBasisDerivativesTensorProduct2d(basisorder,&c->dN_dx,&c->dN_dy);CHKERRQ(ierr);\n    \n    ierr = PetscFree(lx);CHKERRQ(ierr);\n    ierr = PetscFree(ly);CHKERRQ(ierr);\n    ierr = DMDestroy(&dm_ref);CHKERRQ(ierr);\n    break;\n  }\n  \n  c->nqp = c->npe;\n  \n  ierr = PetscMalloc(sizeof(QPntIsotropicElastic)*c->ne,&c->cell_data);CHKERRQ(ierr);\n  ierr = PetscMemzero(c->cell_data,sizeof(QPntIsotropicElastic)*c->ne);CHKERRQ(ierr);\n  \n  ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dim,&c->elbuf_coor);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field2);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscReal)*c->npe*c->dofs,&c->elbuf_field3);CHKERRQ(ierr);\n  ierr = PetscMalloc(sizeof(PetscInt)*c->npe*c->dofs,&c->elbuf_dofs);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxCreateMesh(SpecFECtx c,PetscInt dim,PetscInt mx,PetscInt my,PetscInt mz,PetscInt basisorder,PetscInt ndofs)\n{\n  PetscMPIInt size;\n  PetscErrorCode ierr;\n  \n  ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);\n  if (size == 1) {\n    ierr = SpecFECtxCreateMesh_SEQ(c,dim,mx,my,mz,basisorder,ndofs);CHKERRQ(ierr);\n  } else {\n    ierr = SpecFECtxCreateMesh_MPI(c,dim,mx,my,mz,basisorder,ndofs);CHKERRQ(ierr);\n  }\n  ierr = DMDASetFieldName(c->dm,0,\"_x\");CHKERRQ(ierr);\n  ierr = DMDASetFieldName(c->dm,1,\"_y\");CHKERRQ(ierr);\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxSetConstantMaterialProperties(SpecFECtx c,PetscReal lambda,PetscReal mu,PetscReal rho)\n{\n  PetscInt q;\n  \n  for (q=0; q<c->ne; q++) {\n    c->cell_data[q].lambda = lambda;\n    c->cell_data[q].mu     = mu;\n    c->cell_data[q].rho    = rho;\n  }\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxSetConstantMaterialProperties_Velocity(SpecFECtx c,PetscReal Vp,PetscReal Vs,PetscReal rho)\n{\n  PetscErrorCode ierr;\n  PetscReal mu,lambda;\n  \n  mu = Vs * Vs * rho;\n  lambda = Vp * Vp * rho - 2.0 * mu;\n  ierr = SpecFECtxSetConstantMaterialProperties(c,lambda,mu,rho);CHKERRQ(ierr);\n  PetscPrintf(PETSC_COMM_WORLD,\"  [material]     Vp = %1.8e\\n\",Vp);\n  PetscPrintf(PETSC_COMM_WORLD,\"  [material]     Vs = %1.8e\\n\",Vs);\n  PetscPrintf(PETSC_COMM_WORLD,\"  [material] lambda = %1.8e\\n\",lambda);\n  PetscPrintf(PETSC_COMM_WORLD,\"  [material]     mu = %1.8e\\n\",mu);\n  PetscPrintf(PETSC_COMM_WORLD,\"  [material]    rho = %1.8e\\n\",rho);\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxSetPerturbedMaterialProperties_Velocity(SpecFECtx c,PetscReal Vp0,PetscReal delta_Vp,PetscReal Vs0,PetscReal delta_Vs,PetscReal rho0,PetscReal delta_rho)\n{\n  PetscErrorCode ierr;\n  Vec Vp,Vs,rho;\n  PetscRandom r;\n  const PetscReal *LA_Vp,*LA_Vs,*LA_rho;\n  PetscInt e;\n  \n  ierr = VecCreate(PETSC_COMM_WORLD,&Vp);CHKERRQ(ierr);\n  ierr = VecSetSizes(Vp,c->ne,c->ne_g);CHKERRQ(ierr);\n  ierr = VecSetFromOptions(Vp);CHKERRQ(ierr);\n  ierr = VecDuplicate(Vp,&Vs);CHKERRQ(ierr);\n  ierr = VecDuplicate(Vp,&rho);CHKERRQ(ierr);\n\n  ierr = PetscRandomCreate(PETSC_COMM_WORLD,&r);CHKERRQ(ierr);\n  ierr = PetscRandomSetType(r,PETSCRAND48);CHKERRQ(ierr);\n\n  ierr = PetscRandomSetInterval(r,Vp0-delta_Vp,Vp0+delta_Vp);CHKERRQ(ierr);\n  ierr = PetscRandomSetSeed(r,1);CHKERRQ(ierr);\n  ierr = PetscRandomSeed(r);CHKERRQ(ierr);\n  ierr = VecSetRandom(Vp,r);CHKERRQ(ierr);\n\n  ierr = PetscRandomSetInterval(r,Vs0-delta_Vs,Vs0+delta_Vs);CHKERRQ(ierr);\n  ierr = PetscRandomSetSeed(r,2);CHKERRQ(ierr);\n  ierr = PetscRandomSeed(r);CHKERRQ(ierr);\n  ierr = VecSetRandom(Vs,r);CHKERRQ(ierr);\n  \n  ierr = PetscRandomSetInterval(r,rho0-delta_rho,rho0+delta_rho);CHKERRQ(ierr);\n  ierr = PetscRandomSetSeed(r,3);CHKERRQ(ierr);\n  ierr = PetscRandomSeed(r);CHKERRQ(ierr);\n  ierr = VecSetRandom(rho,r);CHKERRQ(ierr);\n\n  ierr = PetscRandomDestroy(&r);CHKERRQ(ierr);\n\n  ierr = VecGetArrayRead(Vp,&LA_Vp);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(Vs,&LA_Vs);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(rho,&LA_rho);CHKERRQ(ierr);\n  for (e=0; e<c->ne; e++) {\n    PetscReal mu,lambda;\n\n    mu     = LA_Vs[e] * LA_Vs[e] * LA_rho[e];\n    lambda = LA_Vp[e] * LA_Vp[e] * LA_rho[e] - 2.0 * mu;\n    \n    c->cell_data[e].lambda = lambda;\n    c->cell_data[e].mu     = mu;\n    c->cell_data[e].rho    = LA_rho[e];\n  }\n  ierr = VecRestoreArrayRead(rho,&LA_rho);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(Vs,&LA_Vs);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(Vp,&LA_Vp);CHKERRQ(ierr);\n\n  PetscPrintf(PETSC_COMM_WORLD,\"  [material]     Vp0 = %1.8e : delta = %+1.8e\\n\",Vp0,delta_Vp);\n  PetscPrintf(PETSC_COMM_WORLD,\"  [material]     Vs0 = %1.8e : delta = %+1.8e\\n\",Vs0,delta_Vs);\n  PetscPrintf(PETSC_COMM_WORLD,\"  [material]    rho0 = %1.8e : delta = %+1.8e\\n\",rho0,delta_rho);\n  \n  ierr = VecDestroy(&rho);CHKERRQ(ierr);\n  ierr = VecDestroy(&Vs);CHKERRQ(ierr);\n  ierr = VecDestroy(&Vp);CHKERRQ(ierr);\n  PetscFunctionReturn(0);\n}\n\nvoid ElementEvaluateGeometry_CellWiseConstant2d(PetscInt npe,PetscReal el_coords[],\n                                                PetscInt nbasis,PetscReal *detJ)\n{\n  PetscReal J00,J11;\n  PetscReal dx,dy;\n  \n  dx = el_coords[2*(nbasis-1)+0] - el_coords[2*0+0];\n  dy = el_coords[2*(npe-1)+1]    - el_coords[2*0+1];\n  \n  J00 = 0.5 * dx;\n  J11 = 0.5 * dy;\n  \n  *detJ = J00*J11;\n}\n\nvoid ElementEvaluateDerivatives_CellWiseConstant2d(PetscInt nqp,PetscInt npe,PetscReal el_coords[],\n                                                   PetscInt nbasis,PetscReal **dN_dxi,PetscReal **dN_deta,\n                                                   PetscReal **dN_dx,PetscReal **dN_dy)\n{\n  PetscInt k,q;\n  PetscReal J00,J11,iJ00,iJ11;\n  PetscReal dx,dy;\n  \n  dx = el_coords[2*(nbasis-1)+0] - el_coords[2*0+0];\n  dy = el_coords[2*(npe-1)+1]    - el_coords[2*0+1];\n  \n  J00 = 0.5 * dx;\n  J11 = 0.5 * dy;\n  \n  for (q=0; q<nqp; q++) {\n    \n    iJ00 = 1.0/J00;\n    iJ11 = 1.0/J11;\n    \n    /* shape function derivatives */\n    for (k=0; k<npe; k++) {\n      dN_dx[q][k] = iJ00 * dN_dxi[q][k];\n      dN_dy[q][k] = iJ11 * dN_deta[q][k];\n    }\n  }\n}\n\n/*\n Assemble rhs\n L(u) = - \\int B^T D B u dV\n */\nPetscErrorCode AssembleLinearForm_ElastoDynamics2d(SpecFECtx c,Vec u,Vec F)\n{\n  PetscErrorCode ierr;\n  PetscInt  e,nqp,q,i,nbasis,ndof;\n  PetscReal e_vec[3],sigma_vec[3];\n  PetscInt  *element,*elnidx,*eldofs;\n  PetscReal *fe,*ux,*uy,*elcoords,detJ,*field;\n  Vec       coor,ul,fl;\n  const PetscReal *LA_coor,*LA_u;\n  QPntIsotropicElastic *celldata;\n  \n  ierr = VecZeroEntries(F);CHKERRQ(ierr);\n  \n  eldofs   = c->elbuf_dofs;\n  elcoords = c->elbuf_coor;\n  nbasis   = c->npe;\n  nqp      = c->nqp;\n  ndof     = c->dofs;\n  fe       = c->elbuf_field;\n  element  = c->element;\n  field    = c->elbuf_field2;\n  \n  ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  \n  ierr = DMGetLocalVector(c->dm,&ul);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalBegin(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(ul,&LA_u);CHKERRQ(ierr);\n\n  ierr = DMGetLocalVector(c->dm,&fl);CHKERRQ(ierr);\n  ierr = VecZeroEntries(fl);CHKERRQ(ierr);\n\n  ux = &field[0];\n  uy = &field[nbasis];\n  \n  for (e=0; e<c->ne; e++) {\n    /* get element -> node map */\n    elnidx = &element[nbasis*e];\n    \n    \n    /* generate dofs */\n    for (i=0; i<nbasis; i++) {\n      eldofs[2*i  ] = 2*elnidx[i];\n      eldofs[2*i+1] = 2*elnidx[i]+1;\n    }\n    \n    /* get element coordinates */\n    for (i=0; i<nbasis; i++) {\n      PetscInt nidx = elnidx[i];\n      elcoords[2*i  ] = LA_coor[2*nidx  ];\n      elcoords[2*i+1] = LA_coor[2*nidx+1];\n    }\n    \n    /* get element displacements */\n    for (i=0; i<nbasis; i++) {\n      PetscInt nidx = elnidx[i];\n      ux[i] = LA_u[2*nidx  ];\n      uy[i] = LA_u[2*nidx+1];\n    }\n    \n    /* compute derivatives */\n    ElementEvaluateGeometry_CellWiseConstant2d(nbasis,elcoords,c->npe_1d,&detJ);\n    ElementEvaluateDerivatives_CellWiseConstant2d(nqp,nbasis,elcoords,\n                                                  c->npe_1d,c->dN_dxi,c->dN_deta,\n                                                  c->dN_dx,c->dN_dy);\n    \n    ierr = PetscMemzero(fe,sizeof(PetscReal)*nbasis*ndof);CHKERRQ(ierr);\n    \n    /* get access to element->quadrature points */\n    celldata = &c->cell_data[e];\n    \n    for (q=0; q<c->nqp; q++) {\n      PetscReal            fac;\n      PetscReal            c11,c12,c21,c22,c33,lambda_qp,mu_qp;\n      PetscReal            *dNidx,*dNidy;\n      \n      \n      dNidx = c->dN_dx[q];\n      dNidy = c->dN_dy[q];\n      \n      /* compute strain @ quadrature point */\n      /*\n       e = Bu = [ d/dx  0    ][ u v ]^T\n       [ 0     d/dy ]\n       [ d/dy  d/dx ]\n       */\n      e_vec[0] = e_vec[1] = e_vec[2] = 0.0;\n      for (i=0; i<nbasis; i++) {\n        e_vec[0] += dNidx[i] * ux[i];\n        e_vec[1] += dNidy[i] * uy[i];\n        e_vec[2] += (dNidx[i] * uy[i] + dNidy[i] * ux[i]);\n      }\n      \n      /* evaluate constitutive model */\n      lambda_qp  = celldata->lambda;\n      mu_qp      = celldata->mu;\n      \n      /*\n       coeff = E_qp * (1.0 + nu_qp)/(1.0 - 2.0*nu_qp);\n       c11 = coeff*(1.0 - nu_qp);\n       c12 = coeff*(nu_qp);\n       c21 = coeff*(nu_qp);\n       c22 = coeff*(1.0 - nu_qp);\n       c33 = coeff*(0.5 * (1.0 - 2.0 * nu_qp));\n       */\n      c11 = 2.0*mu_qp + lambda_qp;\n      c12 = lambda_qp;\n      c21 = lambda_qp;\n      c22 = 2.0*mu_qp + lambda_qp;\n      c33 = mu_qp;\n      \n      /* compute stress @ quadrature point */\n      sigma_vec[TENS2D_XX] = c11 * e_vec[0] + c12 * e_vec[1];\n      sigma_vec[TENS2D_YY] = c21 * e_vec[0] + c22 * e_vec[1];\n      sigma_vec[TENS2D_XY] = c33 * e_vec[2];\n      //printf(\"s = %1.4e %1.4e %1.4e \\n\",sigma_vec[0],sigma_vec[1],sigma_vec[2]);\n      /*\n       a(u,v) = B^T s\n       = [ d/dx  0    d/dy ][ sxx syy sxy ]^T\n       [ 0     d/dy d/dx ]\n       */\n      \n      fac = detJ * c->w[q];\n      \n      for (i=0; i<nbasis; i++) {\n        fe[2*i  ] += -fac * (dNidx[i] * sigma_vec[TENS2D_XX] + dNidy[i] * sigma_vec[TENS2D_XY]);\n        fe[2*i+1] += -fac * (dNidy[i] * sigma_vec[TENS2D_YY] + dNidx[i] * sigma_vec[TENS2D_XY]);\n      }\n      \n    }\n    //ierr = VecSetValuesLocal(F,nbasis*ndof,eldofs,fe,ADD_VALUES);CHKERRQ(ierr);\n    ierr = VecSetValues(fl,nbasis*ndof,eldofs,fe,ADD_VALUES);CHKERRQ(ierr);\n  }\n  ierr = VecAssemblyBegin(fl);CHKERRQ(ierr);\n  ierr = VecAssemblyEnd(fl);CHKERRQ(ierr);\n  ierr = DMLocalToGlobalBegin(c->dm,fl,ADD_VALUES,F);CHKERRQ(ierr);\n  ierr = DMLocalToGlobalEnd(c->dm,fl,ADD_VALUES,F);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(ul,&LA_u);CHKERRQ(ierr);\n  ierr = DMRestoreLocalVector(c->dm,&ul);CHKERRQ(ierr);\n  ierr = DMRestoreLocalVector(c->dm,&fl);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SpecFECtxGetDRCellData(SpecFECtx c,PetscInt e_index,DRVar **data)\n{\n  *data = &c->dr_qp_data[c->nqp * e_index];\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode EvaluateVelocityAtPoint(SpecFECtx c,const PetscReal LA_v[],PetscReal xr[],PetscReal vr[])\n{\n  PetscReal      gmin[3],gmax[3],dx,dy;\n  PetscInt       k,ei,ej,eid,*element,*elbasis;\n  PetscReal      N[400];\n  PetscErrorCode ierr;\n\n  \n  if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,\"Needs updating to support MPI\");\n  \n  /* get containing element */\n  ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr);\n  dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g);\n  ei = (xr[0] - gmin[0])/dx; /* todo - needs to be sub-domain gmin */\n  \n  dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g);\n  ej = (xr[1] - gmin[1])/dy;\n  \n  eid = ei + ej * c->mx;\n  \n  /* get element -> node map */\n  element = c->element;\n  elbasis = &element[c->npe*eid];\n  \n  {\n    PetscInt  nbasis,i,j;\n    PetscReal **N_s1,**N_s2,xi,eta,x0,y0;\n    \n    x0 = gmin[0] + ei*dx; /* todo - needs to be sub-domain gmin */\n    y0 = gmin[1] + ej*dy;\n    \n    // (xi - (-1))/2 = (x - x0)/dx\n    xi = 2.0*(xr[0] - x0)/dx - 1.0;\n    eta = 2.0*(xr[1] - y0)/dy - 1.0;\n    \n    /* compute basis */\n    ierr = TabulateBasis1d_CLEGENDRE(1,&xi,c->basisorder,&nbasis,&N_s1);CHKERRQ(ierr);\n    ierr = TabulateBasis1d_CLEGENDRE(1,&eta,c->basisorder,&nbasis,&N_s2);CHKERRQ(ierr);\n    \n    k = 0;\n    for (j=0; j<c->npe_1d; j++) {\n      for (i=0; i<c->npe_1d; i++) {\n        N[k] = N_s1[0][i] * N_s2[0][j];\n        k++;\n      }\n    }\n    \n    ierr = PetscFree(N_s1[0]);CHKERRQ(ierr);\n    ierr = PetscFree(N_s1);CHKERRQ(ierr);\n    ierr = PetscFree(N_s2[0]);CHKERRQ(ierr);\n    ierr = PetscFree(N_s2);CHKERRQ(ierr);\n  }\n  \n  vr[0] = vr[1] = 0.0;\n  for (k=0; k<c->npe; k++) {\n    PetscInt nid = elbasis[k];\n    \n    vr[0] += N[k] * LA_v[2*nid+0];\n    vr[1] += N[k] * LA_v[2*nid+1];\n  }\n  \n  PetscFunctionReturn(0);\n}\n\n\nPetscErrorCode PointLocation_v2(SpecFECtx c,const PetscReal xr[],PetscInt *_eid,PetscReal **N1,PetscReal **N2)\n{\n  static PetscBool beenhere = PETSC_FALSE;\n  static PetscReal      gmin[3],gmax[3];\n  PetscReal      dx,dy;\n  PetscInt       ei,ej,eid;\n  PetscInt       nbasis;\n  PetscReal      **N_s1,**N_s2,xi,eta,x0,y0;\n  PetscErrorCode ierr;\n  \n  \n  if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,\"Needs updating to support MPI\");\n  \n  /* get containing element */\n  if (!beenhere) {\n    ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr);\n    beenhere = PETSC_TRUE;\n  }\n  dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g);\n  ei = (xr[0] - gmin[0])/dx; /* todo - needs to be sub-domain gmin */\n  \n  dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g);\n  ej = (xr[1] - gmin[1])/dy;\n  \n  eid = ei + ej * c->mx;\n  \n  x0 = gmin[0] + ei*dx; /* todo - needs to be sub-domain gmin */\n  y0 = gmin[1] + ej*dy;\n  \n  // (xi - (-1))/2 = (x - x0)/dx\n  xi = 2.0*(xr[0] - x0)/dx - 1.0;\n  eta = 2.0*(xr[1] - y0)/dy - 1.0;\n  \n  /* compute basis */\n  ierr = TabulateBasis1d_CLEGENDRE(1,&xi,c->basisorder,&nbasis,&N_s1);CHKERRQ(ierr);\n  ierr = TabulateBasis1d_CLEGENDRE(1,&eta,c->basisorder,&nbasis,&N_s2);CHKERRQ(ierr);\n  \n  *_eid = eid;\n  *N1 = N_s1[0];\n  *N2 = N_s2[0];\n  \n  //ierr = PetscFree(N_s1[0]);CHKERRQ(ierr);\n  ierr = PetscFree(N_s1);CHKERRQ(ierr);\n  //ierr = PetscFree(N_s2[0]);CHKERRQ(ierr);\n  ierr = PetscFree(N_s2);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\n\nPetscErrorCode FaultSDFInit_v2(SpecFECtx c)\n{\n  PetscErrorCode  ierr;\n  PetscInt        e,i,q,nbasis,nqp,ndof;\n  Vec             coor;\n  const PetscReal *LA_coor;\n  PetscInt        *element,*elnidx,*eldofs;\n  PetscReal       *elcoords;\n  DRVar           *dr_celldata;\n  PetscReal       factor;\n  PetscInt        factor_i;\n  \n  eldofs   = c->elbuf_dofs;\n  elcoords = c->elbuf_coor;\n  nbasis   = c->npe;\n  nqp      = c->nqp;\n  ndof     = c->dofs;\n  element  = c->element;\n  \n\n  factor = ((PetscReal)(c->ne)) * 0.1;\n  factor_i = (PetscInt)factor;\n  if (factor_i == 0) { factor_i = 1; }\n  \n  ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  \n  for (e=0; e<c->ne; e++) {\n    /* get element -> node map */\n    elnidx = &element[nbasis*e];\n    \n    \n    /* generate dofs */\n    for (i=0; i<nbasis; i++) {\n      eldofs[2*i  ] = 2*elnidx[i];\n      eldofs[2*i+1] = 2*elnidx[i]+1;\n    }\n    \n    /* get element coordinates */\n    for (i=0; i<nbasis; i++) {\n      PetscInt nidx = elnidx[i];\n      elcoords[2*i  ] = LA_coor[2*nidx  ];\n      elcoords[2*i+1] = LA_coor[2*nidx+1];\n    }\n    \n    ierr = SpecFECtxGetDRCellData(c,e,&dr_celldata);CHKERRQ(ierr);\n    \n    for (q=0; q<c->nqp; q++) {\n      PetscReal coor_qp[2];\n      PetscBool modify_stress_state;\n      \n      coor_qp[0] = elcoords[2*q  ];\n      coor_qp[1] = elcoords[2*q+1];\n      \n      modify_stress_state = PETSC_FALSE;\n      dr_celldata[q].eid[0] = -1;\n      dr_celldata[q].eid[1] = -1;\n      \n      ierr = FaultSDFQuery(coor_qp,c->delta,NULL,&modify_stress_state);CHKERRQ(ierr);\n      \n      if (modify_stress_state) {\n        PetscReal x_plus[2],x_minus[2];\n        \n        //printf(\"[e %d , q %d] x_qp %+1.4e , %+1.4e\\n\",e,q,coor_qp[0],coor_qp[1]);\n        \n        ierr = FaultSDFGetPlusMinusCoor(coor_qp,c->delta,NULL,x_plus,x_minus);CHKERRQ(ierr);\n        \n        ierr = PointLocation_v2(c,(const PetscReal*)x_plus, &dr_celldata[q].eid[0],&dr_celldata[q].N1_plus,&dr_celldata[q].N2_plus);CHKERRQ(ierr);\n        ierr = PointLocation_v2(c,(const PetscReal*)x_minus,&dr_celldata[q].eid[1],&dr_celldata[q].N1_minus,&dr_celldata[q].N2_minus);CHKERRQ(ierr);\n        //printf(\"  [e %d,q %d] x_qp -> x+ %+1.4e , %+1.4e [eid %d]\\n\",e,q,x_plus[0],x_plus[1],dr_celldata[q].eid[0]);\n        //printf(\"  [e %d,q %d] x_qp -> x- %+1.4e , %+1.4e [eid %d]\\n\",e,q,x_minus[0],x_minus[1],dr_celldata[q].eid[1]);\n      }\n      \n    }\n    if (e%factor_i == 0) {\n      printf(\"[Fault point location] Done element %d of %d\\n\",e,c->ne);\n    }\n  }\n  printf(\"[Fault point location-v2] Finished\\n\");\n  \n  ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\n/* Use tabulated basis at delta(+,-) to interpolate velocity */\nPetscErrorCode FaultSDFTabulateInterpolation_v2(SpecFECtx c,const PetscReal LA_v[],DRVar *dr_celldata_q,\n                                                PetscReal v_plus[],PetscReal v_minus[])\n{\n  PetscInt  eid_delta,*element_delta;\n  PetscReal vx_d_e,vy_d_e,Ni;\n  PetscInt i,ii,jj,nbasis,*element,nidx;\n  \n  nbasis   = c->npe;\n  element  = c->element;\n  \n  if (!dr_celldata_q->N1_plus || !dr_celldata_q->N2_plus) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,\"[+] N1,N2 not allocated\");\n  eid_delta = dr_celldata_q->eid[0];\n  element_delta = &element[nbasis*eid_delta];\n  \n  v_plus[0] = v_plus[1] = 0.0;\n  i = 0;\n  for (jj=0; jj<c->npe_1d; jj++) {\n    for (ii=0; ii<c->npe_1d; ii++) {\n      nidx = element_delta[i];\n      \n      Ni = dr_celldata_q->N1_plus[ii] * dr_celldata_q->N2_plus[jj];\n      \n      vx_d_e = LA_v[2*nidx  ];\n      vy_d_e = LA_v[2*nidx+1];\n      v_plus[0] += Ni * vx_d_e;\n      v_plus[1] += Ni * vy_d_e;\n      \n      i++;\n    }\n  }\n\n  if (!dr_celldata_q->N1_minus || !dr_celldata_q->N2_minus) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,\"[-] N1,N2 not allocated\");\n  eid_delta = dr_celldata_q->eid[1];\n  element_delta = &element[nbasis*eid_delta];\n  \n  v_minus[0] = v_minus[1] = 0.0;\n  i = 0;\n  for (jj=0; jj<c->npe_1d; jj++) {\n    for (ii=0; ii<c->npe_1d; ii++) {\n      nidx = element_delta[i];\n      \n      Ni = dr_celldata_q->N1_minus[ii] * dr_celldata_q->N2_minus[jj];\n      \n      vx_d_e = LA_v[2*nidx  ];\n      vy_d_e = LA_v[2*nidx+1];\n      v_minus[0] += Ni * vx_d_e;\n      v_minus[1] += Ni * vy_d_e;\n      \n      i++;\n    }\n  }\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode VoigtTensorContract_ai_Tij_bj(PetscReal a[],PetscReal t[2][2],PetscReal b[],PetscReal *r)\n{\n  PetscReal s=0;\n  PetscInt i,j;\n  \n  for (i=0; i<2; i++) {\n    for (j=0; j<2; j++) {\n      s += a[i] * t[i][j] * b[j];\n    }\n  }\n  *r = s;\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode VoigtTensorConvert(PetscReal T[],PetscReal t[2][2])\n{\n  t[0][0] = T[TENS2D_XX];\n  t[0][1] = T[TENS2D_XY];\n  t[1][0] = T[TENS2D_XY];\n  t[1][1] = T[TENS2D_YY];\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TensorConvertToVoigt(PetscReal t[2][2],PetscReal T[])\n{\n  T[TENS2D_XX] = t[0][0];\n  T[TENS2D_XY] = t[0][1];\n  T[TENS2D_YY] = t[1][1];\n  if (fabs(t[1][0] - t[0][1]) > 1.0e-12) {\n    SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,\"Cannot convert non-symmetric tensor into Voigt format\");\n  }\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TensorZeroEntries(PetscReal t[2][2])\n{\n  t[0][0] = 0;\n  t[0][1] = 0;\n  t[1][0] = 0;\n  t[1][1] = 0;\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TensorScale(PetscReal y[2][2],PetscReal a)\n{\n  y[0][0] = a*y[0][0];\n  y[0][1] = a*y[0][1];\n  y[1][0] = a*y[1][0];\n  y[1][1] = a*y[1][1];\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TensorAXPY(PetscReal y[2][2],PetscReal a,PetscReal x[2][2])\n{\n  y[0][0] += a*x[0][0];\n  y[0][1] += a*x[0][1];\n  y[1][0] += a*x[1][0];\n  y[1][1] += a*x[1][1];\n  PetscFunctionReturn(0);\n}\n\n\nPetscErrorCode VectorContract_ai_bj(PetscReal a[],PetscReal b[],PetscReal t[2][2])\n{\n  PetscInt i,j;\n  \n  for (i=0; i<2; i++) {\n    for (j=0; j<2; j++) {\n      t[i][j] = a[i] * b[j];\n    }\n  }\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode VectorContractAdd_ai_bj(PetscReal a[],PetscReal b[],PetscReal t[2][2])\n{\n  PetscInt i,j;\n  \n  for (i=0; i<2; i++) {\n    for (j=0; j<2; j++) {\n      t[i][j] += a[i] * b[j];\n    }\n  }\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode VectorContractAbsAdd_ai_bj(PetscReal a[],PetscReal b[],PetscReal t[2][2])\n{\n  PetscInt i,j;\n  \n  for (i=0; i<2; i++) {\n    for (j=0; j<2; j++) {\n      t[i][j] += fabs(a[i] * b[j]);\n    }\n  }\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TensorRtAR(PetscReal R[2][2],PetscReal T[2][2],PetscReal Tr[2][2])\n{\n  PetscInt i,j,k,l;\n  \n  // Tr[i][j] = Rt[i][k]T[k][l]R[l][j] = Rt[k][i]T[k][l]R[l][j]\n  for (i=0; i<2; i++) {\n    for (j=0; j<2; j++) {\n      Tr[i][j] = 0.0;\n      for (k=0; k<2; k++) {\n        for (l=0; l<2; l++) {\n          Tr[i][j] += R[k][i] * T[k][l] * R[l][j];\n        }\n      }\n    }\n  }\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TensorTransform(PetscReal e1[],PetscReal e2[],PetscReal T[2][2],PetscReal Tr[2][2])\n{\n  PetscReal R[2][2];\n  \n  R[0][0] = e1[0]; R[0][1] = e2[0];\n  R[1][0] = e1[1]; R[1][1] = e2[1];\n  TensorRtAR(R,T,Tr);\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode TensorInverseTransform(PetscReal e1[],PetscReal e2[],PetscReal T[2][2],PetscReal Tr[2][2])\n{\n  PetscReal R[2][2],iR[2][2],det;\n  \n  R[0][0] = e1[0]; R[0][1] = e2[0];\n  R[1][0] = e1[1]; R[1][1] = e2[1];\n  det = R[0][0] * R[1][1] - R[0][1] * R[1][0];\n  iR[0][0] =  R[1][1]/det;\n  iR[0][1] = -R[0][1]/det;\n  iR[1][0] = -R[1][0]/det;\n  iR[1][1] =  R[0][0]/det;\n  TensorRtAR(iR,T,Tr);\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode AssembleLinearForm_ElastoDynamics_StressGlut2d_tpv(SpecFECtx c,Vec u,Vec v,PetscReal dt,PetscReal time,PetscReal gamma,Vec F)\n{\n  PetscErrorCode ierr;\n  PetscInt  e,nqp,q,i,nbasis,ndof;\n  PetscReal e_vec[3],edot_vec[3],sigma_vec[3],sigma_trial[3],gradu[4],gradv[4],gradv_q[9*9][4];\n  PetscInt  *element,*elnidx,*eldofs;\n  PetscReal *fe,*ux,*uy,*vx,*vy,*elcoords,detJ,*fieldU,*fieldV;\n  Vec       coor,ul,vl,fl;\n  const PetscReal *LA_coor,*LA_u,*LA_v;\n  QPntIsotropicElastic *celldata;\n  DRVar                *dr_celldata;\n\n  // 0.55 is a good fit to matching sem2pack's displacement field...near the point (0,500)\n  PetscReal sigma_n_0 = 120.0 * 1.0e6 * 1.0;\n  PetscReal sigma_t_0 = 70.0  * 1.0e6 * 1.0;\n  PetscReal sigma_n_1  = 120.0 * 1.0e6 * 1.0;\n  PetscReal sigma_t_1  = 81.6  * 1.0e6 * 1.0;\n  static PetscBool beenhere = PETSC_FALSE;\n  static PetscReal gmin[3],gmax[3];\n  PetscReal dx,dy;\n  if (!beenhere) {\n    ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr);\n    beenhere = PETSC_TRUE;\n  }\n  dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g);\n  dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g);\n\n  ierr = VecZeroEntries(F);CHKERRQ(ierr);\n  \n  eldofs   = c->elbuf_dofs;\n  elcoords = c->elbuf_coor;\n  nbasis   = c->npe;\n  nqp      = c->nqp;\n  ndof     = c->dofs;\n  fe       = c->elbuf_field;\n  element  = c->element;\n  fieldU   = c->elbuf_field2;\n  fieldV   = c->elbuf_field3;\n  \n  ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  \n  ierr = DMGetLocalVector(c->dm,&ul);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalBegin(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(ul,&LA_u);CHKERRQ(ierr);\n  \n  ierr = DMGetLocalVector(c->dm,&vl);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalBegin(c->dm,v,INSERT_VALUES,vl);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(c->dm,v,INSERT_VALUES,vl);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(vl,&LA_v);CHKERRQ(ierr);\n  \n  ierr = DMGetLocalVector(c->dm,&fl);CHKERRQ(ierr);\n  ierr = VecZeroEntries(fl);CHKERRQ(ierr);\n  \n  ux = &fieldU[0];\n  uy = &fieldU[nbasis];\n  \n  vx = &fieldV[0];\n  vy = &fieldV[nbasis];\n  \n  \n  for (e=0; e<c->ne; e++) {\n    ierr = SpecFECtxGetDRCellData(c,e,&dr_celldata);CHKERRQ(ierr);\n  }\n  \n  for (e=0; e<c->ne; e++) {\n    PetscReal x_cell[] = {0,0};\n    \n    /* get element -> node map */\n    elnidx = &element[nbasis*e];\n    \n    /* generate dofs */\n    for (i=0; i<nbasis; i++) {\n      eldofs[2*i  ] = 2*elnidx[i];\n      eldofs[2*i+1] = 2*elnidx[i]+1;\n    }\n    \n    /* get element coordinates */\n    for (i=0; i<nbasis; i++) {\n      PetscInt nidx = elnidx[i];\n      elcoords[2*i  ] = LA_coor[2*nidx  ];\n      elcoords[2*i+1] = LA_coor[2*nidx+1];\n      x_cell[0] += elcoords[2*i  ];\n      x_cell[1] += elcoords[2*i+1];\n    }\n    x_cell[0] = x_cell[0] / ((PetscReal)nbasis);\n    x_cell[1] = x_cell[1] / ((PetscReal)nbasis);\n    \n    /* get element displacements & velocities */\n    for (i=0; i<nbasis; i++) {\n      PetscInt nidx = elnidx[i];\n      ux[i] = LA_u[2*nidx  ];\n      uy[i] = LA_u[2*nidx+1];\n      \n      vx[i] = LA_v[2*nidx  ];\n      vy[i] = LA_v[2*nidx+1];\n    }\n    \n    /* compute derivatives */\n    ElementEvaluateGeometry_CellWiseConstant2d(nbasis,elcoords,c->npe_1d,&detJ);\n    ElementEvaluateDerivatives_CellWiseConstant2d(nqp,nbasis,elcoords,\n                                                  c->npe_1d,c->dN_dxi,c->dN_deta,\n                                                  c->dN_dx,c->dN_dy);\n    \n    ierr = PetscMemzero(fe,sizeof(PetscReal)*nbasis*ndof);CHKERRQ(ierr);\n    \n    /* get access to element->quadrature points */\n    celldata = &c->cell_data[e];\n    \n    ierr = SpecFECtxGetDRCellData(c,e,&dr_celldata);CHKERRQ(ierr);\n    \n\n    \n    for (q=0; q<c->nqp; q++) {\n      PetscReal *dNidx,*dNidy;\n      \n      dNidx = c->dN_dx[q];\n      dNidy = c->dN_dy[q];\n      \n      gradv[0] = gradv[1] = gradv[2] = gradv[3] = 0.0;\n      for (i=0; i<nbasis; i++) {\n        gradv[0] += dNidx[i] * vx[i];\n        gradv[1] += dNidy[i] * vx[i];\n        gradv[2] += dNidx[i] * vy[i];\n        gradv[3] += dNidy[i] * vy[i];\n      }\n      gradv_q[q][0] = gradv[0];\n      gradv_q[q][1] = gradv[1];\n      gradv_q[q][2] = gradv[2];\n      gradv_q[q][3] = gradv[3];\n    }\n\n    \n    for (q=0; q<c->nqp; q++) {\n      PetscReal fac;\n      PetscReal c11,c12,c21,c22,c33,lambda_qp,mu_qp;\n      PetscReal *dNidx,*dNidy;\n      PetscReal coor_qp[2];\n      PetscBool inside_fault_region;\n      PetscBool sliding_active;\n      \n      dNidx = c->dN_dx[q];\n      dNidy = c->dN_dy[q];\n      \n      /* compute strain @ quadrature point */\n      /*\n       e = Bu = [ d/dx  0    ][ u v ]^T\n       [ 0     d/dy ]\n       [ d/dy  d/dx ]\n       */\n      e_vec[0] = e_vec[1] = e_vec[2] = 0.0;\n      for (i=0; i<nbasis; i++) {\n        e_vec[0] += dNidx[i] * ux[i];\n        e_vec[1] += dNidy[i] * uy[i];\n        e_vec[2] += (dNidx[i] * uy[i] + dNidy[i] * ux[i]);\n      }\n\n      edot_vec[0] = edot_vec[1] = edot_vec[2] = 0.0;\n      for (i=0; i<nbasis; i++) {\n        edot_vec[0] += dNidx[i] * vx[i];\n        edot_vec[1] += dNidy[i] * vy[i];\n        edot_vec[2] += (dNidx[i] * vy[i] + dNidy[i] * vx[i]);\n      }\n\n      gradu[0] = gradu[1] = gradu[2] = gradu[3] = 0.0;\n      gradv[0] = gradv[1] = gradv[2] = gradv[3] = 0.0;\n      for (i=0; i<nbasis; i++) {\n        gradu[0] += dNidx[i] * ux[i];\n        gradu[1] += dNidy[i] * ux[i];\n        gradu[2] += dNidx[i] * uy[i];\n        gradu[3] += dNidy[i] * uy[i];\n        \n        gradv[0] += dNidx[i] * vx[i];\n        gradv[1] += dNidy[i] * vx[i];\n        gradv[2] += dNidx[i] * vy[i];\n        gradv[3] += dNidy[i] * vy[i];\n      }\n\n      coor_qp[0] = elcoords[2*q  ];\n      coor_qp[1] = elcoords[2*q+1];\n\n      /* evaluate constitutive model */\n      lambda_qp = celldata->lambda;\n      mu_qp     = celldata->mu;\n      \n      /*\n       coeff = E_qp * (1.0 + nu_qp)/(1.0 - 2.0*nu_qp);\n       c11 = coeff*(1.0 - nu_qp);\n       c12 = coeff*(nu_qp);\n       c21 = coeff*(nu_qp);\n       c22 = coeff*(1.0 - nu_qp);\n       c33 = coeff*(0.5 * (1.0 - 2.0 * nu_qp));\n       */\n      c11 = 2.0 * mu_qp + lambda_qp;\n      c12 = lambda_qp;\n      c21 = lambda_qp;\n      c22 = 2.0 * mu_qp + lambda_qp;\n      c33 = mu_qp;\n      \n      /* compute stress @ quadrature point */\n      sigma_vec[TENS2D_XX] = c11 * e_vec[0] + c12 * e_vec[1];\n      sigma_vec[TENS2D_YY] = c21 * e_vec[0] + c22 * e_vec[1];\n      sigma_vec[TENS2D_XY] = c33 * e_vec[2];\n            \n      /*\n       From\n       Day and Ely \"Effect of a Shallow Weak Zone on Fault Rupture: Numerical Simulation of Scale-Model Experiments\",\n       BSSA, 2002\n       \n       alpha = cp\n       beta = cs\n       volumetric terms; rho (cp^2 - 2 cs^2) gamma [div(v)]\n       shear terms; rho cs^2 gamma [v_{i,j} + v_{j,i}]\n       \n       */\n      /*\n      //printf(\"lambda_qp * gamma %+1.4e : mu_qp * gamma %+1.4e\\n\",lambda_qp * gamma,mu_qp * gamma);\n      sigma_vec[TENS2D_XX] += lambda_qp * gamma * edot_vec[0];\n      sigma_vec[TENS2D_YY] += lambda_qp * gamma * edot_vec[1];\n      sigma_vec[TENS2D_XY] += mu_qp * gamma * edot_vec[2];\n      */\n      \n      {\n        PetscReal factor = 1.0;\n        \n        //ierr = FaultSDFMollifer(coor_qp,2.0 * c->delta,NULL,&factor);CHKERRQ(ierr);\n        //printf(\"%+1.4e %+1.4e %+1.4e\\n\",coor_qp[0],coor_qp[1],factor);\n\n        c11 = factor * (2.0 * mu_qp + lambda_qp) * gamma;\n        c12 = factor * (lambda_qp) * gamma;\n        c21 = factor * (lambda_qp) * gamma;\n        c22 = factor * (2.0 * mu_qp + lambda_qp) * gamma;\n        c33 = factor * (mu_qp) * gamma;\n      }\n\n      /* compute stress @ quadrature point */\n      sigma_vec[TENS2D_XX] += c11 * edot_vec[0] + c12 * edot_vec[1];\n      sigma_vec[TENS2D_YY] += c21 * edot_vec[0] + c22 * edot_vec[1];\n      sigma_vec[TENS2D_XY] += c33 * edot_vec[2];\n      \n      sigma_trial[TENS2D_XX] = sigma_vec[TENS2D_XX];\n      sigma_trial[TENS2D_YY] = sigma_vec[TENS2D_YY];\n      sigma_trial[TENS2D_XY] = sigma_vec[TENS2D_XY];\n\n      \n      \n      inside_fault_region = PETSC_FALSE;\n      \n      ierr = FaultSDFQuery(coor_qp,c->delta,NULL,&inside_fault_region);CHKERRQ(ierr);\n      if (fabs(x_cell[1]) > c->delta) { inside_fault_region = PETSC_FALSE; }\n      \n      inside_fault_region = PETSC_FALSE;\n      if (fabs(x_cell[1]) < c->delta && fabs(x_cell[0]) < 15.0e3) { inside_fault_region = PETSC_TRUE; }\n\n      /* NOTE - Not sure how to generalize the notion of an off-fault normal stress for non-planar geometries */\n      /* NOTE - I'm not sure it is even well defined... */\n      if (inside_fault_region) { /* add the initial stress state on fault */\n        if (fabs(coor_qp[0]) < 1.5*1.0e3+1.0) {\n          sigma_trial[TENS2D_XY] += sigma_t_1;\n          sigma_trial[TENS2D_YY] += (-sigma_n_1); /* negative in compression */\n        } else {\n          sigma_trial[TENS2D_XY] += sigma_t_0;\n          sigma_trial[TENS2D_YY] += (-sigma_n_0); /* negative in compression */\n        }\n      } else {\n        sigma_trial[TENS2D_XY] += sigma_t_0;\n        sigma_trial[TENS2D_YY] += (-sigma_n_0); /* negative in compression */\n      }\n      \n      /* Make stress glut corrections here */\n      if (inside_fault_region) {\n        PetscReal x_plus[2],x_minus[2],v_plus[2],v_minus[2];\n        PetscReal normal[2],tangent[2],Vplus,Vminus,slip,slip_k,slip_rate;\n        PetscReal sigma_n,sigma_t,phi_p;\n        PetscReal e_inelastic_xy = 0.0;\n        PetscReal tau,mu_s,mu_d,D_c,mu_friction,T, ttau;\n\n        evaluate_sdf(NULL,coor_qp,&phi_p);\n        //if (phi_p < 0) printf(\"[e %d , q %d] x_qp %+1.4e , %+1.4e : phi %+1.4e \\n\",e,q,coor_qp[0],coor_qp[1],phi_p);\n        //printf(\"  x_qp -> phi %+1.4e\\n\",phi_p);\n        \n        ierr = FaultSDFGetPlusMinusCoor(coor_qp,c->delta,NULL,x_plus,x_minus);CHKERRQ(ierr);\n        //printf(\"  x_qp -> x+ %+1.4e , %+1.4e\\n\",x_plus[0],x_plus[1]);\n        //printf(\"  x_qp -> x- %+1.4e , %+1.4e\\n\",x_minus[0],x_minus[1]);\n        \n\n        \n#if 1\n        /* ================================================================ */\n        ierr = FaultSDFTabulateInterpolation_v2(c,LA_u,&dr_celldata[q],v_plus,v_minus);CHKERRQ(ierr);\n        \n        ierr = FaultSDFNormal(coor_qp,NULL,normal);CHKERRQ(ierr);\n        ierr = FaultSDFTangent(coor_qp,NULL,tangent);CHKERRQ(ierr);\n        \n        /* Resolve velocities at delta(+,-) onto fault */\n        /* [option 2] Removal of normal component method */\n        /* I like this approach as it does not require a tangenet vector */\n        {\n          PetscReal mag_vdotn;\n          \n          mag_vdotn =  (v_plus[0] * normal[0] +  v_plus[1] * normal[1]);\n          v_plus[0] = v_plus[0] - mag_vdotn * normal[0];\n          v_plus[1] = v_plus[1] - mag_vdotn * normal[1];\n          \n          /* Error checking is not generalized to non-planar faults */\n          if (fabs(v_plus[1]) > 1.0e-10) { /* error checking to ensure that the y component is completely removed */\n            printf(\"  phi %+1.8e : v+_y > 0 (%+1.8e)\\n\",phi_p,v_plus[1]);\n            printf(\"  |v+| %+1.8e\\n\",mag_vdotn);\n            printf(\"  x_qp -> v+ %+1.8e , %+1.8e\\n\",v_plus[0],v_plus[1]);\n            exit(1);\n          }\n          \n          mag_vdotn =  (v_minus[0] * normal[0] +  v_minus[1] * normal[1]);\n          v_minus[0] = v_minus[0] - mag_vdotn * normal[0];\n          v_minus[1] = v_minus[1] - mag_vdotn * normal[1];\n          \n          /* Error checking is not generalized to non-planar faults */\n          if (fabs(v_minus[1]) > 1.0e-10) {\n            printf(\"  phi %+1.8e : v-_y > 0 (%+1.8e)\\n\",phi_p,v_minus[1]);\n            printf(\"  |v-| %+1.8e\\n\",mag_vdotn);\n            printf(\"  x_qp -> v+ %+1.8e , %+1.8e\\n\",v_minus[0],v_minus[1]);\n            exit(1);\n          }\n        }\n        \n        /* I believe that extract the first component of the vector is perfectly valid for non-planar faults */\n        Vplus  = v_plus[0];\n        Vminus = v_minus[0];\n        slip = Vplus - Vminus;\n        \n        slip = dr_celldata[q].slip;\n        slip_rate = dr_celldata[q].slip_rate;\n        \n        //slip = (0.5*Vplus*c->delta - 0.5*Vminus*c->delta)/(2.0 * c->delta);\n        \n        /* ================================================================ */\n#endif\n        //slip = dr_celldata[q].slip;\n        \n        // n_i s_ij n_j\n        // = ni si0 n0 + ni si1 n1\n        // = n0 s00 n0 + n1 s10 n0 + n0 s01 n1 + n1 s11 n1\n        sigma_n = 0.0;\n        /* [option 1] */\n        sigma_n += normal[0] * sigma_trial[TENS2D_XX] * normal[0];\n        sigma_n += normal[1] * sigma_trial[TENS2D_XY] * normal[0];\n        sigma_n += normal[0] * sigma_trial[TENS2D_XY] * normal[1];\n        sigma_n += normal[1] * sigma_trial[TENS2D_YY] * normal[1];\n        /* [option 2] - only valid for a horizontal fault! */\n        /* option 1 and 2 are identical for horizontal fault */\n        sigma_n = sigma_trial[TENS2D_YY];\n        \n        sigma_t = 0.0;\n        /* [option 1] - uses the tangent vectors - yuck */\n        sigma_t += tangent[0] * sigma_trial[TENS2D_XX] * normal[0];\n        sigma_t += tangent[1] * sigma_trial[TENS2D_XY] * normal[0];\n        sigma_t += tangent[0] * sigma_trial[TENS2D_XY] * normal[1];\n        sigma_t += tangent[1] * sigma_trial[TENS2D_YY] * normal[1];\n        /* [option 2] - only valid for a horizontal fault! */\n        sigma_t = sigma_trial[TENS2D_XY];\n\n        sigma_t = sigma_t - mu_qp * gradu[2]; // new tweak [March 16]\n\n\n        dr_celldata[q].mu = 0;\n        e_inelastic_xy = 0.0;\n        sliding_active = PETSC_FALSE;\n\n        if (sigma_n < 0) { /* only consider inelastic corrections if in compression */\n          T = sqrt(sigma_t * sigma_t);\n          \n          /* Hard code linear slip weakening */\n          mu_s = c->mu_s;\n          mu_d = c->mu_d;\n          D_c  = c->D_c;\n          FricSW(&mu_friction, mu_s, mu_d, D_c, fabs(slip)); /* note the inclusion of making slip always positive */\n          \n          dr_celldata[q].mu = mu_friction;\n          \n          tau = -mu_friction * sigma_n;\n          if (tau < 0) {\n            printf(\"-mu sigma_n < 0 error\\n\");\n            exit(1);\n          }\n\n          \n          if (T > tau) {\n            PetscReal factor;\n            \n            ierr = FaultSDFMollifer(coor_qp,dy,NULL,&factor);CHKERRQ(ierr);\n\n            e_inelastic_xy = c->delta * (sigma_t - tau) / (mu_qp); // = du / dy\n            \n\n            /**Antiparallel condition between slip rate and critical shear */\n            ttau = tau;\n            if ( sigma_t < 0.0) //slip_rate=v(+)-v(-) defined following Dalguer\n            {\n              ttau = -tau;\n              //printf(\" [phi: %f, T: %f, tau: %f, Coor_x: %f,Coor_y: %f, slipe_rate: %f, sigma_t (PreBlend): %f, slip: %f, e_vec[2]: %f]\\n\", phi_p, T, tau, coor_qp[0], coor_qp[1], slip_rate, sigma_t, slip, e_vec[2]);\n            } \n            sigma_trial[TENS2D_XY] = ttau;\n            /**TP3 - Smoothing for p > 1 */\n            if(c->basisorder > 1)\n            {\n              //ierr = PetscTanHWeighting( &sigma_t,  sigma_t, tau, phi_p , 4.*(c->basisorder)/c->delta,  0.65*c->delta); CHKERRQ(ierr);\n              ierr = PetscTanHWeighting( &sigma_t,  sigma_t, ttau, phi_p , 6.5*(c->basisorder)/c->delta,  0.85*c->delta); CHKERRQ(ierr);\n              sigma_trial[TENS2D_XY] = sigma_t;\n            }\n\n            //printf(\"  sigma_xy %+1.8e\\n\",sigma_vec[TENS2D_XY]);\n            sliding_active = PETSC_TRUE;\n            dr_celldata[q].sliding = PETSC_TRUE;\n          } else {\n            e_inelastic_xy = 0.0;\n            slip_rate = 0;\n            sliding_active = PETSC_FALSE;\n          }\n\n          \n          \n          // Error checking / verification that consistency conditions are approximately satisfied\n          /*\n          if (T > fabs(tau)) {\n            if (fabs(sigma_trial[TENS2D_XY]) - fabs(tau) > 1e-7) {\n              printf(\"  [1] |T_t| - mu |T_n| %+1.12e < = ?\\n\",fabs(sigma_trial[TENS2D_XY]) - fabs(tau));\n            }\n            {\n              double a = slip_rate * fabs(sigma_trial[TENS2D_XY]) - fabs(slip_rate) * sigma_trial[TENS2D_XY];\n              \n              if (fabs(a) > 1.0e-10) {\n                printf(\"  [3] dot s |T_t| - |dot s| T_t %+1.12e = 0 ?\\n\",slip_rate * fabs(sigma_trial[TENS2D_XY]) - fabs(slip_rate) * sigma_trial[TENS2D_XY]);\n              }\n            }\n          }\n          */\n        }\n      }\n\n      /* Remove weird non-generalizable background stress state */\n\n      if (inside_fault_region) { /* remove the initial stress state on fault */\n        if (fabs(coor_qp[0]) < 1.5*1.0e3+1.0) {\n          sigma_trial[TENS2D_XY] -= sigma_t_1;\n          sigma_trial[TENS2D_YY] -= (-sigma_n_1); /* negative in compression */\n        } else {\n          sigma_trial[TENS2D_XY] -= sigma_t_0;\n          sigma_trial[TENS2D_YY] -= (-sigma_n_0); /* negative in compression */\n        }\n      } else {\n        sigma_trial[TENS2D_XY] -= sigma_t_0;\n        sigma_trial[TENS2D_YY] -= (-sigma_n_0); /* negative in compression */\n      }\n\n      /* These components weren't modified in the horizontal fault case - but they might be in general */\n      sigma_vec[TENS2D_XX] = sigma_trial[TENS2D_XX];\n      sigma_vec[TENS2D_YY] = sigma_trial[TENS2D_YY];\n      /* This component was modified in the horizontal fault case - it's likely it might also be modified in the general case */\n      sigma_vec[TENS2D_XY] = sigma_trial[TENS2D_XY];\n      \n      fac = detJ * c->w[q];\n      for (i=0; i<nbasis; i++) {\n        fe[2*i  ] += -fac * (dNidx[i] * sigma_vec[TENS2D_XX] + dNidy[i] * sigma_vec[TENS2D_XY]);\n        fe[2*i+1] += -fac * (dNidy[i] * sigma_vec[TENS2D_YY] + dNidx[i] * sigma_vec[TENS2D_XY]);\n      }\n      \n    }\n    ierr = VecSetValues(fl,nbasis*ndof,eldofs,fe,ADD_VALUES);CHKERRQ(ierr);\n  }\n  ierr = VecAssemblyBegin(fl);CHKERRQ(ierr);\n  ierr = VecAssemblyEnd(fl);CHKERRQ(ierr);\n  ierr = DMLocalToGlobalBegin(c->dm,fl,ADD_VALUES,F);CHKERRQ(ierr);\n  ierr = DMLocalToGlobalEnd(c->dm,fl,ADD_VALUES,F);CHKERRQ(ierr);\n  \n  ierr = VecRestoreArrayRead(vl,&LA_v);CHKERRQ(ierr);\n  ierr = DMRestoreLocalVector(c->dm,&vl);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(ul,&LA_u);CHKERRQ(ierr);\n  ierr = DMRestoreLocalVector(c->dm,&ul);CHKERRQ(ierr);\n  ierr = DMRestoreLocalVector(c->dm,&fl);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n\n  PetscFunctionReturn(0);\n}\n\n\n\nPetscErrorCode Update_StressGlut2d(SpecFECtx c,Vec u,Vec v,PetscReal dt)\n{\n  PetscErrorCode ierr;\n  PetscInt  e,nqp,q,i,nbasis,ndof;\n  PetscReal e_vec[3],gradu[4],gradv[4],gradv_q[9*9][4];\n  PetscInt  *element,*elnidx,*eldofs;\n  PetscReal *ux,*uy,*vx,*vy,*elcoords,detJ,*fieldU,*fieldV;\n  Vec       coor,ul,vl;\n  const PetscReal *LA_coor,*LA_u,*LA_v;\n  QPntIsotropicElastic *celldata;\n  DRVar                *dr_celldata;\n  \n  static PetscBool beenhere = PETSC_FALSE;\n  static PetscReal gmin[3],gmax[3];\n  PetscReal dx,dy;\n  \n  if (!beenhere) {\n    ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr);\n    beenhere = PETSC_TRUE;\n  }\n  dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g);\n  dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g);\n  \n  \n  \n  eldofs   = c->elbuf_dofs;\n  elcoords = c->elbuf_coor;\n  nbasis   = c->npe;\n  nqp      = c->nqp;\n  ndof     = c->dofs;\n  element  = c->element;\n  fieldU   = c->elbuf_field2;\n  fieldV   = c->elbuf_field3;\n  \n  ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  \n  ierr = DMGetLocalVector(c->dm,&ul);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalBegin(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(c->dm,u,INSERT_VALUES,ul);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(ul,&LA_u);CHKERRQ(ierr);\n  \n  ierr = DMGetLocalVector(c->dm,&vl);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalBegin(c->dm,v,INSERT_VALUES,vl);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(c->dm,v,INSERT_VALUES,vl);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(vl,&LA_v);CHKERRQ(ierr);\n  \n  ux = &fieldU[0];\n  uy = &fieldU[nbasis];\n  \n  vx = &fieldV[0];\n  vy = &fieldV[nbasis];\n  \n  for (e=0; e<c->ne; e++) {\n    PetscReal x_cell[] = {0,0};\n    \n    /* get element -> node map */\n    elnidx = &element[nbasis*e];\n    \n    /* generate dofs */\n    for (i=0; i<nbasis; i++) {\n      eldofs[2*i  ] = 2*elnidx[i];\n      eldofs[2*i+1] = 2*elnidx[i]+1;\n    }\n    \n    /* get element coordinates */\n    for (i=0; i<nbasis; i++) {\n      PetscInt nidx = elnidx[i];\n      elcoords[2*i  ] = LA_coor[2*nidx  ];\n      elcoords[2*i+1] = LA_coor[2*nidx+1];\n      x_cell[0] += elcoords[2*i  ];\n      x_cell[1] += elcoords[2*i+1];\n    }\n    x_cell[0] = x_cell[0] / ((PetscReal)nbasis);\n    x_cell[1] = x_cell[1] / ((PetscReal)nbasis);\n    \n    /* get element displacements & velocities */\n    for (i=0; i<nbasis; i++) {\n      PetscInt nidx = elnidx[i];\n      ux[i] = LA_u[2*nidx  ];\n      uy[i] = LA_u[2*nidx+1];\n      \n      vx[i] = LA_v[2*nidx  ];\n      vy[i] = LA_v[2*nidx+1];\n    }\n    \n    /* compute derivatives */\n    ElementEvaluateGeometry_CellWiseConstant2d(nbasis,elcoords,c->npe_1d,&detJ);\n    ElementEvaluateDerivatives_CellWiseConstant2d(nqp,nbasis,elcoords,\n                                                  c->npe_1d,c->dN_dxi,c->dN_deta,\n                                                  c->dN_dx,c->dN_dy);\n    \n    /* get access to element->quadrature points */\n    celldata = &c->cell_data[e];\n    \n    ierr = SpecFECtxGetDRCellData(c,e,&dr_celldata);CHKERRQ(ierr);\n    \n    for (q=0; q<c->nqp; q++) {\n      PetscReal *dNidx,*dNidy;\n      \n      dNidx = c->dN_dx[q];\n      dNidy = c->dN_dy[q];\n      \n      gradv[0] = gradv[1] = gradv[2] = gradv[3] = 0.0;\n      for (i=0; i<nbasis; i++) {\n        gradv[0] += dNidx[i] * vx[i];\n        gradv[1] += dNidy[i] * vx[i];\n        gradv[2] += dNidx[i] * vy[i];\n        gradv[3] += dNidy[i] * vy[i];\n      }\n      gradv_q[q][0] = gradv[0];\n      gradv_q[q][1] = gradv[1];\n      gradv_q[q][2] = gradv[2];\n      gradv_q[q][3] = gradv[3];\n    }\n    \n    \n    for (q=0; q<c->nqp; q++) {\n      PetscReal *dNidx,*dNidy;\n      PetscReal coor_qp[2];\n      PetscBool inside_fault_region;\n      \n      dNidx = c->dN_dx[q];\n      dNidy = c->dN_dy[q];\n      \n      /* compute strain @ quadrature point */\n      /*\n       e = Bu = [ d/dx  0    ][ u v ]^T\n       [ 0     d/dy ]\n       [ d/dy  d/dx ]\n       */\n      e_vec[0] = e_vec[1] = e_vec[2] = 0.0;\n      for (i=0; i<nbasis; i++) {\n        e_vec[0] += dNidx[i] * ux[i];\n        e_vec[1] += dNidy[i] * uy[i];\n        e_vec[2] += (dNidx[i] * uy[i] + dNidy[i] * ux[i]);\n      }\n      \n      gradu[0] = gradu[1] = gradu[2] = gradu[3] = 0.0;\n      gradv[0] = gradv[1] = gradv[2] = gradv[3] = 0.0;\n      for (i=0; i<nbasis; i++) {\n        gradu[0] += dNidx[i] * ux[i];\n        gradu[1] += dNidy[i] * ux[i];\n        gradu[2] += dNidx[i] * uy[i];\n        gradu[3] += dNidy[i] * uy[i];\n        \n        gradv[0] += dNidx[i] * vx[i];\n        gradv[1] += dNidy[i] * vx[i];\n        gradv[2] += dNidx[i] * vy[i];\n        gradv[3] += dNidy[i] * vy[i];\n      }\n      \n      coor_qp[0] = elcoords[2*q  ];\n      coor_qp[1] = elcoords[2*q+1];\n      \n      inside_fault_region = PETSC_FALSE;\n      \n      ierr = FaultSDFQuery(coor_qp,c->delta,NULL,&inside_fault_region);CHKERRQ(ierr);\n      if (fabs(x_cell[1]) > c->delta) { inside_fault_region = PETSC_FALSE; }\n      \n      inside_fault_region = PETSC_FALSE;\n      if (fabs(x_cell[1]) < c->delta && fabs(x_cell[0]) < 15.0e3) { inside_fault_region = PETSC_TRUE; }\n\n      //if (e == 720849) {\n      //  printf(\"e %d : xcell %+1.8e %+1.8e inside? %d\\n\",e,x_cell[0],x_cell[1],(int)inside_fault_region);\n      //}\n      \n      /* Make stress glut corrections here */\n      if (inside_fault_region) {\n        PetscReal x_plus[2],x_minus[2],plus[2],minus[2];\n        PetscReal normal[2],tangent[2],Uplus,Uminus,Vplus,Vminus,slip,slip_rate,phi_p;\n        \n        evaluate_sdf(NULL,coor_qp,&phi_p);\n        \n        ierr = FaultSDFGetPlusMinusCoor(coor_qp,c->delta,NULL,x_plus,x_minus);CHKERRQ(ierr);\n        \n        /* ================================================================ */\n        ierr = FaultSDFTabulateInterpolation_v2(c,LA_v,&dr_celldata[q],plus,minus);CHKERRQ(ierr);\n        ierr = FaultSDFNormal(coor_qp,NULL,normal);CHKERRQ(ierr);\n        ierr = FaultSDFTangent(coor_qp,NULL,tangent);CHKERRQ(ierr);\n        \n        /* Resolve velocities at delta(+,-) onto fault */\n        {\n          PetscReal mag_vdotn;\n          \n          mag_vdotn = plus[0] * normal[0] +  plus[1] * normal[1];\n          plus[0] = plus[0] - mag_vdotn * normal[0];\n          plus[1] = plus[1] - mag_vdotn * normal[1];\n          \n          mag_vdotn = minus[0] * normal[0] +  minus[1] * normal[1];\n          minus[0] = minus[0] - mag_vdotn * normal[0];\n          minus[1] = minus[1] - mag_vdotn * normal[1];\n        }\n\n        Vplus  = plus[0];\n        Vminus = minus[0];\n        slip_rate = Vplus - Vminus;\n\n        /* mid-point quadrature rule */\n        //slip_rate = (0.5*Vplus*c->delta - 0.5*Vminus*c->delta)/(2.0*c->delta);\n\n        \n        /* ================================================================ */\n        ierr = FaultSDFTabulateInterpolation_v2(c,LA_u,&dr_celldata[q],plus,minus);CHKERRQ(ierr);\n        ierr = FaultSDFNormal(coor_qp,NULL,normal);CHKERRQ(ierr);\n        ierr = FaultSDFTangent(coor_qp,NULL,tangent);CHKERRQ(ierr);\n        \n        /* Resolve displacement at delta(+,-) onto fault */\n        {\n          PetscReal mag_vdotn;\n          \n          mag_vdotn = plus[0] * normal[0] +  plus[1] * normal[1];\n          plus[0] = plus[0] - mag_vdotn * normal[0];\n          plus[1] = plus[1] - mag_vdotn * normal[1];\n          \n          mag_vdotn = minus[0] * normal[0] +  minus[1] * normal[1];\n          minus[0] = minus[0] - mag_vdotn * normal[0];\n          minus[1] = minus[1] - mag_vdotn * normal[1];\n        }\n        \n        Uplus  = plus[0];\n        Uminus = minus[0];\n        slip = Uplus - Uminus;\n        \n        /* mid-point quadrature rule */\n        //slip = (0.5*Uplus*c->delta - 0.5*Uminus*c->delta)/(2.0*c->delta);\n\n        /* ================================================================ */\n        \n        \n        if (dr_celldata[q].sliding) {\n          /*\n          dr_celldata[q].slip_rate = slip_rate;\n          dr_celldata[q].slip      += slip_rate * dt;\n\n          dr_celldata[q].slip_rate  = (slip - dr_celldata[q].slip)/dt;\n          dr_celldata[q].slip       = slip;\n          */\n\n          dr_celldata[q].slip_rate = slip_rate;\n          dr_celldata[q].slip      = slip;\n        }\n        \n      }\n      \n    }\n  }\n  \n  ierr = VecRestoreArrayRead(vl,&LA_v);CHKERRQ(ierr);\n  ierr = DMRestoreLocalVector(c->dm,&vl);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(ul,&LA_u);CHKERRQ(ierr);\n  ierr = DMRestoreLocalVector(c->dm,&ul);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\n\nPetscErrorCode AssembleBilinearForm_Mass2d(SpecFECtx c,Vec A)\n{\n  PetscErrorCode ierr;\n  PetscInt  e,index,q,i,nbasis,ndof;\n  PetscInt  *element,*elnidx,*eldofs;\n  PetscReal *elcoords,*Me,detJ;\n  Vec       coor;\n  const PetscReal *LA_coor;\n  QPntIsotropicElastic *celldata;\n  \n  ierr = VecZeroEntries(A);CHKERRQ(ierr);\n  \n  eldofs   = c->elbuf_dofs;\n  elcoords = c->elbuf_coor;\n  nbasis   = c->npe;\n  ndof     = c->dofs;\n  Me       = c->elbuf_field;\n  element  = c->element;\n  \n  ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  \n  for (e=0; e<c->ne; e++) {\n    /* get element -> node map */\n    elnidx = &element[nbasis*e];\n    \n    /* generate dofs */\n    for (i=0; i<nbasis; i++) {\n      \n      eldofs[2*i  ] = 2*elnidx[i];\n      eldofs[2*i+1] = 2*elnidx[i]+1;\n    }\n    \n    /* get element coordinates */\n    for (i=0; i<nbasis; i++) {\n      PetscInt nidx = elnidx[i];\n      elcoords[2*i  ] = LA_coor[2*nidx  ];\n      elcoords[2*i+1] = LA_coor[2*nidx+1];\n    }\n    \n    ElementEvaluateGeometry_CellWiseConstant2d(nbasis,elcoords,c->npe_1d,&detJ);\n    \n    /* get access to element->quadrature points */\n    celldata = &c->cell_data[e];\n\n    for (q=0; q<nbasis; q++) {\n      PetscReal            fac,Me_ii;\n      \n      fac = detJ * c->w[q];\n      \n      Me_ii = fac * (celldata->rho);\n      \n      /* \\int u0v0 dV */\n      index = 2*q;\n      Me[index] = Me_ii;\n      \n      /* \\int u1v1 dV */\n      index = 2*q + 1;\n      Me[index] = Me_ii;\n    }\n    ierr = VecSetValuesLocal(A,nbasis*ndof,eldofs,Me,ADD_VALUES);CHKERRQ(ierr);\n  }\n  ierr = VecAssemblyBegin(A);CHKERRQ(ierr);\n  ierr = VecAssemblyEnd(A);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(coor,&LA_coor);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode ElastoDynamicsConvertLame2Velocity(PetscReal rho,PetscReal mu,PetscReal lambda,PetscReal *Vs,PetscReal *Vp)\n{\n  if (Vs) { *Vs = PetscSqrtReal(mu/rho); }\n  if (Vp) { *Vp = PetscSqrtReal( (lambda + 2.0*mu)/rho); }\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode ElastoDynamicsComputeTimeStep_2d(SpecFECtx ctx,PetscReal *_dt)\n{\n  PetscInt e,q,order;\n  PetscReal dt_min,dt_min_g,polynomial_fac;\n  //QPntIsotropicElastic *qpdata;\n  PetscReal gmin[3],gmax[3],min_el_r,dx,dy;\n  PetscErrorCode ierr;\n  QPntIsotropicElastic *celldata;\n  \n  *_dt = PETSC_MAX_REAL;\n  dt_min = PETSC_MAX_REAL;\n  \n  order = ctx->basisorder;\n  polynomial_fac = 1.0 / (2.0 * (PetscReal)order + 1.0);\n  \n  ierr = DMGetBoundingBox(ctx->dm,gmin,gmax);CHKERRQ(ierr);\n  dx = (gmax[0] - gmin[0])/((PetscReal)ctx->mx_g);\n  dy = (gmax[1] - gmin[1])/((PetscReal)ctx->my_g);\n  \n  min_el_r = dx;\n  min_el_r = PetscMin(min_el_r,dy);\n  \n  /* find smallest dx across the element in local coordinates */\n  {\n    PetscInt  n;\n    PetscReal sep2min,sep2;\n    \n    sep2min = 1.0e32;\n    for (n=0; n<ctx->npe_1d-1; n++) {\n      sep2 = PetscAbsReal(ctx->xi1d[n+1] - ctx->xi1d[n]);\n      /*printf(\" xi %+1.4e [n] : xi %+1.4e [n+1] : delta_xi %+1.6e\\n\",ctx->xi1d[n],ctx->xi1d[n+1],sep2); */\n      if (sep2 < sep2min) {\n        sep2min = sep2;\n      }\n    }\n    \n    polynomial_fac = 1.0;\n    min_el_r = min_el_r * ( sep2min / 2.0 ); /* the factor 2.0 here is associated with the size of the element in the local coordinate system xi \\in [-1,+1] */\n  }\n  \n  \n\n  \n  for (e=0; e<ctx->ne; e++) {\n    PetscReal max_el_Vp,value;\n    \n    /* get max Vp for element */\n    max_el_Vp = PETSC_MIN_REAL;\n    \n    /* get access to element->quadrature points */\n    celldata = &ctx->cell_data[e];\n    \n    for (q=0; q<ctx->nqp; q++) {\n      PetscReal qp_rho,qp_mu,qp_lambda,qp_Vp;\n      \n      qp_rho    = celldata->rho;\n      qp_mu     = celldata->mu;\n      qp_lambda = celldata->lambda;\n      \n      ierr = ElastoDynamicsConvertLame2Velocity(qp_rho,qp_mu,qp_lambda,0,&qp_Vp);CHKERRQ(ierr);\n      \n      max_el_Vp = PetscMax(max_el_Vp,qp_Vp);\n    }\n    \n    value = polynomial_fac * 1.0 * min_el_r / max_el_Vp;\n    \n    dt_min = PetscMin(dt_min,value);\n  }\n  ierr = MPI_Allreduce(&dt_min,&dt_min_g,1,MPIU_REAL,MPIU_MIN,PETSC_COMM_WORLD);CHKERRQ(ierr);\n  \n  *_dt = dt_min_g;\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode RecordUV(SpecFECtx c,PetscReal time,PetscReal xr[],Vec u,Vec v)\n{\n  FILE *fp = NULL;\n  PetscReal gmin[3],gmax[3],dx,dy,sep2min,sep2;\n  const PetscReal *LA_u,*LA_v,*LA_c;\n  Vec coor;\n  static PetscBool beenhere = PETSC_FALSE;\n  PetscErrorCode ierr;\n  PetscInt ei,ej,n,nid,eid,*element,*elbasis;\n  static char filename[PETSC_MAX_PATH_LEN];\n  \n  if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,\"Needs updating to support MPI\");\n  if (!beenhere) {\n    ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN-1,\"receiverCP-%Dx%D-p%D.dat\",c->mx_g,c->my_g,c->basisorder);CHKERRQ(ierr);\n  }\n  \n  ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr);\n  dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g);\n  ei = (xr[0] - gmin[0])/dx; /* todo - needs to be sub-domain gmin */\n  \n  dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g);\n  ej = (xr[1] - gmin[1])/dy; /* todo - needs to be sub-domain gmin */\n  \n  eid = ei + ej * c->mx;\n  \n  /* get element -> node map */\n  element = c->element;\n  elbasis = &element[c->npe*eid];\n  \n  ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr);\n  \n  // find closest //\n  sep2min = 1.0e32;\n  nid = -1;\n  for (n=0; n<c->npe; n++) {\n    sep2  = (xr[0]-LA_c[2*elbasis[n]])*(xr[0]-LA_c[2*elbasis[n]]);\n    sep2 += (xr[1]-LA_c[2*elbasis[n]+1])*(xr[1]-LA_c[2*elbasis[n]+1]);\n    if (sep2 < sep2min) {\n      nid = elbasis[n];\n      sep2min = sep2;\n    }\n  }\n  \n  if (!beenhere) {\n    fp = fopen(filename,\"w\");\n    if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",filename);\n    fprintf(fp,\"# SpecFECtx meta data\\n\");\n    fprintf(fp,\"#   mx %d : my %d : basis order %d\\n\",c->mx_g,c->my_g,c->basisorder);\n    fprintf(fp,\"# Receiver meta data\\n\");\n    fprintf(fp,\"#   + receiver location: x,y %+1.8e %+1.8e\\n\",xr[0],xr[1]);\n    fprintf(fp,\"#   + takes displ/velo from basis nearest to requested receiver location\\n\");\n    fprintf(fp,\"#   + receiver location: x,y %+1.8e %+1.8e --mapped to nearest node --> %+1.8e %+1.8e\\n\",xr[0],xr[1],LA_c[2*nid],LA_c[2*nid+1]);\n    fprintf(fp,\"# Time series header\\n\");\n    fprintf(fp,\"#   time ux uy vx vy\\n\");\n    beenhere = PETSC_TRUE;\n  } else {\n    fp = fopen(filename,\"a\");\n    if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",filename);\n  }\n  \n  ierr = VecGetArrayRead(u,&LA_u);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(v,&LA_v);CHKERRQ(ierr);\n  \n  fprintf(fp,\"%1.4e %+1.8e %+1.8e %+1.8e %+1.8e\\n\",time,LA_u[2*nid],LA_u[2*nid+1],LA_v[2*nid],LA_v[2*nid+1]);\n  \n  ierr = VecRestoreArrayRead(v,&LA_v);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(u,&LA_u);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr);\n  \n  fclose(fp);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode RecordUV_interp(SpecFECtx c,PetscReal time,PetscReal xr[],Vec u,Vec v)\n{\n  FILE *fp = NULL;\n  PetscReal gmin[3],gmax[3],dx,dy,ur[2],vr[2];\n  const PetscReal *LA_u,*LA_v;\n  static PetscBool beenhere = PETSC_FALSE;\n  PetscErrorCode ierr;\n  PetscInt k,ei,ej,eid,*element,*elbasis;\n  static PetscReal N[400];\n  static char filename[PETSC_MAX_PATH_LEN];\n  \n  if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,\"Needs updating to support MPI\");\n  if (!beenhere) {\n    ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN-1,\"receiver-%Dx%D-p%D.dat\",c->mx_g,c->my_g,c->basisorder);CHKERRQ(ierr);\n  }\n  \n  if (!beenhere) {\n    fp = fopen(filename,\"w\");\n    if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",filename);\n    fprintf(fp,\"# SpecFECtx meta data\\n\");\n    fprintf(fp,\"#   mx %d : my %d : basis order %d\\n\",c->mx_g,c->my_g,c->basisorder);\n    fprintf(fp,\"# Receiver meta data\\n\");\n    fprintf(fp,\"#   + receiver location: x,y %+1.8e %+1.8e\\n\",xr[0],xr[1]);\n    fprintf(fp,\"#   + records displ/velo at requested receiver location through interpolating the FE solution\\n\");\n    fprintf(fp,\"# Time series header\\n\");\n    fprintf(fp,\"#   time ux uy vx vy\\n\");\n  } else {\n    fp = fopen(filename,\"a\");\n    if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",filename);\n  }\n  \n  /* get containing element */\n  ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr);\n  dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g);\n  ei = (xr[0] - gmin[0])/dx; /* todo - needs to be sub-domain gmin */\n  \n  dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g);\n  ej = (xr[1] - gmin[1])/dy;\n  \n  eid = ei + ej * c->mx;\n  \n  /* get element -> node map */\n  element = c->element;\n  elbasis = &element[c->npe*eid];\n  \n  if (!beenhere) {\n    PetscInt nbasis,i,j;\n    PetscReal **N_s1,**N_s2,xri[2],xi,eta,x0,y0;\n    const PetscReal *LA_c;\n    Vec coor;\n    \n    /* compute xi,eta */\n    ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr);\n    \n    x0 = gmin[0] + ei*dx; /* todo - needs to be sub-domain gmin */\n    y0 = gmin[1] + ej*dy;\n    \n    // (xi - (-1))/2 = (x - x0)/dx\n    xi = 2.0*(xr[0] - x0)/dx - 1.0;\n    eta = 2.0*(xr[1] - y0)/dy - 1.0;\n    \n    /* compute basis */\n    ierr = TabulateBasis1d_CLEGENDRE(1,&xi,c->basisorder,&nbasis,&N_s1);CHKERRQ(ierr);\n    ierr = TabulateBasis1d_CLEGENDRE(1,&eta,c->basisorder,&nbasis,&N_s2);CHKERRQ(ierr);\n    \n    k = 0;\n    for (j=0; j<c->npe_1d; j++) {\n      for (i=0; i<c->npe_1d; i++) {\n        N[k] = N_s1[0][i] * N_s2[0][j];\n        k++;\n      }\n    }\n    \n    ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr);\n    \n    xri[0] = xri[1] = 0.0;\n    for (k=0; k<c->npe; k++) {\n      PetscInt nid = elbasis[k];\n      \n      xri[0] += N[k] * LA_c[2*nid+0];\n      xri[1] += N[k] * LA_c[2*nid+1];\n    }\n    \n    \n    PetscPrintf(PETSC_COMM_SELF,\"# receiver location: x,y %+1.8e %+1.8e -- interpolated coordinate --> %+1.8e %+1.8e\\n\",xr[0],xr[1],xri[0],xri[1]);\n    \n    ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr);\n    ierr = PetscFree(N_s1[0]);CHKERRQ(ierr);\n    ierr = PetscFree(N_s1);CHKERRQ(ierr);\n    ierr = PetscFree(N_s2[0]);CHKERRQ(ierr);\n    ierr = PetscFree(N_s2);CHKERRQ(ierr);\n  }\n  \n  \n  ierr = VecGetArrayRead(u,&LA_u);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(v,&LA_v);CHKERRQ(ierr);\n  \n  ur[0] = ur[1] = vr[0] = vr[1] = 0.0;\n  for (k=0; k<c->npe; k++) {\n    PetscInt nid = elbasis[k];\n    \n    ur[0] += N[k] * LA_u[2*nid+0];\n    ur[1] += N[k] * LA_u[2*nid+1];\n    \n    vr[0] += N[k] * LA_v[2*nid+0];\n    vr[1] += N[k] * LA_v[2*nid+1];\n  }\n  \n  fprintf(fp,\"%1.4e %+1.8e %+1.8e %+1.8e %+1.8e\\n\",time,ur[0],ur[1],vr[0],vr[1]);\n  \n  ierr = VecRestoreArrayRead(v,&LA_v);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(u,&LA_u);CHKERRQ(ierr);\n  \n  beenhere = PETSC_TRUE;\n  fclose(fp);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode RecordUVA_MultipleStations_NearestGLL_SEQ(SpecFECtx c,PetscReal time,PetscInt nr,PetscReal xr[],Vec u,Vec v,Vec a)\n{\n  FILE             *fp = NULL;\n  const PetscReal  *LA_u,*LA_v,*LA_a;\n  static PetscBool beenhere = PETSC_FALSE;\n  static char      filename[PETSC_MAX_PATH_LEN];\n  static PetscInt  *nid_list = NULL;\n  PetscInt         r;\n  PetscErrorCode   ierr;\n\n  \n  if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,\"Supports sequential only\");\n  if (!beenhere) {\n    const PetscReal *LA_c;\n    Vec coor;\n    PetscReal gmin[3],gmax[3],dx,dy,sep2min,sep2;\n    PetscInt ei,ej,n,nid,eid,*element,*elbasis;\n    \n    ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN-1,\"closestqpsource-receiverCP-uva-%Dx%D-p%D.dat\",c->mx_g,c->my_g,c->basisorder);CHKERRQ(ierr);\n    ierr = PetscMalloc1(nr,&nid_list);CHKERRQ(ierr);\n    \n    ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr);\n    ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr);\n    ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr);\n    \n    for (r=0; r<nr; r++) {\n      \n      if (xr[2*r+0] < gmin[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, x-coordinate (%+1.4e) < min(domain).x (%+1.4e)\",r,xr[2*r+0],gmin[0]);\n      if (xr[2*r+1] < gmin[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, y-coordinate (%+1.4e) < min(domain).y (%+1.4e)\",r,xr[2*r+1],gmin[1]);\n      if (xr[2*r+0] > gmax[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, x-coordinate (%+1.4e) > max(domain).x (%+1.4e)\",r,xr[2*r+0],gmax[0]);\n      if (xr[2*r+1] > gmax[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, y-coordinate (%+1.4e) > max(domain).y (%+1.4e)\",r,xr[2*r+1],gmax[1]);\n      \n      dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g);\n      ei = (xr[2*r+0] - gmin[0])/dx;\n      if (ei == c->mx_g) ei--;\n      \n      dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g);\n      ej = (xr[2*r+1] - gmin[1])/dy;\n      if (ej == c->my_g) ej--;\n      \n      eid = ei + ej * c->mx_g;\n    \n      /* get element -> node map */\n      element = c->element;\n      elbasis = &element[c->npe*eid];\n    \n      // find closest //\n      sep2min = 1.0e32;\n      nid = -1;\n      for (n=0; n<c->npe; n++) {\n        sep2  = (xr[2*r+0]-LA_c[2*elbasis[n]])*(xr[2*r+0]-LA_c[2*elbasis[n]]);\n        sep2 += (xr[2*r+1]-LA_c[2*elbasis[n]+1])*(xr[2*r+1]-LA_c[2*elbasis[n]+1]);\n        if (sep2 < sep2min) {\n          nid = elbasis[n];\n          sep2min = sep2;\n        }\n      }\n      nid_list[r] = nid;\n    }\n  \n    fp = fopen(filename,\"w\");\n    if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",filename);\n    fprintf(fp,\"# SpecFECtx meta data\\n\");\n    fprintf(fp,\"#   mx %d : my %d : basis order %d\\n\",c->mx_g,c->my_g,c->basisorder);\n    fprintf(fp,\"# Receiver meta data\\n\");\n    fprintf(fp,\"#   + number receiver locations: %d\\n\",nr);\n    fprintf(fp,\"#   + takes displ/velo/accel from basis nearest to requested receiver location\\n\");\n    for (r=0; r<nr; r++) {\n      fprintf(fp,\"#   + receiver location [%d]: x,y %+1.8e %+1.8e\\n\",r,xr[2*r+0],xr[2*r+1]);\n      fprintf(fp,\"#   +   mapped to nearest node --> %+1.8e %+1.8e\\n\",LA_c[2*nid_list[r]],LA_c[2*nid_list[r]+1]);\n    }\n    fprintf(fp,\"# Time series header <field>(<column index>)\\n\");\n    fprintf(fp,\"#   time(1)\\n\");\n    for (r=0; r<nr; r++) {\n      PetscInt offset = 1 + r*6; /* 1 is for time */\n      \n      fprintf(fp,\"#     ux(%d) uy(%d) vx(%d) vy(%d) ax(%d) ay(%d) -> station [%d]\\n\",offset+1,offset+2,offset+3,offset+4,offset+5,offset+6,r);\n    }\n    ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr);\n    beenhere = PETSC_TRUE;\n  } else {\n    fp = fopen(filename,\"a\");\n    if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",filename);\n  }\n  \n  ierr = VecGetArrayRead(u,&LA_u);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(v,&LA_v);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(a,&LA_a);CHKERRQ(ierr);\n  \n  fprintf(fp,\"%1.4e\",time);\n  for (r=0; r<nr; r++) {\n    fprintf(fp,\" %+1.8e %+1.8e %+1.8e %+1.8e %+1.8e %+1.8e\",LA_u[2*nid_list[r]],LA_u[2*nid_list[r]+1],LA_v[2*nid_list[r]],LA_v[2*nid_list[r]+1],LA_a[2*nid_list[r]],LA_a[2*nid_list[r]+1]);\n  }\n  fprintf(fp,\"\\n\");\n  \n  ierr = VecRestoreArrayRead(a,&LA_a);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(v,&LA_v);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(u,&LA_u);CHKERRQ(ierr);\n  \n  fclose(fp);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode RecordUVA_MultipleStations_NearestGLL_MPI(SpecFECtx c,PetscReal time,PetscInt nr,PetscReal xr[],Vec u,Vec v,Vec a)\n{\n  FILE             *fp = NULL;\n  const PetscReal  *LA_u,*LA_v,*LA_a,*LA_c;\n  static PetscBool beenhere = PETSC_FALSE;\n  static char      filename[PETSC_MAX_PATH_LEN];\n  static PetscInt  *nid_list = NULL;\n  static PetscInt  *eid_list = NULL;\n  static PetscInt  *gll_list = NULL;\n  static PetscInt  nr_local = 0;\n  PetscInt         r,k;\n  Vec              lu,lv,la,coor;\n  PetscErrorCode   ierr;\n  \n  \n  if (!beenhere) {\n    PetscReal       gmin[3],gmax[3],gmin_domain[3],gmax_domain[3],dx,dy,sep2min,sep2;\n    PetscInt        ei,ej,n,nid,gllid,eid,*element,*elbasis;\n    \n    ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN-1,\"closestqpsource-receiverCP-uva-%Dx%D-p%D-rank%d.dat\",c->mx_g,c->my_g,c->basisorder,(int)c->rank);CHKERRQ(ierr);\n    ierr = PetscMalloc1(nr,&nid_list);CHKERRQ(ierr);\n    ierr = PetscMalloc1(nr,&eid_list);CHKERRQ(ierr);\n    ierr = PetscMalloc1(nr,&gll_list);CHKERRQ(ierr);\n    for (r=0; r<nr; r++) {\n      nid_list[r] = -1;\n      eid_list[r] = -1;\n      gll_list[r] = -1;\n    }\n\n    ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr);\n    ierr = SpecFECtxGetLocalBoundingBox(c,gmin_domain,gmax_domain);CHKERRQ(ierr);\n    \n    ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr);\n    ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr);\n    \n    for (r=0; r<nr; r++) {\n      int count,recv_count;\n      PetscBool receiver_found = PETSC_TRUE;\n      int rank,rank_min_g;\n      \n      if (xr[2*r+0] < gmin[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, x-coordinate (%+1.4e) < min(domain).x (%+1.4e)\",r,xr[2*r+0],gmin[0]);\n      if (xr[2*r+1] < gmin[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, y-coordinate (%+1.4e) < min(domain).y (%+1.4e)\",r,xr[2*r+1],gmin[1]);\n      if (xr[2*r+0] > gmax[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, x-coordinate (%+1.4e) > max(domain).x (%+1.4e)\",r,xr[2*r+0],gmax[0]);\n      if (xr[2*r+1] > gmax[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, y-coordinate (%+1.4e) > max(domain).y (%+1.4e)\",r,xr[2*r+1],gmax[1]);\n      \n      if (xr[2*r+0] < gmin_domain[0]) receiver_found = PETSC_FALSE;\n      if (xr[2*r+1] < gmin_domain[1]) receiver_found = PETSC_FALSE;\n      if (xr[2*r+0] > gmax_domain[0]) receiver_found = PETSC_FALSE;\n      if (xr[2*r+1] > gmax_domain[1]) receiver_found = PETSC_FALSE;\n      \n      dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g);\n      ei = (xr[2*r+0] - gmin_domain[0])/dx;\n      if (ei == c->mx) ei--;\n      \n      dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g);\n      ej = (xr[2*r+1] - gmin_domain[1])/dy;\n      if (ej == c->my) ej--;\n      \n      if (ei < 0) receiver_found = PETSC_FALSE;\n      if (ej < 0) receiver_found = PETSC_FALSE;\n      \n      if (ei > c->mx) receiver_found = PETSC_FALSE;\n      if (ej > c->my) receiver_found = PETSC_FALSE;\n      \n      nid = -1;\n      gllid = -1;\n      if (receiver_found) {\n        eid = ei + ej * c->mx;\n        \n        /* get element -> node map */\n        element = c->element;\n        elbasis = &element[c->npe*eid];\n        \n        // find closest //\n        sep2min = 1.0e32;\n        for (n=0; n<c->npe; n++) {\n          sep2  = (xr[2*r+0]-LA_c[2*elbasis[n]])*(xr[2*r+0]-LA_c[2*elbasis[n]]);\n          sep2 += (xr[2*r+1]-LA_c[2*elbasis[n]+1])*(xr[2*r+1]-LA_c[2*elbasis[n]+1]);\n          if (sep2 < sep2min) {\n            nid = elbasis[n];\n            gllid = n;\n            sep2min = sep2;\n          }\n        }\n      }\n      \n      /* check for duplicates */\n      count = 0;\n      if (receiver_found) {\n        count = 1;\n      }\n      ierr = MPI_Allreduce(&count,&recv_count,1,MPI_INT,MPI_SUM,PETSC_COMM_WORLD);CHKERRQ(ierr);\n      \n      if (recv_count == 0) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,\"A receiver was defined but no rank claimed it\");\n      \n      if (recv_count > 1) {\n        /* resolve duplicates */\n        \n        rank = (int)c->rank;\n        if (!receiver_found) {\n          rank = (int)c->size;\n        }\n        ierr = MPI_Allreduce(&rank,&rank_min_g,1,MPI_INT,MPI_MIN,PETSC_COMM_WORLD);CHKERRQ(ierr);\n        if (rank == rank_min_g) {\n          PetscPrintf(PETSC_COMM_SELF,\"[RecordUVA]  + Multiple ranks located receiver (%+1.4e,%+1.4e) - rank %d claiming ownership\\n\",xr[2*r+0],xr[2*r+1],rank_min_g);\n        }\n        \n        /* mark non-owning ranks as not claiming source */\n        if (rank != rank_min_g) {\n          receiver_found = PETSC_FALSE;\n        }\n      }\n\n      if (receiver_found) {\n        nid_list[r] = nid;\n        eid_list[r] = eid;\n        gll_list[r] = gllid;\n        nr_local++;\n      }\n    }\n    \n    fp = fopen(filename,\"w\");\n    if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",filename);\n    fprintf(fp,\"# SpecFECtx meta data\\n\");\n    fprintf(fp,\"#   mx %d : my %d : basis order %d\\n\",c->mx_g,c->my_g,c->basisorder);\n    fprintf(fp,\"# Receiver meta data\\n\");\n    fprintf(fp,\"#   + number receiver locations: %d\\n\",nr);\n    fprintf(fp,\"#   + number receiver locations <local>: %d\\n\",nr_local);\n    fprintf(fp,\"#   + takes displ/velo/accel from basis nearest to requested receiver location\\n\");\n    for (r=0; r<nr; r++) {\n      if (nid_list[r] == -1) { continue; }\n      fprintf(fp,\"#   + receiver location [%d]: x,y %+1.8e %+1.8e\\n\",r,xr[2*r+0],xr[2*r+1]);\n      fprintf(fp,\"#   +   mapped to nearest node --> %+1.8e %+1.8e\\n\",LA_c[2*nid_list[r]],LA_c[2*nid_list[r]+1]);\n    }\n\n    if (nr_local != 0) {\n      PetscInt count = 0;\n\n      fprintf(fp,\"# Time series header <field>(<column index>)\\n\");\n      fprintf(fp,\"#   time(1)\\n\");\n\n    \n      for (r=0; r<nr; r++) {\n        PetscInt offset;\n        \n        if (nid_list[r] == -1) { continue; }\n\n        offset = 1 + count*7; /* 1 is for time */\n        \n        fprintf(fp,\"#     ux(%d) uy(%d) vx(%d) vy(%d) ax(%d) ay(%d) curl(v) (%d)-> station [%d]\\n\",offset+1,offset+2,offset+3,offset+4,offset+5,offset+6,offset+7,r);\n        count++;\n      }\n    } else {\n      fprintf(fp,\"# <note> No receivers found on this sub-domain\\n\");\n      fprintf(fp,\"# <note> This file will remain empty\\n\");\n    }\n\n    ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr);\n    \n    fclose(fp);\n    fp = NULL;\n  }\n  \n  if (!beenhere) {\n    char metafname[PETSC_MAX_PATH_LEN];\n    FILE *fp_meta = NULL;\n    int *owned,*owned_g;\n    \n    ierr = PetscSNPrintf(metafname,PETSC_MAX_PATH_LEN-1,\"closestqpsource-receiverCP-uva-%Dx%D-p%D.mpimeta\",c->mx_g,c->my_g,c->basisorder);CHKERRQ(ierr);\n    \n    ierr = PetscMalloc1(nr,&owned);CHKERRQ(ierr);\n    ierr = PetscMalloc1(nr,&owned_g);CHKERRQ(ierr);\n    for (r=0; r<nr; r++) {\n      owned[r] = -1;\n      if (nid_list[r] != -1) { owned[r] = (int)c->rank; }\n    }\n    ierr = MPI_Allreduce(owned,owned_g,nr,MPI_INT,MPI_MAX,PETSC_COMM_WORLD);CHKERRQ(ierr);\n    \n    if (c->rank == 0) {\n      fp_meta = fopen(metafname,\"w\");\n      if (!fp_meta) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",metafname);\n    \n      fprintf(fp_meta,\"# SpecFECtx parallel/MPI meta data\\n\");\n      fprintf(fp_meta,\"#   mx %d : my %d : basis order %d\\n\",c->mx_g,c->my_g,c->basisorder);\n      fprintf(fp_meta,\"# Receiver meta data\\n\");\n      fprintf(fp_meta,\"#   + number receiver locations: %d\\n\",nr);\n      for (r=0; r<nr; r++) {\n        fprintf(fp_meta,\"#   + receiver [%d]: mapped to MPI rank %d\\n\",r,owned_g[r]);\n      }\n      \n      fclose(fp_meta);\n    }\n    \n    ierr = PetscFree(owned_g);CHKERRQ(ierr);\n    ierr = PetscFree(owned);CHKERRQ(ierr);\n  }\n  \n  beenhere = PETSC_TRUE;\n\n  ierr = DMGetCoordinatesLocal(c->dm,&coor);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr);\n  \n  ierr = DMGetLocalVector(c->dm,&lu);CHKERRQ(ierr);\n  ierr = DMGetLocalVector(c->dm,&lv);CHKERRQ(ierr);\n  ierr = DMGetLocalVector(c->dm,&la);CHKERRQ(ierr);\n  \n  ierr = DMGlobalToLocalBegin(c->dm,u,INSERT_VALUES,lu);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(c->dm,u,INSERT_VALUES,lu);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalBegin(c->dm,v,INSERT_VALUES,lv);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(c->dm,v,INSERT_VALUES,lv);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalBegin(c->dm,a,INSERT_VALUES,la);CHKERRQ(ierr);\n  ierr = DMGlobalToLocalEnd(c->dm,a,INSERT_VALUES,la);CHKERRQ(ierr);\n  \n  ierr = VecGetArrayRead(lu,&LA_u);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(lv,&LA_v);CHKERRQ(ierr);\n  ierr = VecGetArrayRead(la,&LA_a);CHKERRQ(ierr);\n  \n  if (nr_local != 0) {\n    fp = fopen(filename,\"a\");\n    if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",filename);\n  \n    fprintf(fp,\"%1.4e\",time);\n  \n    for (r=0; r<nr; r++) {\n      PetscInt eidx,gllidx;\n      PetscReal *elcoor,*elvelocity;\n      PetscReal dvxdy,dvydx,curl;\n      PetscReal *grad_N_xi[2];\n      PetscReal *grad_N_x[2];\n      \n      if (eid_list[r] == -1) { continue; }\n      \n      /* write the components of u,v,a */\n      fprintf(fp,\" %+1.8e %+1.8e %+1.8e %+1.8e %+1.8e %+1.8e\",LA_u[2*nid_list[r]],LA_u[2*nid_list[r]+1],LA_v[2*nid_list[r]],LA_v[2*nid_list[r]+1],LA_a[2*nid_list[r]],LA_a[2*nid_list[r]+1]);\n      \n      /* compute and write the k^th component of the curl(v) */\n      eidx   = eid_list[r];\n      gllidx = gll_list[r];\n      \n      grad_N_xi[0] = c->dN_dxi[gllidx];\n      grad_N_xi[1] = c->dN_deta[gllidx];\n      \n      grad_N_x[0] = c->dN_dx[gllidx];\n      grad_N_x[1] = c->dN_dy[gllidx];\n      \n      elcoor = c->elbuf_field;\n      elvelocity = c->elbuf_field2;\n      \n      for (k=0; k<c->npe; k++) {\n        PetscInt basisid = c->element[c->npe*eidx + k];\n        \n        elcoor[2*k+0] = LA_c[2*basisid + 0];\n        elcoor[2*k+1] = LA_c[2*basisid + 1];\n        \n        elvelocity[2*k+0] = LA_v[2*basisid + 0];\n        elvelocity[2*k+1] = LA_v[2*basisid + 1];\n      }\n      \n      ElementEvaluateDerivatives_CellWiseConstant2d(1,c->npe,elcoor,c->npe_1d,&grad_N_xi[0],&grad_N_xi[1],&grad_N_x[0],&grad_N_x[1]);\n      \n      dvxdy = 0.0;\n      dvydx = 0.0;\n      for (k=0; k<c->npe; k++) {\n        PetscReal vx,vy;\n        \n        vx = elvelocity[2*k+0];\n        vy = elvelocity[2*k+1];\n        \n        dvxdy += grad_N_x[1][k] * vx;\n        dvydx += grad_N_x[0][k] * vy;\n      }\n      curl = dvydx - dvxdy;\n      fprintf(fp,\" %+1.8e\",curl);\n    }\n    \n    fprintf(fp,\"\\n\");\n\n    if (fp) {\n      fclose(fp);\n      fp = NULL;\n    }\n  }\n  \n  ierr = VecRestoreArrayRead(a,&LA_a);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(v,&LA_v);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(u,&LA_u);CHKERRQ(ierr);\n  ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr);\n\n  ierr = DMRestoreLocalVector(c->dm,&la);CHKERRQ(ierr);\n  ierr = DMRestoreLocalVector(c->dm,&lv);CHKERRQ(ierr);\n  ierr = DMRestoreLocalVector(c->dm,&lu);CHKERRQ(ierr);\n\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode RecordUVA_MultipleStations_NearestGLL(SpecFECtx c,PetscReal time,PetscInt nr,PetscReal xr[],Vec u,Vec v,Vec a)\n{\n  PetscErrorCode ierr;\n  \n  //if (c->size == 1) {\n  //ierr = RecordUVA_MultipleStations_NearestGLL_SEQ(c,time,nr,xr,u,v,a);CHKERRQ(ierr);\n  //} else {\n  ierr = RecordUVA_MultipleStations_NearestGLL_MPI(c,time,nr,xr,u,v,a);CHKERRQ(ierr);\n  //}\n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode RecordDRVar_MultipleStations_NearestGLL_SEQ(SpecFECtx c,PetscReal time,PetscInt nr,PetscReal xr[])\n{\n  FILE             *fp = NULL;\n  static PetscBool beenhere = PETSC_FALSE;\n  static char      filename[PETSC_MAX_PATH_LEN];\n  static PetscInt  *qid_list = NULL;\n  static PetscInt  *nid_list = NULL;\n  static PetscInt  *eid_list = NULL;\n  PetscInt         r;\n  PetscErrorCode   ierr;\n  \n  \n  if (c->size > 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,\"Supports sequential only\");\n  if (!beenhere) {\n    const PetscReal *LA_c;\n    Vec coor;\n    PetscReal gmin[3],gmax[3],dx,dy,sep2min,sep2;\n    PetscInt ei,ej,n,qid,nid,eid,*element,*elbasis;\n    \n    ierr = PetscSNPrintf(filename,PETSC_MAX_PATH_LEN-1,\"receiverCP-dr-%Dx%D-p%D.dat\",c->mx_g,c->my_g,c->basisorder);CHKERRQ(ierr);\n    ierr = PetscMalloc1(nr,&qid_list);CHKERRQ(ierr);\n    ierr = PetscMalloc1(nr,&nid_list);CHKERRQ(ierr);\n    ierr = PetscMalloc1(nr,&eid_list);CHKERRQ(ierr);\n    \n    ierr = DMGetBoundingBox(c->dm,gmin,gmax);CHKERRQ(ierr);\n    ierr = DMGetCoordinates(c->dm,&coor);CHKERRQ(ierr);\n    ierr = VecGetArrayRead(coor,&LA_c);CHKERRQ(ierr);\n    \n    for (r=0; r<nr; r++) {\n      \n      if (xr[2*r+0] < gmin[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, x-coordinate (%+1.4e) < min(domain).x (%+1.4e)\",r,xr[2*r+0],gmin[0]);\n      if (xr[2*r+1] < gmin[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, y-coordinate (%+1.4e) < min(domain).y (%+1.4e)\",r,xr[2*r+1],gmin[1]);\n      if (xr[2*r+0] > gmax[0]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, x-coordinate (%+1.4e) > max(domain).x (%+1.4e)\",r,xr[2*r+0],gmax[0]);\n      if (xr[2*r+1] > gmax[1]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_USER,\"Receiver %D, y-coordinate (%+1.4e) > max(domain).y (%+1.4e)\",r,xr[2*r+1],gmax[1]);\n      \n      dx = (gmax[0] - gmin[0])/((PetscReal)c->mx_g);\n      ei = (xr[2*r+0] - gmin[0])/dx;\n      if (ei == c->mx_g) ei--;\n      \n      dy = (gmax[1] - gmin[1])/((PetscReal)c->my_g);\n      ej = (xr[2*r+1] - gmin[1])/dy;\n      if (ej == c->my_g) ej--;\n      \n      eid = ei + ej * c->mx_g;\n      eid_list[r] = eid;\n      \n      \n      {\n        PetscBool inside;\n        PetscInt e,i;\n        \n        sep2min = 1.0e32;\n        element = c->element;\n        for (e=0; e<c->ne; e++) {\n          PetscReal xcell[] = {0,0};\n          \n          elbasis = &element[c->npe*e];\n          for (i=0; i<c->npe; i++) {\n            xcell[0] += LA_c[2*elbasis[i]+0];\n            xcell[1] += LA_c[2*elbasis[i]+1];\n          }\n          xcell[0] = xcell[0] / ((PetscReal)c->npe);\n          xcell[1] = xcell[1] / ((PetscReal)c->npe);\n\n          ierr = FaultSDFQuery(xcell,c->delta,NULL,&inside);CHKERRQ(ierr);\n          if (inside) {\n            sep2  = (xr[2*r+0]-xcell[0])*(xr[2*r+0]-xcell[0]);\n            sep2 += (xr[2*r+1]-xcell[1])*(xr[2*r+1]-xcell[1]);\n            if (sep2 < sep2min) {\n              eid = e;\n              sep2min = sep2;\n            }\n          }\n        }\n      }\n      eid_list[r] = eid;\n      \n      \n      /* get element -> node map */\n      element = c->element;\n      elbasis = &element[c->npe*eid];\n      \n      // find closest //\n      sep2min = 1.0e32;\n      nid = -1;\n      qid = -1;\n      for (n=0; n<c->npe; n++) {\n        sep2  = (xr[2*r+0]-LA_c[2*elbasis[n]])*(xr[2*r+0]-LA_c[2*elbasis[n]]);\n        sep2 += (xr[2*r+1]-LA_c[2*elbasis[n]+1])*(xr[2*r+1]-LA_c[2*elbasis[n]+1]);\n        if (sep2 < sep2min) {\n          nid = elbasis[n];\n          qid = n;\n          sep2min = sep2;\n        }\n      }\n      nid_list[r] = nid;\n      qid_list[r] = qid;\n    }\n    \n    fp = fopen(filename,\"w\");\n    if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",filename);\n    fprintf(fp,\"# SpecFECtx meta data\\n\");\n    fprintf(fp,\"#   mx %d : my %d : basis order %d\\n\",c->mx_g,c->my_g,c->basisorder);\n    fprintf(fp,\"# Receiver meta data\\n\");\n    fprintf(fp,\"#   + number receiver locations: %d\\n\",nr);\n    fprintf(fp,\"#   + takes DR variables from quadrature point nearest to requested receiver location\\n\");\n    for (r=0; r<nr; r++) {\n      PetscReal xcell[] = {0,0};\n      PetscInt i;\n      \n      fprintf(fp,\"#   + receiver location [%d]: x,y %+1.8e %+1.8e\\n\",r,xr[2*r+0],xr[2*r+1]);\n      fprintf(fp,\"#   +   mapped to nearest node --> %+1.8e %+1.8e\\n\",LA_c[2*nid_list[r]],LA_c[2*nid_list[r]+1]);\n      fprintf(fp,\"#   +   mapped to nearest element/quad-point --> %d %d\\n\",eid_list[r],qid_list[r]);\n      elbasis = &element[c->npe*eid_list[r]];\n      for (i=0; i<c->npe; i++) {\n        xcell[0] += LA_c[2*elbasis[i]+0];\n        xcell[1] += LA_c[2*elbasis[i]+1];\n      }\n      xcell[0] = xcell[0] / ((PetscReal)c->npe);\n      xcell[1] = xcell[1] / ((PetscReal)c->npe);\n      fprintf(fp,\"#   +   mapped to nearest element --> %d with centroid %+1.8e %+1.8e\\n\",eid_list[r],xcell[0],xcell[1]);\n    }\n    fprintf(fp,\"# Time series header <field>(<column index>)\\n\");\n    fprintf(fp,\"#   time(1)\\n\");\n    for (r=0; r<nr; r++) {\n      PetscInt offset = 1 + r*4; /* 1 is for time */\n      \n      fprintf(fp,\"#     slip(%d) sliprate(%d) mu(%d) sliding(%d) -> station [%d]\\n\",offset+1,offset+2,offset+3,offset+4,r);\n    }\n    ierr = VecRestoreArrayRead(coor,&LA_c);CHKERRQ(ierr);\n    beenhere = PETSC_TRUE;\n  } else {\n    fp = fopen(filename,\"a\");\n    if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",filename);\n  }\n  \n  fprintf(fp,\"%1.4e\",time);\n  for (r=0; r<nr; r++) {\n    DRVar *cell_data;\n    PetscInt e_index,q_index;\n    \n    e_index = eid_list[r];\n    q_index = qid_list[r];\n    ierr = SpecFECtxGetDRCellData(c,e_index,&cell_data);CHKERRQ(ierr);\n    \n    fprintf(fp,\" %+1.8e %+1.8e %+1.8e %+1.2e\",cell_data[q_index].slip,cell_data[q_index].slip_rate,cell_data[q_index].mu,(double)cell_data[q_index].sliding);\n  }\n  fprintf(fp,\"\\n\");\n  \n  fclose(fp);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SE2WaveViewer_JSON(SpecFECtx ctx,PetscInt step,PetscReal time,\n                                  const char data_description[],PetscInt len,const char *fieldname[],const Vec field[],\n                                  const char pbin[],const char jfilename[])\n{\n  PetscErrorCode ierr;\n  char str[PETSC_MAX_PATH_LEN];\n  FILE *fp = NULL;\n  PetscMPIInt commrank;\n  PetscInt k;\n  \n  ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&commrank);CHKERRQ(ierr);\n  if (commrank != 0) PetscFunctionReturn(0);\n  \n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"%s\",jfilename);CHKERRQ(ierr);\n  fp = fopen(str,\"w\");\n  if (!fp) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_FILE_OPEN,\"Failed to open file \\\"%s\\\"\",str);\n  \n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"{\\\"se2wave\\\":{\");CHKERRQ(ierr); fprintf(fp,\"%s\\n\",str);\n  \n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"time\\\": %1.12e\",time);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"step\\\": %D\",step);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"spatial_dimension\\\": %D\",ctx->dim);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"mx\\\": %D\",ctx->mx_g);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"my\\\": %D\",ctx->my_g);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"nx\\\": %D\",ctx->nx_g);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"ny\\\": %D\",ctx->ny_g);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"basis_degree\\\": %D\",ctx->basisorder);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  \n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"fields\\\": [ \");CHKERRQ(ierr); fprintf(fp,\"%s\",str);\n  for (k=0; k<len; k++) {\n    ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"\\\"null\\\"\");CHKERRQ(ierr);\n    if (field[k]) {\n      ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"\\\"%s\\\"\",fieldname[k]);CHKERRQ(ierr);\n    }\n    \n    if (k != (len-1)) { fprintf(fp,\"%s, \",str);\n    } else { fprintf(fp,\"%s\",str); }\n  }\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\" ]\");CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  \n  //ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"datafile\\\": \\\"%s\\\"\",pbin);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"data\\\":{\");CHKERRQ(ierr); fprintf(fp,\"%s\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"    \\\"description\\\": \\\"%s\\\"\",data_description);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  \n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"    \\\"fields\\\": [ \");CHKERRQ(ierr); fprintf(fp,\"%s\",str);\n  for (k=0; k<len; k++) {\n    ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"\\\"null\\\"\");CHKERRQ(ierr);\n    if (field[k]) {\n      ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"\\\"%s\\\"\",fieldname[k]);CHKERRQ(ierr);\n    }\n    \n    if (k != (len-1)) { fprintf(fp,\"%s, \",str);\n    } else { fprintf(fp,\"%s\",str); }\n  }\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\" ]\");CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  \n  \n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"    \\\"writer\\\": \\\"petsc_binary\\\"\");CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"    \\\"type\\\": \\\"Vec\\\"\");CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"    \\\"filename\\\": \\\"%s\\\"\",pbin);CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  /* petsc always writes binary in big endian ordering (even on a small endian machine) */\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"    \\\"endian\\\": \\\"big\\\"\");CHKERRQ(ierr); fprintf(fp,\"%s\\n\",str);\n  /*\n   #ifdef WORDSIZE_BIGENDIAN\n   ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"    \\\"endian\\\": \\\"big\\\"\");CHKERRQ(ierr); fprintf(fp,\"%s\\n\",str);\n   #else\n   ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"    \\\"endian\\\": \\\"little\\\"\");CHKERRQ(ierr); fprintf(fp,\"%s\\n\",str);\n   #endif\n   */\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  }\");CHKERRQ(ierr); fprintf(fp,\"%s,\\n\",str);\n  \n  \n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"  \\\"version\\\": [1,0,0]\");CHKERRQ(ierr); fprintf(fp,\"%s\\n\",str);\n  ierr = PetscSNPrintf(str,PETSC_MAX_PATH_LEN-1,\"}}\");CHKERRQ(ierr); fprintf(fp,\"%s\\n\",str);\n  \n  fclose(fp);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SE2WaveCoordinateViewerViewer(SpecFECtx ctx,PetscInt step,PetscReal time,const char prefix[])\n{\n  PetscErrorCode ierr;\n  PetscViewer vu;\n  Vec coor = NULL;\n  char fname[PETSC_MAX_PATH_LEN];\n  \n  ierr = DMGetCoordinates(ctx->dm,&coor);CHKERRQ(ierr);\n  if (!coor) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,\"Must have a valid coordinate vector\");\n  \n  ierr = PetscSNPrintf(fname,PETSC_MAX_PATH_LEN-1,\"%s_coor.pbin\",prefix);CHKERRQ(ierr);\n  \n  {\n    char jname[PETSC_MAX_PATH_LEN];\n    Vec input[] = {NULL};\n    const char *fieldname[] = { \"coor\" };\n    \n    input[0] = coor;\n    ierr = PetscSNPrintf(jname,PETSC_MAX_PATH_LEN-1,\"%s_coor.json\",prefix);CHKERRQ(ierr);\n    ierr = SE2WaveViewer_JSON(ctx,step,time,\"coordinates\",1,fieldname,input,fname,jname);CHKERRQ(ierr);\n  }\n  \n  ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,fname,FILE_MODE_WRITE,&vu);CHKERRQ(ierr);\n  \n  ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->mx_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);\n  ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->my_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);\n  ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->nx_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);\n  ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->ny_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);\n  \n  ierr = VecView(coor,vu);CHKERRQ(ierr);\n  ierr = PetscViewerDestroy(&vu);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode SE2WaveWaveFieldViewer(SpecFECtx ctx,PetscInt step,PetscReal time,Vec u,Vec v,const char prefix[])\n{\n  PetscErrorCode ierr;\n  PetscViewer vu;\n  char fname[PETSC_MAX_PATH_LEN];\n  \n  if (!u && !v) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,\"At least one of the displacement or velocity vectors must be non-NULL\");\n  \n  ierr = PetscSNPrintf(fname,PETSC_MAX_PATH_LEN-1,\"%s_wavefield.pbin\",prefix);CHKERRQ(ierr);\n  \n  {\n    char jname[PETSC_MAX_PATH_LEN];\n    Vec input[] = {NULL,NULL};\n    const char *fieldname[] = { \"u\", \"v\" };\n    input[0] = u;\n    input[1] = v;\n    \n    ierr = PetscSNPrintf(jname,PETSC_MAX_PATH_LEN-1,\"%s_wavefield.json\",prefix);CHKERRQ(ierr);\n    ierr = SE2WaveViewer_JSON(ctx,step,time,\"wavefield\",2,fieldname,input,fname,jname);CHKERRQ(ierr);\n  }\n  \n  ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,fname,FILE_MODE_WRITE,&vu);CHKERRQ(ierr);\n  \n  ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->mx_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);\n  ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->my_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);\n  ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->nx_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);\n  ierr = PetscViewerBinaryWrite(vu,(void*)&ctx->ny_g,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);\n  \n  ierr = PetscViewerBinaryWrite(vu,(void*)&step,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);\n  ierr = PetscViewerBinaryWrite(vu,(void*)&time,1,PETSC_REAL,PETSC_FALSE);CHKERRQ(ierr);\n  \n  if (u) { ierr = VecView(u,vu);CHKERRQ(ierr); }\n  if (v) { ierr = VecView(v,vu);CHKERRQ(ierr); }\n  ierr = PetscViewerDestroy(&vu);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nPetscErrorCode se2dr_demo(PetscInt mx,PetscInt my)\n{\n  PetscErrorCode ierr;\n  SpecFECtx ctx;\n  PetscInt p,k,nt,of;\n  PetscViewer viewer;\n  Vec u,v,a,f,g,Md;\n  PetscReal time,dt,time_max;\n  PetscInt nrecv;\n  PetscReal *xr_list;\n  PetscBool dump_ic_src_vts = PETSC_FALSE;\n  PetscBool ignore_receiver_output = PETSC_FALSE;\n  PetscReal nrm,max,min,dx,dy;\n  char vts_fname[PETSC_MAX_PATH_LEN];\n  \n  \n  ierr = PetscOptionsGetBool(NULL,NULL,\"-dump_ic_src\",&dump_ic_src_vts,NULL);CHKERRQ(ierr);\n  ierr = PetscOptionsGetBool(NULL,NULL,\"-ignore_receiver_output\",&ignore_receiver_output,NULL);CHKERRQ(ierr);\n  \n  /*\n    Create the structured mesh for the spectral element method.\n   The default mesh is defined over the domain [0,1]^2.\n  */\n  ierr = SpecFECtxCreate(&ctx);CHKERRQ(ierr);\n  p = 2;\n  ierr = PetscOptionsGetInt(NULL,NULL,\"-bdegree\",&p,NULL);CHKERRQ(ierr);\n  ierr = SpecFECtxCreateMesh(ctx,2,mx,my,PETSC_DECIDE,p,2);CHKERRQ(ierr);\n\n  /*\n   Define your domain by shifting and scaling the default [0,1]^2 domain\n  */\n  {\n    PetscReal alpha = 20.0e3;\n    PetscReal scale[] = {  3.0*alpha, 3.0*alpha };\n    PetscReal shift[] = { -1.5*alpha,-1.5*alpha };\n    \n    ierr = SpecFECtxScaleMeshCoords(ctx,scale,shift);CHKERRQ(ierr);\n  }\n\n  /* \n   Specify fault dimensions\n  */\n  {\n    PetscReal gmin[3],gmax[3];\n    \n    ierr = DMGetBoundingBox(ctx->dm,gmin,gmax);CHKERRQ(ierr);\n    dx = (gmax[0] - gmin[0])/((PetscReal)ctx->mx_g);\n    dy = (gmax[1] - gmin[1])/((PetscReal)ctx->my_g);\n  }\n  PetscPrintf(PETSC_COMM_WORLD,\"[se2dr] cell sizes: dx = %1.4e, dy = %1.4e\\n\",dx,dy);\n  \n  \n  ctx->delta = 25.0;\n  ierr = PetscOptionsGetReal(NULL,NULL,\"-delta\",&ctx->delta,NULL);CHKERRQ(ierr);\n  {\n    PetscBool found;\n    PetscReal delta_factor = 0.0;\n    \n    found = PETSC_FALSE;\n    ierr = PetscOptionsGetReal(NULL,NULL,\"-delta_cell_factor\",&delta_factor,&found);CHKERRQ(ierr);\n    if (found) {\n      ctx->delta = dy * delta_factor;\n    }\n  }\n  PetscPrintf(PETSC_COMM_WORLD,\"[se2dr] using fault delta = %1.4e\\n\",ctx->delta);\n  PetscPrintf(PETSC_COMM_WORLD,\"[se2dr] elements across fault = %1.4e\\n\",2.0 * ctx->delta/dy);\n  \n  //ierr = FaultSDFInit_v1(ctx);CHKERRQ(ierr);\n  ierr = FaultSDFInit_v2(ctx);CHKERRQ(ierr);\n  \n  /*\n   Specify the material properties for the domain.\n   This function sets constant material properties in every cell.\n   More general methods can be easily added.\n  */\n  ierr = SpecFECtxSetConstantMaterialProperties_Velocity(ctx,6000.0 ,3464.0, 2670.0);CHKERRQ(ierr); // vp,vs,rho\n  /* Linear slip weakening parameters */\n  ctx->mu_s = 0.677;\n  ctx->mu_d = 0.525;\n  ctx->D_c = 0.40;\n\n  \n  ierr = DMCreateGlobalVector(ctx->dm,&u);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)u,\"disp\");CHKERRQ(ierr);\n  ierr = DMCreateGlobalVector(ctx->dm,&v);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)v,\"velo\");CHKERRQ(ierr);\n  ierr = DMCreateGlobalVector(ctx->dm,&a);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)a,\"accl\");CHKERRQ(ierr);\n  ierr = DMCreateGlobalVector(ctx->dm,&f);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)f,\"f\");CHKERRQ(ierr);\n  ierr = DMCreateGlobalVector(ctx->dm,&g);CHKERRQ(ierr); ierr = PetscObjectSetName((PetscObject)g,\"g\");CHKERRQ(ierr);\n  ierr = DMCreateGlobalVector(ctx->dm,&Md);CHKERRQ(ierr);\n  \n  ierr = VecZeroEntries(u);CHKERRQ(ierr);\n  \n  /*\n   Write out the mesh and intial values for the displacement, velocity and acceleration (u,v,a)\n  */\n  if (dump_ic_src_vts) {\n    ierr = PetscViewerVTKOpen(PETSC_COMM_WORLD,\"uva.vts\",FILE_MODE_WRITE,&viewer);CHKERRQ(ierr);\n    ierr = VecView(u,viewer);CHKERRQ(ierr);\n    ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);\n  }\n  \n  ierr = AssembleBilinearForm_Mass2d(ctx,Md);CHKERRQ(ierr);\n  \n  /*\n   Define the location of the receivers\n  */\n  nrecv = 8;\n  ierr = PetscMalloc1(nrecv*2,&xr_list);CHKERRQ(ierr);\n  xr_list[0] = 4.0e3;\n  xr_list[1] = ctx->delta;\n\n  xr_list[2] = 4.0e3;\n  xr_list[3] = -ctx->delta;\n\n  xr_list[4] = 6.0e3;\n  xr_list[5] = ctx->delta;\n\n  xr_list[6] = 6.0e3;\n  xr_list[7] = -ctx->delta;\n\n  xr_list[8] = 8.0e3;\n  xr_list[9] = ctx->delta;\n\n  xr_list[10] = 8.0e3;\n  xr_list[11] = -ctx->delta;\n\n  xr_list[12] = 10.0e3;\n  xr_list[13] = ctx->delta;\n\n  xr_list[14] = 10.0e3;\n  xr_list[15] = -ctx->delta;\n\n\n  /* Initialize time loop */\n  k = 0;\n  time = 0.0;\n  \n  time_max = 0.4;\n  ierr = PetscOptionsGetReal(NULL,NULL,\"-tmax\",&time_max,NULL);CHKERRQ(ierr);\n  PetscPrintf(PETSC_COMM_WORLD,\"[se2dr] Requested time period: %1.4e\\n\",time_max);\n  \n  ierr = ElastoDynamicsComputeTimeStep_2d(ctx,&dt);CHKERRQ(ierr);\n  dt = dt * 0.5;\n  ierr = PetscOptionsGetReal(NULL,NULL,\"-dt\",&dt,NULL);CHKERRQ(ierr);\n  PetscPrintf(PETSC_COMM_WORLD,\"[se2dr] Using time step size: %1.4e\\n\",dt);\n  \n  nt = 1000000;\n  nt = (PetscInt)(time_max / dt ) + 4;\n  ierr = PetscOptionsGetInt(NULL,NULL,\"-nt\",&nt,NULL);CHKERRQ(ierr);\n  PetscPrintf(PETSC_COMM_WORLD,\"[se2dr] Estimated number of time steps: %D\\n\",nt);\n  \n  of = 5000;\n  ierr = PetscOptionsGetInt(NULL,NULL,\"-of\",&of,NULL);CHKERRQ(ierr);\n  \n  ierr = SE2WaveCoordinateViewerViewer(ctx,0,0.0,\"default_mesh\");CHKERRQ(ierr);\n  {\n    char prefix[PETSC_MAX_PATH_LEN];\n    \n    ierr = PetscSNPrintf(prefix,PETSC_MAX_PATH_LEN-1,\"step-%.4D\",0);CHKERRQ(ierr);\n    ierr = SE2WaveWaveFieldViewer(ctx,k,time,u,v,prefix);CHKERRQ(ierr);\n  }\n  \n  if (k%of == 0) {\n    ierr = PetscSNPrintf(vts_fname,PETSC_MAX_PATH_LEN-1,\"step-%.4D.vts\",0);CHKERRQ(ierr);\n    ierr = PetscViewerVTKOpen(PETSC_COMM_WORLD,vts_fname,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr);\n    ierr = VecView(u,viewer);CHKERRQ(ierr);\n    ierr = VecView(v,viewer);CHKERRQ(ierr);\n    ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);\n  }\n  \n  /* Perform time stepping */\n  for (k=1; k<=nt; k++) {\n    \n    time = time + dt;\n    \n    ierr = VecAXPY(u,dt,v);CHKERRQ(ierr); /* u_{n+1} = u_{n} + dt.v_{n} */\n    \n    ierr = VecAXPY(u,0.5*dt*dt,a);CHKERRQ(ierr); /* u_{n+1} = u_{n+1} + 0.5.dt^2.a_{n} */\n    \n    ierr = VecAXPY(v,0.5*dt,a);CHKERRQ(ierr); /* v' = v_{n} + 0.5.dt.a_{n} */\n    \n    /* Compute f = -F^{int}( u_{n+1} ) */\n    //printf(\"[time:%f] \",time);\n    ierr = AssembleLinearForm_ElastoDynamics_StressGlut2d_tpv(ctx,u,v,dt,time,0.5*dt,f);CHKERRQ(ierr);\n    //ierr = AssembleLinearForm_ElastoDynamics_StressGlut2d_tpv_cellwise(ctx,u,v,dt,time,1.1*dt,f);CHKERRQ(ierr);\n    //ierr = AssembleLinearForm_ElastoDynamics_StressGlut2d_tpv_cellwise_v2(ctx,u,v,dt,time,1.1*dt,f);CHKERRQ(ierr);\n    \n    /* Update force; F^{ext}_{n+1} = f + S(t_{n+1}) g(x) */\n    ierr = VecAXPY(f,1.0,g);CHKERRQ(ierr);\n    \n    /* \"Solve\"; a_{n+1} = M^{-1} f */\n    ierr = VecPointwiseDivide(a,f,Md);CHKERRQ(ierr);\n    \n    /* Update velocity */\n    ierr = VecAXPY(v,0.5*dt,a);CHKERRQ(ierr); /* v_{n+1} = v' + 0.5.dt.a_{n+1} */\n    \n    /* Update slip-rate & slip */\n    ierr = Update_StressGlut2d(ctx,u,v,dt);CHKERRQ(ierr);\n\n    \n    if (k%10 == 0) {\n      PetscPrintf(PETSC_COMM_WORLD,\"[step %9D] time = %1.4e : dt = %1.4e \\n\",k,time,dt);\n      VecNorm(u,NORM_2,&nrm);\n      VecMin(u,0,&min);\n      VecMax(u,0,&max); PetscPrintf(PETSC_COMM_WORLD,\"  [displacement] max = %+1.4e : min = %+1.4e : l2 = %+1.4e \\n\",max,min,nrm);\n      VecNorm(v,NORM_2,&nrm);\n      VecMin(v,0,&min);\n      VecMax(v,0,&max); PetscPrintf(PETSC_COMM_WORLD,\"  [velocity]     max = %+1.4e : min = %+1.4e : l2 = %+1.4e \\n\",max,min,nrm);\n    }\n\n    /*\n      Write out the u,v,a values at each receiver\n    */\n    if (!ignore_receiver_output) {\n      ierr = RecordUVA_MultipleStations_NearestGLL(ctx,time,nrecv,xr_list,u,v,a);CHKERRQ(ierr);\n      ierr = RecordDRVar_MultipleStations_NearestGLL_SEQ(ctx,time,nrecv,xr_list);CHKERRQ(ierr);\n    }\n    \n    if (k%of == 0) {\n      ierr = PetscSNPrintf(vts_fname,PETSC_MAX_PATH_LEN-1,\"step-%.4D.vts\",k);CHKERRQ(ierr);\n      ierr = PetscViewerVTKOpen(PETSC_COMM_WORLD,vts_fname,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr);\n      ierr = VecView(u,viewer);CHKERRQ(ierr);\n      ierr = VecView(v,viewer);CHKERRQ(ierr);\n      ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);\n    }\n    if (k%of == 0) {\n      char prefix[PETSC_MAX_PATH_LEN];\n      ierr = PetscSNPrintf(prefix,PETSC_MAX_PATH_LEN-1,\"step-%.4D\",k);CHKERRQ(ierr);\n      ierr = SE2WaveWaveFieldViewer(ctx,k,time,u,v,prefix);CHKERRQ(ierr);\n    }\n    \n    if (time >= time_max) {\n      break;\n    }\n  }\n  PetscPrintf(PETSC_COMM_WORLD,\"[step %9D] time = %1.4e : dt = %1.4e \\n\",k,time,dt);\n  VecNorm(u,NORM_2,&nrm);\n  VecMin(u,0,&min);\n  VecMax(u,0,&max); PetscPrintf(PETSC_COMM_WORLD,\"  [displacement] max = %+1.4e : min = %+1.4e : l2 = %+1.4e \\n\",max,min,nrm);\n  VecNorm(v,NORM_2,&nrm);\n  VecMin(v,0,&min);\n  VecMax(v,0,&max); PetscPrintf(PETSC_COMM_WORLD,\"  [velocity]     max = %+1.4e : min = %+1.4e : l2 = %+1.4e \\n\",max,min,nrm);\n  \n  /* plot last snapshot */\n  ierr = PetscSNPrintf(vts_fname,PETSC_MAX_PATH_LEN-1,\"step-%.4D.vts\",k);CHKERRQ(ierr);\n  ierr = PetscViewerVTKOpen(PETSC_COMM_WORLD,vts_fname,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr);\n  ierr = VecView(u,viewer);CHKERRQ(ierr);\n  ierr = VecView(v,viewer);CHKERRQ(ierr);\n  ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);\n  \n  \n  ierr = PetscFree(xr_list);CHKERRQ(ierr);\n  ierr = VecDestroy(&u);CHKERRQ(ierr);\n  ierr = VecDestroy(&v);CHKERRQ(ierr);\n  ierr = VecDestroy(&a);CHKERRQ(ierr);\n  ierr = VecDestroy(&f);CHKERRQ(ierr);\n  ierr = VecDestroy(&Md);CHKERRQ(ierr);\n  ierr = VecDestroy(&g);CHKERRQ(ierr);\n  \n  PetscFunctionReturn(0);\n}\n\nint main(int argc,char **args)\n{\n  PetscErrorCode ierr;\n  PetscInt       mx,my;\n  PetscMPIInt    size;\n  \n  ierr = PetscInitialize(&argc,&args,(char*)0,NULL);CHKERRQ(ierr);\n  ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);\n  \n  mx = my = 8;\n  ierr = PetscOptionsGetInt(NULL,NULL,\"-mx\",&mx,NULL);CHKERRQ(ierr);\n  my = mx;\n  ierr = PetscOptionsGetInt(NULL,NULL,\"-my\",&my,NULL);CHKERRQ(ierr);\n\n  ierr = se2dr_demo(mx,my);CHKERRQ(ierr);\n  \n  ierr = PetscFinalize();\n  return(ierr);\n}\n", "meta": {"hexsha": "285c51aa09126a7f1ee053b372dcddc8b875f407", "size": 131063, "ext": "c", "lang": "C", "max_stars_repo_path": "se2dr/Versions/se2drTpv.c", "max_stars_repo_name": "Nicolucas/C-Scripts", "max_stars_repo_head_hexsha": "2608df5c2e635ad16f422877ff440af69f98f960", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "se2dr/Versions/se2drTpv.c", "max_issues_repo_name": "Nicolucas/C-Scripts", "max_issues_repo_head_hexsha": "2608df5c2e635ad16f422877ff440af69f98f960", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "se2dr/Versions/se2drTpv.c", "max_forks_repo_name": "Nicolucas/C-Scripts", "max_forks_repo_head_hexsha": "2608df5c2e635ad16f422877ff440af69f98f960", "max_forks_repo_licenses": ["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.9469582705, "max_line_length": 217, "alphanum_fraction": 0.5910516317, "num_tokens": 45728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.38332036532237385}}
{"text": "/*\nCopyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com>\nLicensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n*/\n \n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <cblas.h>\n#include \"morn_tensor.h\"\n\nstruct TensorResizePara\n{\n    MLayer *prev;\n    \n    int height;\n    int width;\n    \n    int res_valid;\n};\n\nvoid *mTensorResizePara(MList *ini,char *name)\n{\n    struct TensorResizePara *para = (struct TensorResizePara *)mMalloc(sizeof(struct TensorResizePara));\n   \n    para->prev = mNetworkLayer(ini,mINIRead(ini,name,\"prev\"));\n    mException((para->prev == NULL),EXIT,\"invalid prev\");\n    para->res_valid = (strcmp(\"Input\",mLayerType(para->prev))!=0);\n    \n    para->height= DFLT; mINIRead(ini,name,\"height\",\"%d\",&(para->height));\n    para->width = DFLT; mINIRead(ini,name,\"width\" ,\"%d\",&(para->width ));\n    \n    return para;\n}\n\nstruct HandleTensorResize\n{\n    int *lx;\n    int *ly;\n    float *wx;\n    float *wy;\n};\nvoid endTensorResize(void *info)\n{\n    struct HandleTensorResize *handle = (struct HandleTensorResize *)info;\n    if(handle->lx !=NULL) mFree(handle->lx);\n    if(handle->ly !=NULL) mFree(handle->ly);\n    if(handle->wx !=NULL) mFree(handle->wx);\n    if(handle->wy !=NULL) mFree(handle->wy);\n}\n#define HASH_TensorResize 0xb6f42d3a\n\nvoid TensorResizeSet(MLayer *layer)\n{\n    if(layer->state != DFLT) return;\n    struct TensorResizePara *para = (struct TensorResizePara *)(layer->para);\n    MTensor *in = para->prev->tns;\n    MTensor *res= para->prev->res;\n    MTensor *out= layer->tns;\n    \n    MHandle *hdl=mHandle(out,TensorResize);\n    struct HandleTensorResize *handle = (struct HandleTensorResize *)(hdl->handle);\n    \n    if(para->height<=0) para->height= in->height;\n    if(para->width <=0) para->width = in->width;\n    \n    mTensorRedefine(out,in->batch,in->channel,para->height,para->width,NULL);\n    if(morn_network_flag==MORN_TRAIN)\n    {\n        if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);\n        else                    mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);\n    }\n    \n    if(handle->lx !=NULL) {mFree(handle->lx);} handle->lx=(int   *)mMalloc(para->width *sizeof(int));\n    if(handle->ly !=NULL) {mFree(handle->ly);} handle->ly=(int   *)mMalloc(para->height*sizeof(int));\n    if(handle->wx !=NULL) {mFree(handle->wx);} handle->wx=(float *)mMalloc(para->width *sizeof(float));\n    if(handle->wy !=NULL) {mFree(handle->wy);} handle->wy=(float *)mMalloc(para->height*sizeof(float));\n    \n    float kx = (float)(in->width)/(float)(out->width);\n    for(int i=0;i<out->width;i++)\n    {\n        float l=kx*((float)i-0.5);\n        if(l<0) l=0.0f;else if(l>=in->width-1) l=(float)(in->width)-1.00001;\n        handle->lx[i] = (int)l;\n        handle->wx[i] = (float)(handle->lx[i]+1)-l;\n    }\n    \n    float ky = (float)(in->height)/(float)(out->height);\n    for(int i=0;i<out->height;i++)\n    {\n        float l=ky*((float)i-0.5); \n        if(l<0) l=0.0f;else if(l>=in->height-1) l=(float)(in->height)-1.00001;\n        handle->ly[i] = (int)l;\n        handle->wy[i] = (float)(handle->ly[i]+1)-l;\n    }\n    \n    hdl->valid = 1;\n}\n\nvoid mTensorResizeForward(MLayer *layer)\n{\n    mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n    mException(strcmp(\"Resize\",mLayerType(layer)),EXIT,\"invalid layer type\");\n    struct TensorResizePara *para = (struct TensorResizePara *)(layer->para);\n    MTensor *in = para->prev->tns;\n    MTensor *out=layer->tns;\n    \n    TensorResizeSet(layer);\n    \n    MHandle *hdl=mHandle(out,TensorResize);\n    struct HandleTensorResize *handle = (struct HandleTensorResize *)(hdl->handle);\n    \n    int  in_size = in->width* in->height;\n    int out_size =out->width*out->height;\n    \n    for(int h=0;h<out->height;h++)for(int w=0;w<out->width;w++)\n    {\n        int out_idx = h*out->width+w;\n        int in_idx1 =(handle->ly[h]  )*in->width + (handle->lx[w]  );\n        int in_idx2 =(handle->ly[h]  )*in->width + (handle->lx[w]+1);\n        int in_idx3 =(handle->ly[h]+1)*in->width + (handle->lx[w]  );\n        int in_idx4 =(handle->ly[h]+1)*in->width + (handle->lx[w]+1);\n        float w1 = (    handle->wy[h])*(    handle->wx[w]);\n        float w2 = (    handle->wy[h])*(1.0-handle->wx[w]);\n        float w3 = (1.0-handle->wy[h])*(    handle->wx[w]);\n        float w4 = (1.0-handle->wy[h])*(1.0-handle->wx[w]);\n        \n        for(int b=0;b<in->batch;b++)for(int c=0;c<in->channel;c++)\n        {\n            out->data[b][c*out_size+out_idx] = in->data[b][c*in_size+in_idx1]*w1\n                                              +in->data[b][c*in_size+in_idx2]*w2\n                                              +in->data[b][c*in_size+in_idx3]*w3\n                                              +in->data[b][c*in_size+in_idx4]*w4;\n        }\n    }\n    \n    layer->state = MORN_FORWARD;\n}\n\nvoid mTensorResizeBackward(MLayer *layer)\n{\n    mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n    mException(strcmp(\"Resize\",mLayerType(layer)),EXIT,\"invalid layer type\");\n    struct TensorResizePara *para = (struct TensorResizePara *)(layer->para);\n    if(para->res_valid==0) return;\n    MTensor *res= para->prev->res;\n    MTensor *out= layer->res;\n    \n    MHandle *hdl=mHandle(layer->tns,TensorResize);\n    struct HandleTensorResize *handle = (struct HandleTensorResize *)(hdl->handle);\n    mException((hdl->valid == 0),EXIT,\"no forward operate\");\n    \n    int  in_size =res->width*res->height;\n    int out_size =out->width*out->height;\n    \n    if(para->prev->state == MORN_FORWARD)\n    {\n        for(int b=0;b<res->batch;b++) memset(res->data[b],0,in_size*res->channel*sizeof(float));\n        para->prev->state = MORN_BACKWARD;\n    }\n    \n    for(int h=0;h<out->height;h++)for(int w=0;w<out->width;w++)\n    {\n        int out_idx = h*out->width+w;\n        int in_idx1 =(handle->ly[h]  )*res->width + (handle->lx[w]  );\n        int in_idx2 =(handle->ly[h]  )*res->width + (handle->lx[w]+1);\n        int in_idx3 =(handle->ly[h]+1)*res->width + (handle->lx[w]  );\n        int in_idx4 =(handle->ly[h]+1)*res->width + (handle->lx[w]+1);\n        float w1 = (    handle->wy[h])*(    handle->wx[w]);\n        float w2 = (    handle->wy[h])*(1.0-handle->wx[w]);\n        float w3 = (1.0-handle->wy[h])*(    handle->wx[w]);\n        float w4 = (1.0-handle->wy[h])*(1.0-handle->wx[w]);\n        \n        for(int b=0;b<res->batch;b++)for(int c=0;c<res->channel;c++)\n        {\n            res->data[b][c*in_size+in_idx1] += out->data[b][c*out_size+out_idx]*w1;\n            res->data[b][c*in_size+in_idx2] += out->data[b][c*out_size+out_idx]*w2;\n            res->data[b][c*in_size+in_idx3] += out->data[b][c*out_size+out_idx]*w3;\n            res->data[b][c*in_size+in_idx4] += out->data[b][c*out_size+out_idx]*w4;\n        }\n    }\n}\n\n", "meta": {"hexsha": "2cd03eb6e3eb5ce7a26c47426cb94e10d2a0fe10", "size": 7246, "ext": "c", "lang": "C", "max_stars_repo_path": "src/deep_learning/morn_tensor_resize.c", "max_stars_repo_name": "ishine/Morn", "max_stars_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 121.0, "max_stars_repo_stars_event_min_datetime": "2019-09-24T05:53:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:23:49.000Z", "max_issues_repo_path": "src/deep_learning/morn_tensor_resize.c", "max_issues_repo_name": "ishine/Morn", "max_issues_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-09-29T02:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-07T15:05:18.000Z", "max_forks_repo_path": "src/deep_learning/morn_tensor_resize.c", "max_forks_repo_name": "ishine/Morn", "max_forks_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2019-09-26T05:09:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T11:34:47.000Z", "avg_line_length": 38.9569892473, "max_line_length": 501, "alphanum_fraction": 0.5977090809, "num_tokens": 2184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.38329655750105807}}
{"text": "/*********************\n * Time intergral KDK scheme.\n * kick and drifts.\n * \n * This code was initially modified by Jun Koda, \n * from the original serial COLA code\n * by Svetlin Tassev.\n *\n * The kick and drift still supports a COLA compat-mode.\n * Most of the nasty factors are for COLA compat-mode\n * (not needed in PM)\n * We also added a 2LPT mode that does just 2LPT.\n *\n *  Yu Feng <rainwoodman@gmail.com> \n *\n */\n\n#include <math.h>\n#include <string.h>\n#include <assert.h>\n#include <alloca.h>\n#include <mpi.h>\n\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_roots.h>\n#include <gsl/gsl_sf_hyperg.h> \n#include <gsl/gsl_errno.h>\n\n#include <fastpm/libfastpm.h>\n#include <fastpm/logging.h>\n\n#include \"pmpfft.h\"\n#include \"vpm.h\"\n\nstatic double \nSq(double ai, double af, double aRef, double nLPT, FastPMCosmology * c, int USE_NONSTDDA);\n\nstatic double \nSphi(double ai, double af, double aRef, double nLPT, FastPMCosmology * c, int USE_NONSTDDA);\n\nstatic inline void\nfastpm_drift_lookup(FastPMDriftFactor * drift, double af, double * dyyy, double * da1, double * da2)\n{\n    double ind;\n\n    if(af == drift->af) {\n        *dyyy = drift->dyyy[drift->nsamples - 1];\n        *da1  = drift->da1[drift->nsamples - 1];\n        *da2  = drift->da2[drift->nsamples - 1];\n        return;\n    }\n    if(af == drift->ai) {\n        *dyyy = drift->dyyy[0];\n        *da1  = drift->da1[0];\n        *da2  = drift->da2[0];\n        return;\n    }\n    {\n        ind = (af - drift->ai) / (drift->af - drift->ai) * (drift->nsamples - 1);\n        int l = floor(ind);\n        double u = l + 1 - ind;\n        double v = ind - l;\n        if(l + 1 >= drift->nsamples) {\n            fastpm_raise(-1, \"drift beyond factor's available range. \");\n        }\n        *dyyy = drift->dyyy[l] * u + drift->dyyy[l + 1] * v;\n        *da1  = drift->da1[l] * u + drift->da1[l + 1] * v;\n        *da2  = drift->da2[l] * u + drift->da2[l + 1] * v;\n    }\n}\n\ninline void\nfastpm_drift_one(FastPMDriftFactor * drift, FastPMStore * p, ptrdiff_t i, double xo[3], double af)\n{\n\n    double dyyy_f, da1_f, da2_f;\n    double dyyy_i, da1_i, da2_i;\n    double dyyy, da1, da2;\n\n    fastpm_drift_lookup(drift, af, &dyyy_f, &da1_f, &da2_f);\n    fastpm_drift_lookup(drift, p->meta.a_x, &dyyy_i, &da1_i, &da2_i);\n\n    dyyy = dyyy_f - dyyy_i;\n    da1 = da1_f - da1_i;\n    da2 = da2_f - da2_i;\n\n    int d;\n    for(d = 0; d < 3; d ++) {\n        double v;\n        switch(drift->forcemode) {\n            case FASTPM_FORCE_2LPT:\n                xo[d] = p->x[i][d] + p->dx1[i][d] * da1 + p->dx2[i][d] * da2;\n            break;\n            case FASTPM_FORCE_ZA:\n                xo[d] = p->x[i][d] + p->dx1[i][d] * da1;\n            break;\n            case FASTPM_FORCE_FASTPM:\n            case FASTPM_FORCE_PM:\n                xo[d] = p->x[i][d] + p->v[i][d] * dyyy;\n            break;\n            case FASTPM_FORCE_COLA:\n                /* For cola, remove the lpt velocity to find the residual velocity v*/\n                v = p->v[i][d] - (p->dx1[i][d]*drift->Dv1 + p->dx2[i][d]*drift->Dv2);\n                xo[d] = p->x[i][d] + v * dyyy;\n                xo[d] += p->dx1[i][d] * da1 + p->dx2[i][d] * da2;\n            break;\n        }\n        /* if PGDCorrection is enabled, add it */\n        if(p->pgdc) {\n            /* no drift; to protect the pgdc line */\n            if (drift->ai == drift->af) continue;\n            xo[d] += 0.5 * p->pgdc[i][d] * dyyy / drift->dyyy[drift->nsamples-1];\n        }\n    }\n}\nstatic inline void\nfastpm_kick_lookup(FastPMKickFactor * kick, double af, double * dda, double * Dv1, double * Dv2)\n{\n    double ind;\n\n    if(af == kick->af) {\n        *dda = kick->dda[kick->nsamples - 1];\n        *Dv1 = kick->Dv1[kick->nsamples - 1];\n        *Dv2 = kick->Dv2[kick->nsamples - 1];\n        return;\n    }\n    if(af == kick->ai) {\n        *dda = kick->dda[0];\n        *Dv1 = kick->Dv1[0];\n        *Dv2 = kick->Dv2[0];\n        return;\n    }\n    {\n        ind = (af - kick->ai) / (kick->af - kick->ai) * (kick->nsamples - 1);\n        int l = floor(ind);\n        double u = l + 1 - ind;\n        double v = ind - l;\n        if(l + 1 >= kick->nsamples) {\n            fastpm_raise(-1, \"kick beyond factor's available range. \");\n        }\n        *dda = kick->dda[l] * u + kick->dda[l + 1] * v;\n        *Dv1 = kick->Dv1[l] * u + kick->Dv1[l + 1] * v;\n        *Dv2 = kick->Dv2[l] * u + kick->Dv2[l + 1] * v;\n    }\n}\n\ninline void\nfastpm_kick_one(FastPMKickFactor * kick, FastPMStore * p, ptrdiff_t i, float vo[3], double af)\n{\n    double dda_i, Dv1_i, Dv2_i;\n    double dda_f, Dv1_f, Dv2_f;\n    double dda, Dv1, Dv2;\n\n    fastpm_kick_lookup(kick, af, &dda_f, &Dv1_f, &Dv2_f);\n    fastpm_kick_lookup(kick, p->meta.a_v, &dda_i, &Dv1_i, &Dv2_i);\n    dda = dda_f - dda_i;\n    Dv1 = Dv1_f - Dv1_i;\n    Dv2 = Dv2_f - Dv2_i;\n\n    int d;\n    for(d = 0; d < 3; d++) {\n        float ax = p->acc[i][d];       // unlike a_x, which means a at which x is calcd\n        if(kick->forcemode == FASTPM_FORCE_COLA) {\n            ax += (p->dx1[i][d]*kick->q1 + p->dx2[i][d]*kick->q2);\n        }\n        vo[d] = p->v[i][d] + ax * dda;\n        if(kick->forcemode == FASTPM_FORCE_COLA) {\n            vo[d] += (p->dx1[i][d] * Dv1 + p->dx2[i][d] * Dv2);\n        }\n    }\n}\n\n// Leap frog time integration\n\nvoid \nfastpm_kick_store(FastPMKickFactor * kick,\n    FastPMStore * pi, FastPMStore * po, double af)\n{\n    int np = pi->np;\n\n    // Kick using acceleration at a= ac\n    // Assume forces at a=ac is in particles->force\n\n    int i;\n#pragma omp parallel for\n    for(i=0; i<np; i++) {\n        int d;\n        float vo[3];\n        fastpm_kick_one(kick, pi, i, vo, af);\n        for(d = 0; d < 3; d++) {\n            po->v[i][d] = vo[d];\n        }\n    }\n\n    //velocity is now at a= avel1\n    po->meta.a_v = af;\n}\n\nstatic double G_p(FastPMGrowthInfo * growth_info)\n{\n    /* integral of G_p */\n    return growth_info->D1;\n}\nstatic double g_p(FastPMGrowthInfo * growth_info)\n{\n    return DGrowthFactorDa(growth_info);\n}\n\nstatic double G_f(FastPMGrowthInfo * growth_info)\n{\n    /* integral of g_f */\n    double a = growth_info->a;\n    return a * a * a * HubbleEa(a, growth_info->c) * g_p(growth_info);\n}\n\nstatic double g_f(FastPMGrowthInfo * growth_info)\n{\n    double a = growth_info->a;\n    FastPMCosmology * c = growth_info->c;\n\n    double E = HubbleEa(a, c);\n    double dEda = DHubbleEaDa(a, c);\n\n    double dDda = g_p(growth_info);\n    double d2Dda2 = D2GrowthFactorDa2(growth_info);\n\n    double g_f = 3 * a * a * E * dDda\n                   + a * a * a * dEda * dDda\n                   + a * a * a * E * d2Dda2;\n    return g_f;\n}\n\nvoid fastpm_kick_init(FastPMKickFactor * kick, FastPMSolver * fastpm, double ai, double ac, double af)\n{\n    FastPMCosmology * c = fastpm->cosmology;\n    kick->forcemode = fastpm->config->FORCE_TYPE;\n\n    FastPMGrowthInfo gi_i;\n    FastPMGrowthInfo gi_c;\n    FastPMGrowthInfo gi_e;\n\n    fastpm_growth_info_init(&gi_i, ai, c);\n    fastpm_growth_info_init(&gi_c, ac, c);\n\n    double E_i = HubbleEa(ai, c);\n    double E_c = HubbleEa(ac, c);\n\n    double D1_i = gi_i.D1;\n    double D2_i = gi_i.D2;\n    double f1_i = gi_i.f1;\n    double f2_i = gi_i.f2;\n\n    double D1_c = gi_c.D1;\n    double D2_c = gi_c.D2;\n\n    double Omega_m0 = Omega_source(1, c);\n    double Omega_mc = Omega_source(ac, c);\n\n    // kick->q1,2 are used for the COLA force implementation.\n    // growth_mode = ODE and LCDM should match for an LCDM background,\n    // but neither is guaranteed accurate for a background with radiaiton.\n    // We advise using LCDM mode for forcemode = FASTPM_FORCE_COLA, as in the\n    // original implementation of FastPM.\n    kick->q1 = D1_c;\n    switch (c->growth_mode){\n        case FASTPM_GROWTH_MODE_LCDM:\n            kick->q2 = D1_c*D1_c * (1.0 + 7.0/3.0 * pow(Omega_mc, 1.0/143.0));\n        break;\n        case FASTPM_GROWTH_MODE_ODE:\n            kick->q2 = D1_c*D1_c * (1 - D1_c*D1_c/D2_c);\n        break;\n        default:\n            fastpm_raise(-1, \"Please enter a valid growth mode.\\n\");\n    }\n\n    kick->nsamples = 32;\n    int i;\n\n    double Dv1i = D1_i * ai * ai * E_i * f1_i;\n    double Dv2i = D2_i * ai * ai * E_i * f2_i;\n    for(i = 0; i < kick->nsamples; i ++) {\n        double ae = ai * (1.0 * (kick->nsamples - 1 - i) / (kick->nsamples - 1))\n                  + af * (1.0 * i / (kick->nsamples - 1));\n\n        fastpm_growth_info_init(&gi_e, ae, c);\n        double D1_e = gi_e.D1;\n        double f1_e = gi_e.f1;\n        double D2_e = gi_e.D2;\n        double f2_e = gi_e.f2;\n        double E_e = HubbleEa(ae, c);\n\n        if(kick->forcemode == FASTPM_FORCE_FASTPM) {\n            kick->dda[i] = -1.5 * Omega_mc * ac\n               * E_c\n               * (G_f(&gi_e) - G_f(&gi_i)) / g_f(&gi_c);\n        } else {\n            kick->dda[i] = -1.5 * Omega_m0\n                * Sphi(ai, ae, ac, fastpm->config->nLPT, c, kick->forcemode == FASTPM_FORCE_COLA);\n        }\n        kick->Dv1[i] = D1_e * ae * ae * E_e * f1_e - Dv1i;\n        kick->Dv2[i] = D2_e * ae * ae * E_e * f2_e - Dv2i;\n    }\n\n    kick->ai = ai;\n    kick->ac = ac;\n    kick->af = af;\n\n    /* Output growth and FastPM factor at af for reference.\n    This is a weird place to put this, but it's convenient because G and g are static */\n    fastpm_info(\"Growth/FastPM factors at a = %6.4f: D1=%g, D2=%g, f1=%g, f2=%g, G_p=%g, G_f=%g, g_p=%g, g_f=%g\\n\",\n               ai,\n               gi_i.D1,\n               gi_i.D2,\n               gi_i.f1,\n               gi_i.f2,\n               G_p(&gi_i),\n               G_f(&gi_i),\n               g_p(&gi_i),\n               g_f(&gi_i));\n}\n\nvoid\nfastpm_drift_init(FastPMDriftFactor * drift, FastPMSolver * fastpm,\n                double ai, double ac, double af)\n{\n    FastPMCosmology * c = fastpm->cosmology;\n    drift->forcemode = fastpm->config->FORCE_TYPE;\n\n    FastPMGrowthInfo gi_i;\n    FastPMGrowthInfo gi_c;\n    FastPMGrowthInfo gi_e;\n\n    fastpm_growth_info_init(&gi_i, ai, c);\n    fastpm_growth_info_init(&gi_c, ac, c);\n\n    double E_c = HubbleEa(ac, c);\n\n    double D1_i = gi_i.D1;\n    double D2_i = gi_i.D2;\n\n    double D1_c = gi_c.D1;\n    double D2_c = gi_c.D2;\n    double f1_c = gi_c.f1;\n    double f2_c = gi_c.f2;\n\n    drift->nsamples = 32;\n    int i;\n\n    for(i = 0; i < drift->nsamples; i ++ ) {\n        double ae = ai * (1.0 * (drift->nsamples - 1 - i) / (drift->nsamples - 1))\n                  + af * (1.0 * i / (drift->nsamples - 1));\n\n        fastpm_growth_info_init(&gi_e, ae, c);     // overwrite each iteration\n        double D1_e = gi_e.D1;\n        double D2_e = gi_e.D2;\n\n        if (drift->forcemode == FASTPM_FORCE_FASTPM) {\n            drift->dyyy[i] = 1 / (ac * ac * ac * E_c)\n                        * (G_p(&gi_e) - G_p(&gi_i)) / g_p(&gi_c);\n        } else {\n            drift->dyyy[i] = Sq(ai, ae, ac, fastpm->config->nLPT, c, drift->forcemode == FASTPM_FORCE_COLA);\n        }\n        drift->da1[i] = D1_e - D1_i;    // change in D_1lpt\n        drift->da2[i] = D2_e - D2_i;  // change in D_2lpt\n    }\n    drift->af = af;\n    drift->ai = ai;\n    drift->ac = ac;\n    drift->Dv1 = D1_c * ac * ac * E_c * f1_c;\n    drift->Dv2 = D2_c * ac * ac * E_c * f2_c;\n}\n\nvoid\nfastpm_drift_store(FastPMDriftFactor * drift,\n               FastPMStore * pi, FastPMStore * po,\n               double af)\n{\n    int np = pi->np;\n\n    int i;\n    // Drift\n#pragma omp parallel for\n    for(i=0; i<np; i++) {\n        double xo[3] = {0};\n        fastpm_drift_one(drift, pi, i, xo, af);\n        int d;\n        for(d = 0; d < 3; d ++) {\n            po->x[i][d] = xo[d];\n        }\n    }\n    po->meta.a_x = af;\n}\n\n//\n// Functions for our modified time-stepping (used when StdDA=0):\n//\nstruct iparam {\n    FastPMCosmology * cosmology;\n    double nLPT;\n};\n\ndouble gpQ(double a, double nLPT) { \n    return pow(a, nLPT);\n}\n\nstatic double stddriftfunc (double a, struct iparam * iparam) {\n    return 1 / (pow(a, 3) * HubbleEa(a, iparam->cosmology));\n}\n\nstatic double nonstddriftfunc (double a, struct iparam * iparam) {\n    return gpQ(a, iparam->nLPT)/(pow(a, 3) * HubbleEa(a, iparam->cosmology));\n}\n\nstatic double stdkickfunc (double a, struct iparam * iparam) {\n    return 1/ (pow(a, 2) * HubbleEa(a, iparam->cosmology));\n}\n\nstatic double integrand(double a, void * params) {\n    void ** p = (void**) params;\n    double (*func)(double a, struct iparam * s) = p[0];\n    struct iparam * s = p[1];\n    return func(a, s);\n}\n\ndouble integrate(double ai, double af,\n        struct iparam * iparam,\n        double (*func)(double , struct iparam * )) {\n\n    gsl_integration_workspace * w\n        = gsl_integration_workspace_alloc (5000);\n\n    gsl_function F;\n    double error;\n    double result;\n\n    F.params = (void*[]){func, iparam};\n    F.function = integrand;\n\n    gsl_integration_qag (&F, ai, af, 0, 1e-8, 5000, 6,\n            w, &result, &error); \n\n    gsl_integration_workspace_free (w);\n    return result;\n}\n\n/*     \n       When StdDA=0, one needs to set nLPT.\n       assumes time dep. for velocity = B a^nLPT\n       nLPT is a real number. Sane values lie in the range (-4,3.5). Cannot be 0, but of course can be -> 0 (say 0.001).\n       See Section A.3 of TZE.\n       */\n\nstatic double \nSq(double ai, double af, double aRef, double nLPT, FastPMCosmology * c, int USE_NONSTDDA)\n{\n    double resultstd, result;\n    struct iparam iparam[1];\n    iparam->cosmology = c;\n    iparam->nLPT = nLPT;\n\n    resultstd = integrate(ai, af, iparam, stddriftfunc);\n\n    result = integrate(ai, af, iparam, nonstddriftfunc);\n    result /= gpQ(aRef, nLPT);\n\n    /*\n    fastpm_info(\"ref time = %6.4f, std drift =%g, non std drift = %g \\n\",\n        aRef, resultstd, result); */\n\n    if (USE_NONSTDDA)\n        return result;\n    else\n        return resultstd;\n}\n\ndouble DERgpQ(double a, double nLPT) { \n    /* This must return d(gpQ)/da */\n    return nLPT*pow(a, nLPT-1);\n}\n\n\nstatic double \nSphi(double ai, double af, double aRef, double nLPT, FastPMCosmology * c, int USE_NONSTDDA)\n{\n    double result;\n    double resultstd;\n\n    struct iparam iparam[1];\n    iparam->cosmology = c;\n    iparam->nLPT = nLPT;\n\n    result = (gpQ(af, nLPT) - gpQ(ai, nLPT)) * aRef \n        / (pow(aRef, 3) * HubbleEa(aRef, c) * DERgpQ(aRef, nLPT));\n\n    resultstd = integrate(ai, af, iparam, stdkickfunc);\n\n    /*\n    fastpm_info(\"ref time = %6.4f, std kick = %g, non std kick = %g\\n\",\n            aRef, resultstd, result); */\n\n    if (USE_NONSTDDA) {\n        return result;\n    } else {\n        return resultstd;\n    }\n}\n", "meta": {"hexsha": "00d42b2d1e162f5735809da9fb0cf478c0e6743b", "size": 14336, "ext": "c", "lang": "C", "max_stars_repo_path": "fastpm/libfastpm/factors.c", "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fastpm/libfastpm/factors.c", "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_forks_repo_path": "fastpm/libfastpm/factors.c", "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "avg_line_length": 28.2761341223, "max_line_length": 120, "alphanum_fraction": 0.5551757812, "num_tokens": 4880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.38329655750105807}}
{"text": "/* #################################################\n * # stochastic simulation of adapting populations #\n * # with variing constraint type                  #\n * # and exponential mutation kernel               #\n * #################################################\n * \n * 2012-2014, Lukas Geyrhofer\n * \n * \n * #################################################\n * \n * simplest usage (population size 1e7):\n * ./travelingwavepeak_exp -N 1e7 1> out.txt 2> conf.txt\n * \n * ################################################# */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_vector.h>\n\n\nint space = 300;\nint space0 = 100;\ndouble dx = 1e-2;\nint maxSteps = 1000;\n\nint outputstep = 100;\nint quiet = 0;\n\nint noise = 0;\ndouble populationsize = 1.;\ndouble populationvariance;\nint correctformeanfitness =0;\nint printhistotype = 1;\n\nint allshifts = 0;\nint shiftthreshold = 1;\ndouble current_mean_fitness = 0.;\n\nint read_from_file = 0;\nint write_to_file = 0;\nchar c_infile[128],c_outfile[128];\n\nint have_u_infile = 0;\nchar u_infile[128];\ndouble *u_read,*u;\nint dens_ustar_latticeratio = 1;\nint u_space,u_space0;\ndouble u_dx;\ndouble wavespeed = 0.;\ndouble speedprefactor;\n\n\ndouble epsilon = 1e-2;\ndouble twoepssqrt;\ndouble *nn;\ndouble *tmp;\ndouble *x;\n\ndouble mutationrate = 1e-5;\ndouble *mutation_inflow;\ndouble mutation_outflow;\ndouble mutation_sigma = 1e-2;\n\n\nconst gsl_rng* rg; /* gsl, global generator */\nconst gsl_rng_type* T;\nunsigned long int randseed = 0;\n\n\ndouble popdens_0thmom;\ndouble popdens_1stmom;\ndouble popdens_2ndmom;\n\n\n\nint averagepopdens = 0;\nint averagepopdens_center = 1;\nint averagepopdens_resolution = 1;\nint averagepopdens_havefile = 0;\ndouble *averagepopdens_dens;\nchar averagepopdens_outputfile[128];\ndouble averagepopdens_count = 0.;\ndouble averagepopdens_dx;\nint averagepopdens_space;\nint averagepopdens_space0;\nint averagepopdens_lower;\nint averagepopdens_higher;\n\n\nint fixationextinction_events = 0;\ndouble fe_expected_fixationprobability = .5;\ndouble fe_predicted_fixationprobability;\ndouble *ww,*vv;\ndouble *fe_start_ww, *fe_start_vv;\ndouble *tmpw,*tmpv;\ndouble fe_final_threshold = 1e-4; // if (current_fixation_prob > 1 - 1e-4) or (current_fixation_prob < 1e-4), then restart...\ndouble fe_subpopsize;\nint fe_count_extinctions = 0;\nint fe_count_fixations = 0;\ndouble current_fixation_prob;\n\nint print_error(char *msg) {\n  fprintf(stderr,\"ERROR: %s\\n\",msg);\n  exit(1);\n}\n\n// ************************************************************\n// **   parameters\n// ************************************************************\n\n\nvoid parsecomamndline(int argn, char *argv[]) {\n  char c;\n  while((c = getopt(argn,argv,\"s:z:d:S:e:D:O:qQi:o:R:N:CM:u:U:T:H:h:PE:\")) != -1) {\n    switch(c) {\n      case 's':\tspace = atoi(optarg);\n\t\tbreak;\n      case 'z':\tspace0 = atoi(optarg);\n\t\tbreak;\n      case 'd':\tdx = atof(optarg);\n\t\tbreak;\n      case 'i':\tstrcpy(c_infile,optarg);\n\t\tread_from_file = 1;\n\t\tbreak;\n      case 'o':\tstrcpy(c_outfile,optarg);\n\t\twrite_to_file = 1;\n\t\tbreak;\n      case 'u':\tstrcpy(u_infile,optarg);\n\t\tif(noise > 0)\n\t\t  print_error(\"Only a single constraint-type can be used (either option -N POPSIZE or -u FILENAME)\");\n\t\tnoise = 2;\n\t\tbreak;\n      case 'U':\tif(noise == 2) {\n\t\t  dens_ustar_latticeratio = atoi(optarg);\n\t\t}else{\n\t\t  print_error(\"option -u FILENAME needed before option -U RATIO\");\n\t\t}\n\t\tbreak;\n      case 'S':\tmaxSteps = atoi(optarg);\n\t\tbreak;\n      case 'e': epsilon = atof(optarg);\n\t\tbreak;\n      case 'D':\tmutationrate = atof(optarg);\n\t\tbreak;\n      case 'O':\toutputstep = atoi(optarg);\n\t\tbreak;\n      case 'q':\tquiet = 2;\n\t\tbreak;\n      case 'Q':\tquiet = 1;\n\t\tbreak;\n      case 'R':\trandseed =atoi(optarg);\n\t\tbreak;\n      case 'N': populationsize = atof(optarg);\n\t\tif(noise > 0)\n\t\t  print_error(\"Only a single constraint-type can be used (either option -N POPSIZE or -u FILENAME)\");\n\t\tnoise = 1;\n\t\tbreak;\n      case 'C':\tcorrectformeanfitness = 1;\n\t\tbreak;\n      case 'M':\tmutation_sigma = atof(optarg);\n\t\tbreak;\n      case 'T':\tshiftthreshold = atoi(optarg);\n\t\tbreak;\n      case 'h':\tstrcpy(averagepopdens_outputfile,optarg);\n\t\taveragepopdens_havefile = 1;\n\t\taveragepopdens = 1;\n\t\tbreak;\n      case 'H':\taveragepopdens = 1;\n\t\taveragepopdens_resolution = atoi(optarg);\n\t\tif(averagepopdens_resolution < 0) {\n\t\t  averagepopdens_resolution *= -1;\n\t\t  averagepopdens_center = 0;\n\t\t}\n\t\tbreak;\n      case 'P':\tprinthistotype = 0;\n\t\tbreak;\n      case 'E':\tfe_expected_fixationprobability = atof(optarg);\n\t\tbreak;\n    }\n  }\n  if(randseed==0)randseed=time(NULL);\n}\n\n// ************************************************************\n// **   input and output for configuration files\n// ************************************************************\n\nvoid read_popdens(int importparameters) {\n  int i;\n  int icount,dcount;\n  int *ival;\n  double *dval;\n  int c_space,c_space0;\n  double c_dx;\n  FILE *fp;\n  \n  fp = fopen(c_infile,\"rb\");\n  if(fp != NULL) {\n    fread(&icount,sizeof(int),1,fp);\n    fread(&dcount,sizeof(int),1,fp);\n    fread(&c_dx,sizeof(double),1,fp);\n    fread(&c_space,sizeof(int),1,fp);\n    fread(&c_space0,sizeof(int),1,fp);\n    \n    if(importparameters) {\n      space = c_space;\n      space0 = c_space0;\n      dx = c_dx;\n    }\n        \n    if(icount>0) {\n      ival = (int*)malloc(icount*sizeof(int));\n      fread(ival,sizeof(int),icount,fp);\n      free(ival);\n    }\n    \n    if(dcount>0) {\n      dval = (double*)malloc(dcount*sizeof(int));\n      fread(dval,sizeof(double),dcount,fp);\n      free(dval);\n    }\n    \n    if(space != c_space)print_error(\"lattice does not match!\");\n    nn = (double*)malloc(space*sizeof(double));\n    fread(nn,sizeof(double),space,fp);\n    for(i=0;i<space;i++) {\n      nn[i] *= dx;\n    }\n    fclose(fp);\n  }else{\n    print_error(\"could not open c-infile\");\n  }\n  \n}\n\n\n\nvoid write_popdens() {\n  int icount=0,dcount=0;\n  int i;\n  FILE *fpc;\n  \n  fpc=fopen(c_outfile,\"wb\");\n  if(fpc != NULL) {\n    fwrite(&icount,sizeof(int),1,fpc);\n    fwrite(&dcount,sizeof(int),1,fpc);\n    fwrite(&dx,sizeof(double),1,fpc);\n    fwrite(&space,sizeof(int),1,fpc);\n    fwrite(&space0,sizeof(int),1,fpc);\n    for(i=0;i<space;i++)nn[i] /= dx;\n    fwrite(nn,sizeof(double),space,fpc);\n    fclose(fpc);\n  }else{\n    print_error(\"could not open c-outfile\");\n  }  \n}\n\n\n\n\n\nvoid read_constraint(int importparameters) {\n  int icount,dcount;\n  int *ival;\n  double *dval;\n  FILE *fp;\n  \n  fp = fopen(u_infile,\"rb\");\n  if(fp!=NULL) {\n    fread(&icount,sizeof(int),1,fp);\n    fread(&dcount,sizeof(int),1,fp);\n    fread(&u_dx,sizeof(double),1,fp);\n    fread(&u_space,sizeof(int),1,fp);\n    fread(&u_space0,sizeof(int),1,fp);\n    \n    if(icount>0) {\n      ival = (int*)malloc(icount*sizeof(int));\n      fread(ival,sizeof(int),icount,fp);\n      free(ival);\n    }\n    \n    if(dcount>=3) {\n      dval = (double*)malloc(dcount*sizeof(int));\n      fread(dval,sizeof(double),dcount,fp);\n      mutationrate = dval[0];\n      wavespeed = dval[1];\n      mutation_sigma = dval[2];\n      free(dval);\n    }else{\n      print_error(\"not enough values in constraint file! need at least 3 double parameters: mutationrate, wavespeed, mutationsigma!\");\n    }\n    \n    if(importparameters) {\n      space = u_space/dens_ustar_latticeratio;\n      space0 = u_space0/dens_ustar_latticeratio;\n      dx = u_dx*dens_ustar_latticeratio;\n    }else{\n      if((space*dens_ustar_latticeratio != u_space)||(space0*dens_ustar_latticeratio != u_space0))print_error(\"lattice does not match! u\");\n    }\n    \n    u_read = (double*)malloc(u_space*sizeof(double));\n    fread(u_read,sizeof(double),u_space,fp);\n    \n    fclose(fp);\n  }\n    \n  \n  u = (double*)malloc(space*sizeof(double));\n\n  \n}\n\n\n\nvoid flat_constraint(double size) {\n  int i;\n  u=(double*)malloc(space*sizeof(double));\n  for(i=0;i<space;i++)u[i] = 1./size;\n}\n\n\nvoid initialize_with_gaussian_popdens() {\n  int i;\n  double startvariance;\n  if(noise == 2) {\n    startvariance = wavespeed;\n  }else{\n    // Good et al., PNAS (2012)\n    startvariance = mutation_sigma*mutation_sigma*2*log(mutation_sigma*populationsize)/(log(mutation_sigma/mutationrate)*log(mutation_sigma/mutationrate));\n  }\n  for(i=0;i<space;i++) {\n    nn[i] = exp(-(i-space0)*(i-space0)*dx*dx/(2.*startvariance));\n  }\n}\n\n\n// ************************************************************\n// **   screen output\n// ************************************************************\n\n \nvoid print_populationdensity(int timestep) {\n  int i;\n  double corr = allshifts*dx;\n  if(correctformeanfitness)corr += current_mean_fitness;\n  for(i=0;i<space;i++) {\n    fprintf(stderr,\"%lf %14.10lf %20.10e %20.10e\\n\",timestep*epsilon,(i-space0)*dx+corr,ww[i]+vv[i],ww[i]);\n    if(printhistotype)fprintf(stderr,\"%lf %14.10lf %20.10e %20.10e\\n\",timestep*epsilon,(i-space0+1)*dx+corr,ww[i]+vv[i],ww[i]);\n  }\n  fprintf(stderr,\"\\n\");\n}\n\n\n\n\n// ************************************************************\n// **   initialization\n// ************************************************************\n\nint initialize() {\n  int i;\n  \n  if(read_from_file) {\n    read_popdens(1);\n    if(noise == 0)flat_constraint(1.);\n    if(noise == 1)flat_constraint(populationsize);\n    if(noise == 2)read_constraint(0);\n  }else{\n    if(noise == 0)flat_constraint(1.);\n    if(noise == 1)flat_constraint(populationsize);\n    if(noise == 2)read_constraint(1);\n    nn = (double*)calloc(space,sizeof(double));\n    initialize_with_gaussian_popdens();\n  }\n  tmp = (double*)malloc(space*sizeof(double));\n\n  gsl_rng_env_setup();\n  T = gsl_rng_default;\n  rg = gsl_rng_alloc(T);\n  gsl_rng_set(rg, randseed);\n\n  twoepssqrt = sqrt(2.*epsilon);\n  speedprefactor = wavespeed/dx*epsilon;\n  \n  x = (double*)malloc(space*sizeof(double));\n  mutation_inflow = (double*)malloc(space*sizeof(double));\n  mutation_outflow = 0;\n  for(i=1;i<space;i++) {\n    x[i] = (i-space0)*dx;\n    mutation_inflow[i] = epsilon*exp(-i*dx/mutation_sigma)/mutation_sigma*mutationrate*dx;\n    mutation_outflow += mutation_inflow[i];\n  }\n  \n  \n  if(quiet<2) {\n    printf(\"#################################################################################\\n\");\n    printf(\"# stochastic simulation of adapting population with exponential mutation kernel #\\n\");\n    printf(\"#################################################################################\\n\");\n    printf(\"#    mutationrate     = %e\\n\",mutationrate);\n    printf(\"#    mutation_sigma   = %e\\n\",mutation_sigma);\n    if(noise==0) {\n      printf(\"#    constraint       = deterministic\\n\");\n    }\n    if(noise==1) {\n      printf(\"#    constraint       = fixedN\\n\");\n      printf(\"#    populationsize   = %e\\n\",populationsize);\n    }\n    if(noise==2) {\n      printf(\"#    constraint       = ustar\\n\");\n      printf(\"#    wavespeed        = %e\\n\",wavespeed);\n    }\n    printf(\"#    (lattice) space  = %d\\n\",space);\n    printf(\"#    (lattice) space0 = %d\\n\",space0);\n    printf(\"#    (lattice) dx     = %e\\n\",dx);\n    printf(\"#    randseed         = %d\\n\",randseed);\n  }\n\n}\n\n\n// ************************************************************\n// **   average popdens\n// ************************************************************\n\nvoid init_averagepopdens() {\n  \n  averagepopdens_dx = dx/(1.*averagepopdens_resolution);\n  averagepopdens_space = space*averagepopdens_resolution;\n  averagepopdens_space0 = space0*averagepopdens_resolution;\n  \n  averagepopdens_dens = (double*)calloc(averagepopdens_space,sizeof(double));\n  \n  averagepopdens_lower = (int)(-averagepopdens_resolution/2);\n  averagepopdens_higher = (int)(averagepopdens_resolution/2);\n  if(averagepopdens_higher - averagepopdens_lower < averagepopdens_resolution)averagepopdens_higher++;\n  \n}\n\n\nvoid update_averagepopdens() {\n  int i,j,idx;\n  int offset=0;\n  \n  if(averagepopdens_center) {\n    offset = (int)(current_mean_fitness/dx*averagepopdens_resolution);\n  }\n  \n  for(i=0;i<space;i++) {\n    for(j=averagepopdens_lower;j<averagepopdens_higher;j++) {\n      idx = i*averagepopdens_resolution+j-offset;\n      if((averagepopdens_space > idx) &&( idx >= 0))\n\taveragepopdens_dens[idx] += nn[i];\n    }\n  }\n  \n  averagepopdens_count += 1.;\n  \n}\n\n\nvoid write_averagepopdens() {\n  int i;\n  FILE *fp;\n  \n  if(averagepopdens_havefile == 1) {\n    fp = fopen(averagepopdens_outputfile,\"w\");\n  }else{\n    fp = stdout;\n  }\n  \n  for(i=0;i<averagepopdens_space;i++) {\n    fprintf(fp,\"%lf %e\\n\",(i-averagepopdens_space0)*averagepopdens_dx,averagepopdens_dens[i]/averagepopdens_count);\n  }\n  \n  if(averagepopdens_havefile == 1) {\n    fclose(fp);\n  }\n  \n  free(averagepopdens_dens);\n}\n\n  \n// ************************************************************\n// **   main algorithm\n// ************************************************************\n\n\nvoid update_u(int timestep) {\n   // bug if shiftthreshold -T >1, use shiftthreshold only with fixedN\n  int i,j;\n  int baseshift;\n  double fracshift;\n  \n  if(dens_ustar_latticeratio > 1) {\n    baseshift = (int)(timestep*epsilon*wavespeed/u_dx) - allshifts*dens_ustar_latticeratio;\n    fracshift = timestep*epsilon*wavespeed/u_dx - 1.*(baseshift + allshifts*dens_ustar_latticeratio);\n    i = 0;\n    j = 0;\n    while( (i<space) && (j<u_space) ) {\n      if((j+baseshift)%dens_ustar_latticeratio == 0) {\n\tu[i] = (fracshift) * u_read[j];\n      }else if((j+baseshift)%dens_ustar_latticeratio == dens_ustar_latticeratio - 1) {\n\tu[i] += (1.-fracshift) * u_read[j];\n\tu[i] /= (1.*dens_ustar_latticeratio);\n\ti++;\n      }else{\n\tu[i] += u_read[j];\n      }\n      j++;\n    }\n  }else{\n    fracshift = timestep*epsilon*wavespeed/u_dx - 1.*allshifts;\n    // ignore u[0], as it is unlikely that the population has a significant subpop there...\n    for(i=1;i<space;i++)u[i] = fracshift * u_read[i-1] + (1.-fracshift)*u_read[i];\n  }\n}\n\n\nvoid update_mean_fit() {\n  int i;\n  current_mean_fitness = 0.;\n  populationsize = 0.;\n  for(i=0;i<space;i++) {\n    current_mean_fitness += (i-space0)*(ww[i]+vv[i]);\n    populationsize += ww[i] + vv[i];\n  }\n  current_mean_fitness *= dx/populationsize;\n}\n  \n\n\nvoid shift_population_backward(int step) {\n  int i;\n  for(i=0;i<space-step;i++){\n    ww[i] = ww[i+step];\n    vv[i] = vv[i+step];\n  }\n  for(i=space-step;i<space;i++) {\n    ww[i] = 0.;\n    vv[i] = 0.;\n  }\n}\n\n\nvoid shift_population_forward(int step) {\n  int i;\n  for(i=space-1;i>step;i--) {\n    ww[i] = ww[i-step];\n    vv[i] = vv[i-step];\n  }\n  for(i=step;i>=0;i--) {\n    ww[i] = 0.;\n    vv[i] = 0.;\n  }\n}\n\n\nvoid shift_population(int timestep) {\n  int shift = (int)floor(current_mean_fitness/dx);\n  if(shift >= shiftthreshold) {shift_population_backward(shift);}\n  if(shift <= -shiftthreshold) {shift_population_forward(shift);}\n  allshifts += shift;\n  current_mean_fitness -= shift*dx;\n}\n\n\n\n\nvoid reproduce(int timestep) {\n  int i,j;\n  double tmpn;\n  \n  \n  if(noise < 2) {\n    update_mean_fit();\n  }else if(noise == 2) {\n    current_mean_fitness = timestep*wavespeed*epsilon - allshifts*dx;\n  }\n  \n  if((current_mean_fitness > shiftthreshold*dx) || (current_mean_fitness < -shiftthreshold*dx)) {\n    shift_population(timestep);\n  }\n      \n  tmpw[0] = 0;\n  tmpw[space-1] = 0;\n  \n  tmpv[0] = 0;\n  tmpv[space-1] = 0;\n\n  for(i=1;i<space-1;i++) {\n    tmpw[i] = ww[i]*(1.+(x[i]-mutationrate-current_mean_fitness)*epsilon);\n    tmpv[i] = vv[i]*(1.+(x[i]-mutationrate-current_mean_fitness)*epsilon);\n    for(j = 1;j<=i;j++) {\n      tmpw[i] += mutation_inflow[j]*ww[i-j];\n      tmpv[i] += mutation_inflow[j]*vv[i-j];\n    }\n    if(tmpw[i]<0) {\n      tmpw[i] = 0;\n    }else if(noise > 0) {\n      if(tmpw[i] < 1e9) { // Poisson-RNG breaks down for parameters > 1e9. see GSL doc.\n\t\t\t // use smaller bins if this occurs too often or population size too large\n\ttmpw[i] += twoepssqrt*(gsl_ran_poisson(rg,tmpw[i])-tmpw[i]);\n      }else{\n\ttmpw[i] = 1e9;\n      }\n    }\n    \n    if(tmpv[i]<0) {\n      tmpv[i] = 0;\n    }else if(noise > 0) {\n      if(tmpv[i] < 1e9) { // Poisson-RNG breaks down for parameters > 1e9. see GSL doc.\n\t\t\t // use smaller bins if this occurs too often or population size too large\n\ttmpv[i] += twoepssqrt*(gsl_ran_poisson(rg,tmpv[i])-tmpv[i]);\n      }else{\n\ttmpv[i] = 1e9;\n      }\n    }\n    \n  }\n  \n  memcpy(ww,tmpw,space*sizeof(double));\n  memcpy(vv,tmpv,space*sizeof(double));\n  \n}\n\n\nvoid populationconstraint(int timestep) {\n  int i;\n  double sum = 0., inv;\n  \n  if(noise == 2) {\n    update_u(timestep);\n  }\n  current_fixation_prob = 0;\n  popdens_0thmom = 0;\n  popdens_1stmom = 0;\n  popdens_2ndmom = 0;\n  fe_subpopsize = 0;\n  for(i=0;i<space;i++) {\n    sum += (ww[i] + vv[i])*u[i];\n    current_fixation_prob += ww[i]*u[i];\n    fe_subpopsize += ww[i];\n    popdens_0thmom += ww[i] + vv[i];\n    popdens_1stmom += (i-space0)*(ww[i] + vv[i]);\n    popdens_2ndmom += (i-space0)*(i-space0)*(ww[i] + vv[i]);\n  }\n  popdens_1stmom *= dx;\n  popdens_2ndmom *= dx*dx;\n  \n  populationsize = popdens_0thmom;\n  populationvariance = popdens_2ndmom/popdens_0thmom - popdens_1stmom*popdens_1stmom/(popdens_0thmom*popdens_0thmom);\n  \n  inv = 1./(sum);\n  current_fixation_prob *= inv;\n  for(i=0;i<space;i++) {\n    ww[i] *= inv;\n    vv[i] *= inv;\n  }\n}\n\n\n\nvoid initial_constraint() {\n  int i;\n  double sum=0;\n  double inv;\n  for(i=0;i<space;i++)sum += nn[i] * u[i];\n  inv = 1./sum;\n  for(i=0;i<space;i++)nn[i] *= inv;\n}\n\n\n\n\n// ************************************************************\n// **   extinction and fixation events\n// ************************************************************\n\nint init_fe() {\n  int i,j;\n  int startindex = space;\n  double fixprob = 0.,frac_lastbin;\n  \n  ww = (double*)malloc(space*sizeof(double));\n  vv = (double*)malloc(space*sizeof(double));\n  fe_start_ww = (double*)malloc(space*sizeof(double));\n  fe_start_vv = (double*)malloc(space*sizeof(double));\n  tmpw = (double*)malloc(space*sizeof(double));\n  tmpv = (double*)malloc(space*sizeof(double));\n  \n  update_u(0);\n  initial_constraint();\n  while (fixprob < fe_expected_fixationprobability) {\n    startindex--;\n    fixprob += nn[startindex]*u[startindex];\n  }\n  \n  frac_lastbin = 1. + (fe_expected_fixationprobability - fixprob)/(nn[startindex]*u[startindex]);\n  fe_predicted_fixationprobability = fixprob;\n  for(j=0;j<space;j++) {\n    if(j<startindex) {\n      ww[j] = 0;\n      vv[j] = nn[j];\n    }else if(j==startindex){\n      ww[j] = frac_lastbin*nn[j];\n      vv[j] = (1-frac_lastbin)*nn[j];\n    }else{\n      ww[j] = nn[j];\n      vv[j] = 0;\n    }\n  }\n\n  memcpy(fe_start_ww,ww,space*sizeof(double));\n  memcpy(fe_start_vv,vv,space*sizeof(double));\n}\n\n\ndouble reset_fe() {\n  allshifts = 0;\n  memcpy(ww,fe_start_ww,space*sizeof(double));\n  memcpy(vv,fe_start_vv,space*sizeof(double));\n}\n\n\n\n\n// ************************************************************\n// **   cleanup\n// ************************************************************\n\n\n  \nvoid cleanup() {\n  free(nn);\n  free(tmp);\n  free(x);\n  free(mutation_inflow);\n  free(u);\n  if(noise == 2) {\n    free(u_read);\n  }\n  free(ww);\n  free(vv);\n  free(tmpw);\n  free(tmpv);\n  free(fe_start_ww);\n  free(fe_start_vv);\n}\n\n\n\n// ************************************************************\n// **   main\n// ************************************************************\n\n\nint main(int argn, char *argv[]) {\n  int i=1;\n  double v;\n  \n  parsecomamndline(argn,argv);\n  initialize();\n  init_fe();\n  populationconstraint(0);\n  if(averagepopdens) {\n    init_averagepopdens();\n  }\n  if (quiet<2) fprintf(stdout,\"%10.3lf %20.10e %.10e %.10e %.10e %.10e\\n\",i*epsilon,0.,populationvariance,populationsize,fe_subpopsize,current_fixation_prob);\n  \n  \n//   print_populationdensity(0);\n//   exit(1);\n  \n\n  while(fe_count_extinctions + fe_count_fixations < maxSteps) {\n    reproduce(i);\n    populationconstraint(i);\n    \n    \n    \n    if(i%outputstep == 0) {\n      if (quiet<2)fprintf(stdout,\"%10.3lf %20.10e %.10e %.10e %.10e %.10e\\n\",i*epsilon,allshifts*dx + popdens_1stmom/popdens_0thmom,populationvariance,populationsize,fe_subpopsize,current_fixation_prob);\n      if (quiet==0) print_populationdensity(i);\n      if (averagepopdens) update_averagepopdens();\n    }\n    if(current_fixation_prob < fe_final_threshold) {\n      reset_fe();\n      fe_count_extinctions++;\n      printf(\"# event ( %d of %d ): extinction %lf\\n\",fe_count_extinctions+fe_count_fixations,maxSteps,i*epsilon);\n      i=0;\n    }\n    if(current_fixation_prob > 1-fe_final_threshold) {\n      reset_fe();\n      fe_count_fixations++;\n      printf(\"# event ( %d of %d ): fixation %lf\\n\",fe_count_extinctions+fe_count_fixations,maxSteps,i*epsilon);\n      i=0;\n    }\n    i++;\n  }\n  if(write_to_file)write_popdens();\n  if(averagepopdens)write_averagepopdens();\n  cleanup();\n  return 0;\n}\n\n", "meta": {"hexsha": "c5685b5f0df44b6602c29a987f349dfe0bd621ae", "size": 20526, "ext": "c", "lang": "C", "max_stars_repo_path": "stochastics/travelingwavepeak_exp_event.c", "max_stars_repo_name": "lukasgeyrhofer/adaptivewaves", "max_stars_repo_head_hexsha": "073a021b3d09f162445cb2ad38a7308a3e08465d", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-12T19:36:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-26T23:07:47.000Z", "max_issues_repo_path": "stochastics/travelingwavepeak_exp_event.c", "max_issues_repo_name": "lukasgeyrhofer/adaptivewaves", "max_issues_repo_head_hexsha": "073a021b3d09f162445cb2ad38a7308a3e08465d", "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": "stochastics/travelingwavepeak_exp_event.c", "max_forks_repo_name": "lukasgeyrhofer/adaptivewaves", "max_forks_repo_head_hexsha": "073a021b3d09f162445cb2ad38a7308a3e08465d", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2162162162, "max_line_length": 203, "alphanum_fraction": 0.5907142161, "num_tokens": 5959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3832965520328217}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_errno.h>\n\n#include \"ccl.h\"\n\n\n/*----- ROUTINE: dc_NakamuraSuto -----\nINPUT: cosmology, scale factor\nTASK: Computes the peak threshold: delta_c(z) assuming LCDM.\nCosmology dependence of the critical linear density according to the spherical-collapse model.\nFitting function from Nakamura & Suto (1997; arXiv:astro-ph/9710107).\n*/\ndouble dc_NakamuraSuto(ccl_cosmology *cosmo, double a, int *status){\n\n  double Om_mz = ccl_omega_x(cosmo, a, ccl_species_m_label, status);\n  double dc0 = (3./20.)*pow(12.*M_PI,2./3.);\n  double dc = dc0*(1.+0.012299*log10(Om_mz));\n\n  return dc;\n\n}\n\n/*----- ROUTINE: Dv_BryanNorman -----\nINPUT: cosmology, scale factor\nTASK: Computes the virial collapse density contrast with respect to the matter density assuming LCDM.\nCosmology dependence of the virial collapse density according to the spherical-collapse model\nFitting function from Bryan & Norman (1998; arXiv:astro-ph/9710107)\n*/\ndouble Dv_BryanNorman(ccl_cosmology *cosmo, double a, int *status){\n\n  double Om_mz = ccl_omega_x(cosmo, a, ccl_species_m_label, status);\n  double x = Om_mz-1.;\n  double Dv0 = 18.*pow(M_PI,2);\n  double Dv = (Dv0+82.*x-39.*pow(x,2))/Om_mz;\n\n  return Dv;\n}\n\n/*----- ROUTINE: r_delta -----\nINPUT: cosmology, halo mass, scale factor, halo overdensity\nTASK: Computes comoving halo radius assuming the overdensity criteria\n*/\ndouble r_delta(ccl_cosmology *cosmo, double halomass, double a, double odelta, int *status){\n\n  double rho_matter = ccl_rho_x(cosmo, 1., 1, 1, status);\n\n  return pow(halomass*3.0/(4.0*M_PI*rho_matter*odelta),1.0/3.0);\n\n}\n\n// This checks to make sure all necessary halo mass function parameters have been set-up,\n// as well as associated splines.\nvoid ccl_cosmology_compute_hmfparams(ccl_cosmology *cosmo, int *status) {\n  if(cosmo->computed_hmfparams)\n    return;\n\n  gsl_spline* alphahmf = NULL;\n  gsl_spline* betahmf = NULL;\n  gsl_spline* gammahmf = NULL;\n  gsl_spline* phihmf = NULL;\n  gsl_spline* etahmf = NULL;\n\n  // declare parameter splines on case-by-case basis\n  switch(cosmo->config.mass_function_method) {\n  case ccl_tinker10:{\n    double delta[9] = {200.0, 300.0, 400.0, 600.0, 800.0, 1200.0, 1600.0, 2400.0, 3200.0};\n    double lgdelta[9];\n    double alpha[9] = {0.368, 0.363, 0.385, 0.389, 0.393, 0.365, 0.379, 0.355, 0.327};\n    double beta[9] = {0.589, 0.585, 0.544, 0.543, 0.564, 0.623, 0.637, 0.673, 0.702};\n    double gamma[9] ={0.864, 0.922, 0.987, 1.09, 1.20, 1.34, 1.50, 1.68, 1.81};\n    double phi[9] = {-0.729, -0.789, -0.910, -1.05, -1.20, -1.26, -1.45, -1.50, -1.49};\n    double eta[9] = {-0.243, -0.261, -0.261, -0.273, -0.278, -0.301, -0.301, -0.319, -0.336};\n    int nd = 9;\n    int i;\n\n    for(i=0; i<nd; i++) {\n      lgdelta[i] = log10(delta[i]);\n    }\n\n    if (*status == 0) {\n      alphahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);\n      if (alphahmf == NULL) {\n        *status = CCL_ERROR_MEMORY;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating alpha(D) spline\\n\");\n      }\n    }\n    if (*status == 0) {\n      *status = gsl_spline_init(alphahmf, lgdelta, alpha, nd);\n      if (*status) {\n        *status = CCL_ERROR_SPLINE ;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating alpha(D) spline\\n\");\n      }\n    }\n\n    if (*status == 0) {\n      betahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);\n      if (betahmf == NULL) {\n        *status = CCL_ERROR_MEMORY;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating beta(D) spline\\n\");\n      }\n    }\n    if (*status == 0) {\n      *status = gsl_spline_init(betahmf, lgdelta, beta, nd);\n      if (*status) {\n        *status = CCL_ERROR_SPLINE;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating beta(D) spline\\n\");\n      }\n    }\n\n    if (*status == 0) {\n      gammahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);\n      if (gammahmf == NULL) {\n        *status = CCL_ERROR_MEMORY;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating gamma(D) spline\\n\");\n      }\n    }\n    if (*status == 0) {\n      *status = gsl_spline_init(gammahmf, lgdelta, gamma, nd);\n      if (*status) {\n        *status = CCL_ERROR_SPLINE;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating gamma(D) spline\\n\");\n      }\n    }\n\n    if (*status == 0) {\n      phihmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);\n      if (phihmf == NULL) {\n        *status = CCL_ERROR_MEMORY;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating phi(D) spline\\n\");\n      }\n    }\n    if (*status == 0) {\n      *status = gsl_spline_init(phihmf, lgdelta, phi, nd);\n      if (*status) {\n        *status = CCL_ERROR_SPLINE;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating phi(D) spline\\n\");\n      }\n    }\n\n    if (*status == 0) {\n      etahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);\n      if (etahmf == NULL) {\n        *status = CCL_ERROR_MEMORY;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating eta(D) spline\\n\");\n      }\n    }\n    if (*status == 0) {\n      *status = gsl_spline_init(etahmf, lgdelta, eta, nd);\n      if (*status) {\n        *status = CCL_ERROR_SPLINE;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating eta(D) spline\\n\");\n      }\n    }\n\n    if (*status == 0) {\n      cosmo->data.alphahmf = alphahmf;\n      cosmo->data.betahmf = betahmf;\n      cosmo->data.gammahmf = gammahmf;\n      cosmo->data.phihmf = phihmf;\n      cosmo->data.etahmf = etahmf;\n      cosmo->computed_hmfparams = true;\n    }\n    break;\n  }\n  case ccl_tinker:{\n    double delta[9] = {200.0, 300.0, 400.0, 600.0, 800.0, 1200.0, 1600.0, 2400.0, 3200.0};\n    double lgdelta[9];\n    double alpha[9] = {0.186, 0.200, 0.212, 0.218, 0.248, 0.255, 0.260, 0.260, 0.260};\n    double beta[9] = {1.47, 1.52, 1.56, 1.61, 1.87, 2.13, 2.30, 2.53, 2.66};\n    double gamma[9] ={2.57, 2.25, 2.05, 1.87, 1.59, 1.51, 1.46, 1.44, 1.41};\n    double phi[9] = {1.19, 1.27, 1.34, 1.45, 1.58, 1.80, 1.97, 2.24, 2.44};\n    int nd = 9;\n    int i;\n\n    for(i=0; i<nd; i++) {\n      lgdelta[i] = log10(delta[i]);\n    }\n\n    if (*status == 0) {\n      alphahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);\n      if (alphahmf == NULL) {\n        *status = CCL_ERROR_MEMORY;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating alpha(D) spline\\n\");\n      }\n    }\n    if (*status == 0) {\n      *status = gsl_spline_init(alphahmf, lgdelta, alpha, nd);\n      if (*status) {\n        *status = CCL_ERROR_SPLINE;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating alpha(D) spline\\n\");\n      }\n    }\n\n    if (*status == 0) {\n      betahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);\n      if (betahmf == NULL) {\n        *status = CCL_ERROR_MEMORY;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating beta(D) spline\\n\");\n      }\n    }\n    if (*status == 0) {\n      *status = gsl_spline_init(betahmf, lgdelta, beta, nd);\n      if (*status) {\n        *status = CCL_ERROR_SPLINE;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating beta(D) spline\\n\");\n      }\n    }\n\n    if (*status == 0) {\n      gammahmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);\n      if (gammahmf == NULL) {\n        *status = CCL_ERROR_MEMORY;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating gamma(D) spline\\n\");\n      }\n    }\n    if (*status == 0) {\n      *status = gsl_spline_init(gammahmf, lgdelta, gamma, nd);\n      if (*status) {\n        *status = CCL_ERROR_SPLINE;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating gamma(D) spline\\n\");\n      }\n    }\n\n    if (*status == 0) {\n      phihmf = gsl_spline_alloc(cosmo->spline_params.D_SPLINE_TYPE, nd);\n      if (phihmf == NULL) {\n        *status = CCL_ERROR_MEMORY;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error allocating phi(D) spline\\n\");\n      }\n    }\n    if (*status == 0) {\n      *status = gsl_spline_init(phihmf, lgdelta, phi, nd);\n      if (*status) {\n        *status = CCL_ERROR_SPLINE;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_massfunc.c: ccl_cosmology_compute_hmfparams(): Error creating phi(D) spline\\n\");\n      }\n    }\n\n    if (*status == 0) {\n      cosmo->data.alphahmf = alphahmf;\n      cosmo->data.betahmf = betahmf;\n      cosmo->data.gammahmf = gammahmf;\n      cosmo->data.phihmf = phihmf;\n      cosmo->computed_hmfparams = true;\n    }\n\n    break;\n  }\n  default:\n    // Error message could go here if we decide to make this public facing.\n    // Currently not accessible from the API though.\n    break;\n  }\n\n  if (*status) {\n    gsl_spline_free(alphahmf);\n    gsl_spline_free(betahmf);\n    gsl_spline_free(gammahmf);\n    gsl_spline_free(phihmf);\n    gsl_spline_free(etahmf);\n  }\n}\n\n//TODO: some of these are unused, many are included in ccl.h\n\n/*----- ROUTINE: ccl_massfunc_f -----\nINPUT: cosmology+parameters, a halo mass, and scale factor\nTASK: Outputs fitting function for use in halo mass function calculation;\n  currently only supports:\n    ccl_tinker (arxiv 0803.2706 )\n    ccl_tinker10 (arxiv 1001.3162 )\n    ccl_angulo (arxiv 1203.3216 )\n    ccl_watson (arxiv 1212.0095 )\n    ccl_shethtormen (arxiv 9901122)\n-*/\nstatic double massfunc_f(ccl_cosmology *cosmo, double halomass, double a, double odelta, int *status)\n{\n  double fit_A, fit_a, fit_b, fit_c, fit_d, fit_p, overdensity_delta;\n  double Omega_m_a;\n  double delta_c_Tinker, nu;\n\n  double sigma=ccl_sigmaM(cosmo, log10(halomass), a, status);\n  int gslstatus;\n\n  switch(cosmo->config.mass_function_method) {\n\n  // Equation (10) in arxiv: 9901122\n  // Note that Sheth & Tormen (1999) use nu=(dc/sigma)^2 whereas we use nu=dc/sigma\n  case ccl_shethtormen:\n\n    // Check if odelta is outside the interpolated range\n    if (odelta != Dv_BryanNorman(cosmo, a, status)) {\n      *status = CCL_ERROR_HMF_DV;\n      ccl_cosmology_set_status_message(\n        cosmo, \"ccl_massfunc.c: massfunc_f(): Sheth-Tormen called with not virial Delta_v\\n\");\n      return NAN;\n    }\n\n    // ST mass function fitting parameters\n    fit_A = 0.21616;\n    fit_p = 0.3;\n    fit_a = 0.707;\n\n    // nu = delta_c(z) / sigma(M)\n    nu = dc_NakamuraSuto(cosmo, a, status)/ccl_sigmaM(cosmo, log10(halomass), a, status);\n\n    return nu*fit_A*(1.+pow(fit_a*pow(nu,2),-fit_p))*exp(-fit_a*pow(nu,2)/2.);\n\n  case ccl_tinker:\n\n    // Check if odelta is outside the interpolated range\n    if ((odelta < 200) || (odelta > 3200)) {\n      *status = CCL_ERROR_HMF_INTERP;\n      ccl_cosmology_set_status_message(\n        cosmo,\n        \"ccl_massfunc.c: massfunc_f(): Tinker 2008 only \"\n        \"supported in range of Delta = 200 to Delta = 3200.\\n\");\n      return NAN;\n    }\n\n    if (!cosmo->computed_hmfparams) {\n      *status = CCL_ERROR_HMF_INIT;\n      ccl_cosmology_set_status_message(\n        cosmo,\n        \"ccl_massfunc.c: massfunc_f(): mass function parameters splines have not been computed!\");\n      return NAN;\n    }\n\n    // Compute HMF parameter (alpha, beta, gamma, phi) splines if they haven't\n    // been computed already\n    gslstatus = gsl_spline_eval_e(cosmo->data.alphahmf, log10(odelta), NULL, &fit_A);\n    gslstatus |= gsl_spline_eval_e(cosmo->data.betahmf, log10(odelta), NULL, &fit_a);\n    gslstatus |= gsl_spline_eval_e(cosmo->data.gammahmf, log10(odelta), NULL, &fit_b);\n    gslstatus |= gsl_spline_eval_e(cosmo->data.phihmf, log10(odelta), NULL, &fit_c);\n    fit_d = pow(10, -1.0*pow(0.75 / log10(odelta / 75.0), 1.2));\n\n    fit_A = fit_A*pow(a, 0.14);\n    fit_a = fit_a*pow(a, 0.06);\n    fit_b = fit_b*pow(a, fit_d);\n    if(gslstatus != GSL_SUCCESS) {\n      ccl_raise_gsl_warning(gslstatus, \"ccl_massfunc.c: massfunc_f():\");\n      *status |= gslstatus;\n      ccl_cosmology_set_status_message(\n        cosmo, \"ccl_massfunc.c: massfunc_f(): interpolation error for Tinker MF\\n\");\n      return NAN;\n    }\n    return fit_A*(pow(sigma/fit_b,-fit_a)+1.0)*exp(-fit_c/sigma/sigma);\n    break;\n  case ccl_tinker10:\n    // this version uses f(nu) parameterization from Eq. 8 in Tinker et al. 2010\n    // use this for consistency with Tinker et al. 2010 fitting function for halo bias\n\n    // Check if odelta is outside the interpolated range\n    if ((odelta < 200) || (odelta > 3200)) {\n      *status = CCL_ERROR_HMF_INTERP;\n      ccl_cosmology_set_status_message(\n        cosmo,\n        \"ccl_massfunc.c: massfunc_f(): Tinker 2010 only \"\n        \"supported in range of Delta = 200 to Delta = 3200.\\n\");\n      return 0;\n    }\n\n    //critical collapse overdensity assumed in this model\n    delta_c_Tinker = 1.686;\n    nu = delta_c_Tinker/(sigma);\n\n    if (!cosmo->computed_hmfparams) {\n      *status = CCL_ERROR_HMF_INIT;\n      ccl_cosmology_set_status_message(\n        cosmo,\n        \"ccl_massfunc.c: massfunc_f(): mass function parameters splines have not been computed!\");\n      return NAN;\n    }\n\n    gslstatus = gsl_spline_eval_e(cosmo->data.alphahmf, log10(odelta), NULL, &fit_A); //alpha in Eq. 8\n    gslstatus |= gsl_spline_eval_e(cosmo->data.etahmf, log10(odelta), NULL, &fit_a); //eta in Eq. 8\n    gslstatus |= gsl_spline_eval_e(cosmo->data.betahmf, log10(odelta), NULL, &fit_b); //beta in Eq. 8\n    gslstatus |= gsl_spline_eval_e(cosmo->data.gammahmf, log10(odelta), NULL, &fit_c); //gamma in Eq. 8\n    gslstatus |= gsl_spline_eval_e(cosmo->data.phihmf, log10(odelta), NULL, &fit_d); //phi in Eq. 8;\n\n    fit_a *=pow(a, -0.27);\n    fit_b *=pow(a, -0.20);\n    fit_c *=pow(a, 0.01);\n    fit_d *=pow(a, 0.08);\n    if(gslstatus != GSL_SUCCESS) {\n      ccl_raise_gsl_warning(gslstatus, \"ccl_massfunc.c: massfunc_f():\");\n      *status |= gslstatus;\n      ccl_cosmology_set_status_message(\n        cosmo, \"ccl_massfunc.c: massfunc_f(): interpolation error for Tinker 2010 MF\\n\");\n      return NAN;\n    }\n    return nu*fit_A*(1.+pow(fit_b*nu,-2.*fit_d))*pow(nu, 2.*fit_a)*exp(-0.5*fit_c*nu*nu);\n    break;\n\n  case ccl_watson:\n    if(odelta!=200.) {\n      *status = CCL_ERROR_HMF_INTERP;\n      ccl_cosmology_set_status_message(\n        cosmo, \"ccl_massfunc.c: massfunc_f(): Watson HMF only supported for Delta = 200.\\n\");\n      return NAN;\n    }\n    // these parameters from: Angulo et al 2012 (arxiv 1203.3216 )\n    Omega_m_a = ccl_omega_x(cosmo, a, ccl_species_m_label,status);\n    fit_A = Omega_m_a*(0.990*pow(a,3.216)+0.074);\n    fit_a = Omega_m_a*(5.907*pow(a,3.599)+2.344);\n    fit_b = Omega_m_a*(3.136*pow(a,3.058)+2.349);\n    fit_c = 1.318;\n\n    return fit_A*(pow(sigma/fit_b,-fit_a)+1.0)*exp(-fit_c/sigma/sigma);\n\n  case ccl_angulo:\n    if(odelta!=200.) {\n      *status = CCL_ERROR_HMF_INTERP;\n      ccl_cosmology_set_status_message(\n        cosmo, \"ccl_massfunc.c: massfunc_f(): Angulo HMF only supported for Delta = 200.\\n\");\n      return NAN;\n    }\n    // these parameters from: Watson et al 2012 (arxiv 1212.0095 )\n    fit_A = 0.201;\n    fit_a = 2.08;\n    fit_b = 1.7;\n    fit_c = 1.172;\n\n    return fit_A*pow( (fit_a/sigma)+1.0, fit_b)*exp(-fit_c/sigma/sigma);\n\n  default:\n    *status = CCL_ERROR_MF;\n    ccl_cosmology_set_status_message(cosmo ,\n\t    \"ccl_massfunc.c: massfunc_f(): Unknown or non-implemented mass function method: %d \\n\",\n\t    cosmo->config.mass_function_method);\n    return NAN;\n  }\n}\n\nstatic double ccl_halo_b1(ccl_cosmology *cosmo, double halomass, double a, double odelta, int *status)\n{\n  double fit_A, fit_B, fit_C, fit_a, fit_b, fit_c, fit_p, overdensity_delta, y;\n  double delta_c_Tinker, nu;\n  double sigma=ccl_sigmaM(cosmo,log10(halomass),a, status);\n  switch(cosmo->config.mass_function_method) {\n\n  // Equation (12) in  arXiv: 9901122\n  // Derived using the peak-background split applied to the mass function in the same paper\n  // Note that Sheth & Tormen (1999) use nu=(dc/sigma)^2 whereas we use nu=dc/sigma\n  case ccl_shethtormen:\n\n    // Check if Delta_v is the virial Delta_v\n    if (odelta != Dv_BryanNorman(cosmo, a, status)) {\n      *status = CCL_ERROR_HMF_DV;\n      ccl_cosmology_set_status_message(\n        cosmo, \"ccl_massfunc.c: halo_b1(): Sheth-Tormen called with not virial Delta_v\\n\");\n      return NAN;\n    }\n\n    // ST bias fitting parameters (which are the same as for the mass function)\n    fit_p = 0.3;\n    fit_a = 0.707;\n\n    // Cosmology dependent delta_c and nu\n    double delta_c = dc_NakamuraSuto(cosmo, a, status);\n    nu = delta_c/ccl_sigmaM(cosmo, log10(halomass), a, status);\n\n    return 1.+(fit_a*pow(nu,2)-1.+2.*fit_p/(1.+pow(fit_a*pow(nu,2),fit_p)))/delta_c;\n\n    //this version uses b(nu) parameterization, Eq. 6 in Tinker et al. 2010\n    // use this for consistency with Tinker et al. 2010 fitting function for halo bias\n  case ccl_tinker10:\n    y = log10(odelta);\n    //critical collapse overdensity assumed in this model\n    delta_c_Tinker = 1.686;\n    //peak height - note that this factorization is incorrect for e.g. massive neutrino cosmologies\n    nu = delta_c_Tinker/(sigma);\n    // Table 2 in https://arxiv.org/pdf/1001.3162.pdf\n    fit_A = 1.0 + 0.24*y*exp(-pow(4./y,4.));\n    fit_a = 0.44*y-0.88;\n    fit_B = 0.183;\n    fit_b = 1.5;\n    fit_C = 0.019+0.107*y+0.19*exp(-pow(4./y,4.));\n    fit_c = 2.4;\n\n    return 1.-fit_A*pow(nu,fit_a)/(pow(nu,fit_a)+pow(delta_c_Tinker,fit_a))+fit_B*pow(nu,fit_b)+fit_C*pow(nu,fit_c);\n    break;\n\n  default:\n    *status = CCL_ERROR_MF;\n    ccl_cosmology_set_status_message(cosmo ,\n\t    \"ccl_massfunc.c: ccl_halo_b1(): No b(M) fitting function implemented for mass_function_method: %d \\n\",\n      cosmo->config.mass_function_method);\n    return 0;\n  }\n}\n\nvoid ccl_cosmology_compute_sigma(ccl_cosmology *cosmo, int *status)\n{\n  if(cosmo->computed_sigma)\n    return;\n\n  // create linearly-spaced values of the mass.\n  int nm = cosmo->spline_params.LOGM_SPLINE_NM;\n  double *m = NULL;\n  double *y = NULL;\n  double smooth_radius;\n  double na, nb;\n\n  m = ccl_linear_spacing(cosmo->spline_params.LOGM_SPLINE_MIN, cosmo->spline_params.LOGM_SPLINE_MAX, nm);\n  if (m == NULL ||\n      (fabs(m[0]-cosmo->spline_params.LOGM_SPLINE_MIN)>1e-5) ||\n      (fabs(m[nm-1]-cosmo->spline_params.LOGM_SPLINE_MAX)>1e-5) ||\n      (m[nm-1]>10E17)) {\n    *status = CCL_ERROR_MEMORY;\n    ccl_cosmology_set_status_message(cosmo,\"ccl_cosmology_compute_sigmas(): Error creating linear spacing in m\\n\");\n  }\n\n  if (*status == 0) {\n    // create space for y, to be filled with sigma and dlnsigma_dlogm\n    y = malloc(sizeof(double)*nm);\n    if (y == NULL) {\n      *status = CCL_ERROR_MEMORY;\n    }\n  }\n\n  // start up of GSL pointers\n  int gslstatus = 0;\n  gsl_spline *logsigma = NULL;\n  gsl_spline *dlnsigma_dlogm = NULL;\n\n  // fill in sigma, if no errors have been triggered at this time.\n  if (*status == 0) {\n    for (int i=0; i<nm; i++) {\n      smooth_radius = ccl_massfunc_m2r(cosmo, pow(10,m[i]), status);\n      y[i] = log(ccl_sigmaR(cosmo, smooth_radius, 1., status));\n    }\n    logsigma = gsl_spline_alloc(cosmo->spline_params.M_SPLINE_TYPE, nm);\n    if (logsigma == NULL) {\n      *status = CCL_ERROR_MEMORY;\n    }\n  }\n\n  if (*status == 0) {\n    gslstatus = gsl_spline_init(logsigma, m, y, nm);\n    if (gslstatus != GSL_SUCCESS) {\n      *status = CCL_ERROR_SPLINE ;\n      ccl_cosmology_set_status_message(\n        cosmo,\n        \"ccl_massfunc.c: ccl_cosmology_compute_sigma(): Error creating sigma(M) spline\\n\");\n    }\n  }\n\n  // again, making splines assuming nothing bad has happened to this point\n  if (*status == 0 ) {\n    for (int i=0; i<nm; i++) {\n      if(i==0) {\n        gslstatus |= gsl_spline_eval_e(logsigma, m[i], NULL,&na);\n        gslstatus |= gsl_spline_eval_e(logsigma, m[i]+cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&nb);\n        y[i] = 2.*(na-nb)*y[i] / cosmo->spline_params.LOGM_SPLINE_DELTA;\n      }\n      else if (i==nm-1) {\n        gslstatus |= gsl_spline_eval_e(logsigma, m[i]-cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&na);\n        gslstatus |= gsl_spline_eval_e(logsigma, m[i], NULL,&nb);\n        y[i] = 2.*(na-nb)*y[i] / cosmo->spline_params.LOGM_SPLINE_DELTA;\n      }\n      else {\n        gslstatus |= gsl_spline_eval_e(logsigma, m[i]-cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&na);\n        gslstatus |= gsl_spline_eval_e(logsigma, m[i]+cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&nb);\n        y[i] = (na-nb) / cosmo->spline_params.LOGM_SPLINE_DELTA;\n      }\n    }\n\n    if(gslstatus != GSL_SUCCESS ) {\n      ccl_raise_gsl_warning(\n        gslstatus, \"ccl_massfunc.c: ccl_cosmology_compute_sigma():\");\n      *status = CCL_ERROR_SPLINE;\n      ccl_cosmology_set_status_message(\n        cosmo,\n        \"ccl_massfunc.c: ccl_cosmology_compute_sigma(): \"\n        \"Error evaluating grid points for dlnsigma/dlogM spline\\n\");\n    }\n  }\n\n  if (*status == 0) {\n    dlnsigma_dlogm = gsl_spline_alloc(cosmo->spline_params.M_SPLINE_TYPE, nm);\n    if (dlnsigma_dlogm == NULL) {\n      *status = CCL_ERROR_MEMORY;\n    }\n  }\n\n  if (*status == 0) {\n    gslstatus = gsl_spline_init(dlnsigma_dlogm, m, y, nm);\n    if (gslstatus != GSL_SUCCESS) {\n      *status = CCL_ERROR_SPLINE ;\n      ccl_cosmology_set_status_message(\n        cosmo,\n        \"ccl_massfunc.c: ccl_cosmology_compute_sigma(): Error creating dlnsigma/dlogM spline\\n\");\n    }\n  }\n\n  if (*status == 0) {\n    cosmo->data.logsigma = logsigma;\n    cosmo->data.dlnsigma_dlogm = dlnsigma_dlogm;\n    cosmo->computed_sigma = true;\n  } else {\n    gsl_spline_free(logsigma);\n    gsl_spline_free(dlnsigma_dlogm);\n  }\n\n  free(m);\n  free(y);\n}\n\n/*----- ROUTINE: ccl_massfunc -----\nINPUT: ccl_cosmology * cosmo, double halo mass in units of Msun, double scale factor\nTASK: returns halo mass function as dn/dlog10(m) in comoving Msun^-1 Mpc^-3 (haloes per mass interval per volume)\n*/\ndouble ccl_massfunc(ccl_cosmology *cosmo, double halomass, double a, double odelta, int *status)\n{\n  if (cosmo->params.N_nu_mass>0){\n\t  *status = CCL_ERROR_NOT_IMPLEMENTED;\n\t  ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Support for the halo mass function in cosmologies with massive neutrinos is not yet implemented.\\n\");\n\t  return NAN;\n  }\n\n  double logmass;\n  logmass = log10(halomass);\n  if (logmass > cosmo->spline_params.LOGM_SPLINE_MAX || logmass < cosmo->spline_params.LOGM_SPLINE_MIN){\n    *status = CCL_ERROR_HMF_INTERP;\n    ccl_cosmology_set_status_message(cosmo, \"ccl_massfunc(): The specified halo mass is outside of the range.\");\n    return NAN;\n  }\n\n  if (fabs(cosmo->params.mu_0)>1e-14 || fabs(cosmo->params.sigma_0)>1e-14){\n\t  *status = CCL_ERROR_NOT_IMPLEMENTED;\n\t  strcpy(cosmo->status_message,\"ccl_massfunc.c: ccl_massfunc(): The halo mass funcion is not implemented the mu / Sigma modified gravity parameterisation.\\n\");\n\t  return NAN;\n  }\n\n  double f, rho_m;\n\n  rho_m = ccl_constants.RHO_CRITICAL*cosmo->params.Omega_m*cosmo->params.h*cosmo->params.h;\n  f=massfunc_f(cosmo,halomass,a,odelta,status);\n\n  return f*rho_m*ccl_dlnsigM_dlogM(cosmo,logmass,status)/halomass;\n}\n\n/*----- ROUTINE: ccl_halob1 -----\nINPUT: ccl_cosmology * cosmo, double halo mass in units of Msun, double scale factor\nTASK: returns dimensionless linear halo bias\n*/\ndouble ccl_halo_bias(ccl_cosmology *cosmo, double halomass, double a, double odelta, int *status)\n{\n  if (cosmo->params.N_nu_mass>0){\n\t  *status = CCL_ERROR_NOT_IMPLEMENTED;\n\t  ccl_cosmology_set_status_message(cosmo, \"ccl_background.c: ccl_cosmology_compute_growth(): Support for the halo bias in cosmologies with massive neutrinos is not yet implemented.\\n\");\n\t  return NAN;\n  }\n\n  if (fabs(cosmo->params.mu_0)>1e-14 || fabs(cosmo->params.sigma_0)>1e-14){\n\t  *status = CCL_ERROR_NOT_IMPLEMENTED;\n\t  strcpy(cosmo->status_message,\"ccl_massfunc.c: ccl_halobias(): The halo bias is not implemented the mu / Sigma modified gravity parameterisation.\\n\");\n\t  return NAN;\n  }\n\n  double f;\n  f = ccl_halo_b1(cosmo,halomass,a,odelta, status);\n  return f;\n}\n/*---- ROUTINE: ccl_massfunc_m2r -----\nINPUT: ccl_cosmology * cosmo, halomass in units of Msun\nTASK: takes halo mass and converts to halo radius\n  in units of Mpc.\n*/\ndouble ccl_massfunc_m2r(ccl_cosmology *cosmo, double halomass, int *status)\n{\n  double rho_m, smooth_radius;\n\n  // Comoving matter density\n  //rho_m = ccl_constants.RHO_CRITICAL*cosmo->params.Omega_m*cosmo->params.h*cosmo->params.h;\n  rho_m = ccl_rho_x(cosmo, 1., ccl_species_m_label, 1, status);\n\n  smooth_radius = pow((3.0*halomass) / (4*M_PI*rho_m), (1.0/3.0));\n\n  return smooth_radius;\n}\n\n/*----- ROUTINE: ccl_sigma_M -----\nINPUT: ccl_cosmology * cosmo, double halo mass in units of Msun, double scale factor\nTASK: returns sigma from the sigmaM interpolation. Also computes the sigma interpolation if\nnecessary.\n*/\ndouble ccl_sigmaM(ccl_cosmology *cosmo, double log_halomass, double a, int *status)\n{\n  double sigmaM;\n  // Check if sigma has already been calculated\n  if (!cosmo->computed_sigma) {\n    *status = CCL_ERROR_SIGMA_INIT;\n    ccl_cosmology_set_status_message(\n      cosmo,\n      \"ccl_massfunc.c: ccl_sigmaM(): linear power spctrum has not been computed!\");\n    return NAN;\n  }\n\n  double lgsigmaM;\n\n  int gslstatus = gsl_spline_eval_e(cosmo->data.logsigma, log_halomass, NULL, &lgsigmaM);\n\n  if(gslstatus != GSL_SUCCESS) {\n    ccl_raise_gsl_warning(gslstatus, \"ccl_massfunc.c: ccl_sigmaM():\");\n    *status |= gslstatus;\n  }\n\n  // Interpolate to get sigma\n  sigmaM = exp(lgsigmaM)*ccl_growth_factor(cosmo, a, status);\n  return sigmaM;\n}\n\n/*----- ROUTINE: ccl_dlnsigM_dlogM -----\nINPUT: ccl_cosmology *cosmo, double halo mass in units of Msun\nTASK: returns the value of the derivative of ln(sigma^-1) with respect to log10 in halo mass.\n*/\ndouble ccl_dlnsigM_dlogM(ccl_cosmology *cosmo, double log_halomass, int *status)\n{\n  // Check if sigma has already been calculated\n  if (!cosmo->computed_sigma) {\n    *status = CCL_ERROR_SIGMA_INIT;\n    ccl_cosmology_set_status_message(\n      cosmo,\n      \"ccl_massfunc.c: ccl_sigmaM(): linear power spctrum has not been computed!\");\n    return NAN;\n  }\n  \n  double dlsdlgm;\n  int gslstatus = gsl_spline_eval_e(cosmo->data.dlnsigma_dlogm,\n\t\t\t\t    log_halomass, NULL, &dlsdlgm);\n  if(gslstatus) { \n    ccl_raise_gsl_warning(gslstatus, \"ccl_massfunc.c: ccl_dlnsigM_dlogM():\");\n    *status |= gslstatus;\n  }\n  return dlsdlgm;\n}\n", "meta": {"hexsha": "730879d21ab036f0e1de411056ad0f7299d45f78", "size": 27333, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_massfunc.c", "max_stars_repo_name": "benediktdiemer/CCL", "max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_massfunc.c", "max_issues_repo_name": "benediktdiemer/CCL", "max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_massfunc.c", "max_forks_repo_name": "benediktdiemer/CCL", "max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z", "avg_line_length": 34.952685422, "max_line_length": 195, "alphanum_fraction": 0.6602641496, "num_tokens": 8769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.38327125517590604}}
{"text": "#ifndef SVGP_H\n#define SVGP_H\n\n#define M_PI 3.14159265358979323846\n\n#include \"Vector.h\"\n#include \"Matrix.h\"\n#include \"GaussianProcess.h\"\n#include <gsl/gsl_math.h>\n\nclass SVGP //: public GaussianProcess\n\t{\n\tprotected:\n\t\tMatrix X; ///< Samples (N x M)\n\t\tVector Y; ///< Output (N x 1)\n\t\tint N; ///< Number of samples\n\t\tint d;\n\n\t\t// Kernel parameters\n\t\treal noise_var;\n\t\treal sig_var;\n\t\tVector scale_length;\n\t\t\n\t\t/// SVI parameters\n\t\tint num_inducing; ///< inducing inputs (J)\n\t\tMatrix Z; ///< Hidden variables (N x J)\n\t\tVector u; ///< Global variables (N x 1) (targets)\n\n\t\t// variational distribution parametrization\n\t\tMatrix S;\n\t\tVector m;\n\n\t\treal l; //step length\n\t\tint samples; //not currently used.. but should be\n\n\t\tVector p_mean;\n\t\tMatrix p_var;\n\n\t\tMatrix Kmm;\n\t\tMatrix Knm;\n\t\tMatrix Kmn;\n\t\tMatrix Knn;\n\t\tMatrix invKmm;\n\t\tMatrix K_tilde;\n\n\t\treal Beta;\n\t\treal KL;\n\t\treal L;\n\n        Matrix currentSample;\n        Vector currentObservation;\n\n        //preferably these could be done in minibatches but only with single examples for now\n        //the example is repeated <subsamples> times as in Hoffman et al [2013]\n        virtual void local_update(); //updating Z (local/latent variables)\n        virtual void global_update(const Matrix& X_samples, const Vector& Y_samples); //updating m, S (which parametrizes q(u) and in turn gives global param u)\n\t\t//virtual Vector optimize_Z(int max_iters);\n        virtual void init();\n        //virtual real LogLikelihood(double* data); //computes the likelihood given a Z*, to use for optimizing the position of Z\n        virtual void getSamples(Matrix& X_, Vector& Y_);\n\tpublic:\n\t\tSVGP(Matrix& X, Vector& Y, Matrix& Z, real noise_var, real sig_var, Vector scale_length, int samples);\n        //initializes Z through k-means\n\t\tSVGP(Matrix& X, Vector& Y, int num_inducing, real noise_var, real sig_var, Vector scale_length, int samples);\n\t\tvirtual Matrix Kernel(const Matrix& A, const Matrix& B);\n\t\tvirtual void Prediction(const Vector& x, real& mean, real& var);\n\t\tvirtual void UpdateGaussianProcess(); //update \n\t\tvirtual void FullUpdateGaussianProcess();\n\t\tvirtual real LogLikelihood();\n        //virtual real LogLikelihood(const gsl_vector *v);\n\t\tvirtual void AddObservation(const Vector& x, const real& y);\n\t\tvirtual void AddObservation(const std::vector<Vector>& x, const std::vector<real>& y);\n\t\tvirtual void Clear();\n\n};\n#endif\n", "meta": {"hexsha": "1fe0f3e8d38fafd7a4c86095104f4d8d5289504c", "size": 2379, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SVI/svgp.h", "max_stars_repo_name": "revorg7/beliefbox", "max_stars_repo_head_hexsha": "ba974b17fbb46ac98960f31dea66115be470000e", "max_stars_repo_licenses": ["OLDAP-2.3"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-12-02T23:16:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-07T10:54:36.000Z", "max_issues_repo_path": "src/SVI/svgp.h", "max_issues_repo_name": "revorg7/beliefbox", "max_issues_repo_head_hexsha": "ba974b17fbb46ac98960f31dea66115be470000e", "max_issues_repo_licenses": ["OLDAP-2.3"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-12-02T19:47:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-14T13:08:40.000Z", "max_forks_repo_path": "src/SVI/svgp.h", "max_forks_repo_name": "revorg7/beliefbox", "max_forks_repo_head_hexsha": "ba974b17fbb46ac98960f31dea66115be470000e", "max_forks_repo_licenses": ["OLDAP-2.3"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-01-14T14:23:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-29T12:46:41.000Z", "avg_line_length": 30.8961038961, "max_line_length": 160, "alphanum_fraction": 0.6973518285, "num_tokens": 615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3831922318348609}}
{"text": "/*\nCopyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com>\nLicensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n*/\n \n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <cblas.h>\n#include \"morn_tensor.h\"\n\nvoid ConvTensorToMatData(MTensor *tns,int bc,float *mdata,int knl_height,int knl_width,int y_stride,int x_stride);\nvoid ConvMatDataToTensor(float *mdata,MTensor *tns,int bc,int knl_height,int knl_width,int y_stride,int x_stride);\n\nstruct TensorSampleConvPara\n{\n    MLayer *prev;\n    \n    int knl_num;\n    int knl_height;\n    int knl_width;\n    \n    int x_stride;\n    int y_stride;\n    \n    float sample_ratio;\n    \n    int res_valid;\n    \n    float rate;\n    float decay;\n    float momentum;\n};\nvoid *mTensorSampleConvPara(MSheet *ini,char *name)\n{\n    struct TensorSampleConvPara *para = (struct TensorSampleConvPara *)mMalloc(sizeof(struct TensorSampleConvPara));\n   \n    char *value = mINIRead(ini,name,\"prev\");\n    para->prev = mNetworkLayer(ini,value);\n    mException((para->prev == NULL),EXIT,\"invalid prev\");\n    \n    para->res_valid = (strcmp(\"Input\",mLayerType(para->prev))!=0);\n    \n    value = mINIRead(ini,name,\"knl_num\");\n    if(value != NULL) para->knl_num= atoi(value);else para->knl_num= 1; \n    \n    value = mINIRead(ini,name,\"knl_height\");\n    if(value != NULL) para->knl_height= atoi(value);else para->knl_height= 1; \n    \n    value = mINIRead(ini,name,\"knl_width\");\n    if(value != NULL) para->knl_width= atoi(value);else para->knl_width= 1; \n    \n    value = mINIRead(ini,name,\"x_stride\");\n    if(value != NULL) para->x_stride= atoi(value);else para->x_stride= 1;\n    \n    value = mINIRead(ini,name,\"y_stride\");\n    if(value != NULL) para->y_stride= atoi(value);else para->y_stride= 1;\n    \n    value = mINIRead(ini,name,\"sample_ratio\");\n    if(value != NULL) para->sample_ratio = atof(value);else para->sample_ratio = 0.5;\n    \n    value = mINIRead(ini,name,\"rate\");\n    if(value != NULL) para->rate = atof(value);\n    else\n    {\n        value = mINIRead(ini,\"para\",\"rate\");\n        if(value != NULL) para->rate = atof(value);\n        else              para->rate = 0.001;\n    }\n    \n    value = mINIRead(ini,name,\"decay\");\n    if(value != NULL) para->decay = atof(value);\n    else\n    {\n        value = mINIRead(ini,\"para\",\"decay\");\n        if(value != NULL) para->decay = atof(value);\n        else              para->decay = 0.01;\n    }\n    mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,\"invalid para decay\");\n    \n    value = mINIRead(ini,name,\"momentum\");\n    if(value != NULL) para->momentum = atof(value); \n    else\n    {\n        value = mINIRead(ini,\"para\",\"momentum\");\n        if(value != NULL) para->momentum = atof(value);\n        else              para->momentum = 0.9;\n    }\n\n    return para;\n}\n\nstruct HandleTensorSampleConv\n{\n    float *mat;\n    float *data;\n    float *kernel;\n    float *update;\n    int   *locate;\n};\nvoid endTensorSampleConv(void *info)\n{\n    struct HandleTensorSampleConv *handle = (struct HandleTensorSampleConv *)info;\n    if(handle->mat   != NULL) mFree(handle->mat   );\n    if(handle->data  != NULL) mFree(handle->data  );\n    if(handle->kernel!= NULL) mFree(handle->kernel);\n    if(handle->update!= NULL) mFree(handle->update);\n    if(handle->locate!= NULL) mFree(handle->locate);\n}\n#define HASH_TensorSampleConv 0x8a31af2\nvoid TensorSampleConvSet(MLayer *layer)\n{\n    if(layer->state != DFLT) return;\n    \n    struct TensorSampleConvPara *para = (struct TensorSampleConvPara *)(layer->para);\n    MTensor *in = para->prev->tns;\n    MTensor *res= para->prev->res;\n    MTensor *out= layer->tns;\n    \n    MHandle *hdl=mHandle(out,TensorSampleConv);\n    struct HandleTensorSampleConv *handle = (struct HandleTensorSampleConv *)(hdl->handle);\n    \n    int out_height= in->height/para->y_stride;\n    int out_width = in->width /para->x_stride;\n    int mheight = (out_height*out_width);\n    int mwidth = (para->knl_height*para->knl_width*in->channel)*para->sample_ratio;\n    \n    int data_size = para->knl_num*(mwidth+1);\n    \n    mTensorRedefine(out,in->batch,para->knl_num,out_height,out_width,NULL);\n    if(morn_network_flag == MORN_TRAIN)\n    {\n        if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);\n        else                    mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);\n   \n        if(handle->update != NULL) mFree(handle->update);\n        handle->update =(float *)mMalloc(data_size*sizeof(float));\n        memset(handle->update,0,data_size*sizeof(float));\n    }\n    \n    if(handle->kernel !=NULL) mFree(handle->kernel);\n    handle->kernel = (float *)mMalloc(data_size*sizeof(float));\n    \n    if(morn_network_parafile==NULL)\n    {\n        float scale = sqrt(2.0f/mwidth);\n        for(int i=0;i<data_size;i++)\n            handle->kernel[i] = mNormalRand(0.0f,1.0f)*scale;\n    }\n    else\n    {\n        mNetworkParaRead(layer,\"kernel\",handle->kernel,data_size*sizeof(float));\n    }\n    \n    int matwidth = para->knl_height*para->knl_width*in->channel+1;\n    if(handle->mat!=NULL) mFree(handle->mat);\n    handle->mat = (float *)mMalloc(mheight*matwidth*sizeof(float));\n    \n    if(handle->data!=NULL) mFree(handle->data);\n    handle->data= (float *)mMalloc(mheight*(mwidth+1)*sizeof(float));\n    \n    if(handle->locate!=NULL) mFree(handle->locate);\n    handle->locate = (int *)mMalloc(mwidth*para->knl_num*sizeof(int));\n    if(morn_network_parafile==NULL)\n    {\n        char *flag = (char *)mMalloc(para->knl_height*para->knl_width*in->channel*sizeof(char));\n        for(int j=0;j<para->knl_num;j++)\n        {\n            memset(flag,1,para->knl_height*para->knl_width*in->channel*sizeof(char));\n            int *locate = handle->locate+j*mwidth;\n            \n            for(int i=0;i<mwidth;)\n            {\n                locate[i]=mRand(0,para->knl_height*para->knl_width*in->channel);\n                if(flag[i]==0) continue;\n                flag[i]=0; i++;\n            }\n            \n            mAscSortS32(locate,NULL,locate,NULL,mwidth);\n        }\n        mFree(flag);\n    }\n    else\n    {\n        mNetworkParaRead(layer,\"locate\",handle->locate,mwidth*para->knl_num*sizeof(int));\n    }\n    \n    hdl->valid = 1;\n}\n\nvoid mTensorSampleConvForward(MLayer *layer)\n{\n    mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n    mException(strcmp(\"SampleConv\",mLayerType(layer)),EXIT,\"invalid layer type\");\n    struct TensorSampleConvPara *para = (struct TensorSampleConvPara *)(layer->para);\n    \n    MTensor *in = para->prev->tns;\n    MTensor *out=layer->tns;\n    \n    TensorSampleConvSet(layer);\n    \n    MHandle *hdl=mHandle(out,TensorSampleConv);\n    struct HandleTensorSampleConv *handle = (struct HandleTensorSampleConv *)(hdl->handle);\n    \n    int mheight = (out->height*out->width);\n    int mwidth = (para->knl_height*para->knl_width*in->channel)*para->sample_ratio;\n    int matwidth = para->knl_height*para->knl_width*in->channel+1;\n    \n    float *mat_data = handle->mat;\n    float *in_data = handle->data;\n    \n    for(int b=0;b<in->batch;b++)\n    {\n        ConvTensorToMatData(in,b,mat_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);\n        \n        for(int k=0;k<para->knl_num;k++)\n        {\n            int   *locate = handle->locate+k* mwidth;\n            float *kernel = handle->kernel+k*(mwidth+1);\n            float *out_data = out->data[b]+k* mheight;\n            for(int j=0;j<mheight;j++)\n            {\n                for(int i=0;i<mwidth;i++) in_data[j*mwidth+i]=mat_data[j*matwidth+locate[i]];\n                in_data[j*mwidth+mwidth]=1.0f;\n            }\n        \n            cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,\n                        1,mheight,mwidth+1,\n                        1.0f,\n                          kernel,mwidth+1,\n                         in_data,mwidth+1,\n                   0.0f,out_data,mheight);\n        }\n    }\n    \n    layer->state = MORN_FORWARD;\n}\n\nvoid mTensorSampleConvBackward(MLayer *layer)\n{\n    mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n    mException(strcmp(\"SampleConv\",mLayerType(layer)),EXIT,\"invalid layer type\");\n    struct TensorSampleConvPara *para = (struct TensorSampleConvPara *)(layer->para);\n    MTensor *in = para->prev->tns;\n    MTensor *res= para->prev->res;\n    MTensor *out=layer->res;\n    \n    MHandle *hdl=mHandle(layer->tns,TensorSampleConv);\n    struct HandleTensorSampleConv *handle = (struct HandleTensorSampleConv *)(hdl->handle);\n    mException((hdl->valid == 0),EXIT,\"no forward operate\");\n    \n    int mheight = (out->height*out->width);\n    int mwidth = (para->knl_height*para->knl_width*in->channel)*para->sample_ratio;\n    int matwidth = para->knl_height*para->knl_width*in->channel+1;\n    \n    float *mat_data = handle->mat;\n    float *in_data  = handle->data;\n    float *res_data = handle->data;\n    \n    mNetworkParaWrite(layer,\"locate\",handle->locate,mwidth*para->knl_num*sizeof(int));\n    mNetworkParaWrite(layer,\"kernel\",handle->kernel,para->knl_num*mwidth*sizeof(float));\n    \n    for(int b=0;b<out->batch;b++)\n    {\n        ConvTensorToMatData(in,b,mat_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);\n        \n        for(int k=0;k<para->knl_num;k++)\n        {\n            int   *locate = handle->locate+k* mwidth;\n            float *update = handle->update+k*(mwidth+1);\n            float *out_data = out->data[b]+k* mheight;\n            for(int j=0;j<mheight;j++)\n            {\n                for(int i=0;i<mwidth;i++) in_data[j*mwidth+i]=mat_data[j*matwidth+locate[i]];\n                in_data[j*mwidth+mwidth]=1.0f;\n            }\n        \n            cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,\n                        1,mwidth,mheight,\n                        1.0f/mheight,\n                        out_data,mheight,\n                        in_data,mwidth,\n                        (b==0)?para->momentum:1.0f,\n                        update,mwidth);\n                    \n        }\n    }\n    \n    cblas_saxpby(para->knl_num*mwidth,\n                 (0.0f-(para->rate/(float)(in->batch))),handle->update,1, \n                 (1.0f-(para->decay*para->rate))       ,handle->kernel,1);\n    \n    if(para->res_valid==0) return;\n    \n    if(para->prev->state == MORN_FORWARD)\n    {\n        for(int b=0;b<res->batch;b++) \n            memset(res->data[b],0,in->height*in->width*in->channel*sizeof(float));\n        para->prev->state = MORN_BACKWARD;\n    }\n    \n    for(int b=0;b<in->batch;b++)\n    {\n        memset(mat_data,0,matwidth*mheight*sizeof(float));\n        \n        for(int k=0;k<para->knl_num;k++)\n        {\n            int   *locate = handle->locate+k* mwidth;\n            float *kernel = handle->kernel+k*(mwidth+1);\n            float *out_data = out->data[b]+k* mheight;\n            \n            cblas_sgemm(CblasRowMajor,CblasTrans,CblasNoTrans,\n                        mheight,mwidth,1,\n                        1.0f,\n                        out_data,mheight,\n                          kernel,mwidth,\n                    0.0,res_data,mwidth);\n                    \n            for(int j=0;j<mheight;j++)\n            {\n                for(int i=0;i<mwidth;i++) mat_data[j*matwidth+locate[i]]+=res_data[j*mwidth+i];\n            }\n        }\n        \n        ConvMatDataToTensor(mat_data,res,b,para->knl_height,para->knl_width,para->y_stride,para->x_stride);\n    }\n}\n\nvoid DirConvTensorToMatData(MTensor *tns,int bc,float *mdata,int knl_r,int knl_dir,int y_stride,int x_stride)\n{\n    int height = tns->height;\n    int width  = tns->width;\n    int channel= tns->channel;\n    \n    int out_width = width/x_stride;\n    int out_height=height/y_stride;\n    int mwidth = (knl_r+knl_r+1)*channel+1;\n    int mheight= out_height*out_width;\n    \n    int sx=0,sy=0;\n         if(knl_dir==0) {sx=0;sy= 1;}\n    else if(knl_dir==1) {sx=1;sy= 1;}\n    else if(knl_dir==2) {sx=1;sy= 0;}\n    else if(knl_dir==3) {sx=1;sy=-1;}\n    \n    int x0=(width -(out_width -1)*x_stride)/2;\n    int y0=(height-(out_height-1)*y_stride)/2;\n    \n    float *tdata = tns->data[bc];\n    int tsize = tns->height*tns->width;\n    \n    int i,j,c;\n    for(j=out_width;j<mheight;j++)\n    {\n        int n=y0+j/out_width*y_stride-knl_r*sy;\n        int m=x0+j%out_width*x_stride-knl_r*sx;\n        for(i=0;i<mwidth-1;i+=channel)\n        {\n            int h=n;if(h<0)h=0;else if(h>=height)h=height-1;\n            int w=m;if(w<0)w=0;else if(w>= width)w= width-1;\n            for(c=0;c<channel;c++) mdata[(j*mwidth)+i+c]=tdata[c*tsize+h*width+w];\n            n=n+sy;m=m+sx;\n        }\n        mdata[(j*mwidth)+mwidth-1]=1.0f;\n    }\n}\n                \nvoid DirConvMatDataToTensor(float *mdata,MTensor *tns,int bc,int knl_r,int knl_dir,int y_stride,int x_stride)\n{\n    int height = tns->height;\n    int width  = tns->width;\n    int channel= tns->channel;\n    \n    int out_width = width/x_stride;\n    int out_height=height/y_stride;\n    int mwidth = (knl_r+knl_r+1)*channel+1;\n    int mheight= out_height*out_width;\n    \n    int sx=0,sy=0;\n         if(knl_dir==0) {sx=0;sy= 1;}\n    else if(knl_dir==1) {sx=1;sy= 1;}\n    else if(knl_dir==2) {sx=1;sy= 0;}\n    else if(knl_dir==3) {sx=1;sy=-1;}\n    \n    int x0=(width -(out_width -1)*x_stride)/2;\n    int y0=(height-(out_height-1)*y_stride)/2;\n    \n    float *tdata = tns->data[bc];\n    int tsize = tns->height*tns->width;\n    \n    int i,j,c;\n    for(j=0;j<mheight;j++)\n    {\n        int n=y0+j/out_width*y_stride-knl_r*sy;\n        int m=x0+j%out_width*x_stride-knl_r*sx;\n        for(i=0;i<mwidth-1;i+=channel)\n        {\n            int h=n;if(h<0)h=0;else if(h>=height)h=height-1;\n            int w=m;if(w<0)w=0;else if(w>= width)w= width-1;\n            for(c=0;c<channel;c++) tdata[c*tsize+h*width+w]+=mdata[(j*mwidth)+i+c];\n            n=n+sy;m=m+sx;\n        }\n    }\n}\n\nstruct TensorDirConvPara\n{\n    MLayer *prev;\n    \n    int knl_num;\n    int knl_r;\n    \n    int dir;\n    \n    int x_stride;\n    int y_stride;\n    \n    int res_valid;\n    \n    float rate;\n    float decay;\n    float momentum;\n};\nvoid *mTensorDirConvPara(MSheet *ini,char *name)\n{\n    struct TensorDirConvPara *para = (struct TensorDirConvPara *)mMalloc(sizeof(struct TensorDirConvPara));\n   \n    char *value = mINIRead(ini,name,\"prev\");\n    para->prev = mNetworkLayer(ini,value);\n    mException((para->prev == NULL),EXIT,\"invalid prev\");\n    \n    para->res_valid = (strcmp(\"Input\",mLayerType(para->prev))!=0);\n    \n    value = mINIRead(ini,name,\"knl_num\");\n    if(value != NULL) para->knl_num= atoi(value);else para->knl_num= 1; \n    \n    value = mINIRead(ini,name,\"knl_r\");\n    if(value != NULL) para->knl_r= atoi(value);else para->knl_r= 1; \n    \n    value = mINIRead(ini,name,\"dir\");\n    mException((value==NULL),EXIT,\"invalid convolution direction\");\n         if((strcmp(value, \"u-d\" )==0)||(strcmp(value, \"d-u\" )==0)) para->dir=0;     \n    else if((strcmp(value,\"lu-rd\")==0)||(strcmp(value,\"rd-lu\")==0)) para->dir=1;\n    else if((strcmp(value, \"l-r\" )==0)||(strcmp(value, \"r-l\" )==0)) para->dir=2;\n    else if((strcmp(value,\"ru-ld\")==0)||(strcmp(value,\"ld-ru\")==0)) para->dir=3;\n    else mException(1,EXIT,\"invalid convolution direction\");\n    \n    value = mINIRead(ini,name,\"x_stride\");\n    if(value != NULL) para->x_stride= atoi(value);else para->x_stride= 1;\n    \n    value = mINIRead(ini,name,\"y_stride\");\n    if(value != NULL) para->y_stride= atoi(value);else para->y_stride= 1;\n    \n    value = mINIRead(ini,name,\"rate\");\n    if(value != NULL) para->rate = atof(value);\n    else\n    {\n        value = mINIRead(ini,\"para\",\"rate\");\n        if(value != NULL) para->rate = atof(value);\n        else              para->rate = 0.001;\n    }\n    \n    value = mINIRead(ini,name,\"decay\");\n    if(value != NULL) para->decay = atof(value);\n    else\n    {\n        value = mINIRead(ini,\"para\",\"decay\");\n        if(value != NULL) para->decay = atof(value);\n        else              para->decay = 0.01;\n    }\n    mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,\"invalid para decay\");\n    \n    value = mINIRead(ini,name,\"momentum\");\n    if(value != NULL) para->momentum = atof(value); \n    else\n    {\n        value = mINIRead(ini,\"para\",\"momentum\");\n        if(value != NULL) para->momentum = atof(value);\n        else              para->momentum = 0.9;\n    }\n\n    return para;\n}\n\nstruct HandleTensorDirConv\n{\n    float *mat;\n    float *kernel;\n    float *update;\n};\nvoid endTensorDirConv(void *info)\n{\n    struct HandleTensorDirConv *handle = (struct HandleTensorDirConv *)info;\n    if(handle->mat   != NULL) mFree(handle->mat);\n    if(handle->kernel!= NULL) mFree(handle->kernel);\n    if(handle->update!= NULL) mFree(handle->update);\n}\n#define HASH_TensorDirConv 0x9e2674b3\nvoid TensorDirConvSet(MLayer *layer)\n{\n    if(layer->state != DFLT) return;\n    \n    struct TensorDirConvPara *para = (struct TensorDirConvPara *)(layer->para);\n    MTensor *in = para->prev->tns;\n    MTensor *res= para->prev->res;\n    MTensor *out= layer->tns;\n    \n    MHandle *hdl=mHandle(out,TensorDirConv);\n    struct HandleTensorDirConv *handle = (struct HandleTensorDirConv *)(hdl->handle);\n    \n    int out_height= in->height/para->y_stride;\n    int out_width = in->width /para->x_stride;\n    int mheight = (out_height*out_width);\n    int mwidth = (para->knl_r+para->knl_r+1)*in->channel+1;\n    int data_size = para->knl_num*mwidth;\n    \n    mTensorRedefine(out,in->batch,para->knl_num,out_height,out_width,NULL);\n    if(morn_network_flag == MORN_TRAIN)\n    {\n        if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);\n        else                    mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);\n   \n        if(handle->update != NULL) mFree(handle->update);\n        handle->update =(float *)mMalloc(data_size*sizeof(float));\n        memset(handle->update,0,data_size*sizeof(float));\n    }\n    \n    if(handle->kernel !=NULL) mFree(handle->kernel);\n    handle->kernel = (float *)mMalloc(data_size*sizeof(float));\n    \n    if(morn_network_parafile==NULL)\n    {\n        float scale = sqrt(2.0f/mwidth);\n        for(int i=0;i<data_size;i++)\n            handle->kernel[i] = mNormalRand(0.0f,1.0f)*scale;\n    }\n    else\n    {\n        mNetworkParaRead(layer,\"kernel\",handle->kernel,data_size*sizeof(float));\n    }\n    \n    if(handle->mat!=NULL) mFree(handle->mat);\n    handle->mat = (float *)mMalloc(mheight*mwidth*sizeof(float));\n    \n    hdl->valid = 1;\n}\n\nvoid mTensorDirConvForward(MLayer *layer)\n{\n    mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n    mException(strcmp(\"DirConv\",mLayerType(layer)),EXIT,\"invalid layer type\");\n    struct TensorDirConvPara *para = (struct TensorDirConvPara *)(layer->para);\n    \n    MTensor *in = para->prev->tns;\n    MTensor *out=layer->tns;\n    \n    TensorDirConvSet(layer);\n    \n    MHandle *hdl=mHandle(out,TensorDirConv);\n    struct HandleTensorDirConv *handle = (struct HandleTensorDirConv *)(hdl->handle);\n    \n    int mheight = (out->height*out->width);\n    int mwidth = (para->knl_r+para->knl_r+1)*in->channel+1;\n    \n    float *kernel_data= handle->kernel;\n    float *in_data = handle->mat;\n    \n    for(int b=0;b<in->batch;b++)\n    {\n        DirConvTensorToMatData(in,b,in_data,para->knl_r,para->dir,para->y_stride,para->x_stride);\n        float *out_data = out->data[b];\n        \n        cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,\n                    para->knl_num,mheight,mwidth,\n                    1.0f,\n                    kernel_data,mwidth,\n                        in_data,mwidth,\n               0.0f,   out_data,mheight);\n    }\n    \n    layer->state = MORN_FORWARD;\n}\n\nvoid mTensorDirConvBackward(MLayer *layer)\n{\n    mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n    mException(strcmp(\"DirConv\",mLayerType(layer)),EXIT,\"invalid layer type\");\n    struct TensorDirConvPara *para = (struct TensorDirConvPara *)(layer->para);\n    MTensor *in = para->prev->tns;\n    MTensor *res= para->prev->res;\n    MTensor *out=layer->res;\n    \n    MHandle *hdl=mHandle(layer->tns,TensorDirConv);\n    struct HandleTensorDirConv *handle = (struct HandleTensorDirConv *)(hdl->handle);\n    mException((hdl->valid == 0),EXIT,\"no forward operate\");\n    \n    int mheight = (out->height*out->width);\n    int mwidth = (para->knl_r+para->knl_r+1)*in->channel+1;\n    \n    float *kernel_data= handle->kernel;\n    float *update_data= handle->update;\n    float *    in_data= handle->mat;\n    float *   res_data= handle->mat;\n    \n    mNetworkParaWrite(layer,\"kernel\",kernel_data,para->knl_num*mwidth*sizeof(float));\n    \n    for(int b=0;b<out->batch;b++)\n    {\n        DirConvTensorToMatData(in,b,in_data,para->knl_r,para->dir,para->y_stride,para->x_stride);\n        float *out_data = out->data[b];\n        \n        cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,\n                    para->knl_num,mwidth,mheight,\n                    1.0f/mheight,\n                       out_data,mheight,\n                        in_data,mwidth,\n                    (b==0)?para->momentum:1.0f,\n                    update_data,mwidth);\n    }\n    \n    cblas_saxpby(para->knl_num*mwidth,\n                 (0.0f-(para->rate/(float)(in->batch))),update_data,1, \n                 (1.0f-(para->decay*para->rate))       ,kernel_data,1);\n    \n    if(para->res_valid==0) return;\n    \n    if(para->prev->state == MORN_FORWARD)\n    {\n        for(int b=0;b<res->batch;b++) \n            memset(res->data[b],0,in->height*in->width*in->channel*sizeof(float));\n        para->prev->state = MORN_BACKWARD;\n    }\n    \n    for(int b=0;b<in->batch;b++)\n    {\n        float *out_data = out->data[b];\n        \n        cblas_sgemm(CblasRowMajor,CblasTrans,CblasNoTrans,\n                    mheight,mwidth,para->knl_num,\n                    1.0f,\n                       out_data,mheight,\n                    kernel_data,mwidth,\n                0.0,   res_data,mwidth);\n        \n        DirConvMatDataToTensor(res_data,res,b,para->knl_r,para->dir,para->y_stride,para->x_stride);\n    }\n}\n", "meta": {"hexsha": "c25e6db038fdbd30cd4b8c148070eff996b40400", "size": 22350, "ext": "c", "lang": "C", "max_stars_repo_path": "src/deep_learning/morn_tensor_conv2.c", "max_stars_repo_name": "dianjixz/Morn", "max_stars_repo_head_hexsha": "d7617476daf4e7d965ac47b543c8886a6fafce24", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/deep_learning/morn_tensor_conv2.c", "max_issues_repo_name": "dianjixz/Morn", "max_issues_repo_head_hexsha": "d7617476daf4e7d965ac47b543c8886a6fafce24", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/deep_learning/morn_tensor_conv2.c", "max_forks_repo_name": "dianjixz/Morn", "max_forks_repo_head_hexsha": "d7617476daf4e7d965ac47b543c8886a6fafce24", "max_forks_repo_licenses": ["Apache-2.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.3846153846, "max_line_length": 501, "alphanum_fraction": 0.5957941834, "num_tokens": 6384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3831922259688088}}
{"text": "/**\n *\n * @file core_ctrtri.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Julien Langou\n * @author Henricus Bouwmeester\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated c Tue Jan  7 11:44:46 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex32_t\n *\n *  CORE_ctrtri - Computes the inverse of a complex upper or lower\n *  triangular matrix A.\n *\n *******************************************************************************\n *\n * @param[in] uplo\n *          = PlasmaUpper: Upper triangle of A is stored;\n *          = PlasmaLower: Lower triangle of A is stored.\n *\n * @param[in] diag\n *          = PlasmaNonUnit: A is non-unit triangular;\n *          = PlasmaUnit:    A is unit triangular.\n *\n * @param[in] N\n *          The order of the matrix A. N >= 0.\n *\n * @param[in,out] A\n *          On entry, the triangular matrix A.  If UPLO = 'U', the\n *          leading N-by-N upper triangular part of the array A\n *          contains the upper triangular matrix, and the strictly\n *          lower triangular part of A is not referenced.  If UPLO =\n *          'L', the leading N-by-N lower triangular part of the array\n *          A contains the lower triangular matrix, and the strictly\n *          upper triangular part of A is not referenced.  If DIAG =\n *          'U', the diagonal elements of A are also not referenced and\n *          are assumed to be 1.  On exit, the (triangular) inverse of\n *          the original matrix.\n *\n * @param[in] LDA\n *          The leading dimension of the array A. LDA >= max(1,N).\n *\n * @param[out] info\n *          - 0 on successful exit\n *          - <0 if -i, the i-th argument had an illegal value\n *          - >0 if i, A(i,i) is exactly zero.  The triangular\n *          matrix is singular and its inverse can not be computed.\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_ctrtri = PCORE_ctrtri\n#define CORE_ctrtri PCORE_ctrtri\n#endif\nvoid CORE_ctrtri(PLASMA_enum uplo, PLASMA_enum diag, int N, PLASMA_Complex32_t *A, int LDA, int *info)\n{\n    *info = LAPACKE_ctrtri_work(\n        LAPACK_COL_MAJOR,\n        lapack_const(uplo), lapack_const(diag),\n        N, A, LDA);\n}\n", "meta": {"hexsha": "32365b89ebc11a2fbb0a262ad4f5d0adadb367a2", "size": 2478, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_ctrtri.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_ctrtri.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_ctrtri.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.9452054795, "max_line_length": 102, "alphanum_fraction": 0.5694108152, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.38249529699825857}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C code for the initialization of the instrumental noise for LIGO/VIRGO detectors.\n *\n */\n\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"LLVnoise.h\"\n\n\n/******************************************************************************/\n/****** Global variables storing interpolating splines for the noise PSD ******/\n\ngsl_spline* __LLVSimFD_LHONoiseSpline_init = NULL; /* for initialization only */\ngsl_spline** const __LLVSimFD_LHONoiseSpline = &__LLVSimFD_LHONoiseSpline_init;\ngsl_spline* __LLVSimFD_LLONoiseSpline_init = NULL; /* for initialization only */\ngsl_spline** const __LLVSimFD_LLONoiseSpline = &__LLVSimFD_LLONoiseSpline_init;\ngsl_spline* __LLVSimFD_VIRGONoiseSpline_init = NULL; /* for initialization only */\ngsl_spline** const __LLVSimFD_VIRGONoiseSpline = &__LLVSimFD_VIRGONoiseSpline_init;\ngsl_interp_accel* __LLVSimFD_LHONoiseAccel_init = NULL; /* for initialization only */\ngsl_interp_accel** const __LLVSimFD_LHONoiseAccel = &__LLVSimFD_LHONoiseAccel_init;\ngsl_interp_accel* __LLVSimFD_LLONoiseAccel_init = NULL; /* for initialization only */\ngsl_interp_accel** const __LLVSimFD_LLONoiseAccel = &__LLVSimFD_LLONoiseAccel_init;\ngsl_interp_accel* __LLVSimFD_VIRGONoiseAccel_init = NULL; /* for initialization only */\ngsl_interp_accel** const __LLVSimFD_VIRGONoiseAccel = &__LLVSimFD_VIRGONoiseAccel_init;\ndouble __LLVSimFD_LHONoise_fLow = 0;\ndouble __LLVSimFD_LHONoise_fHigh = 0;\ndouble __LLVSimFD_LLONoise_fLow = 0;\ndouble __LLVSimFD_LLONoise_fHigh = 0;\ndouble __LLVSimFD_VIRGONoise_fLow = 0;\ndouble __LLVSimFD_VIRGONoise_fHigh = 0;\nint __LLVSimFD_Noise_setup = FAILURE;\n\n/* The number of points in the noise data files - required as the Read_Vector function needs a gsl vector already initialized to the right length */\n//#define noisedata_pts 3000\n#define noisedata_pts 16365\n\n/**************************************************************/\n/****** Functions loading and evaluating the noise PSD  *******/\n\n/* Function parsing the environment variable $LLV_NOISE_DATA_PATH and trying to run LLVSimFD_Noise_Init in each */\nint LLVSimFD_Noise_Init_ParsePath(void)\n{\n  if (!__LLVSimFD_Noise_setup) return(SUCCESS);\n\n  int ret = FAILURE;\n  char *envpath = NULL;\n  char path[32768];\n  char *brkt, *word;\n  envpath = getenv(\"LLV_NOISE_DATA_PATH\");\n  if(!envpath) {\n    printf(\"Error: the environment variable LLV_NOISE_DATA_PATH, giving the path to the noise data, seems undefined\\n\");\n    exit(1);\n  }\n  strncpy(path, envpath, sizeof(path));\n\n  for(word=strtok_r(path,\":\",&brkt); word; word=strtok_r(NULL,\":\",&brkt))\n  {\n    //printf(\"%s\\n\", word);\n    ret = LLVSimFD_Noise_Init(word);\n    if(ret == SUCCESS) break;\n  }\n  if(ret!=SUCCESS) {\n    printf(\"Error: unable to find LLVSimFD noise data files in $LLV_NOISE_DATA_PATH\\n\");\n    exit(FAILURE);\n  }\n  __LLVSimFD_Noise_setup = ret;\n  return(ret);\n}\n/* Function loading the noise data from a directory */\nint LLVSimFD_Noise_Init(const char dir[]) {\n  if(!__LLVSimFD_Noise_setup) {\n    printf(\"Error: LLVSimFD noise was already set up!\");\n    exit(1);\n  }\n\n  /* Loading noise data in gsl_vectors */\n  int ret = SUCCESS;\n  gsl_matrix* noise_LHO = gsl_matrix_alloc(noisedata_pts, 2);\n  gsl_matrix* noise_LLO = gsl_matrix_alloc(noisedata_pts, 2);\n  gsl_matrix* noise_VIRGO = gsl_matrix_alloc(noisedata_pts, 2);\n  char* file_LIGO = malloc(strlen(dir)+64);\n  char* file_VIRGO = malloc(strlen(dir)+64);\n  //sprintf(file_LIGO, \"%s\", \"LIGO-P1200087-v18-aLIGO_DESIGN.txt\");\n  //sprintf(file_VIRGO, \"%s\", \"LIGO-P1200087-v18-AdV_DESIGN.txt\");\n  sprintf(file_LIGO, \"%s\", \"aLIGO_sensitivity.dat\");\n  sprintf(file_VIRGO, \"%s\", \"aVirgo_sensitivity.dat\");\n  ret |= Read_Text_Matrix(dir, file_LIGO, noise_LHO);\n  ret |= Read_Text_Matrix(dir, file_LIGO, noise_LLO);\n  ret |= Read_Text_Matrix(dir, file_VIRGO, noise_VIRGO);\n\n  if(ret==FAILURE) {\n    printf(\"Error: problem reading LLV noise data.\");\n    exit(1);\n  }\n\n  /* Linear interpolation of the data, after setting the gsl_spline structures */\n  else if(ret==SUCCESS) {\n    /* Extracting te vectors for the frequencies and data */\n    gsl_vector* noise_LHO_freq = gsl_vector_alloc(noisedata_pts);\n    gsl_vector* noise_LLO_freq = gsl_vector_alloc(noisedata_pts);\n    gsl_vector* noise_VIRGO_freq = gsl_vector_alloc(noisedata_pts);\n    gsl_vector* noise_LHO_data = gsl_vector_alloc(noisedata_pts);\n    gsl_vector* noise_LLO_data = gsl_vector_alloc(noisedata_pts);\n    gsl_vector* noise_VIRGO_data = gsl_vector_alloc(noisedata_pts);\n    gsl_matrix_get_col(noise_LHO_freq, noise_LHO, 0);\n    gsl_matrix_get_col(noise_LLO_freq, noise_LLO, 0);\n    gsl_matrix_get_col(noise_VIRGO_freq, noise_VIRGO, 0);\n    gsl_matrix_get_col(noise_LHO_data, noise_LHO, 1);\n    gsl_matrix_get_col(noise_LLO_data, noise_LLO, 1);\n    gsl_matrix_get_col(noise_VIRGO_data, noise_VIRGO, 1);\n    /* Setting the global variables that indicate the range in frequency of these splines */\n    __LLVSimFD_LHONoise_fLow = gsl_vector_get(noise_LHO_freq, 0);\n    __LLVSimFD_LHONoise_fHigh = gsl_vector_get(noise_LHO_freq, noise_LHO_freq->size - 1);\n    __LLVSimFD_LLONoise_fLow = gsl_vector_get(noise_LLO_freq, 0);\n    __LLVSimFD_LLONoise_fHigh = gsl_vector_get(noise_LLO_freq, noise_LLO_freq->size - 1);\n    __LLVSimFD_VIRGONoise_fLow = gsl_vector_get(noise_VIRGO_freq, 0);\n    __LLVSimFD_VIRGONoise_fHigh = gsl_vector_get(noise_VIRGO_freq, noise_VIRGO_freq->size - 1);\n    /* Initializing the splines and accelerators */\n    *__LLVSimFD_LHONoiseSpline = gsl_spline_alloc(gsl_interp_linear, noisedata_pts);\n    *__LLVSimFD_LLONoiseSpline = gsl_spline_alloc(gsl_interp_linear, noisedata_pts);\n    *__LLVSimFD_VIRGONoiseSpline = gsl_spline_alloc(gsl_interp_linear, noisedata_pts);\n    *__LLVSimFD_LHONoiseAccel = gsl_interp_accel_alloc();\n    *__LLVSimFD_LLONoiseAccel = gsl_interp_accel_alloc();\n    *__LLVSimFD_VIRGONoiseAccel = gsl_interp_accel_alloc();\n    gsl_spline_init(*__LLVSimFD_LHONoiseSpline, gsl_vector_const_ptr(noise_LHO_freq, 0), gsl_vector_const_ptr(noise_LHO_data, 0), noisedata_pts);\n    gsl_spline_init(*__LLVSimFD_LLONoiseSpline, gsl_vector_const_ptr(noise_LLO_freq, 0), gsl_vector_const_ptr(noise_LLO_data, 0), noisedata_pts);\n    gsl_spline_init(*__LLVSimFD_VIRGONoiseSpline, gsl_vector_const_ptr(noise_VIRGO_freq, 0), gsl_vector_const_ptr(noise_VIRGO_data, 0), noisedata_pts);\n    /* Setting the global tag to success and clean up */\n    gsl_matrix_free(noise_LHO);\n    gsl_matrix_free(noise_LLO);\n    gsl_matrix_free(noise_VIRGO);\n    gsl_vector_free(noise_LHO_freq);\n    gsl_vector_free(noise_LLO_freq);\n    gsl_vector_free(noise_VIRGO_freq);\n    gsl_vector_free(noise_LHO_data);\n    gsl_vector_free(noise_LLO_data);\n    gsl_vector_free(noise_VIRGO_data);\n    __LLVSimFD_Noise_setup = SUCCESS;\n  }\n  \n  /* Cleaning and output */\n  free(file_LIGO);\n  free(file_VIRGO);\n  return(ret);\n}\n\n/* The noise functions themselves */\ndouble NoiseSnLHO(const double f) {\n  if(__LLVSimFD_Noise_setup==FAILURE) {\n    printf(\"Error: noise interpolation has not been set up\\n\");\n    exit(1);\n  }\n  if ((f < __LLVSimFD_LHONoise_fLow) || (f > __LLVSimFD_LHONoise_fHigh)) {\n    return INFINITY;\n  }\n  else { \n    double sqrtSn = gsl_spline_eval(*__LLVSimFD_LHONoiseSpline, f, *__LLVSimFD_LHONoiseAccel);\n    return sqrtSn * sqrtSn;\n  }\n}\ndouble NoiseSnLLO(const double f) {\n  if(__LLVSimFD_Noise_setup==FAILURE) {\n    printf(\"Error: noise interpolation has not been set up\\n\");\n    exit(1);\n  }\n  if ((f < __LLVSimFD_LLONoise_fLow) || (f > __LLVSimFD_LLONoise_fHigh)) {\n    return INFINITY;\n  }\n  else { \n    double sqrtSn = gsl_spline_eval(*__LLVSimFD_LLONoiseSpline, f, *__LLVSimFD_LLONoiseAccel);\n    return sqrtSn * sqrtSn;\n  }\n}\ndouble NoiseSnVIRGO(const double f) {\n  if(__LLVSimFD_Noise_setup==FAILURE) {\n    printf(\"Error: noise interpolation has not been set up\\n\");\n    exit(1);\n  }\n  if ((f < __LLVSimFD_VIRGONoise_fLow) || (f > __LLVSimFD_VIRGONoise_fHigh)) {\n    return INFINITY;\n  }\n  else { \n    double sqrtSn = gsl_spline_eval(*__LLVSimFD_VIRGONoiseSpline, f, *__LLVSimFD_VIRGONoiseAccel);\n    return sqrtSn * sqrtSn;\n  }\n}\n", "meta": {"hexsha": "22e2f15877cc01a90bf83b142946a36e56618140", "size": 8551, "ext": "c", "lang": "C", "max_stars_repo_path": "LLVsim/LLVnoise.c", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "LLVsim/LLVnoise.c", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LLVsim/LLVnoise.c", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 39.587962963, "max_line_length": 151, "alphanum_fraction": 0.7424862589, "num_tokens": 2597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3822967520964537}}
{"text": "#include \"stdlib.h\"\n#include \"stdio.h\"\n#include \"/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h\"\n#include <gsl/gsl_sf.h>\nint main(int argc, const char * argv[]) {\nunsigned long int hexdouble;\nunsigned int a;\na = atoi(argv[1]);\ndouble result = gsl_sf_airy_zero_Ai(a);\n//printf(\"%.15f\\n\", result);\nVALGRIND_PRINT_VALUES(\"result\", 1, &result);\nreturn 0;\n}", "meta": {"hexsha": "cf3444e4a5cae897a1013f7a296beee57372fcfb", "size": 373, "ext": "c", "lang": "C", "max_stars_repo_path": "others/sf/gsl_sf_airy_zero_Ai.c", "max_stars_repo_name": "floatfeather/FpGenetic", "max_stars_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "others/sf/gsl_sf_airy_zero_Ai.c", "max_issues_repo_name": "floatfeather/FpGenetic", "max_issues_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "others/sf/gsl_sf_airy_zero_Ai.c", "max_forks_repo_name": "floatfeather/FpGenetic", "max_forks_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6923076923, "max_line_length": 78, "alphanum_fraction": 0.7211796247, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3822573929138351}}
{"text": "//\n// Copyright (c) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.\n//\n// CPUMatrix.h : template implementation of all matrix functions on the CPU side\n//\n\n#pragma once\n\n#include \"Basics.h\"\n#include \"File.h\"\n\n#include \"CPUMatrix.h\"\n#include \"TensorOps.h\"\n#include <assert.h>\n#include <stdexcept>\n#include <omp.h>\n#include <math.h>\n#include <random>\n#include <chrono>\n#include <exception>\n#include <thread>\n#include <iostream>\n#include <algorithm>\n#pragma warning(push)\n#pragma warning(disable:4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data\n#include <boost/random/normal_distribution.hpp>\n#pragma warning(pop)\n#include <boost/random/uniform_real_distribution.hpp>\n\n#ifdef _WIN32\n#define NOMINMAX\n#include \"Windows.h\"\n#else\n#include <cfloat>\n#endif\n\n#ifdef LEAKDETECT\n#include <vld.h>\n#endif\n\n#pragma warning(disable : 4100) // unreferenced formal parameter; \"struct TensorOpReduction<ElemType, OPFN, typename ReductionOp, N, -1>\" trigger this\n#pragma warning(disable : 4127) // conditional expression is constant; \"if (sizeof(ElemType)==sizeof(float))\" triggers this\n#pragma warning(disable : 4244) // unreachable code; triggered for unknown reasons\n#pragma warning(disable : 4702) // conversion from 'double' to 'float'\n\n\n#ifdef USE_MKL\n// requires MKL 10.0 and above\n#include <mkl.h>\n#else\n#ifdef _MSC_VER\n// Visual Studio doesn't define standard complex types properly\n#define HAVE_LAPACK_CONFIG_H\n#define LAPACK_COMPLEX_STRUCTURE\n#endif\n#include <cblas.h>\n#include <lapacke.h>\n#endif\n\n#define SWAP(a, b)  \\\n    {               \\\n        (a) ^= (b); \\\n        (b) ^= (a); \\\n        (a) ^= (b); \\\n    }\n#define IDX2C(i, j, ld) (((j) * (ld)) + (i)) // 0 based indexing\nnamespace Microsoft { namespace MSR { namespace CNTK {\n\n#pragma region Helpful Enum Definitions\nenum class MatrixOrder\n{\n    RowMajor = 101, // row-major arrays\n    ColMajor = 102  // column-major arrays\n};\n\nenum class MatrixTranspose : char\n{\n    NoTrans = 'N',  // trans='N'\n    Trans = 'T',    // trans='T'\n    ConjTrans = 'C' // trans='C'\n};\n\nenum class SymMatrixType : char\n{\n    Up = 'U',          // symmetric matrix is stored in the upper part\n    Low = 'L',         // symmetric matrix is stored in thelower part\n    Full = 'F',        // full populated\n    NotSymmetric = 'N' // not a symmetric matrix\n};\n\nenum class MatrixOpSide : char\n{\n    Left = 'L',  // left multiply\n    Right = 'R', // right multiply\n};\n#pragma endregion Helpful Enum Definitions\n\n#pragma region Constructors and Destructor\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>::CPUMatrix()\n{\n    ZeroInit();\n}\n\n// helper to allocate an array of ElemType\n// Use this instead of new[] to get NaN initialization for debugging.\ntemplate <class ElemType>\nstatic ElemType* NewArray(size_t n)\n{\n    ElemType* p = new ElemType[n]();\n#if 0 // _DEBUG\n        ElemType nan = Matrix<ElemType>::MakeNan(__LINE__);\n        for (size_t i = 0; i < n; i++)\n            p[i] = nan;\n#endif\n    return p;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>::CPUMatrix(const size_t numRows, const size_t numCols)\n{\n    ZeroInit();\n\n    m_numRows = numRows;\n    m_numCols = numCols;\n    SetSizeAllocated(GetNumElements());\n\n    if (GetNumElements() != 0)\n    {\n        SetBuffer(NewArray<ElemType>(GetNumElements()), GetNumElements() * sizeof(ElemType));\n    }\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>::CPUMatrix(const size_t numRows, const size_t numCols, ElemType* pArray, const size_t matrixFlags)\n{\n    ZeroInit();\n    SetValue(numRows, numCols, pArray, matrixFlags);\n}\n\n//copy constructor, deep copy\ntemplate <class ElemType>\nCPUMatrix<ElemType>::CPUMatrix(const CPUMatrix<ElemType>& deepCopyFrom)\n{\n    ZeroInit();\n    SetValue(deepCopyFrom);\n}\n\n//assignment operator, deep copy\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::operator=(const CPUMatrix<ElemType>& deepCopyFrom)\n{\n    SetValue(deepCopyFrom);\n    return *this;\n}\n\n//move constructor, shallow copy\ntemplate <class ElemType>\nCPUMatrix<ElemType>::CPUMatrix(CPUMatrix<ElemType>&& moveFrom)\n    : Base(/* shallow */ true)\n{\n    ShallowCopyFrom(moveFrom);\n    moveFrom.ZeroValues();\n}\n\n// Shortcut of default constructor + shallow copy, to avoid one initialization\ntemplate <class ElemType>\nCPUMatrix<ElemType>::CPUMatrix(const CPUMatrix<ElemType>& shallowCopyFrom, bool shallow)\n    : Base(shallow)\n{\n    ShallowCopyFrom(shallowCopyFrom);\n}\n\n//move assignment operator, shallow copy\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::operator=(CPUMatrix<ElemType>&& moveFrom)\n{\n    if (this != &moveFrom)\n    {\n        ShallowCopyFrom(moveFrom);\n        // release the pointer from the source object so that the destructor won't release it twice\n        moveFrom.ZeroValues();\n    }\n    return *this;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::Clear()\n{\n    ZeroInit();\n}\n\n#pragma endregion Constructors and Destructor\n\n#pragma region Basic Operators\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::ColumnSlice(size_t startColumn, size_t numCols) const\n{\n    if (startColumn + numCols > m_numCols)\n        InvalidArgument(\"The slice (%d+%d) is out of range of the source matrix (%d).\", (int) startColumn, (int) numCols, (int) m_numCols);\n\n    CPUMatrix<ElemType> slice(*this, /* shallow= */ true);\n    slice.m_numCols = numCols;\n    slice.m_sliceViewOffset = m_sliceViewOffset + startColumn * m_numRows;\n\n    return slice;\n}\n\n// set this(:, 0:numCols-1) = fromMatrix(:, startColumn : startColumn+numCols-1)\n// TODO: why not say *this = ColumnSlice()?\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignColumnSlice(const CPUMatrix<ElemType>& fromMatrix, size_t startColumn, size_t numCols)\n{\n    if (startColumn + numCols > fromMatrix.m_numCols)\n        InvalidArgument(\"The slice (%d+%d) is out of range of the source matrix (%d).\", (int) startColumn, (int) numCols, (int) fromMatrix.m_numCols);\n\n    Clear();\n\n    ShallowCopyFrom(fromMatrix);\n    m_numCols = numCols;\n    m_sliceViewOffset = fromMatrix.m_sliceViewOffset + startColumn * m_numRows;\n\n    return *this;\n}\n\n// set this(: , startColumn:startColumn+numCols-1)= fromMatrix;\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::SetColumnSlice(const CPUMatrix<ElemType>& fromMatrix, size_t startColumn, size_t numCols)\n{\n    if (startColumn + numCols > m_numCols)\n        LogicError(\"The slice is out of range of the destination matrix.\");\n    if (numCols > fromMatrix.GetNumCols())\n        InvalidArgument(\"The slice (%d) is out of range of the source matrix (%d).\", (int) numCols, (int) fromMatrix.GetNumCols());\n    if (m_numRows != fromMatrix.m_numRows)\n        LogicError(\"The number of rows in source and destination matrices do not match\");\n\n    memcpy(Data() + startColumn * m_numRows, fromMatrix.Data(), numCols * m_numRows * sizeof(ElemType));\n\n    return *this;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::CopyColumnsStrided(const CPUMatrix<ElemType>& fromMatrix, size_t numCols, size_t srcNumColsStride, size_t destNumColsStride)\n{\n    if ((((numCols - 1) * srcNumColsStride) + 1) > fromMatrix.m_numCols)\n        LogicError(\"The numCols to copy and srcNumColsStride specified is out of range of the source matrix.\");\n    if ((((numCols - 1) * destNumColsStride) + 1) > m_numCols)\n        LogicError(\"The numCols to copy and srcNumColsStride specified is out of range of the destination matrix.\");\n    if (m_numRows != fromMatrix.m_numRows)\n        LogicError(\"The number of rows in source and destination matrices do not match\");\n\n    long n = (long) numCols, m = (long) m_numRows;\n\n    auto& us = *this;\n\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (size_t i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j * destNumColsStride) = fromMatrix(i, j * srcNumColsStride);\n            us(i + 1, j * destNumColsStride) = fromMatrix(i + 1, j * srcNumColsStride);\n            us(i + 2, j * destNumColsStride) = fromMatrix(i + 2, j * srcNumColsStride);\n            us(i + 3, j * destNumColsStride) = fromMatrix(i + 3, j * srcNumColsStride);\n        }\n\n        // handle remaining\n        for (size_t i = m & ~3; i < m; i++)\n        {\n            us(i, j * destNumColsStride) = fromMatrix(i, j * srcNumColsStride);\n        }\n    }\n}\n\n//for each column of a, we add all rows of a to this starting from startIndex\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignToRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows)\n{\n    if (a.GetNumRows() != numRows)\n        LogicError(\"AddToRowSliceValuesOf: a.GetNumRows() != numRows.\");\n\n    if (startIndex + numRows > GetNumRows())\n        LogicError(\"AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows().\");\n\n    if (a.GetNumCols() != GetNumCols())\n        LogicError(\"AddToRowSliceValuesOf: columns does not match.\");\n\n    long n = (long) a.GetNumCols(), m = (long) numRows;\n\n    auto& us = *this;\n\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (size_t i = 0, startRow = startIndex; i < (m & ~3); i += 4, startRow += 4)\n        {\n            us(startRow, j) = a(i, j);\n            us(startRow + 1, j) = a(i + 1, j);\n            us(startRow + 2, j) = a(i + 2, j);\n            us(startRow + 3, j) = a(i + 3, j);\n        }\n        // handle remaining stuffs\n        for (size_t i = m & ~3, startRow = startIndex + (m & ~3); i < m; i++, startRow++)\n        {\n            us(startRow, j) = a(i, j);\n        }\n    }\n\n    return *this;\n}\n\n//for each column of a, we assign numRows starting from startIndex to this\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows)\n{\n    if (startIndex + numRows > a.GetNumRows())\n        LogicError(\"AssignRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows().\");\n\n    RequireSize(numRows, a.GetNumCols());\n\n    long n = (long) a.GetNumCols(); // note: OpenMP requires loop indices to be long, not size_t\n    long k = (long) a.GetNumRows();\n\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // memory copy might be faster?\n        memcpy(Data() + j * numRows, a.Data() + j * k + startIndex, sizeof(ElemType) * numRows);\n\n        // //four-way unrolling\n        // for (long i=0, startRow = startIndex; i<(m & ~3); i+=4, startRow+=4)\n        // {\n        //    us(i,j) = a(startRow,j);\n        //    us(i+1,j) = a(startRow+1,j);\n        //    us(i+2,j) = a(startRow+2,j);\n        //    us(i+3,j) = a(startRow+3,j);\n        // }\n        // //handle remaining stuffs\n        // for (long i=m & ~3, startRow = startIndex+(m & ~3); i<m; i++, startRow++)\n        // {\n        //    us(i,j) = a(startRow,j);\n        // }\n    }\n\n    return *this;\n}\n\n//for the row slice of this starting from startIndex we add a to it.\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AddToRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows)\n{\n    if (a.IsEmpty())\n        LogicError(\"AddToRowSliceValuesOf: input matrix a is empty.\");\n\n    if (a.GetNumRows() != numRows)\n        LogicError(\"AddToRowSliceValuesOf: a.GetNumRows() != numRows.\");\n\n    if (startIndex + numRows > GetNumRows())\n        LogicError(\"AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows().\");\n\n    if (a.GetNumCols() != GetNumCols())\n        LogicError(\"AddToRowSliceValuesOf: columns does not match.\");\n\n    long n = (long) a.GetNumCols(), m = (long) numRows;\n\n    auto& us = *this;\n\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0, startRow = (long) startIndex; i < (m & ~3); i += 4, startRow += 4)\n        {\n            us(startRow, j) += a(i, j);\n            us(startRow + 1, j) += a(i + 1, j);\n            us(startRow + 2, j) += a(i + 2, j);\n            us(startRow + 3, j) += a(i + 3, j);\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3, startRow = (long) startIndex + (m & ~3); i < m; i++, startRow++)\n        {\n            us(startRow, j) += a(i, j);\n        }\n    }\n\n    return *this;\n}\n\n//for each column of this, we add row slice of a starting from startIndex\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AddWithRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows)\n{\n    if (a.IsEmpty())\n        LogicError(\"AddWithRowSliceValuesOf: input matrix a is empty.\");\n\n    if (GetNumRows() != numRows)\n        LogicError(\"AddWithRowSliceValuesOf: GetNumRows() != numRows.\");\n\n    if (startIndex + numRows > a.GetNumRows())\n        LogicError(\"AddWithRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows().\");\n\n    if (a.GetNumCols() != GetNumCols())\n        LogicError(\"AddWithRowSliceValuesOf: columns does not match.\");\n\n    long n = (long) a.GetNumCols(), m = (long) numRows;\n\n    auto& us = *this;\n\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0, startRow = (long) startIndex; i < (m & ~3); i += 4, startRow += 4)\n        {\n            us(i, j) += a(startRow, j);\n            us(i + 1, j) += a(startRow + 1, j);\n            us(i + 2, j) += a(startRow + 2, j);\n            us(i + 3, j) += a(startRow + 3, j);\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3, startRow = (long) startIndex + (m & ~3); i < m; i++, startRow++)\n        {\n            us(i, j) += a(startRow, j);\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::Diagonal() const\n{\n    if (m_numRows != m_numCols)\n        LogicError(\"Diagonal can be called only for square matrix. (rows=%d, cols=%d)\", (int) m_numRows, (int) m_numCols);\n\n    CPUMatrix<ElemType> diag(1, m_numCols);\n\n    auto& us = *this;\n\n#pragma omp parallel for\n    for (long i = 0; i < m_numRows; i++)\n    {\n        diag(0, (size_t) i) = us(i, i);\n    }\n\n    return diag;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::MinusOneAt(CPUMatrix<ElemType>& c, const size_t position)\n{\n    if (position < c.GetNumElements())\n        c.Data()[position] -= 1.0;\n    else\n        RuntimeError(\"MinusOneAt: position is out of CPU matrix size\");\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignRepeatOf(const CPUMatrix<ElemType>& a, const size_t numRowRepeats, const size_t numColRepeats)\n{\n    if (this == &a)\n        LogicError(\"AssignRepeatOf: a is the same as [this]. Does not support inplace repeat.\");\n\n    if (a.IsEmpty())\n        LogicError(\"AssignRepeatOf: Matrix a is empty.\");\n\n    RequireSize(a.GetNumRows() * numRowRepeats, a.GetNumCols() * numColRepeats);\n    long n = (long) a.GetNumCols(), m = (long) a.GetNumRows();\n    auto& us = *this;\n\n#pragma omp parallel for\n    for (long q = 0; q < numColRepeats; q++)\n    {\n        for (long p = 0; p < numRowRepeats; p++)\n        {\n            long colOffset = q * n;\n\n            for (long j = 0; j < n; j++, colOffset++)\n            {\n                long rowOffset = p * m;\n\n                // four-way unrolling\n                for (long i = 0; i < (m & ~3); i += 4, rowOffset += 4)\n                {\n                    us(rowOffset, colOffset) = a(i, j);\n                    us(rowOffset + 1, colOffset) = a(i + 1, j);\n                    us(rowOffset + 2, colOffset) = a(i + 2, j);\n                    us(rowOffset + 3, colOffset) = a(i + 3, j);\n                }\n                // handle remaining stuffs\n                for (long i = m & ~3; i < m; i++, rowOffset++)\n                {\n                    us(rowOffset, colOffset) = a(i, j);\n                }\n            }\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AddToRowRepeatValuesOf(const CPUMatrix<ElemType>& a, const size_t numRepeats)\n{\n    if (a.IsEmpty())\n        LogicError(\"AddToRowRepeatValuesOf: input matrix a is empty.\");\n\n    if (a.GetNumRows() != GetNumRows() * numRepeats)\n        LogicError(\"AddToRowRepeatValuesOf: a.GetNumRows() != GetNumRows() * numRepeats.\");\n\n    long n = (long) a.GetNumCols(), m = (long) GetNumRows();\n\n    auto& us = *this;\n\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            for (long k = 0; k < numRepeats; k++)\n            {\n                us(i, j) += a(k * m + i, j);\n                us(i + 1, j) += a(k * m + i + 1, j);\n                us(i + 2, j) += a(k * m + i + 2, j);\n                us(i + 3, j) += a(k * m + i + 3, j);\n            }\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            for (long k = 0; k < numRepeats; k++)\n            {\n                us(i, j) += a(k * m + i, j);\n            }\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignPositiveAndShiftedNegSample(const CPUMatrix<ElemType>& a, const size_t posNumber, const size_t negNumber, const size_t shiftNumber)\n{\n    a;\n    posNumber;\n    negNumber;\n    shiftNumber;\n    NOT_IMPLEMENTED;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AddFoldedPositiveAndShiftedNegSample(const CPUMatrix<ElemType>& a, const size_t posNumber, const size_t negNumber, const size_t shiftNumber)\n{\n    a;\n    posNumber;\n    negNumber;\n    shiftNumber;\n    NOT_IMPLEMENTED;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::Transpose()\n{\n    if (IsEmpty())\n        LogicError(\"Transpose: Matrix is empty.\");\n\n    CPUMatrix<ElemType> c;\n    c.AssignTransposeOf(*this);\n    return c;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTransposeOf(const CPUMatrix<ElemType>& a)\n{\n    if (this == &a)\n        LogicError(\"AssignTransposeOf: a is the same as [this]. Does not support inplace transpose.\");\n\n    if (a.IsEmpty())\n        LogicError(\"AssignTransposeOf: Matrix a is empty.\");\n\n    RequireSize(a.GetNumCols(), a.GetNumRows());\n    long n = (long) a.GetNumCols(), m = (long) a.GetNumRows();\n\n    auto& us = *this;\n\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(j, i) = a(i, j);\n            us(j, i + 1) = a(i + 1, j);\n            us(j, i + 2) = a(i + 2, j);\n            us(j, i + 3) = a(i + 3, j);\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(j, i) = a(i, j);\n        }\n    }\n\n    return *this;\n}\n\n// dst[i] = src[i] * alpha + dst[i] * beta\n// scale a column vector and add it to another\n// The usual special case: If beta = 0, then dst[] is not read, and may be uninitialized or NaN.\ntemplate <class ElemType>\nstatic void ScaleAndAddColumn(ElemType beta, ElemType* dst, const ElemType* src, size_t numRows, ElemType alpha)\n{\n    if (alpha != 1) // rare case: just do the full thing\n        for (size_t i = 0; i < numRows; i++)\n            dst[i] = beta * dst[i] + alpha * src[i];\n    else if (beta == 1) // used in backprop\n        for (size_t i = 0; i < numRows; i++)\n            dst[i] += src[i];\n    else if (beta == 0) // plain assignment\n        memcpy(dst, src, sizeof(ElemType) * numRows);\n    else // alpha=1, arbitrary beta: also rare case\n        for (size_t i = 0; i < numRows; i++)\n            dst[i] = beta * dst[i] + src[i];\n}\n\n// *this[:,j] = a[:,idx[j]] * alpha + *this[:,j] * beta\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::DoGatherColumnsOf(ElemType beta, const CPUMatrix<ElemType>& idx, const CPUMatrix<ElemType>& a, ElemType alpha)\n{\n    if (idx.GetNumRows() != 1) // index is 1-dimensional only\n        InvalidArgument(\"DoGatherColumnsOf: Map must be a row vector.\");\n\n    if (beta)\n        VerifySize(a.GetNumRows(), idx.GetNumCols());\n    else\n        Resize(a.GetNumRows(), idx.GetNumCols());\n\n    auto& us = *this;\n    // race-condition consideration: Since this loops over independent output columns, this has no race condition. Cf. DoScatterColumnsOf().\n#pragma omp parallel for // TODO: Depending in circumstance, it may be more efficient to parallelize over rows.\n    foreach_column(jOut, us)\n    {\n        auto jInF = idx(0, jOut);         // this is the column we need to get\n        if (std::isnan(jInF) || jInF < 0) // negative index means gap\n            continue;\n        size_t jIn = (size_t)jInF;\n        if (jIn >= a.GetNumCols())\n            InvalidArgument(\"DoGatherColumnsOf: Map out of bounds. %ld >= %ld\", (long int)jIn, (long int)a.GetNumCols());\n        ScaleAndAddColumn(beta, &us(0,jOut), &a(0,jIn), us.GetNumRows(), alpha);\n    }\n\n    return *this;\n}\n\n// *this[:,idx[j]] = a[:,j] * alpha + *this[:,idx[j]] * beta\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::DoScatterColumnsOf(ElemType beta, const CPUMatrix<ElemType>& idx, const CPUMatrix<ElemType>& a, ElemType alpha)\n{\n    if (idx.GetNumRows() != 1) // index is 1-dimensional only\n        InvalidArgument(\"DoScatterColumnsOf: Map must be a row vector.\");\n    if (idx.GetNumCols() != a.GetNumCols())\n        InvalidArgument(\"DoScatterColumnsOf: Map must have width of input vector.\");\n    if (a.GetNumRows() != GetNumRows())\n        InvalidArgument(\"DoScatterColumnsOf: Output must have same height as input vector.\");\n\n    auto& us = *this;\n\n    // pre-scale with beta upfront\n    // Scatter may add more than one source column to the same target, so we must pre-scale with beta, and then just keep adding.\n    Scale(beta, us); // if beta is 0, then this will be a memset()\n\n    // race-condition consideration: If idx[] references the same target column multiple times, this can have a race condition,\n    // and hence cannot use parallelism.\n//#pragma omp parallel for // TODO: Depending in circumstance, it may be more efficient to parallelize over rows.\n    foreach_column(jIn, a)\n    {\n        auto jOutF = idx(0, jIn);           // this is the column we copy/add into\n        if (std::isnan(jOutF) || jOutF < 0) // negative index means gap\n            continue;\n        size_t jOut = (size_t)jOutF;\n        if (jOut >= GetNumCols())\n            InvalidArgument(\"DoGatherColumnsOf: Map out of bounds.\");\n        ScaleAndAddColumn(/*beta=*/(ElemType)1, &us(0, jOut), &a(0, jIn), us.GetNumRows(), alpha);\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetValue(const ElemType v)\n{\n    if (IsEmpty())\n        LogicError(\"SetValue: Matrix is empty.\");\n    bool isFinite = std::numeric_limits<ElemType>::is_integer || std::isfinite((double) v);\n    if (isFinite && v == 0)\n    {\n        memset(Data(), 0, sizeof(ElemType) * GetNumElements());\n    }\n    else\n    {\n        ElemType* bufPtr = Data();\n        long m = (long) GetNumElements();\n        // 2-way thread parallelism is sufficient for the memory bound\n        // operation of just setting the values of an array.\n        const unsigned SETVALUE_NUM_THREADS = 2;\n        UNUSED(SETVALUE_NUM_THREADS); // in case OMP is turned off.\n#pragma omp parallel for num_threads(SETVALUE_NUM_THREADS)\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            bufPtr[i] = v;\n            bufPtr[i + 1] = v;\n            bufPtr[i + 2] = v;\n            bufPtr[i + 3] = v;\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            bufPtr[i] = v;\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::MaskColumnsValue(const CPUMatrix<char>& columnsMask, ElemType val, size_t numColsPerMaskEntry)\n{\n    if (GetNumCols() != (columnsMask.GetNumCols() * numColsPerMaskEntry))\n        RuntimeError(\"MaskColumnsValue: Matrix number of columns must equal 'column mask number of columns * numColsPerMaskEntry'.\");\n\n    auto& us = *this;\n    long n = (long)columnsMask.GetNumCols(), m = (long) GetNumRows();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        if (columnsMask(0, j) == 1)\n            continue;\n\n        for (long k = 0; k < numColsPerMaskEntry; ++k)\n        {\n            // four-way unrolling\n            for (size_t i = 0; i < (m & ~3); i += 4)\n            {\n                us(i,     (j * numColsPerMaskEntry) + k) = val;\n                us(i + 1, (j * numColsPerMaskEntry) + k) = val;\n                us(i + 2, (j * numColsPerMaskEntry) + k) = val;\n                us(i + 3, (j * numColsPerMaskEntry) + k) = val;\n            }\n\n            // handle remaining\n            for (size_t i = m & ~3; i < m; i++)\n            {\n                us(i, (j * numColsPerMaskEntry) + k) = val;\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetColumn(const ElemType* colPointer, size_t j)\n{\n    if (IsEmpty())\n        LogicError(\"SetColumn: Matrix is empty.\");\n    if (colPointer == NULL)\n        return;\n\n    auto& us = *this;\n    long m = (long) GetNumRows();\n#pragma omp parallel for\n    // four-way unrolling\n    for (long i = 0; i < (m & ~3); i += 4)\n    {\n        us(i, j) = colPointer[i];\n        us(i + 1, j) = colPointer[i + 1];\n        us(i + 2, j) = colPointer[i + 2];\n        us(i + 3, j) = colPointer[i + 3];\n    }\n    // handle remaining stuffs\n    for (long i = m & ~3; i < m; i++)\n    {\n        us(i, j) = colPointer[i];\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetColumn(const ElemType val, size_t j)\n{\n    if (IsEmpty())\n        LogicError(\"SetColumn: Matrix is empty.\");\n\n    auto& us = *this;\n    long m = (long) GetNumRows();\n#pragma omp parallel for\n    // four-way unrolling\n    for (long i = 0; i < (m & ~3); i += 4)\n    {\n        us(i, j) = val;\n        us(i + 1, j) = val;\n        us(i + 2, j) = val;\n        us(i + 3, j) = val;\n    }\n    // handle remaining stuffs\n    for (long i = m & ~3; i < m; i++)\n    {\n        us(i, j) = val;\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetColumn(const CPUMatrix<ElemType>& valMat, size_t j)\n{\n    if (IsEmpty())\n        LogicError(\"SetColumn: Matrix is empty.\");\n    if (valMat.GetNumRows() != GetNumRows() || valMat.GetNumCols() != 1)\n        LogicError(\"The valMat matrix has incorrect number of rows or columns.\");\n\n    auto& us = *this;\n    long m = (long) GetNumRows();\n#pragma omp parallel for\n    // four-way unrolling\n    for (long i = 0; i < (m & ~3); i += 4)\n    {\n        us(i, j) = valMat(i, 0);\n        us(i + 1, j) = valMat(i + 1, 0);\n        us(i + 2, j) = valMat(i + 2, 0);\n        us(i + 3, j) = valMat(i + 3, 0);\n    }\n    // handle remaining stuffs\n    for (long i = m & ~3; i < m; i++)\n    {\n        us(i, j) = valMat(i, 0);\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetValue(const CPUMatrix<ElemType>& deepCopyFrom)\n{\n    if (this == &deepCopyFrom)\n        return;\n\n    SetValue(deepCopyFrom.GetNumRows(), deepCopyFrom.GetNumCols(), deepCopyFrom.Data(), 0);\n}\n\n#if 0\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetValue(const GPUMatrix<ElemType>& /*deepCopyFrom*/)\n{\n    NOT_IMPLEMENTED;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetValue(const CPUSparseMatrix<ElemType>& deepCopyFrom)\n{\n    deepCopyFrom.AssignColumnSliceToDense(*this, 0, deepCopyFrom.GetNumCols());\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetValue(const GPUSparseMatrix<ElemType>& /*deepCopyFrom*/)\n{\n    NOT_IMPLEMENTED;\n}\n#endif\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetValue(const size_t numRows, const size_t numCols, ElemType* pArray, const size_t matrixFlags)\n{\n    if (pArray == nullptr && numRows * numCols > 0)\n        InvalidArgument(\"Invalid pArray. pArray == nullptr, but matrix is of size %d * %d = %d.\", (int)numRows, (int)numCols, (int)(numRows * numCols));\n\n    SetFormat(matrixFormatDense);\n    SetComputeDeviceId(CPUDEVICE);\n\n    // if it's externally managed, then populate the structure\n    if (matrixFlags & matrixFlagDontOwnBuffer)\n    {\n        // free previous array allocation if any before overwriting\n        delete[] Buffer();\n\n        m_numRows = numRows;\n        m_numCols = numCols;\n        SetBuffer(pArray, GetNumElements() * sizeof(ElemType), true);\n        SetSizeAllocated(GetNumElements());\n    }\n    else\n    {\n        RequireSize(numRows, numCols);\n\n        if (!IsEmpty())\n        {\n            if (!(matrixFlags & matrixFormatRowMajor)) // compatible to internal structure\n                memcpy(Data(), pArray, GetNumElements() * sizeof(ElemType));\n            else // need to transpose\n            {\n                ElemType* bufPtr = Data();\n                auto& us = *this;\n                if (sizeof(ElemType) == sizeof(double))\n                {\n#pragma omp parallel for\n                    foreach_column (j, us)\n                    {\n                        cblas_dcopy((int) numRows, reinterpret_cast<double*>(pArray + j), (int) numCols, reinterpret_cast<double*>(bufPtr + LocateColumn(j)), 1);\n                    }\n                }\n                else\n                {\n#pragma omp parallel for\n                    foreach_column (j, us)\n                    {\n                        {\n#pragma warning(suppress : 4244)\n                            cblas_scopy((int) numRows, reinterpret_cast<float*>(pArray + j), (int) numCols, reinterpret_cast<float*>(bufPtr + LocateColumn(j)), 1);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetDiagonalValue(const ElemType v)\n{\n    if (GetNumRows() != GetNumCols())\n        LogicError(\"SetDiagonalValue: NumRows and NumCols do not agree.\");\n\n    auto& us = *this;\n    long m = (long) GetNumRows();\n#pragma omp parallel for\n    // four-way unrolling\n    for (long i = 0; i < (m & ~3); i += 4)\n    {\n        us(i, i) = v;\n        us(i + 1, i + 1) = v;\n        us(i + 2, i + 2) = v;\n        us(i + 3, i + 3) = v;\n    }\n    // handle remaining stuffs\n    for (long i = m & ~3; i < m; i++)\n    {\n        us(i, i) = v;\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetDiagonalValue(const CPUMatrix<ElemType>& vector)\n{\n    if (IsEmpty() || vector.IsEmpty())\n        LogicError(\"SetDiagonalValue: Matrix is empty.\");\n\n    if (GetNumRows() != GetNumCols())\n        LogicError(\"SetDiagonalValue: NumRows and NumCols do not agree.\");\n\n    if (vector.GetNumRows() != 1 && vector.GetNumCols() != 1)\n        LogicError(\"SetDiagonalValue: input vector must be a vector.\");\n\n    if (vector.GetNumElements() == 1) // reduce to simple form\n        SetDiagonalValue(vector(0, 0));\n    else if (vector.GetNumRows() != GetNumRows() && vector.GetNumCols() != GetNumRows())\n        LogicError(\"SetDiagonalValue: input vector's dimension does not agree with [this].\");\n    else\n    {\n        auto& us = *this;\n\n        long m = (long) GetNumRows();\n        if (vector.GetNumRows() == 1) // row vector\n        {\n#pragma omp parallel for\n            // four-way unrolling\n            for (long i = 0; i < (m & ~3); i += 4)\n            {\n                us(i, i) = vector(0, i);\n                us(i + 1, i + 1) = vector(0, i + 1);\n                us(i + 2, i + 2) = vector(0, i + 2);\n                us(i + 3, i + 3) = vector(0, i + 3);\n            }\n            // handle remaining stuffs\n            for (long i = m & ~3; i < m; i++)\n            {\n                us(i, i) = vector(0, i);\n            }\n        }\n        else\n        {\n#pragma omp parallel for\n            // four-way unrolling\n            for (long i = 0; i < (m & ~3); i += 4)\n            {\n                us(i, i) = vector(i, 0);\n                us(i + 1, i + 1) = vector(i + 1, 0);\n                us(i + 2, i + 2) = vector(i + 2, 0);\n                us(i + 3, i + 3) = vector(i + 3, 0);\n            }\n            // handle remaining stuffs\n            for (long i = m & ~3; i < m; i++)\n            {\n                us(i, i) = vector(i, 0);\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetUniformRandomValue(const ElemType low, const ElemType high, unsigned long seed)\n{\n    if (IsEmpty())\n        LogicError(\"SetUniformRandomValue: Matrix is empty.\");\n\n    std::mt19937_64 generator;\n    generator.seed(seed == USE_TIME_BASED_SEED ? (unsigned long) time(NULL) : seed);\n    boost::random::uniform_real_distribution<ElemType> r(low, high);\n\n    ElemType* bufPtr = Data();\n    long m = (long) GetNumElements();\n    // four-way unrolling\n    for (long i = 0; i < (m & ~3); i += 4)\n    {\n        bufPtr[i] = r(generator);\n        bufPtr[i + 1] = r(generator);\n        bufPtr[i + 2] = r(generator);\n        bufPtr[i + 3] = r(generator);\n    }\n    // handle remaining stuffs\n    for (long i = m & ~3; i < m; i++)\n    {\n        bufPtr[i] = r(generator);\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetGaussianRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed)\n{\n    if (sigma <= 0)\n        InvalidArgument(\"SetUniformRandomValue: sigma must be a positive value.\");\n\n    if (IsEmpty())\n        LogicError(\"SetUniformRandomValue: Matrix is empty.\");\n\n    auto& us = *this;\n\n    std::mt19937_64 generator(seed == USE_TIME_BASED_SEED ? (unsigned long) time(NULL) : seed);\n    boost::random::normal_distribution<ElemType> r(mean, sigma);\n\n    // #pragma omp parallel for   // is it thread safe?\n    foreach_coord (i, j, us)\n    {\n        us(i, j) = r(generator);\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AddGaussianRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed)\n{\n    if (sigma <= 0)\n        InvalidArgument(\"SetUniformRandomValue: sigma must be a positive value.\");\n\n    if (IsEmpty())\n        LogicError(\"SetUniformRandomValue: Matrix is empty.\");\n\n    auto& us = *this;\n\n    std::mt19937_64 generator;\n    generator.seed(seed == USE_TIME_BASED_SEED ? (unsigned long) time(NULL) : seed);\n    boost::random::normal_distribution<ElemType> r(mean, sigma);\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) = r(generator);\n            us(i + 1, j) = r(generator);\n            us(i + 2, j) = r(generator);\n            us(i + 3, j) = r(generator);\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) = r(generator);\n        }\n    }\n}\n\n//maskRate: percentage of values masked out (similar to dropout rate)\n//scaleValue: which scale value to set to the left ones (unmasked items).\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetUniformRandomMask(const ElemType maskRate, const ElemType scaleValue, RNGHandle& rngHandle)\n{\n    if (IsEmpty())\n        LogicError(\"SetUniformRandomValue: Matrix is empty.\");\n\n    CPURNGHandle* cpuRNGHandle = dynamic_cast<CPURNGHandle*>(&rngHandle);\n    if (cpuRNGHandle == nullptr)\n        LogicError(\"rngHandle must be a CPURNGHandle.\");\n\n    auto& us = *this;\n    boost::random::uniform_real_distribution<ElemType> r(0, 1);\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n    ElemType v;\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            v = r(cpuRNGHandle->Generator());\n            us(i, j) = v <= maskRate ? 0 : scaleValue;\n            v = r(cpuRNGHandle->Generator());\n            us(i + 1, j) = v <= maskRate ? 0 : scaleValue;\n            v = r(cpuRNGHandle->Generator());\n            us(i + 2, j) = v <= maskRate ? 0 : scaleValue;\n            v = r(cpuRNGHandle->Generator());\n            us(i + 3, j) = v <= maskRate ? 0 : scaleValue;\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            v = r(cpuRNGHandle->Generator());\n            us(i, j) = v <= maskRate ? 0 : scaleValue;\n        }\n    }\n}\n\ntemplate <class ElemType>\nElemType CPUMatrix<ElemType>::Adagrad(CPUMatrix<ElemType>& gradients, const bool needAveMultiplier)\n{\n    ElemType aveMultiplier = 0;\n\n    if (IsEmpty() || gradients.GetNumCols() != GetNumCols() || gradients.GetNumRows() != GetNumRows())\n    {\n        RequireSize(gradients.GetNumRows(), gradients.GetNumCols());\n        SetValue(0.0);\n    }\n\n    if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != gradients.GetNumCols())\n        LogicError(\"The matrix gradients must have the same rows and columns as this matrix.\");\n\n    ElemType *a = Data(), *d_v = gradients.Data();\n    size_t n = GetNumElements();\n\n    const ElemType floor = 1e-16f;\n    ElemType a0, a1, a2, a3;\n\n    // disable omp here because aveMultiper needs to be added atomically. however, it seems the result is incorrect even if rmp atomic and amp critical are used.\n    // #pragma omp parallel for\n    for (long i = 0; i < (n & ~3); i += 4) // four-way unrolling\n    {\n        a[i] += d_v[i] * d_v[i];\n        a[i + 1] += d_v[i + 1] * d_v[i + 1];\n        a[i + 2] += d_v[i + 2] * d_v[i + 2];\n        a[i + 3] += d_v[i + 3] * d_v[i + 3];\n\n        a0 = sqrt(a[i] + floor);\n        a1 = sqrt(a[i + 1] + floor);\n        a2 = sqrt(a[i + 2] + floor);\n        a3 = sqrt(a[i + 3] + floor);\n\n        d_v[i] /= a0;\n        d_v[i + 1] /= a1;\n        d_v[i + 2] /= a2;\n        d_v[i + 3] /= a3;\n\n        if (needAveMultiplier)\n        {\n            aveMultiplier += 1 / a0 + 1 / a1 + 1 / a2 + 1 / a3;\n        }\n    }\n\n    // get the last few elements if any\n    for (long i = n & ~3; i < n; i++)\n    {\n        a[i] += d_v[i] * d_v[i];\n\n        a0 = sqrt(a[i] + floor);\n        d_v[i] /= a0;\n\n        if (needAveMultiplier)\n        {\n            aveMultiplier += 1 / a0;\n        }\n    }\n\n    if (needAveMultiplier && n > 0)\n        return aveMultiplier / n;\n    else\n        return 1;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::FSAdagrad(CPUMatrix<ElemType>& gradients,\n                                    CPUMatrix<ElemType>& functionValues,\n                                    ElemType learnRatePerSample,\n                                    ElemType momentum,\n                                    ElemType adaWeight,\n                                    ElemType adaMul,\n                                    bool unitGainMomentum)\n{\n    auto unitGainFactor = ElemType(unitGainMomentum ? (1.0 - momentum) : 1.0);\n\n    size_t numColsNeeded = 2 * gradients.GetNumCols();\n\n    if (IsEmpty() || (GetNumCols() < numColsNeeded))\n    {\n        RequireSize(gradients.GetNumRows(), numColsNeeded);\n        SetValue(0.0);\n    }\n\n    if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != numColsNeeded)\n        LogicError(\"The matrix gradients does not have expected dimensions.\");\n\n    size_t n = gradients.GetNumElements();\n    ElemType* grad = gradients.Data();\n    ElemType* smoothAda = Data();\n    ElemType* smoothMom = Data() + n;\n    ElemType* val = functionValues.Data();\n#pragma omp parallel for\n    // TODO: Unroll 4-times for better performance leveraging vectorization\n    for (long i = 0; i < n; i++)\n    {\n        ElemType g = grad[i];\n        ElemType adaSqr = adaWeight * smoothAda[i] + (1.0f - adaWeight) * g * g;\n        smoothAda[i] = adaSqr;\n        if (adaSqr != 0.0f)\n        {\n            ElemType ada = sqrt(adaSqr);\n            ElemType w = adaMul * ((ElemType) 1.0 / ada);\n\n            if (w > 10.0f)\n                w = 10.0f;\n            g *= w;\n        }\n\n        if (momentum > 0.0f)\n        {\n            g = momentum * smoothMom[i] + unitGainFactor * g;\n            smoothMom[i] = g;\n        }\n\n        g *= learnRatePerSample;\n        val[i] -= g;\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::Adam(CPUMatrix<ElemType>& gradients, CPUMatrix<ElemType>& functionValues, ElemType learnRatePerSample,\n    ElemType momentum, ElemType adaWeight, ElemType adaMul, bool unitGainMomentum)\n{\n    size_t numColsNeeded = 2 * gradients.GetNumCols();\n    auto unitGainFactor = ElemType(unitGainMomentum ? (1.0 - momentum) : 1.0);\n\n    if (IsEmpty() || (GetNumCols() < numColsNeeded))\n    {\n        RequireSize(gradients.GetNumRows(), numColsNeeded);\n        SetValue(0.0);\n    }\n\n    if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != numColsNeeded)\n        LogicError(\"The matrix gradients does not have expected dimensions.\");\n\n    size_t n = gradients.GetNumElements();\n    ElemType* grad = gradients.Data();\n    ElemType* smoothAda = Data();\n    ElemType* smoothMom = Data() + n;\n    ElemType* val = functionValues.Data();\n#pragma omp parallel for\n    // TODO: Unroll 4-times for better performance leveraging vectorization\n    for (long i = 0; i < n; i++)\n    {\n        ElemType g = grad[i];\n        ElemType adaSqr = adaWeight * smoothAda[i] + (1.0f - adaWeight) * g * g;\n        smoothAda[i] = adaSqr;\n        ElemType ada = sqrt(adaSqr);\n        ElemType w = adaMul * (ElemType)( 1.0 / (ada + 1e-8));\n        g = momentum * smoothMom[i] + unitGainFactor * g;\n        smoothMom[i] = g;\n        val[i] -= g * w * learnRatePerSample;\n    }\n}\n\ntemplate <class ElemType>\nElemType CPUMatrix<ElemType>::RmsProp(CPUMatrix<ElemType>& gradients,\n                                      ElemType RMS_GAMMA,\n                                      ElemType RMS_WGT_INC,\n                                      ElemType RMS_WGT_MAX,\n                                      ElemType RMS_WGT_DEC,\n                                      ElemType RMS_WGT_MIN,\n                                      const bool needAveMultiplier)\n{\n    const ElemType floor = 1e-6f;\n\n    size_t n = gradients.GetNumElements();\n    ElemType* curr_grad = gradients.Data();\n\n    if (IsEmpty() || GetNumCols() < gradients.GetNumCols() * 3)\n    {\n        RequireSize(gradients.GetNumRows(), gradients.GetNumCols() * 3);\n        SetValue(0.0);\n\n        ElemType* avars = Data();         // accumulated variances for RMS scaling\n        ElemType* steps = Data() + 2 * n; // current step size\n\n        // initialize moving average of gradient-squared\n        for (long i = 0; i < n; i++)\n            avars[i] = curr_grad[i] * curr_grad[i];\n\n        // initialize starting step size\n        for (long i = 0; i < n; i++)\n            steps[i] = ElemType(0.02);\n    }\n\n    ElemType* avars = Data();         // accumulated variances for RMS scaling\n    ElemType* signs = Data() + n;     // sign of previous gradient\n    ElemType* steps = Data() + 2 * n; // current step size\n\n    if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != gradients.GetNumCols() * 3)\n        LogicError(\"The matrix gradients does not have expected dimensions.\");\n\n    ElemType ONE_MINUS_GAMMA = ElemType(1.0) - RMS_GAMMA;\n    // int upd[] = {\n    //    2,2,0,\n    //    2,2,0,\n    //    1,1,1,\n    //    2,2,0,\n    //    1,2,1,\n    //    0,2,2,\n    //    1,1,1,\n    //    0,2,2,\n    //    0,2,2,\n    // };\n\n    //      for (long i=0; i<n; i++)\n    //      {\n    //          avars[i] = RMS_GAMMA * avars[i] + ONE_MINUS_GAMMA * (curr_grad[i] * curr_grad[i]);\n    //    // grad sign base 3: 0->neg, 1->zero, 2->pos\n    //    const int grad_sign = 1 + (ElemType(0) < curr_grad[i]) - (curr_grad[i] < ElemType(0));\n\n    //    // signs[i] contains three consecutive grad_sign\n    //    signs[i]  = 3*(int(signs[i]) % 9) + grad_sign;\n\n    //    switch(upd[int(signs[i])])\n    //    {\n    //    case 0:\n    //        steps[i] = max(steps[i] * RMS_WGT_DEC, RMS_WGT_MIN);\n    //        break;\n    //    case 2:\n    //        steps[i] = min(steps[i] * RMS_WGT_INC, RMS_WGT_MAX);\n    //        break;\n    //    }\n    //    curr_grad[i] *= steps[i] / sqrt(avars[i] + floor);\n    //      }\n\n    ElemType aveMultiplier = 0, a;\n    for (long i = 0; i < n; i++)\n    {\n        avars[i] = RMS_GAMMA * avars[i] + ONE_MINUS_GAMMA * (curr_grad[i] * curr_grad[i]);\n        const int grad_sign = (ElemType(0) < curr_grad[i]) - (curr_grad[i] < ElemType(0));\n\n        if (signs[i] * grad_sign > 0)\n            steps[i] = std::min(steps[i] * RMS_WGT_INC, RMS_WGT_MAX);\n        else\n            steps[i] = std::max(steps[i] * RMS_WGT_DEC, RMS_WGT_MIN);\n\n        a = steps[i] / sqrt(avars[i] + floor);\n        curr_grad[i] *= a;\n        signs[i] = (ElemType) grad_sign;\n\n        if (needAveMultiplier)\n            aveMultiplier += a;\n    }\n\n    if (needAveMultiplier)\n        return aveMultiplier / n;\n    else\n        return 1;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AdaDelta(CPUMatrix<ElemType>& gradients, CPUMatrix<ElemType>& functionValues, ElemType learningRate, ElemType rho, ElemType epsilon)\n{\n    size_t numColsNeeded = 2 * gradients.GetNumCols();\n\n    if (IsEmpty() || (GetNumCols() < numColsNeeded))\n    {\n        RequireSize(gradients.GetNumRows(), numColsNeeded);\n        SetValue(0.0);\n    }\n\n    if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != numColsNeeded)\n        LogicError(\"The matrix gradients does not have expected dimensions.\");\n\n    size_t n = gradients.GetNumElements();\n    ElemType* grad = gradients.Data();\n    ElemType* smoothAda = Data();\n    ElemType* smoothX2 = Data() + n;\n    ElemType* val = functionValues.Data();\n#pragma omp parallel for\n    // TODO: Unroll 4-times for better performance leveraging vectorization\n    for (long i = 0; i < n; i++)\n    {\n        ElemType g = grad[i];\n        ElemType adaSqr = rho * smoothAda[i] + (1 - rho) * g * g;\n        smoothAda[i] = adaSqr;\n        ElemType x2 = smoothX2[i];\n        ElemType deltaX = -sqrt(x2 + epsilon) / sqrt(adaSqr + epsilon) * g;\n        smoothX2[i] = rho * smoothX2[i] + (1 - rho) * deltaX * deltaX;\n        val[i] += learningRate * deltaX;\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::Reshape(const size_t numRows, const size_t numCols)\n{\n    if (numRows * numCols != GetNumElements())\n        InvalidArgument(\"Reshape: Total number of elements does not match.\");\n\n    m_numRows = numRows;\n    m_numCols = numCols;\n}\n\n// RequireSize() -- Tests if the matrix is the right size. If not, resizes the matrix. This avoids the VerifyResizable check if we're already the right size.\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::RequireSize(const size_t numRows, const size_t numCols, bool growOnly /*=true*/)\n{\n    if (GetNumRows() != numRows || GetNumCols() != numCols)\n        Resize(numRows, numCols, growOnly);\n}\n\n// Resize() -- change matrix size\n// This function is cheap if the matrix size does not change.\n// Current content is not preserved.\n// If growOnly is true, resize will not reallocate memory if the current memory is large enough (i.e., will not shrink).\n// If this object does not own its memory then new memory cannot be allocated (one can still shrink and/or reshape).\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::Resize(const size_t numRows, const size_t numCols, bool growOnly /*=true*/)\n{\n    if (GetNumRows() == numRows && GetNumCols() == numCols)\n        return;\n\n    VerifyResizable(__func__);\n\n    size_t numElements = numRows * numCols;\n    if (numElements > GetSizeAllocated() ||                 // grow allocation\n        (!growOnly && (numElements != GetSizeAllocated()))) // shrink allocation (not if 'growOnly')\n    {\n        // reallocate buffer\n        ElemType* pArray = nullptr;\n        if (numElements > 0)\n        {\n            pArray = NewArray<ElemType>(numElements);\n        }\n        // success: update the object\n        delete[] Buffer();\n\n        SetBuffer(pArray, numElements * sizeof(ElemType));\n        SetSizeAllocated(numElements);\n    }\n\n    // success\n    m_sliceViewOffset = 0;\n    m_numRows         = numRows;\n    m_numCols         = numCols;\n}\n\n// allocated by the callee but should be deleted by the caller\n// TODO: change to use STL vector instead\ntemplate <class ElemType>\nElemType* CPUMatrix<ElemType>::CopyToArray() const\n{\n    size_t numElements = GetNumElements();\n    if (numElements != 0)\n    {\n        ElemType* arrayCopyTo = NewArray<ElemType>(numElements);\n        memcpy(arrayCopyTo, Data(), sizeof(ElemType) * numElements);\n        return arrayCopyTo;\n    }\n    else\n    {\n        return nullptr;\n    }\n}\n\n//memory will be allocated by the callee if not enough but need to be deleted by the caller after it's done\n//return number of elements copied\ntemplate <class ElemType>\nsize_t CPUMatrix<ElemType>::CopyToArray(ElemType*& arrayCopyTo, size_t& currentArraySize) const\n{\n    size_t numElements = GetNumElements();\n\n    if (numElements > currentArraySize)\n    {\n        delete arrayCopyTo;\n        arrayCopyTo = NewArray<ElemType>(numElements);\n        currentArraySize = numElements;\n    }\n\n    if (numElements != 0)\n    {\n        memcpy(arrayCopyTo, Data(), sizeof(ElemType) * numElements);\n    }\n\n    return numElements;\n}\n\ntemplate <typename ElemType>\nvoid CPUMatrix<ElemType>::CopySection(size_t /*numRows*/, size_t /*numCols*/, ElemType* /*dst*/, size_t /*colStride*/) const\n{\n    // REVIEW alexeyk: currently not used by CPU, but implement when possible.\n    RuntimeError(\"Not implemented.\");\n}\n\ntemplate <class ElemType>\ninline size_t CPUMatrix<ElemType>::LocateColumn(const size_t col) const\n{\n    // For performance reason avoid extra validation in release.\n    assert(col == 0 || col < GetNumCols());\n    return col * m_numRows; // matrix in column-wise storage\n}\n\ntemplate <class ElemType>\ninline size_t CPUMatrix<ElemType>::LocateElement(const size_t row, const size_t col) const\n{\n    // For performance reason avoid extra validation in release.\n    assert(row < m_numRows);\n\n    return LocateColumn(col) + row; // matrix in column-wise storage\n}\n\n#pragma endregion Basic Operators\n\n#pragma region Member BLAS Functions\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::operator+=(ElemType alpha)\n{\n    return AssignSumOf(alpha, *this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::operator+(ElemType alpha) const\n{\n    CPUMatrix<ElemType> c(GetNumRows(), GetNumCols());\n    c.AssignSumOf(alpha, *this);\n    return c;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSumOf(const ElemType alpha, const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignSumOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) = alpha + a(i, j);\n            us(i + 1, j) = alpha + a(i + 1, j);\n            us(i + 2, j) = alpha + a(i + 2, j);\n            us(i + 3, j) = alpha + a(i + 3, j);\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) = alpha + a(i, j);\n        }\n    }\n\n    return *this;\n}\n\n//if [this] and a have same dimension then [this]=[this]+a\n//if a is a column vector, add to all columns of [this]\n//if a is a row vector, add to all rows of [this]\n//if a is a scalar, add it to all elements.\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::operator+=(const CPUMatrix<ElemType>& a)\n{\n    // if (a.GetNumElements() == 1)\n    //    *this += a(0,0);\n    // else\n    ScaleAndAdd(1, a, *this);\n\n    return *this;\n}\n\n//if [this] and a have same dimension then OUTPUT=[this]+a\n//if a is a column vector, add to all columns of [this]\n//if a is a row vector, add to all rows of [this]\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::operator+(const CPUMatrix<ElemType>& a) const\n{\n    if (GetNumElements() == 1)\n    {\n        CPUMatrix<ElemType> c(a);\n        c += (*this)(0, 0);\n        return c;\n    }\n    else if (a.GetNumElements() == 1)\n    {\n        CPUMatrix<ElemType> c(*this);\n        c += a(0, 0);\n        return c;\n    }\n    else\n    {\n        CPUMatrix<ElemType> c(*this); // this implementation will introduce a copy overhead. but make resue of the code\n        c += a;\n        return c;\n    }\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSumOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b)\n{\n    if (a.GetNumElements() == 1)\n    {\n        SetValue(b);\n        (*this) += a;\n    }\n    else\n    {\n        SetValue(a);\n        (*this) += b;\n    }\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::operator-=(ElemType alpha)\n{\n    return AssignDifferenceOf(*this, alpha);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::operator-(ElemType alpha) const\n{\n    CPUMatrix<ElemType> c(GetNumRows(), GetNumCols());\n    c.AssignDifferenceOf(*this, alpha);\n    return c;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignDifferenceOf(const ElemType alpha, const CPUMatrix<ElemType>& a)\n{\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) = alpha - a(i, j);\n            us(i + 1, j) = alpha - a(i + 1, j);\n            us(i + 2, j) = alpha - a(i + 2, j);\n            us(i + 3, j) = alpha - a(i + 3, j);\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) = alpha - a(i, j);\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignDifferenceOf(const CPUMatrix<ElemType>& a, const ElemType alpha)\n{\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) = a(i, j) - alpha;\n            us(i + 1, j) = a(i + 1, j) - alpha;\n            us(i + 2, j) = a(i + 2, j) - alpha;\n            us(i + 3, j) = a(i + 3, j) - alpha;\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) = a(i, j) - alpha;\n        }\n    }\n    return *this;\n}\n\n//if [this] and a have same dimension then [this]=[this]-a\n//if a is a column vector, minus it from all columns of [this]\n//if a is a row vector, minus it from all rows of [this]\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::operator-=(const CPUMatrix<ElemType>& a)\n{\n    ScaleAndAdd(-1, a, *this);\n\n    return *this;\n}\n\n//if [this] and a have same dimension then output=[this]-a\n//if a is a column vector, minus it from all columns of [this]\n//if a is a row vector, minus it from all rows of [this]\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::operator-(const CPUMatrix<ElemType>& a) const\n{\n    CPUMatrix<ElemType> c(*this); // this implementation will introduce a copy overhead. but make resue of the code\n    c -= a;\n    return c;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignDifferenceOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b)\n{\n    if (this != &a)\n    {\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n        SetValue(a);\n    }\n    (*this) -= b;\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::operator*=(ElemType alpha)\n{\n    Scale(alpha, *this);\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::operator*(ElemType alpha) const\n{\n    CPUMatrix<ElemType> c(GetNumRows(), GetNumCols());\n    Scale(alpha, *this, c);\n    return c;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignProductOf(const ElemType alpha, const CPUMatrix<ElemType>& a)\n{\n    Scale(alpha, a, *this);\n    return *this;\n}\n\n// [this]=a*b\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignProductOf(const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB)\n{\n    if (a.GetNumElements() == 1)\n    {\n        if (transposeB)\n            AssignTransposeOf(b);\n        (*this) *= a(0, 0);\n    }\n    else if (b.GetNumElements() == 1)\n    {\n        if (transposeA)\n            AssignTransposeOf(a);\n        (*this) *= b(0, 0);\n    }\n    else\n        Multiply(a, transposeA, b, transposeB, *this);\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::operator*(const CPUMatrix<ElemType>& a) const\n{\n    auto& us = *this;\n    if (GetNumElements() == 1)\n    {\n        CPUMatrix<ElemType> c;\n        c.AssignProductOf(us(0, 0), a);\n        return c;\n    }\n    else if (a.GetNumElements() == 1)\n    {\n        CPUMatrix<ElemType> c;\n        c.AssignProductOf(a(0, 0), us);\n        return c;\n    }\n    else\n    {\n        CPUMatrix<ElemType> c;\n        Multiply(*this, a, c);\n        return c;\n    }\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::operator/=(ElemType alpha)\n{\n    (*this) *= 1 / alpha;\n    return (*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::operator/(ElemType alpha) const\n{\n    return ((*this) * (1 / alpha));\n}\n\n//element-wise power\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::operator^=(ElemType alpha)\n{\n    auto& us = *this;\n    ElementWisePower(alpha, us, us);\n    return us;\n}\n\n//element-wise power\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::operator^(ElemType alpha) const\n{\n    CPUMatrix<ElemType> c(GetNumRows(), GetNumCols());\n    ElementWisePower(alpha, *this, c);\n    return c;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementPowerOf(const CPUMatrix<ElemType>& a, const ElemType power)\n{\n    ElementWisePower(power, a, *this);\n    return *this;\n}\n\n//[this]=[this] .* a (we cannot override operator .* in c++)\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::ElementMultiplyWith(const CPUMatrix<ElemType>& a)\n{\n    return AssignElementProductOf(*this, a);\n}\n\n//[this]=[this] .* a (we cannot override operator .* in c++)\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::ElementDivideBy(const CPUMatrix<ElemType>& a)\n{\n    return AssignElementDivisionOf(*this, a);\n}\n\n//[this]=a .* b\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"AssignElementProductOf: Matrix is empty.\");\n\n    if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()))\n        InvalidArgument(\"AssignElementProductOf: The input matrix dimensions do not match.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) = a(i, j) * b(i, j);\n            us(i + 1, j) = a(i + 1, j) * b(i + 1, j);\n            us(i + 2, j) = a(i + 2, j) * b(i + 2, j);\n            us(i + 3, j) = a(i + 3, j) * b(i + 3, j);\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) = a(i, j) * b(i, j);\n        }\n    }\n    return *this;\n}\n\n//[this] +=a .* b\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AddElementProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"AddElementProductOf: Matrix is empty.\");\n\n    if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()))\n        InvalidArgument(\"AddElementProductOf : The input matrix dimensions do not match.\");\n\n    if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == GetNumCols()))\n        InvalidArgument(\"AddElementProductOf : The input matrix dimensions do not match [this].\");\n\n    auto& us = *this;\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) += a(i, j) * b(i, j);\n            us(i + 1, j) += a(i + 1, j) * b(i + 1, j);\n            us(i + 2, j) += a(i + 2, j) * b(i + 2, j);\n            us(i + 3, j) += a(i + 3, j) * b(i + 3, j);\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) += a(i, j) * b(i, j);\n        }\n    }\n\n    return *this;\n}\n\n//[this]=a ./ b\n// TODO: This clips the divisor by a small value. Is that really what one would want?\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementDivisionOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"AssignElementDivisionOf: Matrix is empty.\");\n\n    if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()))\n        InvalidArgument(\"AssignElementDivisionOf : The input matrix dimensions do not match.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    ElemType smallValue = EPS_IN_INVERSE;\n\n#pragma omp parallel for\n    foreach_coord (i, j, us)\n    {\n        ElemType v = b(i, j);\n        if (v >= 0 && v < smallValue)\n            us(i, j) = a(i, j) / smallValue;\n        else if (v < 0 && v > -smallValue)\n            us(i, j) = a(i, j) / (-smallValue);\n        else\n            us(i, j) = a(i, j) / v;\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::ColumnElementMultiplyWith(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty() || IsEmpty())\n        LogicError(\"ColumnElementMultiplyWith: Matrix is empty.\");\n\n    if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1))\n        InvalidArgument(\"ColumnElementMultiplyWith: The input matrix should be a col vector and match [this]'s rows.\");\n\n    auto& us = *this;\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) *= a(i, 0);\n            us(i + 1, j) *= a(i + 1, 0);\n            us(i + 2, j) *= a(i + 2, 0);\n            us(i + 3, j) *= a(i + 3, 0);\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) *= a(i, 0);\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::RowElementMultiplyWith(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty() || IsEmpty())\n        LogicError(\"RowElementMultiplyWith: Matrix is empty.\");\n\n    if (!(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols()))\n        InvalidArgument(\"RowElementMultiplyWith: The input matrix should be a row vector and match [this]'s columns.\");\n\n    auto& us = *this;\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        ElemType v = a(0, j);\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) *= v;\n            us(i + 1, j) *= v;\n            us(i + 2, j) *= v;\n            us(i + 3, j) *= v;\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) *= v;\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::RowElementDivideBy(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty() || IsEmpty())\n        LogicError(\"RowElementDivideBy: Matrix is empty.\");\n\n    if (!(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols()))\n        InvalidArgument(\"RowElementDivideBy: The input matrix should be a row vector and match [this]'s columns.\");\n\n    auto& us = *this;\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        ElemType v = a(0, j);\n        if (v >= 0 && v < EPS_IN_INVERSE)\n            v = EPS_IN_INVERSE;\n        else if (v < 0 && v > -EPS_IN_INVERSE)\n            v = (-EPS_IN_INVERSE);\n\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) /= v;\n            us(i + 1, j) /= v;\n            us(i + 2, j) /= v;\n            us(i + 3, j) /= v;\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) /= v;\n        }\n    }\n\n    return *this;\n}\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::ColumnElementDivideBy(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty() || IsEmpty())\n        LogicError(\"ColumnElementDivideBy: Matrix is empty.\");\n\n    if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1))\n        InvalidArgument(\"ColumnElementDivideBy: The input matrix should be a col vector and match [this]'s rows.\");\n\n    auto& us = *this;\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n\n    ElemType smallValue = EPS_IN_INVERSE;\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        for (long i = 0; i < m; i++)\n        {\n            ElemType v = a(i, 0);\n            if (v >= 0 && v < smallValue)\n                us(i, j) /= smallValue;\n            else if (v < 0 && v > -smallValue)\n                us(i, j) /= (-smallValue);\n            else\n                us(i, j) /= v;\n        }\n    }\n\n    return *this;\n}\n\n//[this]=1 ./ a\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::ElementInverse()\n{\n    return AssignElementInverseOf(*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementInverseOf(const CPUMatrix<ElemType>& a)\n{\n    ElemType smallValue = EPS_IN_INVERSE;\n\n    if (a.IsEmpty())\n        LogicError(\"AssignElementInverseOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n#pragma omp parallel for\n    foreach_coord (i, j, us)\n    {\n        if (a(i, j) < 0 && a(i, j) > -smallValue)\n            us(i, j) = 1 / (-smallValue);\n        else if (a(i, j) >= 0 && a(i, j) < smallValue)\n            us(i, j) = 1 / smallValue;\n        else\n            us(i, j) = 1 / a(i, j);\n    }\n\n    return *this;\n}\n\n//[this]=sigmoid([this]) element wise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSigmoid()\n{\n    return AssignSigmoidOf(*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSigmoidOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignSigmoidOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n#pragma omp parallel for\n    foreach_coord (i, j, us)\n    {\n        if (a(i, j) >= 0)\n            us(i, j) = 1 / (1 + exp(-a(i, j)));\n        else\n        {\n            ElemType v = exp(a(i, j));\n            us(i, j) = v / (1 + v);\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLinearRectifierDerivative()\n{\n    return AssignLinearRectifierDerivativeOf(*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLinearRectifierDerivativeOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignLinearRectifierDerivativeOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) = a(i, j) > 0.0f ? 1.0f : 0.0f;\n            us(i + 1, j) = a(i + 1, j) > 0.0f ? 1.0f : 0.0f;\n            us(i + 2, j) = a(i + 2, j) > 0.0f ? 1.0f : 0.0f;\n            us(i + 3, j) = a(i + 3, j) > 0.0f ? 1.0f : 0.0f;\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) = a(i, j) > 0.0f ? 1.0f : 0.0f;\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSigmoidDerivative()\n{\n    return AssignSigmoidDerivativeOf(*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSigmoidDerivativeOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignSigmoidDerivativeOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            ElemType v = a(i, j);\n            us(i, j) = v * (1 - v);\n\n            ElemType v1 = a(i + 1, j);\n            us(i + 1, j) = v1 * (1 - v1);\n\n            ElemType v2 = a(i + 2, j);\n            us(i + 2, j) = v2 * (1 - v2);\n\n            ElemType v3 = a(i + 3, j);\n            us(i + 3, j) = v3 * (1 - v3);\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            ElemType v = a(i, j);\n            us(i, j) = v * (1 - v);\n        }\n    }\n\n    return *this;\n}\n\n//[this]=tanh([this]) element wise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTanh()\n{\n    return AssignTanhOf(*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTanhOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignTanhOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) = tanh(a(i, j));\n            us(i + 1, j) = tanh(a(i + 1, j));\n            us(i + 2, j) = tanh(a(i + 2, j));\n            us(i + 3, j) = tanh(a(i + 3, j));\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) = tanh(a(i, j));\n        }\n    }\n\n    return *this;\n}\n\n//[this]=softmax([this]) element wise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLogSoftmax(const bool isColWise)\n{\n    return AssignLogSoftmaxOf(*this, isColWise);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLogSoftmaxOf(const CPUMatrix<ElemType>& a, const bool isColWise)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignLogSoftmaxOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    if (isColWise)\n    {\n#pragma omp parallel for\n        foreach_column (j, a)\n        {\n            // we need to extract max before applying exp to avoid overflow\n            ElemType maxV = a(0, j);\n            foreach_row (i, a)\n                maxV = std::max(maxV, a(i, j));\n\n            ElemType sum = 0;\n            foreach_row (i, a)\n                sum += exp(us(i, j) = a(i, j) - maxV);\n            sum = log(sum);\n            foreach_row (i, us)\n                us(i, j) -= sum;\n        }\n    }\n    else\n    {\n#pragma omp parallel for\n        foreach_row (i, a)\n        {\n            // we need to extract max before applying exp to avoid overflow\n            ElemType maxV = a(i, 0);\n            foreach_column (j, a)\n                maxV = std::max(maxV, a(i, j));\n\n            ElemType sum = 0;\n            foreach_column (j, a)\n                sum += exp(us(i, j) = a(i, j) - maxV);\n            sum = log(sum);\n            foreach_column (j, us)\n                us(i, j) -= sum;\n        }\n    }\n\n    return *this;\n}\n\n//[this]=hardmax([this])\n//the max element is 1 else is 0\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceHardmax(const bool isColWise)\n{\n    return AssignHardmaxOf(*this, isColWise);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignHardmaxOf(const CPUMatrix<ElemType>& a, const bool isColWise)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignHardmaxOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    if (isColWise)\n    {\n#pragma omp parallel for\n        foreach_column (j, a)\n        {\n            // we need to extract max\n            ElemType maxV = a(0, j);\n            long maxI = 0;\n            foreach_row (i, a)\n            {\n                if (maxV < a(i, j))\n                {\n                    maxV = a(i, j);\n                    maxI = i;\n                }\n            }\n\n            foreach_row (i, us)\n                us(i, j) = (i == maxI) ? 1.0f : 0.0f;\n        }\n    }\n    else\n    {\n#pragma omp parallel for\n        foreach_row (i, a)\n        {\n            // we need to extract max\n            ElemType maxV = a(i, 0);\n            long maxJ = 0;\n            foreach_column (j, a)\n            {\n                if (maxV < a(i, j))\n                {\n                    maxV = a(i, j);\n                    maxJ = j;\n                }\n            }\n\n            foreach_column (j, us)\n                us(i, j) = (j == maxJ) ? 1.0f : 0.0f;\n        }\n    }\n\n    return *this;\n}\n\n//[this]=sqrt([this]) element wise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSqrt()\n{\n    return AssignSqrtOf(*this);\n}\n\n//to prevent negative values caused by floating operations, we force inputs to be >=0\n//this may, however, hide problems in the caller.\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSqrtOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignSqrtOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j)     = sqrt(max((ElemType)0, a(i, j)));\n            us(i + 1, j) = sqrt(max((ElemType)0, a(i + 1, j)));\n            us(i + 2, j) = sqrt(max((ElemType)0, a(i + 2, j)));\n            us(i + 3, j) = sqrt(max((ElemType)0, a(i + 3, j)));\n        }\n        // remaining\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) = sqrt(max((ElemType)0, a(i, j)));\n        }\n    }\n\n    return *this;\n}\n\n//[this]=exp([this]) element wise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceExp()\n{\n    return AssignExpOf(*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignExpOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignExpOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) = exp(a(i, j));\n            us(i + 1, j) = exp(a(i + 1, j));\n            us(i + 2, j) = exp(a(i + 2, j));\n            us(i + 3, j) = exp(a(i + 3, j));\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) = exp(a(i, j));\n        }\n    }\n\n    return *this;\n}\n\n//[this]=exp([this]) element wise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceAbs()\n{\n    return AssignAbsOf(*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAbsOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignAbsOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            us(i, j) = abs(a(i, j));\n            us(i + 1, j) = abs(a(i + 1, j));\n            us(i + 2, j) = abs(a(i + 2, j));\n            us(i + 3, j) = abs(a(i + 3, j));\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            us(i, j) = abs(a(i, j));\n        }\n    }\n\n    return *this;\n}\n\n//[this]=log([this]) element wise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLog()\n{\n    return AssignLogOf(*this);\n}\n\n//[this]=log([this]) element wise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLog10()\n{\n    return AssignLog10Of(*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLogOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignLogOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n#pragma omp parallel for\n    foreach_coord (i, j, a)\n    {\n        const ElemType v = a(i, j);\n        if (v < EPS_IN_LOG)\n        {\n            us(i, j) = LOG_OF_EPS_IN_LOG;\n        }\n        else\n            us(i, j) = log(v);\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLog10Of(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignLogOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n#pragma omp parallel for\n    foreach_coord (i, j, a)\n    {\n        const ElemType v = a(i, j);\n        if (v <= 0)\n            LogicError(\"AssignLogOf: Log can only applied to numbers larger than 0.\");\n        else if (v < EPS_IN_LOG)\n        {\n            us(i, j) = LOG10_OF_EPS_IN_LOG;\n        }\n        else\n            us(i, j) = log10(v);\n    }\n\n    return *this;\n}\n\n//[this]=cos([this]) element wise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceCosine()\n{\n    return AssignCosineOf(*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignCosineOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignCosineOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n#pragma omp parallel for\n    foreach_coord (i, j, a)\n    {\n        const ElemType v = a(i, j);\n        us(i, j) = cos(v);\n    }\n\n    return *this;\n}\n\n//[this]=-sin([this]) element wise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceNegativeSine()\n{\n    return AssignNegativeSineOf(*this);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignNegativeSineOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignCosineOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n#pragma omp parallel for\n    foreach_coord (i, j, a)\n    {\n        const ElemType v = a(i, j);\n        us(i, j) = -sin(v);\n    }\n\n    return *this;\n}\n\n//Threshold truncating: this[i] = max( this[i], threshold )\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTruncateBottom(const ElemType threshold)\n{\n    if (IsEmpty())\n        LogicError(\"InplaceTruncateBottom: Matrix is empty.\");\n\n    auto& us = *this;\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            if (us(i, j) < threshold)\n                us(i, j) = threshold;\n\n            if (us(i + 1, j) < threshold)\n                us(i + 1, j) = threshold;\n\n            if (us(i + 2, j) < threshold)\n                us(i + 2, j) = threshold;\n\n            if (us(i + 3, j) < threshold)\n                us(i + 3, j) = threshold;\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            if (us(i, j) < threshold)\n                us(i, j) = threshold;\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTruncate(const ElemType threshold)\n{\n    if (IsEmpty())\n        LogicError(\"InplaceTruncate: Matrix is empty.\");\n\n    auto& us = *this;\n    ElemType locThresholdPos = abs(threshold);\n    ElemType locTHresholdNeg = -locThresholdPos;\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols();\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        // four-way unrolling\n        for (long i = 0; i < (m & ~3); i += 4)\n        {\n            if (us(i, j) > locThresholdPos)\n                us(i, j) = locThresholdPos;\n            else if (us(i, j) < locTHresholdNeg)\n                us(i, j) = locTHresholdNeg;\n\n            if (us(i + 1, j) > locThresholdPos)\n                us(i + 1, j) = locThresholdPos;\n            else if (us(i + 1, j) < locTHresholdNeg)\n                us(i + 1, j) = locTHresholdNeg;\n\n            if (us(i + 2, j) > locThresholdPos)\n                us(i + 2, j) = locThresholdPos;\n            else if (us(i + 2, j) < locTHresholdNeg)\n                us(i + 2, j) = locTHresholdNeg;\n\n            if (us(i + 3, j) > locThresholdPos)\n                us(i + 3, j) = locThresholdPos;\n            else if (us(i + 3, j) < locTHresholdNeg)\n                us(i + 3, j) = locTHresholdNeg;\n        }\n        // handle remaining stuffs\n        for (long i = m & ~3; i < m; i++)\n        {\n            if (us(i, j) > locThresholdPos)\n                us(i, j) = locThresholdPos;\n            else if (us(i, j) < locTHresholdNeg)\n                us(i, j) = locTHresholdNeg;\n        }\n    }\n\n    return *this;\n}\n\n//x= x-threshold if x>threshold, x+threshold if x<-threshold, 0 otherwise\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSoftThreshold(const ElemType threshold)\n{\n    if (IsEmpty())\n        LogicError(\"InplaceTruncate: Matrix is empty.\");\n\n    long m = (long) GetNumElements();\n\n    ElemType* bufPtr = Data();\n#pragma omp parallel for\n    for (long i = 0; i < (m & ~3); i += 4) // four-way unrolling\n    {\n        if (bufPtr[i] > threshold)\n            bufPtr[i] -= threshold;\n        else if (bufPtr[i] < -threshold)\n            bufPtr[i] += threshold;\n        else\n            bufPtr[i] = 0;\n\n        if (bufPtr[i + 1] > threshold)\n            bufPtr[i + 1] -= threshold;\n        else if (bufPtr[i + 1] < -threshold)\n            bufPtr[i + 1] += threshold;\n        else\n            bufPtr[i + 1] = 0;\n\n        if (bufPtr[i + 2] > threshold)\n            bufPtr[i + 2] -= threshold;\n        else if (bufPtr[i + 2] < -threshold)\n            bufPtr[i + 2] += threshold;\n        else\n            bufPtr[i + 2] = 0;\n\n        if (bufPtr[i + 3] > threshold)\n            bufPtr[i + 3] -= threshold;\n        else if (bufPtr[i + 3] < -threshold)\n            bufPtr[i + 3] += threshold;\n        else\n            bufPtr[i + 3] = 0;\n    }\n    // handle remaining stuffs\n    for (long i = m & ~3; i < m; i++)\n    {\n        if (bufPtr[i] > threshold)\n            bufPtr[i] -= threshold;\n        else if (bufPtr[i] < -threshold)\n            bufPtr[i] += threshold;\n        else\n            bufPtr[i] = 0;\n    }\n\n    return *this;\n}\n\n//Threshold truncating: this[i] = max( a[i], threshold )\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTruncateBottomOf(const CPUMatrix<ElemType>& a, const ElemType threshold)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignTruncateBottomOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n#pragma omp parallel for\n    foreach_coord (i, j, a)\n    {\n        if (a(i, j) < threshold)\n            us(i, j) = threshold;\n        else\n            us(i, j) = a(i, j);\n    }\n\n    return *this;\n}\n\n//Threshold truncating: this[i] = min( this[i], threshold )\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTruncateTop(const ElemType threshold)\n{\n    if (IsEmpty())\n        LogicError(\"InplaceTruncateTop: Matrix is empty.\");\n\n    auto& us = *this;\n\n#pragma omp parallel for\n    foreach_coord (i, j, us)\n    {\n        if (us(i, j) > threshold)\n            us(i, j) = threshold;\n    }\n\n    return *this;\n}\n\n//Threshold truncating: this[i] = min( a[i], threshold )\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTruncateTopOf(const CPUMatrix<ElemType>& a, const ElemType threshold)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignTruncateTopOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n#pragma omp parallel for\n    foreach_coord (i, j, a)\n    {\n        if (a(i, j) > threshold)\n            us(i, j) = threshold;\n        else\n            us(i, j) = a(i, j);\n    }\n\n    return *this;\n}\n//Threshold truncating: this[i] = 0 if abs(this[i]<threshold).\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::SetToZeroIfAbsLessThan(const ElemType threshold)\n{\n    if (IsEmpty())\n        LogicError(\"SetToZeroIfAbsLessThan: Matrix is empty.\");\n\n    auto& us = *this;\n\n#pragma omp parallel for\n    foreach_coord (i, j, us)\n    {\n        if (abs(us(i, j)) < threshold)\n            us(i, j) = 0;\n    }\n\n    return *this;\n}\n\n//sum of all abs(elements)\ntemplate <class ElemType>\nElemType CPUMatrix<ElemType>::SumOfAbsElements() const\n{\n    if (IsEmpty())\n        LogicError(\"SumOfAbsElements: Matrix is empty.\");\n\n    if (sizeof(ElemType) == sizeof(double))\n    {\n        return (ElemType) cblas_dasum((int) GetNumElements(), reinterpret_cast<double*>(Data()), 1);\n    }\n    else\n    {\n#pragma warning(suppress : 4244)\n        return cblas_sasum((int) GetNumElements(), reinterpret_cast<float*>(Data()), 1);\n    }\n}\n\n//sum of all elements\ntemplate <class ElemType>\nElemType CPUMatrix<ElemType>::SumOfElements() const\n{\n    if (IsEmpty())\n        LogicError(\"SumOfElements: Matrix is empty.\");\n\n    ElemType sum = 0;\n    long m = (long) GetNumElements(); // note: OpenMP requires loop indices to be long, not size_t\n\n    ElemType* bufPtr = Data();\n//four-way unrolling\n#pragma omp parallel for reduction(+ : sum)\n    for (long i = 0; i < (m & ~3); i += 4)\n    {\n        sum += bufPtr[i] + bufPtr[i + 1] + bufPtr[i + 2] + bufPtr[i + 3];\n    }\n    // handle remaining stuffs\n    for (long i = m & ~3; i < m; i++)\n    {\n        sum += bufPtr[i];\n    }\n\n    return sum;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSumOfElements(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignSumOfElements: Matrix a is empty.\");\n\n    auto& us = *this;\n    us.RequireSize(1, 1);\n    us(0, 0) = a.SumOfElements();\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignOneHot(const CPUMatrix<ElemType>& a, vector<size_t>& shape, size_t axis)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignOneHot: Matrix a is empty.\");\n\n    if (axis >= shape.size())\n        LogicError(\"AssignOneHot: axis is not correct\");\n    \n    size_t item_size = 1;\n    for (size_t i = 0; i < shape.size() && i < axis; i++)\n        item_size *= shape[i];\n\n    size_t num_class = shape[axis];\n\n    auto& us = *this;\n    auto nCols = a.GetNumCols();\n    auto nRows = num_class * a.GetNumRows();\n    us.RequireSize(nRows, nCols);\n    \n    ElemType* bufPtr = Data();\n    ElemType* aBufPtr = a.Data();\n    memset(bufPtr, 0, sizeof(ElemType) * nRows *nCols);\n#pragma omp parallel for\n    for (long i = 0; i < a.GetNumElements(); i++)\n    {\n        if (aBufPtr[i] >= 0 && aBufPtr[i] < num_class)\n        {\n            size_t block_id = i / item_size;\n            size_t item_id = i % item_size;\n            bufPtr[block_id * num_class * item_size + item_id + item_size * (size_t)aBufPtr[i]] = 1;\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nbool CPUMatrix<ElemType>::IsEqualTo(const CPUMatrix<ElemType>& a, const ElemType threshold /*= 1e-8*/) const\n{\n    return AreEqual(*this, a, threshold);\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::VectorSum(const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c, const bool isColWise)\n{\n    if (a.IsEmpty())\n        LogicError(\"VectorSum:  Input matrix a is empty.\");\n\n    const int m = (int) a.GetNumRows();\n    const int n = (int) a.GetNumCols();\n\n    assert(m > 0 && n > 0); // converting from size_t to int may cause overflow\n\n    if (isColWise) // col-wise\n    {\n        c.RequireSize(1, n);\n\n#pragma omp parallel for\n        foreach_column (j, a)\n        {\n            ElemType v = 0;\n            foreach_row (i, a)\n            {\n#pragma omp atomic\n                v += a(i, j);\n            }\n            c(0, j) = v;\n        }\n    }\n    else\n    {\n        c.RequireSize(m, 1);\n\n#pragma omp parallel for\n        foreach_row (i, a)\n        {\n            ElemType v = 0;\n            foreach_column (j, a)\n            {\n#pragma omp atomic\n                v += a(i, j);\n            }\n            c(i, 0) = v;\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::VectorNorm1(CPUMatrix<ElemType>& c, const bool isColWise) const\n{\n    if (IsEmpty())\n        LogicError(\"VectorNorm1: Matrix is empty.\");\n\n    auto& us = *this;\n\n    const int m = (int) us.GetNumRows();\n    const int n = (int) us.GetNumCols();\n\n    assert(m > 0 && n > 0); // converting from size_t to int may cause overflow\n\n    if (isColWise) // col-wise\n    {\n        c.RequireSize(1, n);\n\n#pragma omp parallel for\n        foreach_column (j, us)\n        {\n            ElemType v = 0;\n            foreach_row (i, us)\n            {\n#pragma omp atomic\n                v += abs(us(i, j));\n            }\n            c(0, j) = v;\n        }\n    }\n    else\n    {\n        c.RequireSize(m, 1);\n\n#pragma omp parallel for\n        foreach_row (i, us)\n        {\n            ElemType v = 0;\n            foreach_column (j, us)\n            {\n#pragma omp atomic\n                v += abs(us(i, j));\n            }\n            c(i, 0) = v;\n        }\n    }\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignVectorNorm1Of(CPUMatrix<ElemType>& a, const bool isColWise)\n{\n    a.VectorNorm1(*this, isColWise);\n    return *this;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::VectorNorm2(CPUMatrix<ElemType>& c, const bool isColWise) const\n{\n    if (IsEmpty())\n        LogicError(\"VectorNorm2: Matrix is empty.\");\n\n    auto& us = *this;\n\n    const int m = (int) us.GetNumRows();\n    const int n = (int) us.GetNumCols();\n\n    assert(m > 0 && n > 0); // converting from size_t to int may cause overflow\n\n    ElemType* bufPtr = us.Data();\n    if (isColWise) // col-wise\n    {\n        c.RequireSize(1, n);\n\n        if (sizeof(ElemType) == sizeof(double))\n        {\n#pragma omp parallel for\n            foreach_column (j, c)\n            {\n                c(0, j) = (ElemType) cblas_dnrm2(m, reinterpret_cast<double*>(bufPtr + us.LocateColumn(j)), 1);\n            }\n        }\n        else\n        {\n#pragma omp parallel for\n            foreach_column (j, c)\n            {\n#pragma warning(suppress : 4244)\n                c(0, j) = cblas_snrm2(m, reinterpret_cast<float*>(bufPtr + us.LocateColumn(j)), 1);\n            }\n        }\n    }\n    else\n    {\n        c.RequireSize(m, 1);\n\n        if (sizeof(ElemType) == sizeof(double))\n        {\n#pragma omp parallel for\n            foreach_row (i, c)\n            {\n                c(i, 0) = cblas_dnrm2(n, reinterpret_cast<double*>(bufPtr + i), m);\n            }\n        }\n        else\n        {\n#pragma omp parallel for\n            foreach_row (i, c)\n            {\n#pragma warning(suppress : 4244)\n                c(i, 0) = cblas_snrm2(n, reinterpret_cast<float*>(bufPtr + i), m);\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignVectorNorm2Of(CPUMatrix<ElemType>& a, const bool isColWise)\n{\n    a.VectorNorm2(*this, isColWise);\n    return *this;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::VectorNormInf(CPUMatrix<ElemType>& c, const bool isColWise) const\n{\n    if (IsEmpty())\n        LogicError(\"VectorNormInf: Matrix is empty.\");\n\n    auto& us = *this;\n\n    const int m = (int) us.GetNumRows();\n    const int n = (int) us.GetNumCols();\n\n    assert(m > 0 && n > 0); // converting from size_t to int may cause overflow\n\n    if (isColWise) // col-wise\n    {\n        c.RequireSize(1, n);\n\n        // #pragma omp parallel for\n        foreach_column (j, us)\n        {\n            ElemType v = 0;\n            foreach_row (i, us)\n            {\n                v = std::max(v, abs(us(i, j)));\n            }\n            c(0, j) = v;\n        }\n    }\n    else\n    {\n        c.RequireSize(m, 1);\n\n        // #pragma omp parallel for\n        foreach_row (i, us)\n        {\n            ElemType v = 0;\n            foreach_column (j, us)\n            {\n                v = std::max(v, abs(us(i, j)));\n            }\n            c(i, 0) = v;\n        }\n    }\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignVectorNormInfOf(CPUMatrix<ElemType>& a, const bool isColWise)\n{\n    a.VectorNormInf(*this, isColWise);\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignInnerProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const bool isColWise)\n{\n    InnerProduct(a, b, *this, isColWise);\n    return *this;\n}\n\n//column-wise crossproduct\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignKhatriRaoProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"AssignKhatriRaoProductOf: Matrix is empty.\");\n\n    long cols = (long) a.GetNumCols();\n    if (cols != b.GetNumCols())\n        InvalidArgument(\"a.GetNumCols() != b.GetNumCols()\");\n\n    long rowsA = (long) a.GetNumRows();\n    long rowsB = (long) b.GetNumRows();\n    RequireSize(rowsA * rowsB, cols);\n\n#ifdef __INTEL_COMPILER // TODO: check this\n#pragma simd statement\n#endif\n#pragma omp parallel for\n    for (long k = 0; k < cols; k++)\n    {\n        long jj = 0;\n        for (long j = 0; j < rowsB; j++)\n        {\n            for (long i = 0; i < rowsA; i++)\n            {\n                (*this)(jj++, k) = a(i, k) * b(j, k);\n            }\n        }\n    }\n\n    return *this;\n}\n\n//column-wise reshaped product. Used to compute KhatriRaoProduct Gradient\n//   this = reshape each column of a from (K1xK2,1) to (K1, K2)\n//   if each column of a is not transposed, each (K1, K2) times each column of b (K2, frames).\n//   the output is a (K1, frames) matrix\n//   if each column of a is tranposed, each (K1, K2)^T times each column of b(K1, frames) and output is (K2, frames)\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AddColumnReshapeProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const bool transposeAColumn)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"AddColumnReshapeProductOf: Matrix is empty.\");\n\n    long cols = (long) a.GetNumCols();\n    if (cols != b.GetNumCols())\n        InvalidArgument(\"AddColumnReshapeProductOf: a.GetNumCols() != b.GetNumCols()\");\n\n    long rowsA = (long) a.GetNumRows();\n    long rowsB = (long) b.GetNumRows();\n\n    if (rowsA % rowsB != 0)\n        InvalidArgument(\"AddColumnReshapeProductOf: number of rows in a should be multiples of that in b.\");\n\n    long rowsC = rowsA / rowsB;\n    if (rowsC != GetNumRows() || cols != GetNumCols())\n        InvalidArgument(\"AddColumnReshapeProductOf: This matrix does not have the right size.\");\n\n    auto& us = *this;\n\n    if (transposeAColumn)\n    {\n        // find nrows and ncols of tbe reshaped a\n        long nrows = rowsB;\n        long ncols = rowsC;\n\n#ifdef __INTEL_COMPILER // TODO: check this\n#pragma simd statement\n#endif\n#pragma omp parallel for\n        foreach_column (t, a)\n        {\n            size_t k = 0;\n            for (size_t j = 0; j < ncols; j++) // row and col is transposed\n            {\n                ElemType v = 0;\n                for (size_t i = 0; i < nrows; i++)\n                {\n                    v += a(k, t) * b(i, t);\n                    k++;\n                }\n                us(j, t) += v;\n            }\n        }\n    }\n    else\n    {\n        size_t ncols = rowsB;\n        size_t nrows = rowsC;\n\n#ifdef __INTEL_COMPILER // TODO: check this\n#pragma simd statement\n#endif\n#pragma omp parallel for\n        foreach_column (t, a)\n        {\n            size_t k = 0;\n            for (size_t j = 0; j < ncols; j++)\n            {\n                for (size_t i = 0; i < nrows; i++)\n                {\n                    us(i, t) += a(k, t) * b(j, t);\n                    k++;\n                }\n            }\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AddWithScaleOf(ElemType alpha, const CPUMatrix<ElemType>& a)\n{\n    ScaleAndAdd(alpha, a, *this);\n    return *this;\n}\n\ntemplate <class ElemType>\nElemType CPUMatrix<ElemType>::FrobeniusNorm() const\n{\n    if (IsEmpty())\n        LogicError(\"FrobeniusNorm: Matrix is empty.\");\n\n    ElemType v = 0;\n\n    long m = (long) GetNumElements();\n\n    ElemType* bufPtr = Data();\n//four-way unrolling\n#pragma omp parallel for reduction(+ : v)\n    for (long i = 0; i < (m & ~3); i += 4)\n    {\n        v += bufPtr[i] * bufPtr[i] + bufPtr[i + 1] * bufPtr[i + 1] + bufPtr[i + 2] * bufPtr[i + 2] + bufPtr[i + 3] * bufPtr[i + 3];\n    }\n    // handle remaining stuffs\n    for (long i = m & ~3; i < m; i++)\n    {\n        v += bufPtr[i] * bufPtr[i];\n    }\n\n    return sqrt(v);\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignFrobeniusNormOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignFrobeniusNormOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    us.RequireSize(1, 1);\n    us(0, 0) = a.FrobeniusNorm();\n\n    return us;\n}\n\ntemplate <class ElemType>\nElemType CPUMatrix<ElemType>::MatrixNormInf() const\n{\n    if (IsEmpty())\n        LogicError(\"MatrixNormInf: Matrix is empty.\");\n\n    auto& us = *this;\n\n    ElemType v = 0;\n#pragma omp parallel for\n    foreach_coord (i, j, us)\n    {\n#pragma omp critical\n        {\n            v = std::max(v, abs(us(i, j)));\n        }\n    }\n    return v;\n}\n\ntemplate <class ElemType>\nElemType CPUMatrix<ElemType>::MatrixNorm0() const\n{\n    if (IsEmpty())\n        LogicError(\"MatrixNorm0: Matrix is empty.\");\n\n    auto& us = *this;\n\n    ElemType v = 0;\n#pragma omp parallel for\n    foreach_coord (i, j, us)\n    {\n        if (us(i, j) != 0)\n        {\n#pragma omp critical\n            {\n                ++v;\n            }\n        }\n    }\n    return v;\n}\n\ntemplate <class ElemType>\nElemType CPUMatrix<ElemType>::MatrixNorm1() const\n{\n    if (IsEmpty())\n        LogicError(\"MatrixNorm1: Matrix is empty.\");\n\n    auto& us = *this;\n\n    ElemType sum = 0;\n#pragma omp parallel for reduction(+ : sum)\n    foreach_coord (i, j, us)\n    {\n        sum += abs(us(i, j));\n    }\n    return sum;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSignOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AssignSignOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n#pragma omp parallel for\n    foreach_column (j, us)\n    {\n        foreach_row (i, us)\n        {\n            ElemType v = a(i, j);\n            if (!std::isnan(v))\n                us(i, j) = (v == (ElemType) 0 ? (ElemType) 0 : (v > 0 ? (ElemType) 1 : (ElemType)(-1)));\n            else\n                us(i, j) = v;\n        }\n    }\n\n    return us;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AddSignOf(const CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"AddSignOf: Matrix a is empty.\");\n\n    auto& us = *this;\n    if (this != &a)\n        RequireSize(a.GetNumRows(), a.GetNumCols());\n\n#pragma omp parallel for\n    foreach_column (j, us)\n    {\n        foreach_row (i, us)\n        {\n            ElemType v = a(i, j);\n            if (!std::isnan(v))\n                us(i, j) += (v == (ElemType) 0 ? (ElemType) 0 : (v > 0 ? (ElemType) 1 : (ElemType)(-1)));\n            else\n                us(i, j) = v;\n        }\n    }\n\n    return us;\n}\n//I decided to use CPUMatrix<ElemType>& maxIndexes instead of integer vector because the result may be used to do additional calculation\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::VectorMax(CPUMatrix<ElemType>& maxIndexes, CPUMatrix<ElemType>& maxValues, const bool isColWise, int topK) const\n{\n    if (IsEmpty())\n        LogicError(\"VectorMax: Matrix is empty.\");\n\n    auto& us = *this;\n    const int m = (int) GetNumRows();\n    const int n = (int) GetNumCols();\n    if (topK > m)\n        InvalidArgument(\"VectorMax: TopK must be less or equal than the number of rows\");\n\n    assert(m > 0 && n > 0); // converting from size_t to int may cause overflow\n\n    if (isColWise) // col-wise\n    {\n        maxValues.RequireSize(topK, n);\n        maxIndexes.RequireSize(topK, n);\n\n        if (topK == 1)\n        {\n#pragma omp parallel for\n            for (int j = 0; j < n; j++)\n            {\n                ElemType v = us(0, j);\n                size_t index = 0;\n                foreach_row (i, us)\n                {\n                    if (v < us(i, j))\n                    {\n                        index = i;\n                        v = us(i, j);\n                    }\n                }\n                maxValues(0, j) = v;\n                maxIndexes(0, j) = (ElemType) index;\n            }\n        }\n        else\n        {\n            std::vector<int> indices(m);\n            int i = 0;\n            std::generate(indices.begin(), indices.end(), [&i]\n                          {\n                              return i++;\n                          });\n\n            const ElemType* curVal =            Data();\n            ElemType* curIdx       = maxIndexes.Data();\n            ElemType* curMax       =  maxValues.Data();\n            for (int icol = 0; icol < n; icol++, curVal += m, curIdx += topK, curMax += topK)\n            {\n                // Partial sort, descending order.\n                std::nth_element(indices.begin(), indices.begin() + topK, indices.end(),\n                                 [curVal](const int& a, const int& b)\n                                 {\n                                     return curVal[a] > curVal[b];\n                                 });\n                // REVIEW alexeyk: the following produces warning (see SCL_SECURE_NO_WARNINGS) so use loop instead.\n                // std::transform(indices.begin(), indices.begin() + topK, curIdx, [](const int& a) { return static_cast<ElemType>(a); });\n                for (int i2 = 0; i2 < topK; i2++)\n                {\n                    curIdx[i2] = static_cast<ElemType>(indices[i2]);\n                    curMax[i2] = curVal[indices[i2]];\n                }\n            }\n        }\n    }\n    else\n    {\n        if (topK > 1)\n            RuntimeError(\"Row-wise TopK max is not supported.\");\n\n        maxValues.RequireSize(m, 1);\n        maxIndexes.RequireSize(m, 1);\n\n#pragma omp parallel for\n        for (int i = 0; i < m; i++)\n        {\n            ElemType v = us(i, 0);\n            size_t index = 0;\n            foreach_column (j, us)\n            {\n                if (v < us(i, j))\n                {\n                    index = j;\n                    v = us(i, j);\n                }\n            }\n            maxValues(i, 0) = v;\n            maxIndexes(i, 0) = (ElemType) index;\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::VectorMin(CPUMatrix<ElemType>& minIndexes, CPUMatrix<ElemType>& minValues, const bool isColWise) const\n{\n    if (IsEmpty())\n        LogicError(\"VectorMin: Matrix is empty.\");\n\n    auto& us = *this;\n    const int m = (int) GetNumRows();\n    const int n = (int) GetNumCols();\n\n    assert(m > 0 && n > 0); // converting from size_t to int may cause overflow\n\n    if (isColWise) // col-wise\n    {\n        minValues.RequireSize(1, n);\n        minIndexes.RequireSize(1, n);\n\n#pragma omp parallel for\n        for (int j = 0; j < n; j++)\n        {\n            ElemType v = us(0, j);\n            size_t index = 0;\n            foreach_row (i, us)\n            {\n                if (v > us(i, j))\n                {\n                    index = i;\n                    v = us(i, j);\n                }\n            }\n            minValues(0, j) = v;\n            minIndexes(0, j) = (ElemType) index;\n        }\n    }\n    else\n    {\n        minValues.RequireSize(m, 1);\n        minIndexes.RequireSize(m, 1);\n\n#pragma omp parallel for\n        for (int i = 0; i < m; i++)\n        {\n            ElemType v = us(i, 0);\n            size_t index = 0;\n            foreach_column (j, us)\n            {\n                if (v > us(i, j))\n                {\n                    index = j;\n                    v = us(i, j);\n                }\n            }\n            minValues(i, 0) = v;\n            minIndexes(i, 0) = (ElemType) index;\n        }\n    }\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignNumOfDiff(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, bool searchInCol)\n{\n    if (a.GetNumCols() != b.GetNumCols())\n        throw std::invalid_argument(\"AssignNumOfDiff: a and b must have the same number of columns.\");\n    if (!searchInCol && a.GetNumRows() != b.GetNumRows())\n        throw std::invalid_argument(\"AssignNumOfDiff: a and b must have the same number of rows.\");\n\n    ElemType n = 0;\n    if (!searchInCol)\n    {\n        foreach_coord (i, j, a)\n        {\n            n += (a(i, j) != b(i, j));\n        }\n    }\n    else\n    {\n        size_t crow = b.GetNumRows();\n        const ElemType* curCol = b.Data();\n        for (size_t icol = 0; icol < a.GetNumCols(); icol++, curCol += crow)\n        {\n            auto res = std::find(curCol, curCol + crow, a(0, icol));\n            if (res == curCol + crow)\n                n++;\n        }\n    }\n\n    RequireSize(1, 1); // result should be one element\n    (*this)(0, 0) = n;\n\n    return *this;\n}\n\n#pragma endregion Member BLAS Functions\n\n#pragma region Other helper Functions\n\nstruct PrintRange\n{\n    // print from begin to skipBegin, then from skipEnd to end\n    // skipBegin = end if no split\n    size_t begin;\n    size_t skipBegin;\n    size_t skipEnd;\n    size_t end;\n    bool IsEmpty() const { return end <= begin; }\n\n    // examples:\n    //  * 3..10\n    //  * -3..-3: include end-3..end and 0..3\n    PrintRange(ptrdiff_t first, ptrdiff_t last, size_t total)\n    {\n        if (first >= 0 && last >= 0)\n        {\n            begin = (size_t)first;\n            end = (size_t)last + 1;\n            if (end > total)    // allow INT_MAX, meaning to end\n                end = total;\n            skipBegin = end;\n            skipEnd = end;\n        }\n        else if (first < 0 && last < 0)\n        {\n            begin = 0;\n            skipBegin = (size_t)(-last);\n            skipEnd = (size_t)(total + first);\n            if (skipEnd <= skipBegin)\n                skipBegin = skipEnd = total;\n            end = total;\n        }\n        else    // if other combinations are ever of interest then implement them here\n            LogicError(\"Print: Bounds must be either both positive or both negative.\");\n    }\n};\n\n// use negative ranges to print corners, e.g. Print(\"name\", -3, -3, -3, -3) will print the first 3 and last 3 rows/cols\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::Print(const char* matrixName, ptrdiff_t rowFirst, ptrdiff_t rowLast, ptrdiff_t colFirst, ptrdiff_t colLast) const\n{\n    fprintf(stderr, \"\\n###### \");\n    if (matrixName != nullptr)\n        fprintf(stderr, \"%s \", matrixName);\n    fprintf(stderr, \"(%lu, %lu)\", (unsigned long)GetNumRows(), (unsigned long)GetNumCols());\n    if (rowFirst != 0 || colFirst != 0 || (size_t)(rowLast + 1) != GetNumRows() || (size_t)(colLast + 1) != GetNumCols())\n        fprintf(stderr, \" [%ld:%ld, %ld:%ld]\", (long)rowFirst, (long)rowLast, (long)colFirst, (long)colLast);\n    fprintf(stderr, \" ######\\n\\n\");\n\n    if (IsEmpty())\n    {\n        fprintf(stderr, \"(empty)\\n\");\n        return;\n    }\n\n    PrintRange rowRange(rowFirst, rowLast, GetNumRows());\n    PrintRange colRange(colFirst, colLast, GetNumCols());\n\n    if (rowRange.IsEmpty() || colRange.IsEmpty())\n    {\n        fprintf(stderr, \"(empty)\\n\");\n        return;\n    }\n\n    const auto& us = *this;\n    if (rowRange.begin > 0)\n        fprintf(stderr, \"...\\n\");\n    for (size_t i = rowRange.begin; i < rowRange.end; i++)\n    {\n        if (i == rowRange.skipBegin)        // insert ... between the two blocks if any\n        {\n            fprintf(stderr, \"...\\n\");\n            i = rowRange.skipEnd;\n        }\n        if (colRange.begin > 0)             // ... at line start\n            fprintf(stderr, \"...\\t\");\n        for (size_t j = colRange.begin; j < colRange.end; j++)\n        {\n            if (j == colRange.skipBegin)\n            {\n                fprintf(stderr, \"...\\t\");\n                j = colRange.skipEnd;\n            }\n            fprintf(stderr, \"%.10f\\t\", us(i, j));\n        }\n        if (colRange.end < GetNumCols())    // ... at line end\n            fprintf(stderr, \"...\");\n        fprintf(stderr, \"\\n\");\n    }\n    if (rowRange.end < GetNumRows())\n        fprintf(stderr, \"...\\n\");\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::Print(const char* matrixName /*=nullptr*/) const\n{\n    Print(matrixName, 0, GetNumRows() - 1, 0, GetNumCols() - 1);\n}\n\n// file I/O\n//matrixName is used to verify that correct matrix is read.\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::ReadFromFile(FILE*, const char* /*matrixName*/)\n{\n    RuntimeError(\"not implemented.\");\n}\n\n//matrixName is used to verify that correct matrix is read.\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::WriteToFile(FILE*, const char* /*matrixName*/)\n{\n    RuntimeError(\"not implemented.\");\n}\n\n//assume each column is an input sample. Each sample is stored in [channel, row, col]  (r00, g00, b00, r01, g01, b01, r10, g10, b10, r11, g11, b11)\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignPackedConvolutionInput(const CPUMatrix<ElemType>& inputSubBatch,\n                                                                       const size_t inputWidth, const size_t inputHeight, const size_t inputChannels,\n                                                                       const size_t outputWidth, const size_t outputHeight, const size_t /*outputChannels*/,\n                                                                       const size_t kernelWidth, const size_t kernelHeight, const size_t horizontalSubsample, const size_t verticalSubsample,\n                                                                       const bool zeroPadding)\n{\n    if (verticalSubsample > kernelHeight || horizontalSubsample > kernelWidth)\n        LogicError(\"Arguments verticalSubsample (or horitzontalSubsample) must be less or equal than kernelHeight (or kernelWidth).\");\n\n    const size_t packedInputRows = kernelWidth * kernelHeight * inputChannels;\n    const size_t packedInputColsPerSample = outputWidth * outputHeight; // output size per channel\n    const size_t inputDim = inputWidth * inputHeight * inputChannels;\n    const size_t smallBatchSize = inputSubBatch.GetNumCols();\n    const long inputHeightTimesChannel = (long) (inputHeight * inputChannels);\n    RequireSize(packedInputRows, packedInputColsPerSample * smallBatchSize);\n    if (zeroPadding)\n        SetValue((ElemType) 0);\n\n    const long halfKernelWidth = (long) kernelWidth / 2;\n    const long halfKernelHeight = (long) kernelHeight / 2;\n\n#pragma omp parallel for // each input element is copied to many places\n    for (long sample = 0; sample < smallBatchSize; sample++)\n    {\n        for (long id = 0; id < inputDim; id++)\n        {\n            // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * inputChannels)\n            // IN_ELEM_COLPOS = sample\n\n            const long y = id / inputHeightTimesChannel;   // inputCol\n            const long nXC = id % inputHeightTimesChannel; // channel + inputRow*inputChannels\n            const long x = nXC / (long) inputChannels;     // inputRow\n            const long c = nXC % (long) inputChannels;     // channel\n\n            long x0 = 0, y0 = 0, x1 = 0, y1 = 0;\n            if (zeroPadding)\n            {\n                x0 = (long) max((ElemType)0, ceil((x - (ElemType)kernelHeight + 1.0f + halfKernelHeight) / (ElemType)verticalSubsample)); // row : first wrow in which x is in\n                x1 = (long) (x + halfKernelHeight - x0 * verticalSubsample);                                                      // first posxInKernel\n                y0 = (long) max((ElemType)0, ceil((y - (ElemType)kernelWidth + 1.0f + halfKernelWidth) / (ElemType)horizontalSubsample)); // col : first wcol in which y is in\n                y1 = (long) (y + halfKernelWidth - y0 * horizontalSubsample);                                                     // first posyInKernel\n            }\n            else\n            {\n                x0 = (long) max((ElemType)0, ceil((x - (ElemType)kernelHeight + 1) / (ElemType)verticalSubsample));  // row : first wrow in which x is in\n                x1 = (long) (x - x0 * verticalSubsample);                                                    // first posxInKernel\n                y0 = (long) max((ElemType)0, ceil((y - (ElemType)kernelWidth + 1) / (ElemType)horizontalSubsample)); // col : first wcol in which y is in\n                y1 = (long) (y - y0 * horizontalSubsample);                                                  // first posyInKernel\n            }\n\n            assert(x1 >= 0 && x1 < kernelHeight && y1 >= 0 && y1 < kernelWidth);\n\n            // PACK_ELEM_ROWPOS(channel, posxInKernel, posyInKernel) = (channel * kernelWidth * kernelHeight + posxInKernel + posyInKernel * kernelHeight)\n            // PACK_ELEM_COLPOS(sample, wrow, wcol) = (sample*packedInputColsPerSample + outputHeight*wcol + wrow\n\n            ElemType currentInputValue = inputSubBatch(id, sample);\n            long packColBase = (long) (sample * packedInputColsPerSample + y0 * outputHeight);\n            for (long wcol = y0, posyInKernel = y1; wcol < (long) outputWidth && posyInKernel >= 0; wcol++, posyInKernel -= (long) horizontalSubsample)\n            {\n                long packRowBase = (long) (c * kernelWidth * kernelHeight + posyInKernel * kernelHeight);\n                for (long wrow = x0, posxInKernel = x1; wrow < (long) outputHeight && posxInKernel >= 0; wrow++, posxInKernel -= (long) verticalSubsample)\n                {\n                    const long packRow = packRowBase + posxInKernel;\n                    const long packCol = packColBase + wrow;\n                    (*this)(packRow, packCol) = currentInputValue;\n                }\n                packColBase += (long) outputHeight;\n            }\n        }\n    }\n\n    return *this;\n}\n//assume each column is an input sample. Each sample is stored in [channel, row, col]  (r00, g00, b00, r01, g01, b01, r10, g10, b10, r11, g11, b11)\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::UnpackConvolutionInput(CPUMatrix<ElemType>& inputSubBatch,\n                                                                 const size_t inputWidth, const size_t inputHeight, const size_t inputChannels,\n                                                                 const size_t outputWidth, const size_t outputHeight, const size_t /*outputChannels*/,\n                                                                 const size_t kernelWidth, const size_t kernelHeight, const size_t horizontalSubsample, const size_t verticalSubsample,\n                                                                 const bool zeroPadding) const\n{\n    if (verticalSubsample > kernelHeight || horizontalSubsample > kernelWidth)\n        LogicError(\"Arguments verticalSubsample (or horizonSubsample) must be less than or equal to kernelHeight (or kernelWidth).\");\n\n    const size_t packedInputColsPerSample = outputWidth * outputHeight; // output size per channel\n    const size_t inputDim = inputWidth * inputHeight * inputChannels;\n    const size_t smallBatchSize = inputSubBatch.GetNumCols();\n    const long inputHeightTimesChannel = (long) (inputHeight * inputChannels);\n\n    const long halfKernelWidth = (long) kernelWidth / 2;\n    const long halfKernelHeight = (long) kernelHeight / 2;\n\n#pragma omp parallel for // each input element is copied to many places\n    for (long sample = 0; sample < smallBatchSize; sample++)\n    {\n        for (long id = 0; id < inputDim; id++)\n        {\n            // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * inputChannels)\n            // IN_ELEM_COLPOS = sample\n\n            const long y = id / inputHeightTimesChannel;   // inputCol\n            const long nXC = id % inputHeightTimesChannel; // channel + inputRow*inputChannels\n            const long x = nXC / (long) inputChannels;     // inputRow\n            const long c = nXC % (long) inputChannels;     // channel\n\n            long x0 = 0, y0 = 0, x1 = 0, y1 = 0;\n            if (zeroPadding)\n            {\n                x0 = (long) max((ElemType)0, ceil((x - (ElemType) kernelHeight + 1.0f + halfKernelHeight) / (ElemType) verticalSubsample)); // row : first wrow in which x is in\n                x1 = (long) (x + halfKernelHeight - x0 * verticalSubsample);                                                      // first posxInKernel\n                y0 = (long) max((ElemType)0, ceil((y - (ElemType) kernelWidth + 1.0f + halfKernelWidth) / (ElemType) horizontalSubsample)); // col : first wcol in which y is in\n                y1 = (long) (y + halfKernelWidth - y0 * horizontalSubsample);                                                     // first posyInKernel\n            }\n            else\n            {\n                x0 = (long) max((ElemType)0, ceil((x - (ElemType) kernelHeight + 1) / (ElemType) verticalSubsample));  // row : first wrow in which x is in\n                x1 = (long) (x - x0 * verticalSubsample);                                                    // first posxInKernel\n                y0 = (long) max((ElemType)0, ceil((y - (ElemType) kernelWidth + 1) / (ElemType) horizontalSubsample)); // col : first wcol in which y is in\n                y1 = (long) (y - y0 * horizontalSubsample);                                                  // first posyInKernel\n            }\n\n            assert(x1 >= 0 && x1 < kernelHeight && y1 >= 0 && y1 < kernelWidth);\n\n            // PACK_ELEM_ROWPOS(channel, posxInKernel, posyInKernel) = (channel * kernelWidth * kernelHeight + posxInKernel + posyInKernel * kernelHeight)\n            // PACK_ELEM_COLPOS(sample, wrow, wcol) = (sample*packedInputColsPerSample + outputHeight*wcol + wrow\n\n            ElemType currentInputValue = inputSubBatch(id, sample);\n            long packColBase = (long) (sample * packedInputColsPerSample + y0 * outputHeight);\n            for (long wcol = y0, posyInKernel = y1; wcol < (long) outputWidth && posyInKernel >= 0; wcol++, posyInKernel -= (long) horizontalSubsample)\n            {\n                long packRowBase = (long) (c * kernelWidth * kernelHeight + posyInKernel * kernelHeight);\n                for (long wrow = x0, posxInKernel = x1; wrow < (long) outputHeight && posxInKernel >= 0; wrow++, posxInKernel -= (long) verticalSubsample)\n                {\n                    const long packRow = packRowBase + posxInKernel;\n                    const long packCol = packColBase + wrow;\n                    currentInputValue += (*this)(packRow, packCol);\n                }\n                packColBase += (long) outputHeight;\n            }\n            inputSubBatch(id, sample) = currentInputValue;\n        }\n    }\n\n    return inputSubBatch;\n}\n\n//assume each column is an input sample. Each sample is stored in  (r00, g00, b00, r01, g01, b01, r10, g10, b10, r11, g11, b11)\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignMaxPoolingResult(const CPUMatrix<ElemType>& inputBatch, const size_t channels,\n                                                                 const size_t /*inputWidth*/, const size_t inputHeight, const size_t /*inputSizePerSample*/,\n                                                                 const size_t /*outputWidth*/, const size_t outputHeight, const size_t outputSizePerSample,\n                                                                 const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample)\n{\n    const long inputHeightTimesChannel = (long) (inputHeight * channels);\n    const long outputHeightTimesChannel = (long) (outputHeight * channels);\n    const size_t batchSize = inputBatch.GetNumCols();\n    RequireSize(outputSizePerSample, batchSize);\n\n// IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels)\n// IN_ELEM_COLPOS = sample\n\n// OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels)\n// OUT_ELEM_COLPOS = sample\n\n#pragma omp parallel for\n    for (long sample = 0; sample < (long) batchSize; sample++)\n    {\n        for (long outputIndexWithinSample = 0; outputIndexWithinSample < outputSizePerSample; outputIndexWithinSample++)\n        {\n            const long y = outputIndexWithinSample / outputHeightTimesChannel;   // wcol\n            const long nXC = outputIndexWithinSample % outputHeightTimesChannel; // channel + wrow*channels\n            const long x = (long) (nXC / channels);                              // wrow\n            const long c = (long) (nXC % channels);                              // channel\n\n            ElemType maxVal = -FLT_MAX;\n            ElemType minVal = FLT_MAX;\n            const long rowInWindowBase = (long) ((x * verticalSubsample + y * horizontalSubsample * inputHeight) * channels + c);\n            for (long colInWindow = 0; colInWindow < windowWidth; colInWindow++)\n            {\n                long rowInInput = rowInWindowBase + colInWindow * inputHeightTimesChannel;\n                for (long rowInWindow = 0; rowInWindow < windowHeight; rowInWindow++)\n                {\n                    const ElemType val = inputBatch(rowInInput, sample); // pf[rowInWindow*channels];\n                    maxVal = std::max(maxVal, val);\n                    minVal = std::min(minVal, val);\n                    rowInInput += (long) channels;\n                }\n            }\n\n            (*this)(outputIndexWithinSample, sample) = maxVal;\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AddMaxPoolingGradient(const CPUMatrix<ElemType>& outputGradientBatch, const CPUMatrix<ElemType>& inputBatch, const CPUMatrix<ElemType>& outputBatch,\n                                                                const size_t channels,\n                                                                const size_t /*inputWidth*/, const size_t inputHeight, const size_t inputSizePerSample,\n                                                                const size_t outputWidth, const size_t outputHeight, const size_t /*outputSizePerSample*/,\n                                                                const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample)\n{\n    size_t batchSize = inputBatch.GetNumCols();\n    const long inputHeightTimesChannel = (long) (inputHeight * channels);\n    const long outputHeightTimesChannel = (long) (outputHeight * channels);\n\n// IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels)\n// IN_ELEM_COLPOS = sample\n\n// OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels)\n// OUT_ELEM_COLPOS = sample\n\n#pragma omp parallel for\n    for (long sample = 0; sample < batchSize; sample++)\n    {\n        for (long inputIndexWithinSample = 0; inputIndexWithinSample < inputSizePerSample; inputIndexWithinSample++)\n        {\n            const long y = inputIndexWithinSample / inputHeightTimesChannel;   // col in input\n            const long nXC = inputIndexWithinSample % inputHeightTimesChannel; // channel + row*chanels\n            const long x = (long) (nXC / channels);                            // row in input\n            const long c = (long) (nXC % channels);                            // channel\n\n            long startOutX = (long) max((ElemType)0, ceil((x - (ElemType) windowHeight + 1) / (ElemType) verticalSubsample));          // inclusive start\n            long endOutX = (long) ((x / verticalSubsample < outputHeight - 1) ? x / verticalSubsample : outputHeight - 1);   // inclusive end\n            long startOutY = (long) max((ElemType)0, ceil((y - (ElemType) windowWidth + 1) / (ElemType) horizontalSubsample));         // inclusive start\n            long endOutY = (long) ((y / horizontalSubsample < outputWidth - 1) ? y / horizontalSubsample : outputWidth - 1); // inclusive end\n\n            ElemType inputValue = inputBatch(inputIndexWithinSample, sample);\n            for (long outY = startOutY; outY <= endOutY; outY++)\n            {\n                for (long outX = startOutX; outX <= endOutX; outX++)\n                {\n                    long outputIndex = (long) (outY * outputHeightTimesChannel + outX * channels + c);\n                    if (inputValue == outputBatch(outputIndex, sample))\n                        (*this)(inputIndexWithinSample, sample) += outputGradientBatch(outputIndex, sample);\n                }\n            }\n        }\n    }\n\n    return *this;\n}\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAveragePoolingResult(const CPUMatrix<ElemType>& inputBatch, const size_t channels,\n                                                                     const size_t /*inputWidth*/, const size_t inputHeight, const size_t /*inputSizePerSample*/,\n                                                                     const size_t /*outputWidth*/, const size_t outputHeight, const size_t outputSizePerSample,\n                                                                     const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample)\n{\n    const long inputHeightTimesChannel = (long) (inputHeight * channels);\n    const long outputHeightTimesChannel = (long) (outputHeight * channels);\n    const size_t batchSize = inputBatch.GetNumCols();\n    const size_t windowSize = windowWidth * windowHeight;\n    RequireSize(outputSizePerSample, batchSize);\n\n// IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels)\n// IN_ELEM_COLPOS = sample\n\n// OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels)\n// OUT_ELEM_COLPOS = sample\n\n#pragma omp parallel for\n    for (long sample = 0; sample < batchSize; sample++)\n    {\n        for (long outputIndexWithinSample = 0; outputIndexWithinSample < outputSizePerSample; outputIndexWithinSample++)\n        {\n            const long y = outputIndexWithinSample / outputHeightTimesChannel;   // wcol\n            const long nXC = outputIndexWithinSample % outputHeightTimesChannel; // channel + wrow*channels\n            const long x = (long) (nXC / channels);                              // wrow\n            const long c = (long) (nXC % channels);                              // channel\n\n            ElemType sum = 0;\n            const long rowInWindowBase = (long) ((x * verticalSubsample + y * horizontalSubsample * inputHeight) * channels + c);\n            for (long colInWindow = 0; colInWindow < windowWidth; colInWindow++)\n            {\n                long rowInInput = rowInWindowBase + colInWindow * inputHeightTimesChannel;\n                for (long rowInWindow = 0; rowInWindow < windowHeight; rowInWindow++)\n                {\n                    sum += inputBatch(rowInInput, sample);\n                    rowInInput += (long) channels;\n                }\n            }\n\n            (*this)(outputIndexWithinSample, sample) = sum / windowSize;\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AddAveragePoolingGradient(const CPUMatrix<ElemType>& outputGradientBatch,\n                                                                    const size_t channels,\n                                                                    const size_t /*inputWidth*/, const size_t inputHeight, const size_t inputSizePerSample,\n                                                                    const size_t outputWidth, const size_t outputHeight, const size_t /*outputSizePerSample*/,\n                                                                    const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample)\n{\n    size_t batchSize = outputGradientBatch.GetNumCols();\n    const long inputHeightTimesChannel = (long) (inputHeight * channels);\n    const long outputHeightTimesChannel = (long) (outputHeight * channels);\n    const long windowSize = (long) (windowWidth * windowHeight);\n\n// IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels)\n// IN_ELEM_COLPOS = sample\n\n// OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels)\n// OUT_ELEM_COLPOS = sample\n\n#pragma omp parallel for\n    for (long sample = 0; sample < batchSize; sample++)\n    {\n        for (long inputIndexWithinSample = 0; inputIndexWithinSample < inputSizePerSample; inputIndexWithinSample++)\n        {\n            const long y = inputIndexWithinSample / inputHeightTimesChannel;   // col in input\n            const long nXC = inputIndexWithinSample % inputHeightTimesChannel; // channel + row*chanels\n            const long x = nXC / (long) channels;                              // row in input\n            const long c = nXC % (long) channels;                              // channel\n\n            long startOutX = (long) max((ElemType)0, ceil((x - (ElemType) windowHeight + 1) / (ElemType) verticalSubsample));               // inclusive start\n            long endOutX = (long) ((x / verticalSubsample < outputHeight - 1) ? x / (long) verticalSubsample : outputHeight - 1); // inclusive end\n            long startOutY = (long) max((ElemType)0, ceil((y - (ElemType) windowWidth + 1) / (ElemType) horizontalSubsample));              // inclusive start\n            long endOutY = (long) ((y / horizontalSubsample < outputWidth - 1) ? y / horizontalSubsample : outputWidth - 1);      // inclusive end\n\n            for (long outY = startOutY; outY <= endOutY; outY++)\n            {\n                for (long outX = startOutX; outX <= endOutX; outX++)\n                {\n                    long outputIndex = outY * outputHeightTimesChannel + outX * (long) channels + c;\n                    (*this)(inputIndexWithinSample, sample) += outputGradientBatch(outputIndex, sample) / windowSize;\n                }\n            }\n        }\n    }\n\n    return *this;\n}\n#pragma endregion Other Helper Functions\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::ConvolutionForward(const CPUMatrix<ElemType>& kernel, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIwht,\n                                             const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const\n{\n#pragma omp parallel for\n    for (int64_t sample = 0; sample < (int64_t)output.GetNumCols(); sample++)\n    {\n        for (size_t row = 0; row < output.GetNumRows(); row++)\n        {\n            int colBase = mpRowCol(row, 0);\n            int ivBase = mpRowIwht(row, 0);\n            assert(0 <= colBase && colBase < GetNumRows());\n\n            ElemType sum = 0;\n            int i0 = mpRowRun(row, 0);\n            int skip = runs(i0++, 0);\n            int size = runs(i0++, 0);\n            int imask = i0 + size;\n            for (int i = 0; i < size; i++)\n            {\n                if (runs(imask + i, 0) == 0)\n                    continue;\n                int dcol = runs(i0 + i, 0);\n                assert(0 <= colBase + dcol && colBase + dcol < GetNumRows());\n                sum += kernel.Data()[ivBase + skip + i] * (*this)(colBase + dcol, sample);\n            }\n            output(row, sample) = sum;\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::ConvolutionBackwardData(const CPUMatrix<ElemType>& kernel, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIwht,\n                                                  const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& grad) const\n{\n#pragma omp parallel for\n    for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++)\n    {\n        for (size_t row = 0; row < GetNumRows(); row++)\n        {\n            int colBase = mpRowCol(row, 0);\n            int ivBase = mpRowIwht(row, 0);\n            assert(0 <= colBase && colBase < grad.GetNumRows());\n\n            ElemType curGrad = (*this)(row, sample);\n\n            int i0 = mpRowRun(row, 0);\n            int skip = runs(i0++, 0);\n            int size = runs(i0++, 0);\n            int imask = i0 + size;\n            for (int i = 0; i < size; i++)\n            {\n                if (runs(imask + i, 0) == 0)\n                    continue;\n                int dcol = runs(i0 + i, 0);\n                assert(0 <= colBase + dcol && colBase + dcol < grad.GetNumRows());\n                grad(colBase + dcol, sample) += curGrad * kernel.Data()[ivBase + skip + i];\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::ConvolutionBackwardKernel(const CPUMatrix<ElemType>& in, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIwht,\n                                                    const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& kernelGrad) const\n{\n    // Do NOT parallelize these loops!\n    for (size_t sample = 0; sample < GetNumCols(); sample++)\n    {\n        for (size_t row = 0; row < GetNumRows(); row++)\n        {\n            int colBase = mpRowCol(row, 0);\n            int ivBase = mpRowIwht(row, 0);\n            assert(0 <= colBase && colBase < in.GetNumRows());\n\n            ElemType curGrad = (*this)(row, sample);\n\n            int i0 = mpRowRun(row, 0);\n            int skip = runs(i0++, 0);\n            int size = runs(i0++, 0);\n            int imask = i0 + size;\n            for (int i = 0; i < size; i++)\n            {\n                if (runs(imask + i, 0) == 0)\n                    continue;\n                int dcol = runs(i0 + i, 0);\n                assert(0 <= colBase + dcol && colBase + dcol < in.GetNumRows());\n                kernelGrad.Data()[ivBase + skip + i] += curGrad * in(colBase + dcol, sample);\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::UnrollConvolutionInput(size_t unrollCols, size_t mapOutSize, const CPUMatrix<int>& mpRowCol,\n                                                 const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const\n{\n    size_t batchSize = GetNumCols();\n\n#pragma omp parallel for\n    for (int64_t sample = 0; sample < (int64_t)batchSize; sample++)\n    {\n        for (size_t row = 0; row < mapOutSize; row++)\n        {\n            int colBase = mpRowCol(row, 0);\n            assert(0 <= colBase && colBase < GetNumRows());\n\n            int i0 = mpRowRun(row, 0);\n            int skip = runs(i0++, 0);\n            int size = runs(i0++, 0);\n            int imask = i0 + size;\n            for (int i = 0; i < size; i++)\n            {\n                if (runs(imask + i, 0) == 0)\n                    continue;\n                int dcol = runs(i0 + i, 0);\n                assert(0 <= colBase + dcol && colBase + dcol < GetNumRows());\n                output.Data()[(row * batchSize + sample) * unrollCols + skip + i] = (*this)(colBase + dcol, sample);\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::UnrollConvolutionOutput(size_t unrollCols, size_t mapInCount, size_t mapOutCount, const CPUMatrix<int>& mpRowCol,\n                                                  const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const\n{\n    if (mpRowCol.GetNumRows() % mapOutCount != 0)\n        InvalidArgument(\"The number of rows in mpRowCol must be multiple of mapOutCount.\");\n    size_t mapOutSize = mpRowCol.GetNumRows() / mapOutCount;\n    size_t batchSize = GetNumCols();\n\n    size_t kernelSize = runs(1, 0);\n    if (kernelSize % mapInCount != 0)\n        InvalidArgument(\"kernelSize must be multiple of mapInCount.\");\n    size_t kernelMapSize = kernelSize / mapInCount;\n\n#pragma omp parallel for\n    for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++)\n    {\n        for (size_t row = 0; row < mapOutSize; row++)\n        {\n            int colBase = mpRowCol(row, 0);\n\n            int i0 = mpRowRun(row, 0);\n            int skip = runs(i0++, 0);\n            int size = runs(i0++, 0);\n            int imask = i0 + size;\n            for (int i = 0; i < std::min(size, (int)kernelMapSize); i++)\n            {\n                if (runs(imask + i, 0) == 0)\n                    continue;\n                int dcol = runs(i0 + i, 0);\n                size_t isrc = row;\n                size_t idst = ((colBase + dcol) * batchSize + sample) * unrollCols + ((skip + i) % kernelMapSize) * mapOutCount;\n                for (size_t outMap = 0; outMap < mapOutCount; outMap++, isrc += mapOutSize)\n                {\n                    assert(isrc < GetNumElements());\n                    assert(idst + outMap < output.GetNumElements());\n\n                    output.Data()[idst + outMap] = (*this)(isrc, sample);\n                }\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::UnrollConvolutionInputForKernelBackprop(size_t mapOutSize, const CPUMatrix<int>& mpRowCol,\n                                                                  const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const\n{\n    size_t batchSize = GetNumCols();\n    size_t unrollCols = mapOutSize * batchSize;\n\n#pragma omp parallel for\n    for (int64_t sample = 0; sample < (int64_t)batchSize; sample++)\n    {\n        for (size_t row = 0; row < mapOutSize; row++)\n        {\n            int colBase = mpRowCol(row, 0);\n            assert(0 <= colBase && colBase < GetNumRows());\n\n            int i0 = mpRowRun(row, 0);\n            int skip = runs(i0++, 0);\n            int size = runs(i0++, 0);\n            int imask = i0 + size;\n            for (int i = 0; i < size; i++)\n            {\n                if (runs(imask + i, 0) == 0)\n                    continue;\n                int dcol = runs(i0 + i, 0);\n                assert(0 <= colBase + dcol && colBase + dcol < GetNumRows());\n                size_t idst = (skip + i) * unrollCols + row * batchSize + sample;\n                assert(idst < output.GetNumElements());\n                output.Data()[idst] = (*this)(colBase + dcol, sample);\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::MaxPoolingForward(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& output) const\n{\n#pragma omp parallel for\n    for (int64_t sample = 0; sample < (int64_t)output.GetNumCols(); sample++)\n    {\n        for (size_t row = 0; row < output.GetNumRows(); row++)\n        {\n            int colBase = mpRowCol(row, 0);\n            assert(0 <= colBase && colBase < GetNumRows());\n\n            assert(std::numeric_limits<ElemType>::has_infinity);\n            ElemType res = -std::numeric_limits<ElemType>::infinity();\n\n            int i0 = mpRowIndices(row, 0);\n            int size = indices(i0++, 0);\n            assert(size > 0);\n            for (int i = 0; i < size; i++)\n            {\n                int dcol = indices(i0 + i, 0);\n                assert(0 <= colBase + dcol && colBase + dcol < GetNumRows());\n                res = std::max(res, (*this)(colBase + dcol, sample));\n            }\n            output(row, sample) = res;\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::MaxPoolingBackward(const CPUMatrix<ElemType>& out, const CPUMatrix<ElemType>& in,\n                                             const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices,\n                                             CPUMatrix<ElemType>& grad) const\n{\n#pragma omp parallel for\n    for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++)\n    {\n        for (size_t row = 0; row < GetNumRows(); row++)\n        {\n            int colBase = mpRowCol(row, 0);\n            assert(0 <= colBase && colBase < grad.GetNumRows());\n\n            int i0 = mpRowIndices(row, 0);\n            int size = indices(i0++, 0);\n            assert(size > 0);\n            ElemType g = (*this)(row, sample);\n            ElemType m = out(row, sample);\n            for (int i = 0; i < size; i++)\n            {\n                int dcol = indices(i0 + i, 0);\n                assert(0 <= colBase + dcol && colBase + dcol < grad.GetNumRows());\n                if (in(colBase + dcol, sample) >= m)\n                {\n#pragma omp atomic \n                    grad(colBase + dcol, sample) += g;\n                    break; \n                }\n            }\n        }\n    }\n}\n\n// For each image, for each ROI, this function treats that ROI as an image\n// and does max pooling so that it has output size pooledHeight x pooledWidth.\n// It loops over each location in the output tensor, computes which ROI\n// and image should populate that location, computes the subset of the image\n// corresponding to the ROI and which pixels in that subset should go into the\n// output location, then takes the max value over that window.\n// src: Images              [W x H x C x N]\n// roiData: ROIs            [4 x numROIs x N], \n// dst: Pooled ROIs         [PW x PH x C x numROIs x N]\n// argmax: max positions    [PW x PH x C x numROIs x N]\n// where PW = Pooled Width, PH = Pooled Height, C = Channels, N = Batch Size\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::ROIPoolingForward(const size_t numRois, const size_t numImg, const size_t channels, const size_t width, const size_t height,\n                                            const size_t pooledWidth, const size_t pooledHeight, const CPUMatrix<ElemType>& roiData, CPUMatrix<ElemType>& output, \n                                            CPUMatrix<ElemType>& argmax) const\n{\n    size_t roiOutputSize = pooledHeight * pooledWidth * channels;\n\n#pragma omp parallel for\n    for (int imgIdx = 0; imgIdx < numImg; imgIdx++)\n    {\n        auto img = ColumnSlice(imgIdx, 1);\n        auto rois = roiData.ColumnSlice(imgIdx, 1);\n#pragma omp parallel for\n        for (int roiIdx = 0; roiIdx < numRois; roiIdx++)\n        {\n            // each ROI is 4 elements: (x, y, w, h).\n            int base = roiIdx * 4;\n\n            // scaled ROI numbers (relative to original image size)\n            // roi points are doubles that represent location relative to image\n            ElemType scX = rois(base, (ElemType)0);\n            ElemType scY = rois(base + (ElemType)1, (ElemType)0);\n            ElemType scW = rois(base + (ElemType)2, (ElemType)0);\n            ElemType scH = rois(base + (ElemType)3, (ElemType)0);\n\n            // compute actual spatial location of the ROI in our featuremap.\n            size_t x = (size_t)round(scX * width);\n            size_t y = (size_t)round(scY * height);\n            ElemType roiW = (ElemType)max(round(scW * width),  (ElemType)1);\n            ElemType roiH = (ElemType)max(round(scH * height), (ElemType)1);\n\n            const ElemType winW = roiW / (ElemType)pooledWidth;\n            const ElemType winH = roiH / (ElemType)pooledHeight;\n\n            // inspired by Ross Girshick fast-rcnn caffe cpu: https://github.com/rbgirshick/fast-rcnn\n            // loop over spatial locations in output.\n#pragma omp parallel for\n            for (int outw = 0; outw < pooledWidth; outw++)\n            {\n                for (int outh = 0; outh < pooledHeight; outh++)\n                {\n                    // compute the top left corner of the input\n                    // spatial window corresponding to this output unit\n                    size_t hstart = (size_t)floor(outh * winH);\n                    size_t wstart = (size_t)floor(outw * winW);\n\n                    // compute bottom right corner (not included)\n                    size_t hend = (size_t)ceil((outh + 1) * winH);\n                    size_t wend = (size_t)ceil((outw + 1) * winW);\n\n                    // offset window based on ROI top left corner.\n                    // these indices are into the input slice.\n                    hstart = min(max(hstart + y, (size_t)0), height);\n                    wstart = min(max(wstart + x, (size_t)0), width);\n                    hend   = min(max(hend + y,   (size_t)0), height);\n                    wend   = min(max(wend + x,   (size_t)0), width);\n\n                    bool isempty = (hend <= hstart) || (wend <= wstart);\n\n                    for (size_t c = 0; c < channels; c++) \n                    {\n                        // [W x H x C x R x N]; R = ROIs per image\n                        size_t outputIdx = roiIdx * roiOutputSize + outw + outh * pooledWidth + c * pooledHeight * pooledWidth;\n                        size_t maxidx = 0;\n                        ElemType maxval = isempty ? (ElemType)0 : -FLT_MAX;\n                        size_t baseIdx = c * height * width;\n\n                        for (size_t h = hstart; h < hend; h++)\n                        {\n                            for (size_t w = wstart; w < wend; w++)\n                            {\n                                // stored argmax indices are relative to the current channel.\n                                size_t dataIdx = w + h * width;\n                                if (img(baseIdx + dataIdx, 0) > maxval)\n                                {\n                                    maxval = img(baseIdx + dataIdx, 0);\n                                    maxidx = dataIdx;\n                                }\n                            }\n                        }\n                        output(outputIdx, imgIdx) = maxval;\n                        argmax(outputIdx, imgIdx) = maxidx;\n                    }\n                }\n            }\n        }\n    }\n}\n\n// This function loops over locations in the input to the ROIPoolingNode (image locations).\n// It loops over the ROIs corresponding to that image, seeing which ones could contain the current location\n// in their output. For each ROI, it checks the argmax data to see if that ROI indeed chose\n// this pixel location as the maximum. If so, it increments the gradient term for the input location.\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::ROIPoolingBackward(const size_t numRois, const size_t numImg, const size_t channels, const size_t width, const size_t height,\n                                             const size_t pooledWidth, const size_t pooledHeight, const CPUMatrix<ElemType>& roiData, CPUMatrix<ElemType>& grad, \n                                             CPUMatrix<ElemType>& argmax) const\n{\n    // loop over images in the batch.\n#pragma omp parallel for\n    for (int imgIdx = 0; imgIdx < numImg; imgIdx++) \n    {\n        // ROIs for this image. length 4*numRois;\n        auto rois = roiData.ColumnSlice(imgIdx, 1).Data();\n        // gradient values for all ROIs from this image. length numRois*pooledHeight*pooledWidth*channels;\n        auto pooledGrad = ColumnSlice(imgIdx, 1).Data();\n        auto argmaxCol = argmax.ColumnSlice(imgIdx, 1).Data();\n\n        // loop over spatial locations in the image.\n#pragma omp parallel for\n        for (int w = 0; w < width; w++) \n        {\n#pragma omp parallel for\n            for (int h = 0; h < width; h++) \n            {\n                // loop over the ROIs seeing which ones contain this location.\n                for (int roiN = 0; roiN < numRois; roiN++) \n                {\n                    // each ROI is 4 elements: (x, y, w, h).\n                    int roiOffset = roiN * 4;\n\n                    // ROI data is relative to original image size\n                    size_t roiStartW =     (size_t)round(rois[roiOffset + 0] * width);\n                    size_t roiStartH =     (size_t)round(rois[roiOffset + 1] * height);\n                    size_t roiWidth  = max((size_t)round(rois[roiOffset + 2] * width),  (size_t)1);\n                    size_t roiHeight = max((size_t)round(rois[roiOffset + 3] * height), (size_t)1);\n\n                    // skip this ROI if it doesn't contain the current input location.\n                    const bool inROI = (w >= roiStartW && w < roiStartW + roiWidth &&\n                                        h >= roiStartH && h < roiStartH + roiHeight);\n                    if (!inROI)\n                        continue;\n\n                    ElemType winH = (ElemType)roiHeight / (ElemType)pooledHeight;\n                    ElemType winW = (ElemType)roiWidth  / (ElemType)pooledWidth;\n\n                    // what pooled nodes in the output for this ROI could have pooled this input location?\n                    size_t phstart = (size_t)((h - roiStartH) / winH);\n                    size_t pwstart = (size_t)((w - roiStartW) / winW);\n                    size_t phend   = (size_t)(ceil((h - roiStartH + 1) / winH));\n                    size_t pwend   = (size_t)(ceil((w - roiStartW + 1) / winW));\n\n                    phstart = min(max(phstart, (size_t)0), pooledHeight);\n                    phend   = min(max(phend,   (size_t)0), pooledHeight);\n                    pwstart = min(max(pwstart, (size_t)0), pooledWidth);\n                    pwend   = min(max(pwend,   (size_t)0), pooledWidth);\n\n                    for (size_t c = 0; c < channels; c++) \n                    {\n                        ElemType gradient = 0;\n                        // [W x H x C x N]\n                        size_t index = w + h*width + c*height*width;\n                        // go right up to channel c of the current ROI.\n                        size_t offset = (roiN * channels + c) * pooledWidth * pooledHeight;\n                        const ElemType* offsetPoolGrad = pooledGrad + offset;\n                        const ElemType* offsetArgmax = argmaxCol + offset;\n                        for (size_t ph = phstart; ph < phend; ph++)\n                        {\n                            for (size_t pw = pwstart; pw < pwend; pw++)\n                            {\n                                if ((size_t)offsetArgmax[ph * pooledWidth + pw] == (w + h * width))\n                                    gradient += offsetPoolGrad[ph * pooledWidth + pw];\n                            }\n                        }\n                        grad(index, imgIdx) = gradient;\n                    }\n                }\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::MaxUnpooling(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices,\n                                       const CPUMatrix<int>& indices, const CPUMatrix<ElemType>& poolInput,\n                                       CPUMatrix<ElemType>& input) const\n{\n#pragma omp parallel for\n    for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++)\n    {\n        for (size_t row = 0; row < GetNumRows(); row++)\n        {\n            int colBase = mpRowCol(row, 0);\n            assert(0 <= colBase && colBase < input.GetNumRows());\n\n            int i0 = mpRowIndices(row, 0);\n            int size = indices(i0++, 0);\n            assert(size > 0);\n\n            ElemType curMax = poolInput(colBase + indices(i0, 0), sample);\n            ElemType prevMax = curMax;\n            int imax = 0;\n            for (int i = 1; i < size; i++)\n            {\n                int dcol = indices(i0 + i, 0);\n                assert(0 <= colBase + dcol && colBase + dcol < poolInput.GetNumRows());\n                curMax = std::max(curMax, poolInput(colBase + dcol, sample));\n                if (curMax > prevMax)\n                {\n                    prevMax = curMax;\n                    imax = i;\n                }\n            }\n\n            int dcol = indices(i0 + imax, 0);\n            assert(0 <= colBase + dcol && colBase + dcol < input.GetNumRows());\n            input(colBase + dcol, sample) = (*this)(row, sample);\n\n            //int i = (int)poolIn(row, sample);\n            //assert(0 <= i && i < size);\n            //int dcol = indices(i0 + i, 0);\n            //assert(0 <= colBase + dcol && colBase + dcol < input.GetNumRows());\n            //input(colBase + dcol, sample) = (*this)(row, sample);\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AveragePoolingForward(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& output, const bool poolIncludePad) const\n{\n#pragma omp parallel for\n    for (int64_t sample = 0; sample < (int64_t)output.GetNumCols(); sample++)\n    {\n        for (size_t row = 0; row < output.GetNumRows(); row++)\n        {\n            int colBase = mpRowCol(row, 0);\n            assert(0 <= colBase && colBase < GetNumRows());\n\n            ElemType sum = 0;\n\n            int i0 = mpRowIndices(row, 0);\n            int size = indices(i0++, 0);\n            assert(size > 0);\n            for (int i = 0; i < size; i++)\n            {\n                int dcol = indices(i0 + i, 0);\n                assert(0 <= colBase + dcol && colBase + dcol < GetNumRows());\n                sum += (*this)(colBase + dcol, sample);\n            }\n            // Note that we divide by size which is the number of actual elements (does not include padding).\n            // if poolIncludePad == true, use avg_pool_include_pad\n            if (poolIncludePad)\n                size = indices(0, 0);\n            output(row, sample) = sum / size;\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AveragePoolingBackward(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& grad, const bool poolIncludePad) const\n{\n#pragma omp parallel for\n    for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++)\n    {\n        for (size_t row = 0; row < GetNumRows(); row++)\n        {\n            int colBase = mpRowCol(row, 0);\n            assert(0 <= colBase && colBase < grad.GetNumRows());\n\n            int i0 = mpRowIndices(row, 0);\n            int size = indices(i0++, 0);\n            int tmp = size;\n            if (poolIncludePad)\n                size = indices(0, 0);\n            assert(size > 0);\n            ElemType g = (*this)(row, sample) / size;\n            size = tmp;\n            for (int i = 0; i < size; i++)\n            {\n                int dcol = indices(i0 + i, 0);\n                assert(0 <= colBase + dcol && colBase + dcol < grad.GetNumRows());\n#pragma omp atomic \n                grad(colBase + dcol, sample) += g;\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::BatchNormalizationForward(const CPUMatrix<ElemType>& scale, const CPUMatrix<ElemType>& bias, bool inferenceOnly, double expAvgFactor, double blendFactor,\n                                                    CPUMatrix<ElemType>& runMean, CPUMatrix<ElemType>& runVariance, CPUMatrix<ElemType>& out, double epsilon,\n                                                    CPUMatrix<ElemType>& saveMean, CPUMatrix<ElemType>& saveInvStdDev) const\n{\n    if (GetNumRows() % scale.GetNumRows() != 0)\n        LogicError(\"The number of rows of this matrx must be multiple of the number of rows of the scale matrix.\");\n\n    if (!inferenceOnly || expAvgFactor != 0 || blendFactor != 1)\n        RuntimeError(\"Batch normalization training on CPU is not yet implemented.\");\n\n    saveMean.Resize(0, 0); // only doing inference: these two are not produced\n    saveInvStdDev.Resize(0, 0);\n\n    bool spatial = GetNumRows() != scale.GetNumRows();\n    if (spatial)\n    {\n        size_t spatialSize = GetNumRows() / scale.GetNumRows();\n#pragma omp parallel for\n        for (long icol = 0; icol < out.GetNumCols(); icol++)\n        {\n            for (long irow = 0; irow < out.GetNumRows(); irow++)\n            {\n                size_t imap = irow / spatialSize;\n                ElemType stdDev = sqrt(runVariance(imap, 0) + epsilon);\n                out(irow, icol) = scale(imap, 0) * ((*this)(irow, icol) - runMean(imap, 0)) / stdDev + bias(imap, 0);\n            }\n        }\n    }\n    else\n    {\n#pragma omp parallel for\n        for (long icol = 0; icol < out.GetNumCols(); icol++)\n        {\n            for (long irow = 0; irow < out.GetNumRows(); irow++)\n            {\n                ElemType stdDev = sqrt(runVariance(irow, 0) + epsilon);\n                out(irow, icol) = scale(irow, 0) * ((*this)(irow, icol) - runMean(irow, 0)) / stdDev + bias(irow, 0);\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::BatchNormalizationBackward(const CPUMatrix<ElemType>& in, CPUMatrix<ElemType>& grad, const CPUMatrix<ElemType>& scale, double blendFactor,\n                                                     const CPUMatrix<ElemType>& saveMean, const CPUMatrix<ElemType>& saveInvStdDev,\n                                                     CPUMatrix<ElemType>& scaleGrad, CPUMatrix<ElemType>& biasGrad) const\n{\n    UNUSED(in); UNUSED(grad); UNUSED(scale); UNUSED(blendFactor), UNUSED(saveMean); UNUSED(saveInvStdDev); UNUSED(scaleGrad); UNUSED(biasGrad);\n    RuntimeError(\"Batch normalization training on CPU is not yet implemented.\");\n}\n\n\n#pragma region Static BLAS Functions\n\n/// <summary>Matrix-matrix multiply with col-major matrices (a and b may be transposed): c = alpha * op(a) * op(b) + beta*c</summary>\n/// <param name=\"alpha\">Scalar</param>\n/// <param name=\"a\">Input matrix</param>\n/// <param name=\"transposeA\">Whether matrix a is transposed</param>\n/// <param name=\"b\">Input matrix</param>\n/// <param name=\"transposeB\">Whether matrix b is transposed</param>\n/// <param name=\"beta\">Scalar</param>\n/// <param name=\"c\">Resulting matrix, user is responsible for allocating this</param>\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::MultiplyAndWeightedAdd(ElemType alpha, const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB,\n                                                 ElemType beta, CPUMatrix<ElemType>& c, shared_ptr<QuantizedMultiplier<ElemType>> pQuantizedMultiplier)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        return;\n\n    int m, n, k, l;\n    int lda, ldb, ldc;\n    CBLAS_TRANSPOSE mklTransA;\n    CBLAS_TRANSPOSE mklTransB;\n\n    if (transposeA)\n    {\n        m = (int) a.GetNumCols();\n        k = (int) a.GetNumRows();\n        lda = k;\n        mklTransA = CBLAS_TRANSPOSE::CblasTrans;\n    }\n    else\n    {\n        m = (int) a.GetNumRows();\n        k = (int) a.GetNumCols();\n        lda = m;\n        mklTransA = CBLAS_TRANSPOSE::CblasNoTrans;\n    }\n\n    if (transposeB)\n    {\n        l = (int) b.GetNumCols();\n        n = (int) b.GetNumRows();\n        ldb = n;\n        mklTransB = CBLAS_TRANSPOSE::CblasTrans;\n    }\n    else\n    {\n        l = (int) b.GetNumRows();\n        n = (int) b.GetNumCols();\n        ldb = l;\n        mklTransB = CBLAS_TRANSPOSE::CblasNoTrans;\n    }\n\n    assert(m > 0 && k > 0 && l > 0 && n > 0); // converting from size_t to int may cause overflow\n    if (k != l)\n        InvalidArgument(\"CPUMatrix<ElemType>::MultiplyAndWeightedAdd : The inner dimensions of a and b must match.\");\n\n    if (beta == 0)\n        c.RequireSize(m, n);\n    else\n        c.VerifySize(m, n); // Can't resize if beta != 0\n\n    ldc = (int) c.GetNumRows();\n\n    if (pQuantizedMultiplier == nullptr)\n    {\n        if (sizeof(ElemType) == sizeof(double))\n        {\n            cblas_dgemm((CBLAS_ORDER) (int)MatrixOrder::ColMajor, mklTransA, mklTransB, m, n, k, alpha, reinterpret_cast<double*>(a.Data()), lda, reinterpret_cast<double*>(b.Data()), ldb, beta, reinterpret_cast<double*>(c.Data()), ldc);\n        }\n        else\n        {\n#pragma warning(suppress : 4244)\n            cblas_sgemm((CBLAS_ORDER) (int)MatrixOrder::ColMajor, mklTransA, mklTransB, m, n, k, alpha, reinterpret_cast<float*>(a.Data()), lda, reinterpret_cast<float*>(b.Data()), ldb, beta, reinterpret_cast<float*>(c.Data()), ldc);\n        }\n    }\n    else\n    {\n        // TODO: support transpose product\n        if (mklTransA == CBLAS_TRANSPOSE::CblasTrans || mklTransB == CBLAS_TRANSPOSE::CblasTrans)\n            LogicError(\"Quantized multiplier currently doesn't support transpose.\");\n\n        pQuantizedMultiplier->Multiply(m, n, k, a.Data(), b.Data(), c.Data());\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::Multiply1x1AndWeightedAdd(ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b,\n                                                    ElemType beta, CPUMatrix<ElemType>& c)\n{\n    if (a.GetNumElements() != 1)\n        InvalidArgument(\"the argument a must be a scalar\"); // a is a scalar\n\n    ElemType f = alpha * a.Get00Element();\n    if (beta == 0) // don't even read the memory if beta is 0\n#pragma omp parallel for\n        foreach_coord (i, j, c)\n            c(i, j) = b(i, j) * f;\n    else\n#pragma omp parallel for\n        foreach_coord (i, j, c)\n            c(i, j) = b(i, j) * f + c(i, j) * beta;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::ColumnwiseScaleAndWeightedAdd(ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& v, ElemType beta, CPUMatrix<ElemType>& c)\n{\n    if (v.GetNumRows() != 1 && v.GetNumCols() != 1)\n        InvalidArgument(\"the argument v must be a vector\"); // v is a vector\n\n    if (beta == 0)\n        c.RequireSize(a.GetNumRows(), a.GetNumCols());\n    else\n        c.VerifySize(a.GetNumRows(), a.GetNumCols()); // Can't resize if beta != 0\n\n    const ElemType* vd = v.Data();\n\n    if (beta == 0) // don't even read the memory if beta is 0\n#pragma omp parallel for\n        foreach_coord(i, j, c)\n            c(i, j) = alpha * a(i, j) * vd[j];\n    else\n#pragma omp parallel for\n        foreach_coord(i, j, c)\n            c(i, j) = alpha * a(i, j) * vd[j] + c(i, j) * beta;\n}\n\n/* compute singular value decomposition as\n    A = U*SIGMA*VT\n    W is used as temp working memory\n    */\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SVD(const CPUMatrix<ElemType>& A, CPUMatrix<ElemType>& SIGMA, CPUMatrix<ElemType>& U, CPUMatrix<ElemType>& VT, CPUMatrix<ElemType>& W)\n{\n    if (A.IsEmpty())\n        LogicError(\"SVD:  input matrix is empty.\");\n\n    int info;\n    int m, n, lda, ldu, ldvt;\n    m = (int) A.GetNumRows();\n    n = (int) A.GetNumCols();\n    W.GetNumRows(); // W is used as temp working memory\n    lda = m;\n    ldu = m;\n    ldvt = n;\n    U.RequireSize(m, m);\n    SIGMA.RequireSize(std::min(m, n), 1);\n    VT.RequireSize(n, n);\n\n    if (sizeof(ElemType) == sizeof(double))\n    {\n#ifdef USE_MKL\n        double wkopt;\n        int lwork = -1;\n        dgesvd(\"All\", \"All\", &m, &n, reinterpret_cast<double*>(A.Data()), &lda, reinterpret_cast<double*>(SIGMA.Data()), reinterpret_cast<double*>(U.Data()), &ldu, reinterpret_cast<double*>(VT.Data()), &ldvt, &wkopt, &lwork, &info);\n        lwork = (int) wkopt;\n        W.RequireSize(lwork, 1);\n        dgesvd(\"All\", \"All\", &m, &n, reinterpret_cast<double*>(A.Data()), &lda, reinterpret_cast<double*>(SIGMA.Data()), reinterpret_cast<double*>(U.Data()), &ldu, reinterpret_cast<double*>(VT.Data()), &ldvt, reinterpret_cast<double*>(W.Data()), &lwork, &info);\n#else\n        std::vector<double> superb(std::max(std::min(m, n) - 1, 1));\n        info = LAPACKE_dgesvd((int) MatrixOrder::ColMajor, 'A', 'A', (int) m, (int) n, reinterpret_cast<double*>(A.Data()), (int) lda, reinterpret_cast<double*>(SIGMA.Data()),\n            reinterpret_cast<double*>(U.Data()), (int) ldu, reinterpret_cast<double*>(VT.Data()), (int) ldvt, &superb[0]);\n#endif\n    }\n    else\n    {\n#ifdef USE_MKL\n        float wkopt;\n        int lwork = -1;\n        sgesvd(\"All\", \"All\", &m, &n, reinterpret_cast<float*>(A.Data()), &lda, reinterpret_cast<float*>(SIGMA.Data()), reinterpret_cast<float*>(U.Data()), &ldu, reinterpret_cast<float*>(VT.Data()), &ldvt, &wkopt, &lwork, &info);\n        lwork = (int) wkopt;\n        W.RequireSize(lwork, 1);\n        sgesvd(\"All\", \"All\", &m, &n, reinterpret_cast<float*>(A.Data()), &lda, reinterpret_cast<float*>(SIGMA.Data()), reinterpret_cast<float*>(U.Data()), &ldu, reinterpret_cast<float*>(VT.Data()), &ldvt, reinterpret_cast<float*>(W.Data()), &lwork, &info);\n#else\n        std::vector<float> superb(std::max(std::min(m, n) - 1, 1));\n        info = LAPACKE_sgesvd((int) MatrixOrder::ColMajor, 'A', 'A', (int) m, (int) n, reinterpret_cast<float*>(A.Data()), (int) lda, reinterpret_cast<float*>(SIGMA.Data()),\n            reinterpret_cast<float*>(U.Data()), (int) ldu, reinterpret_cast<float*>(VT.Data()), (int) ldvt, &superb[0]);\n#endif\n    }\n\n    if (info > 0)\n    {\n        RuntimeError(\"The algorithm computing SVD failed to converge.\\n\");\n    }\n}\n\n/// <summary>Matrix-matrix multiply with col-major matrices (a and b may be transposed): c =  op(a) * op(b) + c</summary>\n/// <param name=\"a\">Input matrix</param>\n/// <param name=\"transposeA\">Whether matrix a is transposed</param>\n/// <param name=\"b\">Input matrix</param>\n/// <param name=\"transposeB\">Whether matrix b is transposed</param>\n/// <param name=\"c\">Resulting matrix, user is responsible for allocating this</param>\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::MultiplyAndAdd(const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB,\n                                         CPUMatrix<ElemType>& c)\n{\n    return CPUMatrix<ElemType>::MultiplyAndWeightedAdd(1.0, a, transposeA, b, transposeB, 1.0, c);\n}\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AssignSoftmaxSum(const CPUMatrix<ElemType>& softmax, CPUMatrix<ElemType>& c)\n{\n    ElemType log_likelihood = 0.0;\n    size_t batch_size = GetNumCols();\n#pragma omp parallel for reduction(+ : log_likelihood)\n    for (int instance_id = 0; instance_id < batch_size; instance_id++)\n    {\n        int sample = (int) (*this)(0, instance_id);\n        log_likelihood += softmax(instance_id, sample);\n    }\n    c(0, 0) = -log_likelihood;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AssignNCEUnnormalizedEval(const CPUMatrix<ElemType>& a,\n                                                    const CPUMatrix<ElemType>& b, const CPUMatrix<ElemType>& bias, CPUMatrix<ElemType>& c)\n//this: samples+probs\n// a:   hidden\n// b:   embedding\n// tmp:  softmax\n//  c: loglikelihood\n{\n    ElemType log_likelihood = 0.0;\n    size_t batch_size = GetNumCols();\n#pragma omp parallel for reduction(+ : log_likelihood)\n    for (int instance_id = 0; instance_id < batch_size; instance_id++)\n    {\n        int sample = -(int) (*this)(0, instance_id);\n        ElemType score = bias(sample, 0);\n        for (int dim = 0; dim < b.GetNumRows(); dim++)\n            score += b(dim, sample) * a(dim, instance_id);\n        log_likelihood += score;\n    }\n    c(0, 0) = -log_likelihood;\n}\n\n//samples+prob                         gradient           hidden               embedding          embedding/hidden\n//a.m_CPUMatrix->AssignNCEDerivative(*tmp.m_CPUMatrix, *a.m_CPUMatrix, *b.m_CPUMatrix, inputIndex, *c.m_CPUMatrix);\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignNCEDerivative(const CPUMatrix<ElemType>& tmp, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t inputIndex, CPUMatrix<ElemType>& c)\n{\n    size_t sample_size = GetNumRows() / 2;\n    size_t batch_size = GetNumCols();\n    if (inputIndex == 1)\n    {\n#pragma omp parallel for\n        for (int instance_id = 0; instance_id < batch_size; instance_id++)\n            for (int sample_id = 0; sample_id < sample_size; sample_id++)\n            {\n                int sample = (int) (*this)(2 * sample_id, instance_id);\n                for (int dim = 0; dim < b.GetNumRows(); dim++)\n                    c(dim, instance_id) -= b(dim, sample) * tmp(sample_id, instance_id);\n            }\n    }\n    else if (inputIndex == 2)\n    {\n        int i_blocks = omp_get_num_threads() * 16;\n// Assume only one block in k direction.\n// We don't need to explicitly block in the j direction.\n#pragma omp parallel for\n        for (int ib = 0; ib < i_blocks; ib++)\n            for (int instance_id = 0; instance_id < batch_size; instance_id++)\n                for (int sample_id = 0; sample_id < sample_size; sample_id++)\n                {\n                    int sample = (int) (*this)(2 * sample_id, instance_id);\n                    if (sample % i_blocks == ib)\n                        for (int dim = 0; dim < b.GetNumRows(); dim++)\n                            c(dim, sample) -= a(dim, instance_id) * tmp(sample_id, instance_id);\n                }\n    }\n    else if (inputIndex == 3)\n    {\n        // Assume only one block in k direction.\n        // We don't need to explicitly block in the j direction.\n        for (int instance_id = 0; instance_id < batch_size; instance_id++)\n            for (int sample_id = 0; sample_id < sample_size; sample_id++)\n            {\n                int sample = (int) (*this)(2 * sample_id, instance_id);\n                c(0, sample) -= tmp(sample_id, instance_id);\n            }\n    }\n    else \n        InvalidArgument(\"The argument inputIndex must be 1 or 2 or 3.\");\n    return *this;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AssignNoiseContrastiveEstimation(const CPUMatrix<ElemType>& a,\n                                                           const CPUMatrix<ElemType>& b, const CPUMatrix<ElemType>& bias, CPUMatrix<ElemType>& tmp, CPUMatrix<ElemType>& c)\n//this: samples+probs\n// a:   hidden\n// b:   embedding\n// tmp:  softmax\n// c: loglikelihood\n{\n    double log_likelihood = 0.0;\n    size_t sample_size = GetNumRows() / 2;\n    size_t batch_size = GetNumCols();\n    size_t num_noise_samples = sample_size - 1;\n    double log_num_noise_samples = std::log(num_noise_samples);\n#pragma omp parallel for reduction(+ : log_likelihood)\n    for (int instance_id = 0; instance_id < batch_size; instance_id++)\n        for (int sample_id = 0; sample_id < sample_size; sample_id++)\n        {\n            int sample = (int) (*this)(2 * sample_id, instance_id);\n            double score = bias(0, sample);\n            for (int dim = 0; dim < b.GetNumRows(); dim++)\n                score += a(dim, instance_id) * b(dim, sample);\n            double sample_prob = -(*this)(2 * sample_id + 1, instance_id);\n            if (sample_id == 0)\n                sample_prob = -sample_prob;\n            double score_noise = log_num_noise_samples + sample_prob;\n            double z = LogAdd(score, score_noise);\n            double logprob = score - z;\n            double logprob_noise = score_noise - z;\n            tmp(sample_id, instance_id) = (ElemType) -std::exp(logprob);\n            if (sample_id == 0)\n                tmp(sample_id, instance_id) += 1;\n            log_likelihood += sample_id == 0 ? logprob : logprob_noise;\n        }\n    c(0, 0) = (ElemType) -log_likelihood;\n}\n\n/// <summary>Matrix-matrix multiply with col-major matrices (a and b may be transposed): c =  op(a) * op(b)</summary>\n/// <param name=\"a\">Input matrix</param>\n/// <param name=\"transposeA\">Whether matrix a is transposed</param>\n/// <param name=\"b\">Input matrix</param>\n/// <param name=\"transposeB\">Whether matrix b is transposed</param>\n/// <param name=\"c\">Resulting matrix, user is responsible for allocating this</param>\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::Multiply(const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB,\n                                   CPUMatrix<ElemType>& c)\n{\n    return CPUMatrix<ElemType>::MultiplyAndWeightedAdd(1.0, a, transposeA, b, transposeB, 0.0, c);\n}\n\n/// <summary>Matrix-matrix multiply with col-major matrices (a and b are not transposed): c =  a * b</summary>\n/// <param name=\"a\">Input matrix</param>\n/// <param name=\"b\">Input matrix</param>\n/// <param name=\"c\">Resulting matrix, user is responsible for allocating this</param>\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::Multiply(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c)\n{\n    return CPUMatrix<ElemType>::MultiplyAndWeightedAdd(1.0, a, false, b, false, 0.0, c);\n}\n\n/// <summary>Matrix-scalar multiply with col-major matrices: c = alpha * a + c</summary>\n/// if a is a column vector, add to all columns of c\n/// if a is a row vector, add to all rows of c\n/// if a is a scalar, add to all rows of c\n/// <param name=\"alpha\">Scalar</param>\n/// <param name=\"a\">Input matrix</param>\n/// <param name=\"c\">Resulting matrix, user is responsible for allocating this</param>\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::ScaleAndAdd(ElemType alpha, const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c)\n{\n    if (a.IsEmpty() || c.IsEmpty())\n        LogicError(\"ScaleAndAdd:  one of the input matrices is empty.\");\n\n    if (a.GetNumRows() != 1 && a.GetNumCols() != 1) // a is not a col or row vector\n    {\n        const int m = (int) a.GetNumRows();\n        const int n = (int) a.GetNumCols();\n        const int len = m * n;\n        const int incx = 1;\n        const int incy = 1;\n\n        assert(m > 0 && n > 0 && len > 0); // converting from size_t to int may cause overflow\n        if ((int) c.GetNumRows() != m || (int) c.GetNumCols() != n)\n            InvalidArgument(\"Dimension of matrix c does not match dimension of matrix a.\");\n\n        if (sizeof(ElemType) == sizeof(double))\n        {\n            cblas_daxpy(len, alpha, reinterpret_cast<double*>(a.Data()), incx, reinterpret_cast<double*>(c.Data()), incy);\n        }\n        else\n        {\n#pragma warning(suppress : 4244)\n            cblas_saxpy(len, alpha, reinterpret_cast<float*>(a.Data()), incx, reinterpret_cast<float*>(c.Data()), incy);\n        }\n    }\n    else if (a.GetNumElements() == 1) // scalar, add to all elements\n    {\n        ElemType v = alpha * a(0, 0);\n        long m = (long) c.GetNumRows(), n = (long) c.GetNumCols();\n#pragma omp parallel for\n        for (long j = 0; j < n; j++)\n        {\n            // four-way unrolling\n            for (long i = 0; i < (m & ~3); i += 4)\n            {\n                c(i, j) += v;\n                c(i + 1, j) += v;\n                c(i + 2, j) += v;\n                c(i + 3, j) += v;\n            }\n            // handle remaining stuffs\n            for (long i = m & ~3; i < m; i++)\n            {\n                c(i, j) += v;\n            }\n        }\n    }\n    else if (a.GetNumCols() == 1) // col vector, add it to all columns\n    {\n        int m = (int) c.GetNumRows();\n        if (m != (int) a.GetNumRows())\n            InvalidArgument(\"To add column vector, rows should match.\");\n\n        ElemType* aBufPtr = a.Data();\n        ElemType* cBufPtr = c.Data();\n        if (sizeof(ElemType) == sizeof(double))\n        {\n#pragma omp parallel for\n            foreach_column (j, c)\n            {\n                cblas_daxpy(m, alpha, reinterpret_cast<double*>(aBufPtr), 1, reinterpret_cast<double*>(cBufPtr + c.LocateColumn(j)), 1);\n            }\n        }\n        else\n        {\n#pragma omp parallel for\n            foreach_column (j, c)\n            {\n#pragma warning(suppress : 4244)\n                cblas_saxpy(m, alpha, reinterpret_cast<float*>(aBufPtr), 1, reinterpret_cast<float*>(cBufPtr + c.LocateColumn(j)), 1);\n            }\n        }\n    }\n    else // row vector, add it to all rows\n    {\n        int m = (int) c.GetNumRows();\n        int n = (int) c.GetNumCols();\n        if (n != (int) a.GetNumCols())\n            InvalidArgument(\"To add row vector, cols should match.\");\n\n        ElemType* aBufPtr = a.Data();\n        ElemType* cBufPtr = c.Data();\n        if (sizeof(ElemType) == sizeof(double))\n        {\n#pragma omp parallel for\n            foreach_row (i, c)\n            {\n                cblas_daxpy(n, alpha, reinterpret_cast<double*>(aBufPtr), 1, reinterpret_cast<double*>(cBufPtr + i), m);\n            }\n        }\n        else\n        {\n#pragma omp parallel for\n            foreach_row (i, c)\n            {\n#pragma warning(suppress : 4244)\n                cblas_saxpy(n, alpha, reinterpret_cast<float*>(aBufPtr), 1, reinterpret_cast<float*>(cBufPtr + i), m);\n            }\n        }\n    }\n}\n/// <summary>c += alpha * (a-b)</summary>\n/// if a, b, c  must have same dim\n/// <param name=\"alpha\">Scalar</param>\n/// <param name=\"a\">Input matrix</param>\n/// <param name=\"b\">Input matrix</param>\n/// <param name=\"c\">Resulting matrix, user is responsible for allocating this</param>\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AddScaledDifference(const ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c)\n{\n    if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumRows() == c.GetNumRows() &&\n          a.GetNumCols() == b.GetNumCols() && a.GetNumCols() == c.GetNumCols()))\n    {\n        InvalidArgument(\"AddScaledDifference:  a, b, and c must have same dimension.\");\n    }\n\n    if (a.IsEmpty())\n        LogicError(\"AddScaledDifference:  Input matrix a is empty.\");\n\n    ElemType* aBufPtr = a.Data();\n    ElemType* bBufPtr = b.Data();\n    ElemType* cBufPtr = c.Data();\n    long m = (long) c.GetNumElements();\n#pragma omp parallel for\n    // four-way unrolling\n    for (long i = 0; i < (m & ~3); i += 4)\n    {\n        cBufPtr[i] += alpha * (aBufPtr[i] - bBufPtr[i]);\n        cBufPtr[i + 1] += alpha * (aBufPtr[i + 1] - bBufPtr[i + 1]);\n        cBufPtr[i + 2] += alpha * (aBufPtr[i + 2] - bBufPtr[i + 2]);\n        cBufPtr[i + 3] += alpha * (aBufPtr[i + 3] - bBufPtr[i + 3]);\n    }\n    // handle remaining stuffs\n    for (long i = m & ~3; i < m; i++)\n    {\n        cBufPtr[i] += alpha * (aBufPtr[i] - bBufPtr[i]);\n    }\n}\n\n/// <summary> c = alpha * (a-b)</summary>\n/// if a, b, c  must have same dim\n/// <param name=\"alpha\">Scalar</param>\n/// <param name=\"a\">Input matrix</param>\n/// <param name=\"b\">Input matrix</param>\n/// <param name=\"c\">Resulting matrix, user is responsible for allocating this</param>\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AssignScaledDifference(const ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c)\n{\n    if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()))\n    {\n        InvalidArgument(\"AssignScaledDifference: a, b must have same dimension.\");\n    }\n\n    if (a.IsEmpty())\n        LogicError(\"AssignScaledDifference:  Input matrix a is empty.\");\n\n    if (&c != &a && &c != &b)\n        c.RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    ElemType* aBufPtr = a.Data();\n    ElemType* bBufPtr = b.Data();\n    ElemType* cBufPtr = c.Data();\n    long m = (long) c.GetNumElements();\n#pragma omp parallel for\n    // four-way unrolling\n    for (long i = 0; i < (m & ~3); i += 4)\n    {\n        cBufPtr[i] = alpha * (aBufPtr[i] - bBufPtr[i]);\n        cBufPtr[i + 1] = alpha * (aBufPtr[i + 1] - bBufPtr[i + 1]);\n        cBufPtr[i + 2] = alpha * (aBufPtr[i + 2] - bBufPtr[i + 2]);\n        cBufPtr[i + 3] = alpha * (aBufPtr[i + 3] - bBufPtr[i + 3]);\n    }\n    // handle remaining stuffs\n    for (long i = m & ~3; i < m; i++)\n    {\n        cBufPtr[i] = alpha * (aBufPtr[i] - bBufPtr[i]);\n    }\n}\n\n// c[ci,cj] += a[ai,aj]\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AddElementToElement(ElemType beta, const CPUMatrix<ElemType>& a, const size_t ai, const size_t aj, CPUMatrix<ElemType>& c, const size_t ci, const size_t cj)\n{\n    if (ai >= a.GetNumRows() || aj >= a.GetNumCols() ||\n        ci >= c.GetNumRows() || cj >= c.GetNumCols())\n        InvalidArgument(\"AddElementToElement:  index out of range.\");\n\n    ElemType us = beta ? beta * c(ci, cj) : 0; // do not multiply if beta is 0, could be a NaN\n    us += a(ai, aj);\n    c(ci, cj) = us;\n}\n\n////c[ci,cj] += a[ai,aj]\n//template<class ElemType>\n//void CPUMatrix<ElemType>::AddLogElementToElement(const CPUMatrix<ElemType>& a, const size_t ai, const size_t aj, CPUMatrix<ElemType>& c, const size_t ci, const size_t cj)\n//{\n//    if (ai >= a.GetNumRows() || aj >=a.GetNumCols() ||\n//        ci >= c.GetNumRows() || cj >=c.GetNumCols())\n//        InvalidArgument(\"AddElementToElement:  index out of range.\");\n//\n//    ElemType v = a(ai,aj);\n//    c(ci, cj) += ((v < EPS_IN_LOG) ? LOG_OF_EPS_IN_LOG : log(v));\n//}\n\n#if 0 // now done as AddElementToElement (beta=0)\n// c[ci,cj] = a[ai,aj]\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AssignElementToElement(const CPUMatrix<ElemType>& a, const size_t ai, const size_t aj, CPUMatrix<ElemType>& c, const size_t ci, const size_t cj)\n{\n    if (ai >= a.GetNumRows() || aj >= a.GetNumCols() ||\n        ci >= c.GetNumRows() || cj >= c.GetNumCols())\n        InvalidArgument(\"AssignElementToElement:  index out of range.\");\n\n    c(ci, cj) = a(ai, aj);\n}\n#endif\n\n/// <summary>c += alpha * (a-b)</summary>\n/// if a, b, c  must have same dim\n/// <param name=\"alpha\">1X1 matrix</param>\n/// <param name=\"a\">Input matrix</param>\n/// <param name=\"b\">Input matrix</param>\n/// <param name=\"c\">Resulting matrix, user is responsible for allocating this</param>\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AddScaledDifference(const CPUMatrix<ElemType>& alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c)\n{\n    if (alpha.GetNumElements() != 1)\n        InvalidArgument(\"AddScaledDifference:  alpha must be a 1X1 matrix.\");\n\n    AddScaledDifference(alpha(0, 0), a, b, c);\n}\n\n/// <summary> c = alpha * (a-b)</summary>\n/// if a, b, c  must have same dim\n/// <param name=\"alpha\">1X1 matrix</param>\n/// <param name=\"a\">Input matrix</param>\n/// <param name=\"b\">Input matrix</param>\n/// <param name=\"c\">Resulting matrix, user is responsible for allocating this</param>\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::AssignScaledDifference(const CPUMatrix<ElemType>& alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c)\n{\n    if (alpha.GetNumElements() != 1)\n        InvalidArgument(\"AddScaledDifference:  alpha must be a 1X1 matrix.\");\n\n    AssignScaledDifference(alpha(0, 0), a, b, c);\n}\n/// <summary>Matrix-scalar multiply with col-major matrices: c = alpha * a</summary>\n/// <param name=\"alpha\">Scalar</param>\n/// <param name=\"a\">Input matrix</param>\n/// <param name=\"c\">Resulting matrix, user is responsible for allocating this</param>\ntemplate <class ElemType>\n/*static*/ void CPUMatrix<ElemType>::Scale(ElemType alpha, const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c)\n{\n    if (a.IsEmpty())\n        LogicError(\"Scale:  Input matrix a is empty.\");\n\n    const int m = (int) a.GetNumRows();\n    const int n = (int) a.GetNumCols();\n\n    assert(m > 0 && n > 0); // converting from size_t to int may cause overflow\n    c.RequireSize(m, n);\n\n    ElemType* aBufPtr = a.Data();\n    ElemType* cBufPtr = c.Data();\n\n    if (alpha == 0)\n    {\n        memset(cBufPtr, 0, sizeof(ElemType) * c.GetNumElements());\n        return;\n    }\n\n    long size = (long) c.GetNumElements();\n#pragma omp parallel for\n    // four-way unrolling\n    for (long i = 0; i < (size & ~3); i += 4)\n    {\n        cBufPtr[i]     = alpha * aBufPtr[i];\n        cBufPtr[i + 1] = alpha * aBufPtr[i + 1];\n        cBufPtr[i + 2] = alpha * aBufPtr[i + 2];\n        cBufPtr[i + 3] = alpha * aBufPtr[i + 3];\n    }\n    // remaining elements\n    for (long i = size & ~3; i < size; i++)\n    {\n        cBufPtr[i] = alpha * aBufPtr[i];\n    }\n}\n\n/// <summary>Matrix-scalar multiply with col-major matrices: a = alpha * a</summary>\n/// <param name=\"alpha\">Scalar</param>\n/// <param name=\"a\">Input matrix</param>\ntemplate <class ElemType>\n/*static*/ void CPUMatrix<ElemType>::Scale(ElemType alpha, CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"Scale:  Input matrix a is empty.\");\n\n    const int m = (int) a.GetNumRows();\n    const int n = (int) a.GetNumCols();\n    const int len = m * n;\n    const int incx = 1;\n\n    assert(m > 0 && n > 0 && len > 0); // converting from size_t to int may cause overflow\n\n    if (alpha == 0 && incx == 1)\n    {\n        memset(a.Data(), 0, sizeof(ElemType) * len);\n    }\n    else if (sizeof(ElemType) == sizeof(double))\n    {\n        cblas_dscal(len, alpha, reinterpret_cast<double*>(a.Data()), incx);\n    }\n    else\n    {\n#pragma warning(suppress : 4244)\n        cblas_sscal(len, alpha, reinterpret_cast<float*>(a.Data()), incx);\n    }\n}\n\n/// <summary>Matrix multiply with col-major matrices: a = alpha[1,1] * a</summary>\n/// <param name=\"alpha\">1x1 matrix</param>\n/// <param name=\"a\">Input matrix</param>\ntemplate <class ElemType>\n/*static*/ void CPUMatrix<ElemType>::Scale(CPUMatrix<ElemType> alpha, CPUMatrix<ElemType>& a)\n{\n    if (a.IsEmpty())\n        LogicError(\"Scale:  Input matrix a is empty.\");\n    if (alpha.GetNumElements() != 1)\n        LogicError(\"Matrix alpha must be 1x1\");\n    CPUMatrix<ElemType>::Scale(alpha(0, 0), a);\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::InnerProduct(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c, const bool isColWise)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"InnerProduct:  one of the input matrices is empty.\");\n\n    const int m = (int) a.GetNumRows();\n    const int n = (int) a.GetNumCols();\n    const int k = (int) b.GetNumRows();\n    const int l = (int) b.GetNumCols();\n\n    assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow\n    if (m != k || n != l)\n        InvalidArgument(\"InnerProduct: Matrices a and b should have same dimension.\");\n\n    if ((isColWise && m == 1) || !isColWise && n == 1) // in this case it's equivalent to element-wise product\n    {\n        c.AssignElementProductOf(a, b);\n    }\n    else if (isColWise) // col-wise\n    {\n        c.RequireSize(1, n);\n\n        ElemType* aBufPtr = a.Data();\n        ElemType* bBufPtr = b.Data();\n        if (sizeof(ElemType) == sizeof(double))\n        {\n#pragma omp parallel for\n            foreach_column (j, c)\n            {\n                c(0, j) = (ElemType) cblas_ddot(m, reinterpret_cast<double*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<double*>(bBufPtr + b.LocateColumn(j)), 1);\n            }\n        }\n        else\n        {\n#pragma omp parallel for\n            foreach_column (j, c)\n            {\n#pragma warning(suppress : 4244)\n                c(0, j) = (ElemType) cblas_sdot(m, reinterpret_cast<float*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<float*>(bBufPtr + b.LocateColumn(j)), 1);\n            }\n        }\n    }\n    else\n    {\n        c.RequireSize(m, 1);\n\n        ElemType* aBufPtr = a.Data();\n        ElemType* bBufPtr = b.Data();\n        if (sizeof(ElemType) == sizeof(double))\n        {\n#pragma omp parallel for\n            foreach_row (i, c)\n            {\n                c(i, 0) = cblas_ddot(n, reinterpret_cast<double*>(aBufPtr + i), m, reinterpret_cast<double*>(bBufPtr + i), m);\n            }\n        }\n        else\n        {\n#pragma omp parallel for\n            foreach_row (i, c)\n            {\n#pragma warning(suppress : 4244)\n                c(i, 0) = cblas_sdot(n, reinterpret_cast<float*>(aBufPtr + i), m, reinterpret_cast<float*>(bBufPtr + i), m);\n            }\n        }\n    }\n}\n\n// treat matrices as vectors. do vec(a)^T vec(b)\ntemplate <class ElemType>\nElemType CPUMatrix<ElemType>::InnerProductOfMatrices(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"InnerProductOfMatrices:  one of the input matrices is empty.\");\n\n    const int m = (int) a.GetNumRows();\n    const int n = (int) a.GetNumCols();\n    const int k = (int) b.GetNumRows();\n    const int l = (int) b.GetNumCols();\n\n    assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow\n    if (m != k || n != l)\n        InvalidArgument(\"InnerProductOfMatrices: Matrices a and b should have same dimension.\");\n\n    if (sizeof(ElemType) == sizeof(double))\n    {\n        return (ElemType) cblas_ddot((int) a.GetNumElements(), reinterpret_cast<double*>(a.Data()), 1, reinterpret_cast<double*>(b.Data()), 1);\n    }\n    else\n    {\n#pragma warning(suppress : 4244)\n        return (ElemType) cblas_sdot((int) a.GetNumElements(), reinterpret_cast<float*>(a.Data()), 1, reinterpret_cast<float*>(b.Data()), 1);\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::ElementWisePower(ElemType alpha, const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c)\n{\n    if (a.IsEmpty())\n        LogicError(\"Scale:  The input matrix a is empty.\");\n\n    c.RequireSize(a.GetNumRows(), a.GetNumCols());\n\n    if (alpha == 2)\n    {\n#pragma omp parallel for\n        foreach_coord (i, j, c)\n        {\n            c(i, j) = a(i, j) * a(i, j);\n        }\n    }\n    else if (alpha == 3)\n    {\n#pragma omp parallel for\n        foreach_coord (i, j, c)\n        {\n            c(i, j) = a(i, j) * a(i, j) * a(i, j);\n        }\n    }\n    else\n    {\n#pragma omp parallel for\n        foreach_coord (i, j, c)\n        {\n            c(i, j) = pow(a(i, j), alpha);\n        }\n    }\n}\n\ntemplate <class ElemType>\nbool CPUMatrix<ElemType>::AreEqual(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const ElemType threshold /*= 1e-8*/)\n{\n    if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols())\n        return false;\n\n    bool result = true;\n#pragma omp parallel for\n    foreach_coord (i, j, a)\n    {\n        if (abs(a(i, j) - b(i, j)) > threshold)\n        {\n            result = false;\n            break;\n        }\n    }\n\n    return result;\n}\n\n// see Matrix<ElemType>::TensorShuffleScaleAndAdd() for comments\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::TensorShuffleScaleAndAdd(ElemType keepWeight, const CPUMatrix<ElemType>& a, size_t D, size_t S, size_t M, size_t K, size_t T, ElemType scaleFactor, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c)\n{\n    size_t N = D * S * M * K * T;\n    const auto pa = a.Data();\n    const auto pb = b.Data();\n    auto pc = c.Data();\n    // Note: This code is written to match a GPU implementation. It is not super-efficient on the CPU.\n    for (size_t na = 0; na < N; na++) // loop over all elements\n    {\n        // recover the 5 indices from the loop counter\n        size_t d = na % D;\n        size_t s = (na / D) % S;\n        size_t m = (na / D / S) % M;\n        size_t k = (na / D / S / M) % K;\n        size_t t = (na / D / S / M / K) % T;\n        // compute index for the a and b/c tensors\n        assert(na == (((t * K + k) * M + m) * S + s) * D + d); // input tensor of dimension (D x S x M x K x T)\n        size_t nb = (((t * S + s) * M + m) * K + k) * D + d;   // output tensor of dimension (D x K x M x S x T): k/K and s/S swapped\n        assert(nb < N);\n        // perform the computation\n        ElemType cval = keepWeight ? keepWeight * pb[nb] : 0; // if weight is 0 then don't bother to read memory (efficiency) or to multiply (NaN-safe)\n        cval += scaleFactor * pa[na];\n        pc[nb] = cval;\n    }\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::Ones(const size_t rows, const size_t cols)\n{\n    CPUMatrix<ElemType> c(rows, cols); // will initialize to 0\n    c.SetValue(1);\n    return c;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::Zeros(const size_t rows, const size_t cols)\n{\n    CPUMatrix<ElemType> c(rows, cols); // will initialize to 0\n    c.SetValue(0);\n    return c;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::Eye(const size_t rows)\n{\n    CPUMatrix<ElemType> c(rows, rows); // will initialize to 0\n    c.SetDiagonalValue(1);\n    return c;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::RandomUniform(const size_t rows, const size_t cols, const ElemType low, const ElemType high, unsigned long seed)\n{\n    CPUMatrix<ElemType> c(rows, cols); // will initialize to 0\n    c.SetUniformRandomValue(low, high, seed);\n    return c;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType> CPUMatrix<ElemType>::RandomGaussian(const size_t rows, const size_t cols, const ElemType mean, const ElemType sigma, unsigned long seed)\n{\n    CPUMatrix<ElemType> c(rows, cols); // will initialize to 0\n    c.SetGaussianRandomValue(mean, sigma, seed);\n    return c;\n}\n\ntemplate <class ElemType>\nbool CPUMatrix<ElemType>::HasElement(const CPUMatrix<ElemType>& mat, const ElemType v)\n{\n    bool bHas = false;\n\n    bool isvFinite = std::isfinite(v);\n#pragma omp parallel for\n    for (long j = 0; j < mat.GetNumElements(); j++)\n    {\n#pragma omp flush(bHas)\n        if (!bHas)\n        {\n            ElemType cur = mat.Data()[j];\n            if (isvFinite && std::isfinite(cur))\n            {\n                if (cur == v)\n                    bHas = true;\n            }\n            else if (std::isnan(v) && std::isnan(cur))\n                bHas = true;\n            else if (std::isinf(v) && std::isinf(cur) && std::signbit(v) == std::signbit(cur))\n                bHas = true;\n        }\n    }\n\n    return bHas;\n}\n\n//        CPUMatrix<ElemType>& AssignElementProductOfWithShiftNeg(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift, size_t negnumber);\n//[this]=a .* b\n// here, a and b must be two row vectors of the same size, i.e. [1,m]\n// the inputs are two rwo vectors\n// the output is a matrix of size(neg+1, col)\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementProductOfWithShiftNeg(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift, size_t negnumber)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"AssignElementProductOfWithShiftNeg: Matrix is empty.\");\n\n    if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols()))\n        InvalidArgument(\"AssignElementProductOfWithShiftNeg: The input matrix dimensions do not match.\");\n\n    if (a.GetNumRows() != 1)\n        InvalidArgument(\"AssignElementProductOfWithShiftNeg: The input matrix must be a row vector.\");\n\n    auto& us = *this;\n    if (this != &a)\n    {\n        RequireSize(negnumber + 1, a.GetNumCols());\n        //            RequireSize(a.GetNumRows(), a.GetNumCols());\n    }\n\n    long m = (long) GetNumRows(), n = (long) GetNumCols(); // a and b are of size (1,n)\n    // #pragma omp parallel for\n\n    for (long j = 0; j < n; j++)\n    {\n        us(0, j) = a(0, j) * b(0, j);\n    }\n    for (long j = 0; j < n; j++)\n    {\n        for (long i = 1; i < m; i++)\n        {\n            us(i, j) = a(0, j) * b(0, (j + shift + i - 1) % n);\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::InnerProductWithShiftNeg(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c, const bool isColWise, size_t shift, size_t negnumber)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"InnerProduct:  one of the input matrices is empty.\");\n\n    const int m = (int) a.GetNumRows();\n    const int n = (int) a.GetNumCols();\n    const int k = (int) b.GetNumRows();\n    const int l = (int) b.GetNumCols();\n\n    assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow\n    if (m != k || n != l)\n        InvalidArgument(\"InnerProduct: Matrices a and b should have same dimension.\");\n\n    if ((isColWise && m == 1) || !isColWise && n == 1) // in this case it's equivalent to element-wise product\n    {\n        InvalidArgument(\"InnerProduct: Both matrices should be normal ones, not vectors\");\n        //            c.AssignElementProductOf(a, b);\n    }\n    else if (isColWise) // col-wise\n    {\n        c.RequireSize(negnumber + 1, n); // this line ischanged\n\n        ElemType* aBufPtr = a.Data();\n        ElemType* bBufPtr = b.Data();\n        if (sizeof(ElemType) == sizeof(double))\n        {\n            for (long j = 0; j < n; j++)\n            {\n                c(0, j) = (ElemType) cblas_ddot(m, reinterpret_cast<double*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<double*>(bBufPtr + b.LocateColumn(j)), 1);\n            }\n            for (long j = 0; j < n; j++)\n            {\n                for (long i = 1; i < negnumber + 1; i++)\n                {\n                    c(i, j) = (ElemType) cblas_ddot(m, reinterpret_cast<double*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<double*>(bBufPtr + b.LocateColumn((j + shift + i - 1) % n)), 1);\n                }\n            }\n        }\n        else\n        {\n            for (long j = 0; j < n; j++)\n            {\n                c(0, j) = (ElemType) cblas_sdot(m, reinterpret_cast<float*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<float*>(bBufPtr + b.LocateColumn(j)), 1);\n            }\n            for (long j = 0; j < n; j++)\n            {\n                for (long i = 1; i < negnumber + 1; i++)\n                {\n                    c(i, j) = (ElemType) cblas_sdot(m, reinterpret_cast<float*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<float*>(bBufPtr + b.LocateColumn((j + shift + i - 1) % n)), 1);\n                }\n            }\n        }\n    }\n    else\n    {\n        InvalidArgument(\"InnerProduct: Rowwise is not supported yet\");\n\n        c.RequireSize(m, 1);\n\n        ElemType* aBufPtr = a.Data();\n        ElemType* bBufPtr = b.Data();\n        if (sizeof(ElemType) == sizeof(double))\n        {\n#pragma omp parallel for\n            foreach_row (i, c)\n            {\n                c(i, 0) = (ElemType) cblas_ddot(n, reinterpret_cast<double*>(aBufPtr + i), m, reinterpret_cast<double*>(bBufPtr + i), m);\n            }\n        }\n        else\n        {\n#pragma omp parallel for\n            foreach_row (i, c)\n            {\n#pragma warning(suppress : 4244)\n                c(i, 0) = cblas_sdot(n, reinterpret_cast<float*>(aBufPtr + i), m, reinterpret_cast<float*>(bBufPtr + i), m);\n            }\n        }\n    }\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::GetARowByIndex(const CPUMatrix<ElemType>& a, size_t index)\n{\n    if (a.IsEmpty())\n        LogicError(\"GetARowByIndex:  the input matrices is empty.\");\n\n    const int m = (int) a.GetNumRows();\n    const int n = (int) a.GetNumCols();\n\n    if (index < 0 || index >= m)\n        LogicError(\"GetARowByIndex:  the row index is out of range.\");\n\n    assert(m > 0 && n > 0); // converting from size_t to int may cause overflow\n\n    auto& us = *this;\n    RequireSize(1, n);\n    for (long j = 0; j < n; j++)\n    {\n        us(0, j) = a(index, j);\n    }\n\n    return *this;\n}\n\n// input: a, a row vector\n// input: b, a matrix. b.col == a.col\n// input firstmatrixfixed: If true, keep a's order. Otherwise, keep b's order\n// output: c, a matrix. c.size == b.size\n/*\n    Example, a = [a1 a2 a3]\n    b = [b11 b12 b13;\n    b21 b22 b23 ]\n\n    if true:\n    shift = 1\n\n    then c = [a1*b12 a2*b13 a3*b11\n    a1*b22 a2*b23 a3*b21]\n\n    if shift = 2\n    then c = [  a1*b13 a2*b11 a3*b12\n    a1*b23 a2*b21 a3*b22]\n    i.e. we do column-wise shift\n\n    if false:\n    shift = 1\n\n    then c = [a2*b11 a3*b12 a1*b13\n    a2*b21 a3*b22 a1*b23]\n\n    shift = 2\n\n    then c = [  a3*b11 a1*b12 a2*b13\n    a3*b21 a1*b22 a2*b23]\n\n\n    */\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::ConductRowElementMultiplyWithShift(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c, size_t shift, bool bFirstmatrixfixed)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"InnerProduct:  one of the input matrices is empty.\");\n\n    const int m = (int) a.GetNumRows();\n    const int n = (int) a.GetNumCols();\n    const int k = (int) b.GetNumRows();\n    const int l = (int) b.GetNumCols();\n\n    assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow\n    if (m != 1 || n != l)\n        InvalidArgument(\"InnerProduct: Matrices a and b should have same dimension.\");\n\n    c.RequireSize(k, l); // c must the the same size of b\n\n    if (bFirstmatrixfixed)\n    {\n        for (long j = 0; j < l; j++)\n        {\n            for (long i = 0; i < k; i++)\n            {\n                c(i, j) = a(0, j) * b(i, (j + shift) % l);\n            }\n        }\n    }\n    else\n    {\n        for (long j = 0; j < l; j++)\n        {\n            for (long i = 0; i < k; i++)\n            {\n                c(i, j) = a(0, (j + shift) % l) * b(i, j);\n            }\n        }\n    }\n}\n\n//        CPUMatrix<ElemType>& AssignElementProductOfWithShift(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift);\n//[this]=a .* b\n// here, a and b must be two row vectors of the same size, i.e. [1,m]. We will do element product with shift.\n// inputs are 2 row vectors\n// output is a row vector\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementProductOfWithShift(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift)\n{\n    if (a.IsEmpty() || b.IsEmpty())\n        LogicError(\"AssignElementProductOfWithShiftNeg: Matrix is empty.\");\n\n    if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols())\n        InvalidArgument(\"AssignElementProductOfWithShiftNeg: The input matrix dimensions do not match.\");\n\n    if (a.GetNumRows() != 1)\n        InvalidArgument(\"AssignElementProductOfWithShiftNeg: The input matrix must be a row vector.\");\n\n    auto& us = *this;\n    if (this != &a)\n    {\n        RequireSize(1, a.GetNumCols());\n        //            RequireSize(a.GetNumRows(), a.GetNumCols());\n    }\n\n    // long m = (long)GetNumRows(), n = (long)GetNumCols();  // a and b are of size (1,n)\n    long n = (long) GetNumCols(); // a and b are of size (1,n)\n#pragma omp parallel for\n    for (long j = 0; j < n; j++)\n    {\n        us(0, j) = a(0, j) * b(0, (j + shift) % n);\n    }\n    return *this;\n}\n\n#pragma endregion Static BLAS Functions\n\n// 'double' version of LogAdd\ninline double LogAddD(double x, double y)\n{\n    return LogAdd(x, y);\n}\n\ntemplate <class ElemType>\nElemType CPUMatrix<ElemType>::LogSumOfElements() const\n{\n    ElemType fAlpha = (ElemType) LZERO;\n    ElemType* bufPtr = Data();\n    for (int k = 0; k < GetNumElements(); k++)\n        fAlpha = (ElemType) LogAddD(fAlpha, bufPtr[k]);\n    return fAlpha;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::RCRFBackwardCompute(const CPUMatrix<ElemType>& alpha, CPUMatrix<ElemType>& beta,\n                                              const CPUMatrix<ElemType>& lbls,\n                                              const CPUMatrix<ElemType>& pair_scores)\n{\n    int iNumPos = (int) lbls.GetNumCols();\n    int iNumLab = (int) lbls.GetNumRows();\n\n    int lastLbl = -1;\n    for (int ik = 0; ik < lbls.GetNumRows(); ik++)\n        if (lbls(ik, iNumPos - 1) != 0)\n        {\n            lastLbl = ik;\n            break;\n        }\n\n    beta.RequireSize(iNumLab, iNumPos);\n\n    for (int t = iNumPos - 1; t >= 0; t--)\n    {\n#pragma omp parallel for\n        for (int k = 0; k < iNumLab; k++)\n        {\n            _rcrfBackwardCompute(t, k, alpha, beta, pair_scores);\n        }\n    }\n};\n\n// Calculate alpha in forward-backward calculation. equation (6), (7) in http://machinelearning.wustl.edu/mlpapers/paper_files/icml2006_GravesFGS06.pdf\n// GPU x dimension corresponds to utterances, y dimension corresponds to phone sequence in each utterance\n// prob (input): the posterior output from the network\n// alpha (output): alpha for forward-backward calculation. \n// phoneSeq (input): phone ID sequence for each utterance in this minibatch, each col is one utterance \n// phoneBound (input): phone boundary (frame index) of each phone for each utterance in this minibatch, each col is one utterance \n// uttToChanInd (input):  map from utterance ID to minibatch channel ID. We need this because each channel may contain more than one utterance.\n// uttFrameNum (input): the frame number of each utterance. The size of this vector =  the number of all utterances in this minibatch\n// uttBeginFrame(input): the positon of the first frame of each utterance in the minibatch channel. We need this because each channel may contain more than one utterance.\n// uttPhoneNum (input): the phone number of each utterance. The size of this vector =  the number of all utterances in this minibatch\n// numChannels (input): channel number in this minibatch\n// uttNum (input): number of utterances\n// t (input): time stamp to process\n// maxPhoneNum (input): the max number of phones between utterances\n// totalPhoneNum (input): the total number of phones of all utterances\n// blankTokenId (input): id of the CTC blank token\n// delayConstraint -- label output delay constraint introduced during training that allows to have shorter delay during inference.\n//      Alpha and Beta scores outside of the delay boundary are set to zero.\n//      Setting this parameter smaller will result in shorted delay between label output during decoding.\n//      delayConstraint=-1 means no constraint\ntemplate<class ElemType>\nvoid _assignAlphaScore(\n    const ElemType *prob,\n    ElemType *alphaScore,\n    ElemType *phoneSeq,\n    ElemType *phoneBound,\n    const std::vector<size_t>& uttToChanInd,\n    const std::vector<size_t>& uttFrameNum,\n    const std::vector<size_t>& uttBeginFrame,\n    const std::vector<size_t>& uttPhoneNum,\n    size_t numChannels,\n    const size_t uttNum,\n    const size_t  t,\n    const size_t maxPhoneNum, // Maximum length of utterance in this MB\n    const size_t totalPhoneNum, // Total number of phones\n    const size_t blankTokenId,\n    const int delayConstraint)\n{\n    for (size_t uttId = 0;uttId < uttNum;uttId++) {\n\n        // Number of phones and frames in this utterance\n        size_t frameNum = uttFrameNum[uttId];\n        if (t >= frameNum) continue;\n\n        size_t phoneNum = uttPhoneNum[uttId];\n\n#pragma omp parallel for\n        for (int phoneSeqId = 1;phoneSeqId < phoneNum - 1;phoneSeqId++) {\n            // Index of the label in the sequence\n\n            // Current and previous phone indices in phoneSeq matrix\n            size_t labelid = uttId*maxPhoneNum + phoneSeqId;\n\n            // Actual current phone label\n            size_t phoneId = (size_t)(phoneSeq[labelid]);\n\n            // Index of the current frame in minibatch\n            size_t timeId = (t + uttBeginFrame[uttId])*numChannels + uttToChanInd[uttId];\n\n            // Index of probability of observing phoneId at frame timeId\n            size_t probId = timeId*totalPhoneNum + phoneId;\n\n            size_t alphaId = maxPhoneNum* timeId + phoneSeqId; // alpha_t(s)\n\n            if (t == 0)\n            {\n                // Initialize recursion\n                if (phoneSeqId == 1 || phoneSeqId == 2)\n                {\n                    alphaScore[alphaId] = prob[probId];\n                }\n            }\n            else\n            {\n                if (phoneSeqId >= 1)\n                {\n                    size_t timeId_1 = timeId - numChannels; // Index corresponding to (t-1)\n                    size_t alphaId_0 = maxPhoneNum* timeId_1 + phoneSeqId; // alpha_{t-1}(s)\n                    size_t alphaId_1 = alphaId_0 - 1; // alpha_{t-1}(s-1)\n                    size_t alphaId_2 = alphaId_0 - 2; // alpha_{t-1}(s-2)\n                    ElemType x = LZERO;\n\n                    ElemType ascore;\n                    if (phoneSeqId > 2)\n                    {\n                        size_t labelid_2 = labelid - 2;\n                        // if current label is not blank and not equal prev non-blank label\n                        if ((size_t)(phoneSeq[labelid]) != blankTokenId && phoneId != (size_t)(phoneSeq[labelid_2]))\n                        {\n                            x = LogAdd(x, alphaScore[alphaId_2]);\n                        }\n                    }\n\n                    if (phoneSeqId > 1)\n                    {\n                        x = LogAdd(x, alphaScore[alphaId_1]);\n                    }\n\n                    x = LogAdd(x, alphaScore[alphaId_0]);\n\n                    if (phoneId != SIZE_MAX)\n                        ascore = prob[probId]; // Probability of observing given label at given time\n                    else\n                        ascore = 0;\n                    alphaScore[alphaId] = (ElemType)x + ascore;\n                    if (delayConstraint != -1)\n                    {\n                        size_t labelid_r = labelid + 2;\n                        size_t phoneBoundId_r = (size_t)(phoneBound[labelid_r]);\n                        if (phoneId == blankTokenId)\n                        {\n                            // only constraint right side\n                            if (t > phoneBoundId_r + delayConstraint - 1)\n                                alphaScore[alphaId] = LZERO;\n                        }\n                        else if (phoneId != blankTokenId)\n                        {\n                            if (t > phoneBoundId_r + delayConstraint)\n                                alphaScore[alphaId] = LZERO;\n                        }\n                    }\n                }\n\n            }\n        }\n    }\n}\n\n// Calculate beta in forward-backward calculation, equation (10), (11) in http://machinelearning.wustl.edu/mlpapers/paper_files/icml2006_GravesFGS06.pdf \n// See _assignAlphaScore for the explanation of parameters\ntemplate<class ElemType>\nvoid _assignBetaScore(\n    const ElemType *prob,\n    ElemType *betaScore,\n    ElemType *phoneSeq,\n    ElemType *phoneBound,\n    const std::vector<size_t>& uttToChanInd,\n    const std::vector<size_t>& uttFrameNum,\n    const std::vector<size_t>& uttBeginFrame,\n    const std::vector<size_t>& uttPhoneNum,\n    const size_t numChannels,\n    const size_t uttNum,\n    const long  t,\n    const size_t maxPhoneNum,\n    const size_t totalPhoneNum,\n    const size_t blankTokenId,\n    const int delayConstraint)\n{\n    for (size_t uttId = 0;uttId < uttNum;uttId++) {\n\n        // Number of phones and frames in this utterance\n        size_t frameNum = uttFrameNum[uttId];\n        if (t >= frameNum) continue;\n\n        size_t phoneNum = uttPhoneNum[uttId];\n\n#pragma omp parallel for\n        for (int phoneSeqId = 1;phoneSeqId < phoneNum - 1;phoneSeqId++) {\n\n            size_t labelid = uttId*maxPhoneNum + phoneSeqId;\n            size_t labelid_2 = labelid + 2;\n            size_t phoneId = (LONG64)(phoneSeq[labelid]);\n            size_t timeId = (t + uttBeginFrame[uttId])*numChannels + uttToChanInd[uttId];\n            size_t probId = timeId*totalPhoneNum + phoneId;\n            size_t betaid = maxPhoneNum* timeId + phoneSeqId;\n            size_t timeId_1 = timeId + numChannels;\n            size_t betaid_0 = maxPhoneNum* timeId_1 + phoneSeqId;\n            size_t betaid_1 = betaid_0 + 1;\n            size_t betaid_2 = betaid_0 + 2;\n\n            if (t == frameNum - 1)\n            {\n                if (phoneSeqId == phoneNum - 3 || phoneSeqId == phoneNum - 2)\n                {\n                    betaScore[betaid] = prob[probId];\n                }\n            }\n            else\n            {\n                if (phoneSeqId >= 1)\n                {\n                    ElemType x = LZERO;\n                    ElemType ascore;\n                    if (phoneSeqId < phoneNum - 3)\n                    {\n                        if (phoneSeq[labelid] != blankTokenId && phoneId != phoneSeq[labelid_2])\n                        {\n                            x = LogAdd(x, betaScore[betaid_2]);\n                        }\n                    }\n\n                    if (phoneSeqId < phoneNum - 2)\n                    {\n                        x = LogAdd(x, betaScore[betaid_1]);\n                    }\n\n                    x = LogAdd(x, betaScore[betaid_0]);\n\n                    if (phoneId != SIZE_MAX)\n                        ascore = prob[probId];\n                    else\n                        ascore = 0;\n                    betaScore[betaid] = (ElemType)x + ascore;\n                    if (delayConstraint != -1)\n                    {\n                        size_t phoneBoundId_r = (size_t)(phoneBound[labelid_2]);\n                        if (phoneId == blankTokenId)\n                        {\n                            if (t > phoneBoundId_r + delayConstraint - 1)\n                                betaScore[betaid] = LZERO;\n                        }\n                        else if (phoneId != blankTokenId)\n                        {\n                            if (t > phoneBoundId_r + delayConstraint)\n                                betaScore[betaid] = LZERO;\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\n// Calculate CTC score. equation (8) in http://machinelearning.wustl.edu/mlpapers/paper_files/icml2006_GravesFGS06.pdf \ntemplate<class ElemType>\nvoid _assignTotalScore(ElemType *betaScore,\n    std::vector<ElemType>& totalScore,\n    const size_t uttNum,\n    const std::vector<size_t>& uttToChanInd,\n    const std::vector<size_t>& uttBeginFrame,\n    const size_t numChannels,\n    const size_t maxPhoneNum)\n{\n#pragma omp parallel for\n    for (int uttId = 0; uttId < uttNum; uttId++) {\n        if (uttId < uttNum)\n        {\n            LONG64 alphaId_0 = (uttBeginFrame[uttId] * numChannels + uttToChanInd[uttId]) * maxPhoneNum;\n\n            betaScore[alphaId_0] = LogAdd(betaScore[alphaId_0 + 1], betaScore[alphaId_0 + 2]);\n            totalScore[uttId] = betaScore[alphaId_0];\n        }\n    }\n}\n\n// Calculate derivative, equation (15) in http://machinelearning.wustl.edu/mlpapers/paper_files/icml2006_GravesFGS06.pdf\n// See _assignAlphaScore for the explanation of parameters\ntemplate<class ElemType>\nvoid _assignCTCScore(\n    ElemType *CTCscore,\n    ElemType *prob,\n    ElemType *alphaScore,\n    ElemType *betaScore,\n    ElemType *phoneSeq,\n    const size_t uttNum,\n    const std::vector<size_t>& uttToChanInd,\n    const std::vector<size_t>& uttBeginFrame,\n    const std::vector<size_t>& uttPhoneNum,\n    const std::vector<size_t>& uttFrameNum,\n    const size_t numChannels,\n    const size_t maxPhoneNum,\n    const size_t totalPhoneNum)\n{\n    for (size_t uttId = 0;uttId < uttNum;uttId++) {\n#pragma omp parallel for\n        for (int t = 0; t < uttFrameNum[uttId]; t++) {\n            size_t phoneNum = uttPhoneNum[uttId];\n            size_t alphaId_0 = (uttBeginFrame[uttId] * numChannels + uttToChanInd[uttId]) * maxPhoneNum;\n            size_t timeId = (t + uttBeginFrame[uttId])*numChannels + uttToChanInd[uttId];\n            ElemType P_lx = betaScore[alphaId_0];\n\n            for (int s = 1; s < phoneNum - 1; s++)\n            {\n                long phoneId = phoneSeq[uttId*maxPhoneNum + s];\n                size_t alphaId = maxPhoneNum* timeId + s;\n                size_t probId = timeId*totalPhoneNum + phoneId;\n\n                if (phoneId != SIZE_MAX)\n                {\n                    ElemType logoccu = alphaScore[alphaId] + betaScore[alphaId] - prob[probId] - (ElemType)P_lx;\n                    CTCscore[probId] = LogAdd(CTCscore[probId], logoccu);\n                }\n            }\n\n            for (int s = 0; s < totalPhoneNum; s++)\n            {\n                size_t probId = timeId*totalPhoneNum + s;\n                ElemType logoccu = CTCscore[probId];\n                if (logoccu < LZERO)\n                    CTCscore[probId] = 0.0f;\n                else\n                    CTCscore[probId] = exp(logoccu);\n            }\n        }\n    }\n}\n\ntemplate<class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignCTCScore(\n    const CPUMatrix<ElemType>& prob, CPUMatrix<ElemType>& alpha, CPUMatrix<ElemType>& beta,\n    const CPUMatrix<ElemType>& phoneSeq, const CPUMatrix<ElemType>& phoneBoundary, ElemType &totalScore, const std::vector<size_t>& uttToChanInd, const std::vector<size_t> & uttBeginFrame, const std::vector<size_t> & uttFrameNum,\n    const std::vector<size_t> & uttPhoneNum, const size_t numParallelSequences, const size_t maxFrameNum, const size_t blankTokenId, const int delayConstraint, const bool isColWise)\n{\n    // Column wise representation of sequences in input matrices (each column is one sequence/utterance)\n    if (isColWise)\n    {\n        // Total number of phones\n        size_t totalPhoneNum = prob.GetNumRows();\n        size_t uttNum = uttFrameNum.size();\n\n        // Max number of phones in utterances in this minibatch\n        size_t maxPhoneNum = phoneSeq.GetNumRows();\n\n        for (size_t t = 0; t < maxFrameNum; t++)\n        {\n            _assignAlphaScore(prob.Data(), alpha.Data(), phoneSeq.Data(), phoneBoundary.Data(), uttToChanInd,\n                uttFrameNum, uttBeginFrame, uttPhoneNum, numParallelSequences, uttNum, t, maxPhoneNum, totalPhoneNum, blankTokenId, delayConstraint);\n        }\n\n        for (LONG64 t = maxFrameNum - 1; t >= 0; t--)\n        {\n            _assignBetaScore(prob.Data(), beta.Data(), phoneSeq.Data(), phoneBoundary.Data(), uttToChanInd,\n                uttFrameNum, uttBeginFrame, uttPhoneNum, numParallelSequences, uttNum, t, maxPhoneNum, totalPhoneNum, blankTokenId, delayConstraint);\n        }\n\n        std::vector<ElemType> scores(uttNum);\n        _assignTotalScore(beta.Data(), scores, uttNum, uttToChanInd, uttBeginFrame, numParallelSequences, maxPhoneNum);\n\n        _assignCTCScore(Data(), prob.Data(), alpha.Data(), beta.Data(), phoneSeq.Data(), uttNum, uttToChanInd,\n            uttBeginFrame, uttPhoneNum, uttFrameNum, numParallelSequences, maxPhoneNum, totalPhoneNum);\n\n        for (size_t utt = 0; utt < uttNum; utt++)\n        {\n            totalScore += scores[utt];\n        }\n\n        return *this;\n\n    }\n    else {\n        LogicError(\"Only ColWise minibatch layout is supported.\");\n    }\n\n    return *this;\n}\n\n/// the kernel function for RCRF backward computation\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::_rcrfBackwardCompute(size_t t, size_t k, const CPUMatrix<ElemType>& alpha,\n                                               CPUMatrix<ElemType>& beta,\n                                               const CPUMatrix<ElemType>& pair_scores)\n{\n    size_t iNumLab = alpha.GetNumRows();\n    size_t iNumPos = alpha.GetNumCols();\n\n    ElemType fSum;\n    ElemType fTmp = (ElemType) LZERO;\n    if (t == iNumPos - 1)\n    {\n        fSum = (ElemType) LZERO;\n        for (int j = 0; j < iNumLab; j++)\n        {\n            fSum = (ElemType) LogAddD(fSum, alpha(j, t));\n        }\n\n        fTmp = alpha(k, t) - fSum;\n        beta(k, t) = fTmp;\n    }\n    else\n    {\n        for (int j = 0; j < iNumLab; j++)\n        {\n            fSum = (ElemType) LZERO;\n            for (int m = 0; m < iNumLab; m++)\n            {\n                fSum = (ElemType) LogAddD(fSum, alpha(m, t) + pair_scores(j, m));\n            }\n\n            fTmp = (ElemType) LogAddD(fTmp, beta(j, t + 1) + alpha(k, t) + pair_scores(j, k) - fSum);\n        }\n        beta(k, t) = fTmp;\n    }\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::RCRFTransGrdCompute(const CPUMatrix<ElemType>& lbls,\n                                              const CPUMatrix<ElemType>& alpha,\n                                              const CPUMatrix<ElemType>& beta,\n                                              const CPUMatrix<ElemType>& pair_scores,\n                                              CPUMatrix<ElemType>& grd)\n{\n    int iNumPos = (int) alpha.GetNumCols();\n    int iNumLab = (int) alpha.GetNumRows();\n\n    int firstLbl = -1;\n    for (int ik = 0; ik < lbls.GetNumRows(); ik++)\n        if (lbls(ik, 0) != 0)\n        {\n            firstLbl = ik;\n            break;\n        }\n\n    for (size_t tPos = 0; tPos < iNumPos; tPos++)\n    {\n        CPUMatrix<ElemType> b = beta.ColumnSlice(tPos, 1);\n        CPUMatrix<ElemType> a;\n        if (tPos > 0)\n            a = alpha.ColumnSlice(tPos - 1, 1);\n\n#pragma omp parallel for\n        for (int i = 0; i < iNumLab; i++)\n        {\n            _rcrfTransGrdCompute(i, lbls, alpha, beta, pair_scores, grd, tPos);\n        }\n\n        // transition score\n        int i = -1;\n        if (tPos == 0)\n            i = firstLbl;\n        else\n        {\n            for (int ik = 0; ik < lbls.GetNumRows(); ik++)\n                if (lbls(ik, tPos - 1) != 0)\n                {\n                    i = ik;\n                    break;\n                }\n        }\n\n        int j = -1;\n        for (int ik = 0; ik < lbls.GetNumRows(); ik++)\n        {\n            if (lbls(ik, tPos) != 0)\n            {\n                j = ik;\n                break;\n            }\n        }\n\n        grd(j, i) -= 1.0;\n    }\n};\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::_rcrfTransGrdCompute(size_t i,\n                                               const CPUMatrix<ElemType>& lbls,\n                                               const CPUMatrix<ElemType>& alpha,\n                                               const CPUMatrix<ElemType>& beta,\n                                               const CPUMatrix<ElemType>& pair_scores,\n                                               CPUMatrix<ElemType>& grd,\n                                               const size_t tPos // position\n                                               )\n{\n    int iNumLab = (int) alpha.GetNumRows();\n\n    int firstLbl = -1;\n    for (int ik = 0; ik < lbls.GetNumRows(); ik++)\n        if (lbls(ik, 0) != 0)\n        {\n            firstLbl = ik;\n            break;\n        }\n\n    CPUMatrix<ElemType> b = beta.ColumnSlice(tPos, 1);\n    CPUMatrix<ElemType> a;\n    if (tPos > 0)\n        a = alpha.ColumnSlice(tPos - 1, 1);\n\n    {\n        ElemType fTmp = (ElemType) LZERO;\n        for (int j = 0; j < iNumLab; j++)\n        {\n            if (tPos == 0)\n            {\n                if (i == firstLbl)\n                {\n                    fTmp = 0;\n                }\n                else\n                {\n                    fTmp = (ElemType) LZERO;\n                }\n            }\n            else\n            {\n                fTmp = a(i, 0);\n            }\n            fTmp += pair_scores(j, i);\n\n            ElemType fSum = (ElemType) LZERO;\n            for (int k = 0; k < iNumLab; k++)\n            {\n                ElemType fTmp2;\n                if (tPos == 0)\n                {\n                    if (k == firstLbl)\n                    {\n                        fTmp2 = 0;\n                    }\n                    else\n                    {\n                        fTmp2 = (ElemType) LZERO;\n                    }\n                }\n                else\n                {\n                    fTmp2 = a(k, 0);\n                }\n                fSum = (ElemType) LogAddD(fSum, fTmp2 + pair_scores(j, k));\n            }\n\n            fTmp -= fSum;\n            fTmp += b(j, 0);\n\n            grd(j, i) += exp(fTmp);\n        }\n    }\n};\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::DropFrame(const CPUMatrix<ElemType>& label, const CPUMatrix<ElemType>& gamma, const ElemType& threshhold)\n{\n    auto& us = *this;\n    if (us.GetNumCols() != gamma.GetNumCols() || us.GetNumRows() != gamma.GetNumRows())\n        LogicError(\"DropFrame: target matrix is not in the same size as gamm matrix.\");\n\n#pragma omp parallel for\n    foreach_column (j, label)\n    {\n\n        bool dropframe = false;\n        foreach_row (i, label)\n        {\n            if (fabs(label(i, j) - 1.0f) < 0.1)\n            {\n                if (gamma(i, j) < threshhold)\n                    dropframe = true;\n                break;\n            }\n        }\n\n        foreach_row (i, label)\n        {\n            us(i, j) = 0.0f;\n        }\n    }\n\n    return *this;\n}\n\ntemplate <class ElemType>\nCPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSequenceError(const ElemType hsmoothingWeight, const CPUMatrix<ElemType>& label,\n                                                              const CPUMatrix<ElemType>& dnnoutput, const CPUMatrix<ElemType>& gamma, ElemType alpha)\n{\n    auto& us = *this;\n    foreach_coord (i, j, us)\n        us(i, j) += alpha * (label(i, j) - (1 - hsmoothingWeight) * dnnoutput(i, j) - hsmoothingWeight * gamma(i, j));\n    return *this;\n}\n\n// note: this function does not depend on the <ElemType> parameter\ntemplate <class ElemType>\nint CPUMatrix<ElemType>::SetNumThreads(int numThreads)\n{\n    if (numThreads == 0) // use default\n        return numThreads;\n\n    int mthreads = (int) std::thread::hardware_concurrency();\n\n    if (numThreads <= 0)\n        numThreads = std::max(1, mthreads + numThreads);\n    if (numThreads > mthreads)\n        numThreads = mthreads;\n\n#ifdef _OPENMP\n    omp_set_num_threads(numThreads);\n    numThreads = omp_get_max_threads();\n\n    #ifdef USE_MKL\n        mkl_set_num_threads(numThreads);\n    #elif defined(USE_OPENBLAS)\n        openblas_set_num_threads(numThreads);\n    #endif\n#endif\n    return numThreads;\n}\n\ntemplate <class ElemType>\nint CPUMatrix<ElemType>::GetMaxNumThreads()\n{\n    int numThreads = (int)std::thread::hardware_concurrency();\n#ifdef _OPENMP\n    numThreads = omp_get_max_threads();\n#endif\n    return numThreads;\n}\n\n// To ensure Intel MKL calls return the same results on all Intel or Intel compatible CPUs,\n// the function set CBWR compatible mode.\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::SetCompatibleMode()\n{\n    #ifdef USE_MKL\n        if (mkl_cbwr_set(MKL_CBWR_COMPATIBLE) != MKL_CBWR_SUCCESS)\n            RuntimeError(\"Could not set MKL compatible mode.\");\n    #endif\n}\n\n// =======================================================================\n// TensorView support\n// =======================================================================\n\n// To save time, this makes extensive use of templates and macros.\n\n// -----------------------------------------------------------------------\n// function to compute the value for a given output location (perform reduction if needed)\n// -----------------------------------------------------------------------\n\n// perform loop over reduction index m\n// This function is declared inside a wrapper struct to allow partial specialization (m = -1).\ntemplate <class ElemType, typename OPFN, typename ReductionOp, size_t N, int m>\nstruct TensorOpReduction\n{\n    // reduction case (non-reduction case is specialized)\n    static inline ElemType Loop(array<ElemType*, N> pointers, const OPFN& opfn, const ReductionOp& reductionOp,\n                                const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides)\n    {\n        array<ptrdiff_t, N - 1> strides;   // N-1 because last one is the result pointer, which is unused in reduction\n        for (size_t i = 0; i < N - 1; i++) // N = a small constant, this will be unrolled\n            strides[i] = reducingStrides[i][(size_t) m];\n\n        double aggregate = TensorOpReduction<ElemType, OPFN, ReductionOp, N, m - 1>::Loop(pointers, opfn, reductionOp, reducingOpDims, reducingStrides);\n        for (size_t dim = reducingOpDims[(size_t)m] - 1; dim-- > 0;)\n        {\n            // advance the pointers\n            for (size_t i = 0; i < N - 1; i++)\n                pointers[i] += strides[i]; // note: last pointer (result) is unused and untouched here\n\n            // need to descend into one loop deeper\n            aggregate = reductionOp(aggregate, TensorOpReduction<ElemType, OPFN, ReductionOp, N, m - 1>::Loop(pointers, opfn, reductionOp, reducingOpDims, reducingStrides));\n        }\n        // Actually it would be nicer to return double but we keep ElementType so that test don't return different numbers than previous implementation.\n        return static_cast<double>(aggregate);\n    }\n};\n\n// perform loop over reduction index m\n// This is the specialized version for m = -1, which terminates the recursion.\ntemplate <class ElemType, typename OPFN, typename ReductionOp, size_t N>\nstruct TensorOpReduction<ElemType, OPFN, ReductionOp, N, -1>\n{\n    static inline ElemType Loop(array<ElemType*, N> pointers, const OPFN& opfn, const ReductionOp& reductionOp,\n                                const SmallVector<size_t>&, const array<SmallVector<ptrdiff_t>, N>&)\n    {\n        return opfn(pointers); // finally we are doing some work!!!\n    }\n};\n\n// perform loop over reduction index m, while keeping track of the number of elements and their corresponding indices.\n// This function is declared inside a wrapper struct to allow partial specialization (m = -1).\ntemplate <class ElemType, size_t N, int m>\nstruct TensorArgOpReduction\n{\n    static inline std::pair<ElemType, size_t> ReduceAll(array<ElemType*, N> pointers, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides,\n        ElementWiseOperator reductionOp)\n    {\n        size_t counter = 0;\n        size_t index = 0;\n        ElemType val = (ElemType)0;\n\n        switch (reducingOpDims.size())\n        {\n        case 3:\n            val = TensorArgOpReduction<ElemType, N, 2>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index);\n            break;\n        case 2:\n            val = TensorArgOpReduction<ElemType, N, 1>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index);\n            break;\n        case 1:\n            val = TensorArgOpReduction<ElemType, N, 0>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index);\n            break;\n        case 0:\n            val = TensorArgOpReduction<ElemType, N, -1>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index);\n            break;\n        default:\n            LogicError(\"TensorOp: %d non-flattened input dimensions are not supported.\", (int)reducingOpDims.size());\n        }\n\n        return make_pair(val, index);\n    }\n\n    // reduction case (non-reduction case is specialized)\n    static inline ElemType Loop(array<ElemType*, N> pointers, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides,\n                                ElementWiseOperator reductionOp, size_t& counter, size_t& index)\n    {\n        array<ptrdiff_t, N - 1> strides;   // N-1 because last one is the result pointer, which is unused in reduction\n        for (size_t i = 0; i < N - 1; i++) // N = a small constant, this will be unrolled\n            strides[i] = reducingStrides[i][(size_t)m];\n\n        ElemType aggregate = TensorArgOpReduction<ElemType, N, m - 1>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index);\n        for (size_t dim = reducingOpDims[(size_t)m] - 1; dim-- > 0;)\n        {\n            // advance the pointers\n            for (size_t i = 0; i < N - 1; i++)\n                pointers[i] += strides[i]; // note: last pointer (result) is unused and untouched here\n\n            ElemType val = TensorArgOpReduction<ElemType, N, m - 1>::Loop(pointers, reducingOpDims, reducingStrides, reductionOp, counter, index);\n\n            bool update = false;\n            switch (reductionOp)\n            {\n            case ElementWiseOperator::opArgmin:\n                update = (aggregate > val);\n                break;\n            case ElementWiseOperator::opArgmax:\n                update = (aggregate < val);\n                break;\n            }\n\n            if (update)\n            {\n                aggregate = val;\n                index = counter - 1;\n            }\n        }\n\n        return aggregate;\n    }\n};\n\n// perform loop over reduction index m\n// This is the specialized version for m = -1, which terminates the recursion.\ntemplate <class ElemType, size_t N>\nstruct TensorArgOpReduction<ElemType, N, -1>\n{\n    static inline ElemType Loop(array<ElemType*, N> pointers,\n        const SmallVector<size_t>&, const array<SmallVector<ptrdiff_t>, N>&, ElementWiseOperator reductionOp, size_t& counter, size_t& index)\n    {\n        counter++;\n        return *pointers[0]; // finally we are doing some work!!!\n    }\n};\n\n// -----------------------------------------------------------------------\n// perform loop over regular index k for N-nary operations (N counting the output)\n// -----------------------------------------------------------------------\n\n// perform loop over regular index k and reducing index m for N operands (counting the output)\ntemplate <class ElemType, typename OPFN, typename ReductionOp, size_t N, bool vectorizable, int m, int k>\nstruct TensorOpIteration\n{\n    static inline void Loop(ElemType beta, array<ElemType*, N> pointers, ElemType alpha, const OPFN& opfn, const ReductionOp& reductionOp,\n                            const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, N>& regularStrides,\n                            const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides)\n    {\n        // non-scalar case: still nested result loops left\n        array<ptrdiff_t, N> strides;\n        for (size_t i = 0; i < N; i++) // N = a small constant, this will be unrolled\n            strides[i] = regularStrides[i][(size_t) k];\n        for (size_t dim = regularOpDims[(size_t) k]; dim-- > 0;)\n        {\n            // need to descend into one loop deeper\n            TensorOpIteration<ElemType, OPFN, ReductionOp, N, vectorizable, m, k - 1>::Loop(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n            // advance the pointers\n            for (size_t i = 0; i < N; i++)\n                pointers[i] += strides[i];\n        }\n    }\n};\n\n// Special version for innermost loop with strides all being 1 and no further reduction. Compiler can use SSE.\n// This is a very common case, e.g. adding vectors or computing the Sigmoid.\ntemplate <class ElemType, typename OPFN, typename ReductionOp>\nstruct TensorOpIteration<ElemType, OPFN, ReductionOp, 3, true /*vectorizable*/, -1 /*no reduction*/, 0 /*innermost loop*/>\n{\n    static inline void Loop(ElemType beta, array<ElemType*, 3> pointers, ElemType alpha, const OPFN& opfn, const ReductionOp& reductionOp,\n                            const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 3>& regularStrides,\n                            const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 3>& reducingStrides)\n    {\n        ElemType* pa = pointers[0];\n        ElemType* pb = pointers[1];\n        ElemType* pc = pointers[2];\n        size_t K = regularOpDims[0];\n        // special-case beta and alpha to allow the compiler to short-circuit it\n        if (beta != 0)\n#pragma omp parallel for\n            for (int k = 0; k < (int) K; k++)\n                TensorOpIteration<ElemType, OPFN, ReductionOp, 3, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(beta, array<ElemType*, 3>{pa + k, pb + k, pc + k}, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n        else if (alpha != 1)\n#pragma omp parallel for\n            for (int k = 0; k < (int) K; k++)\n                TensorOpIteration<ElemType, OPFN, ReductionOp, 3, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(0, array<ElemType*, 3>{pa + k, pb + k, pc + k}, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n        else\n#pragma omp parallel for\n            for (int k = 0; k < (int) K; k++)\n                TensorOpIteration<ElemType, OPFN, ReductionOp, 3, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(0, array<ElemType*, 3>{pa + k, pb + k, pc + k}, 1, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n        // TODO: According to Amit, the VS compiler is not able to vectorize into lambdas. Solution: change the lambda to take an N, or to implement the loop inside (with 1 element by default).\n        // TODO: The signedness of k (required for omp) causes an extra sign-extend.\n        // TODO: OMP adds LOTS of overhead. Do we need a guard, a min size when to use it?\n    }\n};\n// and unary\ntemplate <class ElemType, typename OPFN, typename ReductionOp>\nstruct TensorOpIteration<ElemType, OPFN, ReductionOp, 2, true /*vectorizable*/, -1 /*no reduction*/, 0 /*innermost loop*/>\n{\n    static inline void Loop(ElemType beta, array<ElemType*, 2> pointers, ElemType alpha, const OPFN& opfn, const ReductionOp& reductionOp,\n                            const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 2>& regularStrides,\n                            const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 2>& reducingStrides)\n    {\n        ElemType* pa = pointers[0];\n        ElemType* pb = pointers[1];\n        size_t K = regularOpDims[0];\n        // special-case beta and alpha to allow the compiler to short-circuit it\n        if (beta != 0)\n#pragma omp parallel for\n            for (int k = 0; k < (int) K; k++)\n                TensorOpIteration<ElemType, OPFN, ReductionOp, 2, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(beta, array<ElemType*, 2>{pa + k, pb + k}, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n        else if (alpha != 1)\n#pragma omp parallel for\n            for (int k = 0; k < (int) K; k++)\n                TensorOpIteration<ElemType, OPFN, ReductionOp, 2, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(0, array<ElemType*, 2>{pa + k, pb + k}, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n        else\n#pragma omp parallel for\n            for (int k = 0; k < (int) K; k++)\n                TensorOpIteration<ElemType, OPFN, ReductionOp, 2, true /*vectorizable*/, -1 /*no reduction*/, -1 /*scalar*/>::Loop(0, array<ElemType*, 2>{pa + k, pb + k}, 1, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n    }\n};\n\ntemplate <class ElemType, typename OPFN, typename ReductionOp, size_t N, bool vectorizable, int m>\nstruct TensorOpIteration<ElemType, OPFN, ReductionOp, N, vectorizable, m, -1>\n{\n    static inline void Loop(ElemType beta, array<ElemType*, N> pointers, ElemType alpha, const OPFN& opfn, const ReductionOp& reductionOp,\n                            const SmallVector<size_t>&, const array<SmallVector<ptrdiff_t>, N>&,\n                            const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides)\n    {\n        // we are at element level for the result: perform the op (there may still be reduction)\n        ElemType val = TensorOpReduction<ElemType, OPFN, ReductionOp, N, m>::Loop(pointers, opfn, reductionOp, reducingOpDims, reducingStrides);\n        // scale\n        val *= alpha;\n        // combine with previous value in target matrix, then write it out\n        auto* pout = pointers.back();\n        if (beta != 0)\n            val += beta * *pout;\n        // save\n        *pout = val;\n        return;\n    }\n};\n\n// perform loop over regular index k and reducing index m for N operands (counting the output), the difference\n// between TensorOpIteration and TensorArgOpIteration, is that the latter store the index of the result, instead of \n// the result. The reason that they aren't combined is because of performance.\ntemplate <class ElemType, size_t N, int k>\nstruct TensorArgOpIteration\n{\n    static inline void Loop(array<ElemType*, N> pointers,\n        const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, N>& regularStrides,\n        const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides, ElementWiseOperator reductionOp)\n    {\n        // non-scalar case: still nested result loops left\n        array<ptrdiff_t, N> strides;\n        for (size_t i = 0; i < N; i++) // N = a small constant, this will be unrolled\n            strides[i] = regularStrides[i][(size_t)k];\n        for (size_t dim = regularOpDims[(size_t)k]; dim-- > 0;)\n        {\n            // need to descend into one loop deeper\n            TensorArgOpIteration<ElemType, N, k - 1>::Loop(pointers, regularOpDims, regularStrides, reducingOpDims, reducingStrides, reductionOp);\n            // advance the pointers\n            for (size_t i = 0; i < N; i++)\n                pointers[i] += strides[i];\n        }\n    }\n};\n\ntemplate <class ElemType, size_t N>\nstruct TensorArgOpIteration<ElemType, N, -1>\n{\n    static inline void Loop(array<ElemType*, N> pointers,\n        const SmallVector<size_t>&, const array<SmallVector<ptrdiff_t>, N>&,\n        const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides, ElementWiseOperator reductionOp)\n    {\n        // we are at element level for the result: perform the op (there may still be reduction)\n        auto val = TensorArgOpReduction<ElemType, N, 2>::ReduceAll(pointers, reducingOpDims, reducingStrides, reductionOp);\n\n        auto* pout = pointers.back();\n        *pout = (ElemType)val.second;\n        return;\n    }\n};\n\n// -----------------------------------------------------------------------\n// map runtime parameters N to template parameters\n// -----------------------------------------------------------------------\n\n// tensor operation with k+1 dimensions (-1 means scalar)\ntemplate <class ElemType, typename OPFN, typename ReductionOp, size_t N, int k>\nstatic void TensorOpWithRegularLoop(ElemType beta, const array<ElemType*, N>& pointers, ElemType alpha, const OPFN& opfn, ReductionOp reductionOp,\n                                    const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, N>& regularStrides,\n                                    const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides)\n{\n    size_t dims = reducingOpDims.size();\n    switch (dims)\n    {\n    case 2:\n        return TensorOpIteration<ElemType, OPFN, ReductionOp, N, false /*vectorizable*/, 1, k>::Loop(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n    case 1:\n        return TensorOpIteration<ElemType, OPFN, ReductionOp, N, false /*vectorizable*/, 0, k>::Loop(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n    case 0:\n    {\n        // if all leading dimensions are 1, we can let the compiler do some unrolling\n        bool leadingAllOne = true;\n        for (size_t i = 0; i < N; i++)\n            leadingAllOne &= k >= 0 && regularStrides[i][0] == 1;\n        if (leadingAllOne) // special version that uses a hard-coded increment of 1 for all leading dimensions\n            return TensorOpIteration<ElemType, OPFN, ReductionOp, N, true /*vectorizable*/, -1, k>::Loop(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n        else\n            return TensorOpIteration<ElemType, OPFN, ReductionOp, N, false /*vectorizable*/, -1, k>::Loop(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n    }\n    default:\n        LogicError(\"TensorOp: %d non-flattened reduction dimensions are not supported.\", (int) dims);\n    }\n}\n\n// tensor operation, generalized in number of arguments, operation already provided as a lambda\n// This function now expands into different k.\ntemplate <class ElemType, typename OPFN, typename ReductionOp, size_t N>\nstatic void TensorOpWithFnAndReduction(ElemType beta, array<ElemType*, N> pointers, ElemType alpha, const OPFN& opfn, const ReductionOp& reductionOp,\n    const array<size_t, N>& offsets,\n    const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, N>& regularStrides,\n    const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides)\n{\n    for (size_t i = 0; i < N; i++) // N = a small constant, this will be unrolled\n        pointers[i] += offsets[i];\n    size_t dims = regularOpDims.size();\n    switch (dims)\n    {\n    case 4:\n        return TensorOpWithRegularLoop<ElemType, OPFN, ReductionOp, N, 3>(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n    case 3:\n        return TensorOpWithRegularLoop<ElemType, OPFN, ReductionOp, N, 2>(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n    case 2:\n        return TensorOpWithRegularLoop<ElemType, OPFN, ReductionOp, N, 1>(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n    case 1:\n        return TensorOpWithRegularLoop<ElemType, OPFN, ReductionOp, N, 0>(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n    case 0:\n        return TensorOpWithRegularLoop<ElemType, OPFN, ReductionOp, N, -1>(beta, pointers, alpha, opfn, reductionOp, regularOpDims, regularStrides, reducingOpDims, reducingStrides);\n    default:\n        LogicError(\"TensorOp: %d non-flattened input dimensions are not supported.\", (int)dims);\n    }\n}\n\n// tensor operation, generalized in number of arguments, operation already provided as a lambda\n// This function now expands into different reductionOps\ntemplate <class ElemType, typename OPFN, size_t N>\nstatic void TensorOpWithFn(ElemType beta, array<ElemType*, N> pointers, ElemType alpha, const OPFN& opfn, ElementWiseOperator reductionOp,\n    const array<size_t, N>& offsets,\n    const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, N>& regularStrides,\n    const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, N>& reducingStrides)\n{\n// BUGBUG: Using always 'double' as type of aggregator even for ElemType==float. Reason: otherwise some e2e test would fail as historically we \n// used double for aggregator of sum. But:\n// * for min and max reductions this is meaningless.\n// * It is not consitent with what we do on GPU, there we aggregate on ElemType.\n// * It costs performance.\n// TODO: apdapt e2e tests to run with aggregator of type ElemType.\n#define CaseTensorOpWithFnAndReduction(oper)                                                  \\\n    case ElementWiseOperator::op##oper:                                                       \\\n    return TensorOpWithFnAndReduction(beta, pointers, alpha, opfn, [](double a, double b)     \\\n                                    {                                                         \\\n                                    return Op##oper(a, b);                                    \\\n                                    },                                                        \\\n                                    offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides)\n\n    switch (reductionOp)\n    {\n        CaseTensorOpWithFnAndReduction(Sum);\n        CaseTensorOpWithFnAndReduction(LogSum);\n        CaseTensorOpWithFnAndReduction(Min);\n        CaseTensorOpWithFnAndReduction(Max);\n        CaseTensorOpWithFnAndReduction(ElementwiseProduct);\n    default:\n        LogicError(\"Specified ElementWiseOperator op %d not suported as reduction operation.\", (int)reductionOp);\n    }\n}\n\n// -----------------------------------------------------------------------\n// entry points from Matrix.cpp; also map op to a lambda\n// -----------------------------------------------------------------------\n\n// perform unary operation 'op' on a giving 'this', reinterpreting the matrices as tensors as specified by the dims and strides\n// This maps 'op' to a lambda.\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::TensorOp(ElemType beta, const CPUMatrix<ElemType>& a, ElemType alpha, ElementWiseOperator op, ElementWiseOperator reductionOp,\n                                   const array<size_t, 2>& offsets,\n                                   const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 2>& regularStrides,\n                                   const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 2>& reducingStrides)\n{\n    if (reductionOp != ElementWiseOperator::opSum    &&\n        reductionOp != ElementWiseOperator::opLogSum &&\n        reductionOp != ElementWiseOperator::opMin    &&\n        reductionOp != ElementWiseOperator::opMax    &&\n        reductionOp != ElementWiseOperator::opElementwiseProduct)\n        InvalidArgument(\"TensorOp: Unary reduction operations other than opMax, opMin, opSum, and opLogSum are not implemented.\");\n\n// TODO: Change the lambda to take a pointer and a number of elements, so that we can pass it 1 or 4 elements, in order for it to SSE-vectorize.\n#define CaseUnaryTensorOp(oper)                                                        \\\n    case ElementWiseOperator::op##oper:                                                \\\n        return TensorOpWithFn(beta, pointers, alpha, [](const array<ElemType*, 2>& pp) \\\n                              {                                                        \\\n                                  return Op##oper((*(pp[0])));                         \\\n                              },                                                       \\\n                              reductionOp, offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides)\n\n    array<ElemType*, 2> pointers = {a.Data(), Data()};\n    switch (op)\n    {\n        ForAllUnaryOps(CaseUnaryTensorOp);\n    default:\n        LogicError(\"TensorOp: Unknown unary op code %d.\", (int) op);\n    }\n}\n\n// perform binary operation 'op' on a and b giving 'this', reinterpreting the matrices as tensors as specified by the dims and strides\n// This maps 'op' to a lambda.\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::TensorOp(ElemType beta, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, ElemType alpha, ElementWiseOperator op, ElementWiseOperator reductionOp,\n                                   const array<size_t, 3>& offsets,\n                                   const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 3>& regularStrides,\n                                   const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 3>& reducingStrides)\n{\n    if (reductionOp != ElementWiseOperator::opSum)\n        InvalidArgument(\"TensorOp (binary): The only permitted binary reduction operation is opSum.\");\n\n#define CaseBinaryTensorOp(oper)                                                       \\\n    case ElementWiseOperator::op##oper:                                                \\\n        return TensorOpWithFn(beta, pointers, alpha, [](const array<ElemType*, 3>& pp) \\\n                              {                                                        \\\n                                  return Op##oper((*(pp[0])), (*(pp[1])));             \\\n                              },                                                       \\\n                              reductionOp, offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides)\n\n    array<ElemType*, 3> pointers = {a.Data(), b.Data(), Data()};\n    switch (op)\n    {\n        ForAllBinaryOps(CaseBinaryTensorOp);\n    default:\n        LogicError(\"TensorOp: Unknown op binary code %d.\", (int) op);\n    }\n}\n\n// perform ternary operation 'op' on a, and c giving 'this', reinterpreting the matrices as tensors as specified by the dims and strides\n// This maps 'op' to a lambda.\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::TensorOp(ElemType beta, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const CPUMatrix<ElemType>& c, ElemType alpha, ElementWiseOperator op, ElementWiseOperator reductionOp,\n                                   const array<size_t, 4>& offsets,\n                                   const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 4>& regularStrides,\n                                   const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 4>& reducingStrides)\n{\n    if (reductionOp != ElementWiseOperator::opSum)\n        InvalidArgument(\"TensorOp: The only permitted ternary reduction operation is opSum.\");\n\n#define CaseTernaryTensorOp(oper)                                                      \\\n    case ElementWiseOperator::op##oper:                                                \\\n        return TensorOpWithFn(beta, pointers, alpha, [](const array<ElemType*, 4>& pp) \\\n                              {                                                        \\\n                                  return Op##oper((*(pp[0])), (*(pp[1])), (*(pp[2]))); \\\n                              },                                                       \\\n                              reductionOp, offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides)\n\n    array<ElemType*, 4> pointers = {a.Data(), b.Data(), c.Data(), Data()};\n    switch (op)\n    {\n        ForAllTernaryOps(CaseTernaryTensorOp);\n    default:\n        LogicError(\"TensorOp: Unknown ternary op code %d.\", (int) op);\n    }\n}\n\ntemplate <class ElemType>\nint CPUMatrix<ElemType>::Argmin() const\n{\n    int minArg = -1;\n    ElemType minValue = std::numeric_limits<ElemType>::max();\n\n#pragma omp parallel \n    {\n        int localMinArg = -1;\n        ElemType localMinValue = std::numeric_limits<ElemType>::max();\n\n        #pragma omp for\n        for (int index = 0; index < (int)GetNumElements(); ++index)\n        {\n            if (localMinValue > Data()[index])\n            {\n                localMinArg = index;\n                localMinValue = Data()[index];\n            }\n            // If we have more then one min value, select the one with lower index.\n            else if ((localMinValue == Data()[index]) && (localMinArg > index))\n            {\n                localMinArg = index;\n            }\n        }\n\n        #pragma omp critical\n        {\n            if (minValue > localMinValue)\n            {\n                minArg = localMinArg;\n                minValue = localMinValue;\n            }\n            // If we have more then one min value, select the one with lower index.\n            else if ((minValue == localMinValue) && (minArg > localMinArg))\n            {\n                minArg = localMinArg;\n            }\n        }\n    }\n    return minArg;\n}\n\ntemplate <class ElemType>\nint CPUMatrix<ElemType>::Argmax() const\n{\n    int maxArg = -1;\n    ElemType maxValue = std::numeric_limits<ElemType>::min();\n\n#pragma omp parallel \n    {\n        int localMaxArg = -1;\n        ElemType localMaxValue = std::numeric_limits<ElemType>::min();\n\n#pragma omp for\n        for (int index = 0; index < (int)GetNumElements(); ++index)\n        {\n            if (localMaxValue < Data()[index])\n            {\n                localMaxArg = index;\n                localMaxValue = Data()[index];\n            }\n            // If we have more then one max value, select the one with lower index.\n            else if ((localMaxValue == Data()[index]) && (localMaxArg > index))\n            {\n                localMaxArg = index;\n            }\n        }\n\n#pragma omp critical\n        {\n            if (maxValue < localMaxValue)\n            {\n                maxArg = localMaxArg;\n                maxValue = localMaxValue;\n            }\n            // If we have more then one max value, select the one with lower index.\n            else if ((maxValue == localMaxValue) && (maxArg > localMaxArg))\n            {\n                maxArg = localMaxArg;\n            }\n        }\n    }\n    return maxArg;\n}\n\ntemplate <class ElemType>\nint CPUMatrix<ElemType>::ArgOp(ElementWiseOperator reductionOp) const\n{\n    switch (reductionOp)\n    {\n        case ElementWiseOperator::opArgmin:\n            return Argmin();\n            break;\n        case ElementWiseOperator::opArgmax:\n            return Argmax();\n            break;\n    }\n\n    InvalidArgument(\"ArgOp: Arg reduction operations other than opArgmax, and opArgmin are not implemented.\");\n    return -1;\n}\n\ntemplate <class ElemType>\nvoid CPUMatrix<ElemType>::TensorArgOp(const CPUMatrix<ElemType>& a, ElementWiseOperator reductionOp,\n                                      const array<size_t, 2>& offsets,\n                                      const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 2>& regularStrides,\n                                      const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 2>& reducingStrides)\n{\n    if (reductionOp != ElementWiseOperator::opArgmin &&\n        reductionOp != ElementWiseOperator::opArgmax)\n        InvalidArgument(\"TensorOp: Arg reduction operations other than opArgmax, and opArgmin are not implemented.\");\n\n    if (GetNumElements() == 1)\n    {\n        Data()[0] = (ElemType) a.ArgOp(reductionOp);\n    }\n    else\n    {\n        const size_t N = 2;\n        array<ElemType*, N> pointers = { a.Data(), Data() };\n        for (size_t i = 0; i < N; i++)\n            pointers[i] += offsets[i];\n\n        switch (regularOpDims.size())\n        {\n            case 2:\n                TensorArgOpIteration<ElemType, N, 1>::Loop(pointers, regularOpDims, regularStrides, reducingOpDims, reducingStrides, reductionOp);\n                break;\n            case 1:\n                TensorArgOpIteration<ElemType, N, 0>::Loop(pointers, regularOpDims, regularStrides, reducingOpDims, reducingStrides, reductionOp);\n                break;\n            case 0:\n                TensorArgOpIteration<ElemType, N, -1>::Loop(pointers, regularOpDims, regularStrides, reducingOpDims, reducingStrides, reductionOp);\n                break;\n            default:\n                LogicError(\"TensorOp: %d non-flattened input dimensions are not supported.\", (int)regularOpDims.size());\n        }\n    }\n}\n\n// We use Matrix<char> as the backing store for QuantizedMatrix\n// Let's explicitly instantiate the methods we need for that purpose\ntemplate CPUMatrix<char>::CPUMatrix(const size_t numRows, const size_t numCols);\ntemplate CPUMatrix<char>::CPUMatrix(const size_t numRows, const size_t numCols, char* pArray, const size_t matrixFlags);\ntemplate CPUMatrix<char>::CPUMatrix();\ntemplate CPUMatrix<char>::CPUMatrix(CPUMatrix<char> const&);\ntemplate CPUMatrix<char>::CPUMatrix(CPUMatrix<char>&&);\ntemplate size_t CPUMatrix<char>::LocateElement(size_t, size_t) const;\ntemplate CPUMatrix<char> CPUMatrix<char>::ColumnSlice(size_t startColumn, size_t numCols) const;\ntemplate CPUMatrix<char>& CPUMatrix<char>::operator=(CPUMatrix<char>&&);\ntemplate void CPUMatrix<char>::SetValue(const char);\ntemplate void CPUMatrix<char>::SetValue(const size_t numRows, const size_t numCols, char* pArray, size_t matrixFlags);\ntemplate void CPUMatrix<char>::SetValue(CPUMatrix<char> const&);\n//template void CPUMatrix<char>::SetValue(GPUMatrix<char> const&);\n//template void CPUMatrix<char>::SetValue(CPUSparseMatrix<char> const&);\n//template void CPUMatrix<char>::SetValue(GPUSparseMatrix<char> const&);\ntemplate void CPUMatrix<char>::RequireSize(const size_t numRows, const size_t numCols, bool growOnly);\ntemplate void CPUMatrix<char>::Resize(const size_t numRows, const size_t numCols, bool growOnly);\ntemplate char* CPUMatrix<char>::CopyToArray(void) const;\ntemplate void CPUMatrix<char>::CopySection(size_t numRows, size_t numCols, char* dst, size_t colStride) const;\ntemplate void CPUMatrix<char>::Reshape(const size_t, const size_t);\n\n// Support <short>\ntemplate CPUMatrix<short>::CPUMatrix(const size_t numRows, const size_t numCols);\ntemplate CPUMatrix<short>::CPUMatrix(const size_t numRows, const size_t numCols, short* pArray, const size_t matrixFlags);\ntemplate CPUMatrix<short>::CPUMatrix();\ntemplate CPUMatrix<short>::CPUMatrix(CPUMatrix<short> const&);\ntemplate CPUMatrix<short>::CPUMatrix(CPUMatrix<short>&&);\ntemplate size_t CPUMatrix<short>::LocateElement(size_t, size_t) const;\ntemplate CPUMatrix<short> CPUMatrix<short>::ColumnSlice(size_t startColumn, size_t numCols) const;\ntemplate CPUMatrix<short>& CPUMatrix<short>::operator=(CPUMatrix<short>&&);\ntemplate void CPUMatrix<short>::SetValue(const short);\ntemplate void CPUMatrix<short>::SetValue(const size_t numRows, const size_t numCols, short* pArray, size_t matrixFlags);\ntemplate void CPUMatrix<short>::SetValue(CPUMatrix<short> const&);\n//template void CPUMatrix<short>::SetValue(GPUMatrix<short> const&);\n//template void CPUMatrix<short>::SetValue(CPUSparseMatrix<short> const&);\n//template void CPUMatrix<short>::SetValue(GPUSparseMatrix<short> const&);\ntemplate void CPUMatrix<short>::RequireSize(const size_t numRows, const size_t numCols, bool growOnly);\ntemplate void CPUMatrix<short>::Resize(const size_t numRows, const size_t numCols, bool growOnly);\ntemplate short* CPUMatrix<short>::CopyToArray(void) const;\ntemplate void CPUMatrix<short>::CopySection(size_t numRows, size_t numCols, short* dst, size_t colStride) const;\ntemplate void CPUMatrix<short>::Reshape(const size_t, const size_t);\n\ntemplate CPUMatrix<int>::CPUMatrix(const size_t, const size_t, int*, const size_t);\n\n}}}\n\n", "meta": {"hexsha": "aae1cae785d1ab712567c8bc79a39c7fa2615dac", "size": 260589, "ext": "h", "lang": "C", "max_stars_repo_path": "Source/Math/CPUMatrixImpl.h", "max_stars_repo_name": "vschs007/CNTK", "max_stars_repo_head_hexsha": "894d9e1a5d65d30cd33803c06a988844bb87fcb7", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-08-28T08:27:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T21:12:52.000Z", "max_issues_repo_path": "Source/Math/CPUMatrixImpl.h", "max_issues_repo_name": "vschs007/CNTK", "max_issues_repo_head_hexsha": "894d9e1a5d65d30cd33803c06a988844bb87fcb7", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Math/CPUMatrixImpl.h", "max_forks_repo_name": "vschs007/CNTK", "max_forks_repo_head_hexsha": "894d9e1a5d65d30cd33803c06a988844bb87fcb7", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-23T11:42:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T08:41:32.000Z", "avg_line_length": 36.0776685588, "max_line_length": 272, "alphanum_fraction": 0.5698053256, "num_tokens": 70645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3822573929138351}}
{"text": "/**\n *\n * @file pzgbrdb.c\n *\n *  PLASMA auxiliary routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Azzam Haidar\n * @date 2011-05-15\n * @precisions normal z -> c d s\n *\n **/\n#include \"common.h\"\n#include <lapacke.h>\n\n#undef REAL\n#define COMPLEX\n\n#define DEP(m)  &(DEP[m])\n#define A(_m, _n) (PLASMA_Complex64_t *)plasma_geteltaddr(&A, (_m), (_n), eltsize)\n/***************************************************************************//**\n *  Parallel Reduction from BAND Bidiagonal to the final condensed form - dynamic scheduler\n **/\nvoid plasma_pzgbrdb_quark(PLASMA_enum uplo,\n                          PLASMA_desc A, double *D, double *E, PLASMA_desc T,\n                          PLASMA_sequence *sequence, PLASMA_request *request)\n{\n    plasma_context_t *plasma;\n    Quark_Task_Flags task_flags = Quark_Task_Flags_Initializer;\n\n#ifdef COMPLEX\n    static double dzero = (double) 0.0;\n    double absztmp;\n#endif\n\n    static PLASMA_Complex64_t zone  = (PLASMA_Complex64_t) 1.0;\n    static PLASMA_Complex64_t zzero = (PLASMA_Complex64_t) 0.0;\n    PLASMA_Complex64_t *VQ, *TAUQ,*VP, *TAUP;\n    PLASMA_Complex64_t ztmp, V, TAU;\n    int M, N, NB, MINMN, INgrsiz, INthgrsiz, BAND;\n    int myid, grsiz, shift=3, stt, st, ed, stind, edind;\n    int blklastind, colpt, PCOL, ACOL, MCOL;\n    int stepercol, mylastid, grnb, grid;\n    int *DEP,*MAXID;\n    int i, sweepid, m;\n    int thgrsiz, thgrnb, thgrid, thed;\n    size_t eltsize = plasma_element_size(A.dtyp);\n\n    plasma = plasma_context_self();\n    if (sequence->status != PLASMA_SUCCESS)\n        return;\n\n    QUARK_Task_Flag_Set(&task_flags, TASK_SEQUENCE, (intptr_t)sequence->quark_sequence);\n\n    M     = A.m;\n    N     = A.n;\n    NB    = A.mb;\n    MINMN = min(M,N);\n\n    /* Quick return */\n    if ( MINMN == 0 ){\n        return;\n    }\n    if ( NB == 0 ) {\n        memset(D, 0,  MINMN   *sizeof(double));\n        memset(E, 0, (MINMN-1)*sizeof(double));\n#ifdef COMPLEX\n        for (i=0; i<MINMN; i++)\n            D[i] = cabs(*A(i,i));\n#else\n        for (i=0; i<MINMN; i++)\n            D[i] = *A(i,i);\n#endif\n        return;\n    }\n\n    /*\n     * Barrier is used because the bulge have to wait until\n     * the reduction to band has been finish.\n     * otherwise, I can remove this BARRIER when I integrate\n     * the function dependencies link inside the reduction to\n     * band. Keep in mind the case when NB=1, where no bulge-chasing.\n     */\n    /***************************************************************/\n    QUARK_Barrier(plasma->quark);\n    /***************************************************************/\n\n    /*\n     * Case NB=1 ==> matrix is already Bidiagonal. no need to bulge.\n     * Make diagonal and superdiagonal elements real, storing them in\n     * D and E. if PlasmaLower, first transform lower bidiagonal form\n     * to upper bidiagonal by applying plane rotations/ Householder\n     * from the left, overwriting superdiagonal elements then make\n     * elements real of the resulting upper Bidiagonal. if PlasmaUpper\n     * then make its elements real.  For Q, PT: ZSCAL should be done\n     * in case of WANTQ.\n     */\n    if ( NB == 1 ) {\n        memset(D, 0, MINMN*sizeof(double));\n        memset(E, 0, (MINMN-1)*sizeof(double));\n\n        if(uplo==PlasmaLower){\n            for (i=0; i<(MINMN-1); i++)\n            {\n                /* generate Householder to annihilate a(i+1,i) and create a(i,i+1) */\n                V             = *A((i+1), i);\n                *A((i+1),  i) = zzero;\n                LAPACKE_zlarfg_work( 2, A(i, i), &V, 1, &TAU);\n                /* apply Left*/\n                TAU  = conj(TAU);\n                ztmp = TAU*V;\n                V    = conj(V);\n                *A(i,   i+1) = - V * TAU * (*A(i+1, i+1));\n                *A(i+1, i+1) = *(A(i+1, i+1)) * (zone - V * ztmp);\n            }\n        }\n        /* PlasmaLower or PlasmaUpper, both are now upper */\n        /* Make diagonal and superdiagonal elements real,\n         * storing them in D and E\n         */\n#ifdef COMPLEX\n        ztmp = zone;\n        for (i=0; i<MINMN; i++)\n        {\n            ztmp     = *A(i, i) * conj(ztmp);\n            absztmp  = cabs(ztmp);\n            D[i]     = absztmp;               /* diag value */\n            if(absztmp != dzero)\n                ztmp = (PLASMA_Complex64_t) (ztmp / absztmp);\n            else\n                ztmp = zone;\n            if(i<(MINMN-1)) {\n                ztmp     = *A(i, (i+1)) * conj(ztmp);\n                absztmp  = cabs(ztmp);\n                E[i]     = absztmp;            /* upper off-diag value */\n                if(absztmp != dzero)\n                    ztmp = (PLASMA_Complex64_t) (ztmp / absztmp);\n                else\n                    ztmp = zone;\n            }\n        }\n#else\n        for (i=0; i < MINMN-1; i++) {\n            D[i] = *A(i, i  );\n            E[i] = *A(i, i+1);\n        }\n        D[i] = *A(i, i);\n#endif\n        return;\n    }\n\n    /*\n     * Case MINMN<NB ==> matrix is very small and better to call lapack ZGETRD.\n     *\n     *    Use fact that one row of block is stored the same way than in LAPACK\n     *    Doesn't work if M > NB because of tile storage\n     */\n    if ( MINMN <= 0 )\n    {\n        PLASMA_Complex64_t *work, *taup, *tauq;\n        int info, ldwork = N*N;\n        work = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, ldwork, PlasmaComplexDouble);\n        taup = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, MINMN,  PlasmaComplexDouble);\n        tauq = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, MINMN,  PlasmaComplexDouble);\n        \n        info = LAPACKE_zgebrd_work(LAPACK_COL_MAJOR, M, N,\n                                   A(0,0), A.lm, D, E, taup, tauq, work, ldwork);\n        plasma_shared_free(plasma, (void*) work);\n        plasma_shared_free(plasma, (void*) taup);\n        plasma_shared_free(plasma, (void*) tauq);\n\n        if( info == 0 )\n            sequence->status = PLASMA_SUCCESS;\n        else\n            plasma_sequence_flush(plasma->quark, sequence, request, info);\n        return;\n    }\n\n    /* General case NB > 1 && N > NB */\n    DEP   = (int *)                plasma_shared_alloc(plasma, MINMN+1, PlasmaInteger      );\n    MAXID = (int *)                plasma_shared_alloc(plasma, MINMN+1, PlasmaInteger      );\n    memset(MAXID,0,(MINMN+1)*sizeof(int));\n    VQ    = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN,   PlasmaComplexDouble);\n    TAUQ  = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN,   PlasmaComplexDouble);\n    VP    = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN,   PlasmaComplexDouble);\n    TAUP  = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN,   PlasmaComplexDouble);\n    memset(VQ,0,2*MINMN*sizeof(PLASMA_Complex64_t));\n    memset(TAUQ,0,2*MINMN*sizeof(PLASMA_Complex64_t));\n    memset(VP,0,2*MINMN*sizeof(PLASMA_Complex64_t));\n    memset(TAUP,0,2*MINMN*sizeof(PLASMA_Complex64_t));\n\n    /***************************************************************************\n     *                       START BULGE CHASING CODE\n     **************************************************************************/\n    printf(\"converting tile to lap A.lm %d   ln %d \\n\",A.lm,A.ln);\n    PLASMA_Complex64_t *AB =   (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, A.lm*A.ln,   PlasmaComplexDouble);\n    memset(AB,0,A.lm*A.ln*sizeof(PLASMA_Complex64_t));\n    plasma_zooptile2lap( A,   AB, NB, NB,  A.lm, A.ln,  sequence, request);\n    int LDAB = A.lm;\n/*\n    plasma_dynamic_call_6( plasma_pzhbcpy_t2bl,\n        PLASMA_enum, uplo,\n        PLASMA_desc, A,\n        PLASMA_Complex64_t*, &(AB[NB]),\n        int, M,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n*/\n\n    QUARK_Barrier(plasma->quark);\n\n    /* \n     * Initialisation of local parameter. those parameter should be\n     * input or tuned parameter.\n     */\n    INgrsiz = 1;\n    if( NB > 160 ) {\n        INgrsiz = 2;\n    }\n    else if( NB > 100 ) {\n        if( MINMN < 5000 )\n            INgrsiz = 2;\n        else\n            INgrsiz = 4;\n    } else {\n        INgrsiz = 6;\n    }\n    INthgrsiz = MINMN;\n    BAND      = 0;\n\n    grsiz   = INgrsiz;\n    thgrsiz = INthgrsiz;\n    if( grsiz   == 0 ) grsiz   = 6;\n    if( thgrsiz == 0 ) thgrsiz = MINMN;\n\n    i = shift/grsiz;\n    stepercol =  i*grsiz == shift ? i:i+1;\n\n    i       = (MINMN-1)/thgrsiz;\n    thgrnb  = i*thgrsiz == (MINMN-1) ? i:i+1;\n\n    printf(\"starting code grsiz %d thgr %d\\n\", grsiz, thgrsiz);\n    for (thgrid = 1; thgrid<=thgrnb; thgrid++){\n        stt  = (thgrid-1)*thgrsiz+1;\n        thed = min( (stt + thgrsiz -1), (MINMN-1));\n        for (i = stt; i <= MINMN-1; i++){\n            ed=min(i,thed);\n            if(stt>ed)break;\n            for (m = 1; m <=stepercol; m++){\n                st=stt;\n                for (sweepid = st; sweepid <=ed; sweepid++){\n                    /* PCOL:  dependency on the ID of the master of the group of the previous column.  (Previous Column:PCOL). */\n                    /* ACOL:  dependency on the ID of the master of the previous group of my column.   (Acctual  Column:ACOL). (it is 0(NULL) for myid=1) */\n                    /* MCOL:  OUTPUT dependency on the my ID, to be used by the next ID. (My Column: MCOL). I am the master of this group. */\n                    myid     = (i-sweepid)*(stepercol*grsiz) +(m-1)*grsiz + 1;\n                    mylastid = myid+grsiz-1;\n                    PCOL     = mylastid+shift-1;  /* to know the dependent ID of the previous column. need to know the master of its group*/\n                    MAXID[sweepid] = myid;\n                    PCOL     = min(PCOL,MAXID[sweepid-1]); /* for the last columns, we might do only 1 or 2 kernel, so the PCOL will be wrong. this is to force it to the last ID of the previous col.*/\n                    grnb     = PCOL/grsiz;\n                    grid     = grnb*grsiz == PCOL ? grnb:grnb+1;\n                    PCOL     = (grid-1)*grsiz +1; /* give me the ID of the master of the group of the previous column.*/\n                    ACOL     = myid-grsiz;\n                    if(myid==1)ACOL=0;\n                    MCOL     = myid;\n\n                    QUARK_CORE_zbrdalg2(\n                        plasma->quark, &task_flags,\n                        uplo, MINMN, NB,\n                        AB, LDAB, VQ, TAUQ, VP, TAUP, i, sweepid, m, grsiz, BAND,\n                        DEP(PCOL), DEP(ACOL), DEP(MCOL) );\n\n                    if(mylastid%2 ==0){\n                        blklastind      = (mylastid/2)*NB+1+sweepid-1;\n                    }else{\n                        colpt      = ((mylastid+1)/2)*NB + 1 +sweepid -1 ;\n                        stind      = colpt-NB+1;\n                        edind      = min(colpt,MINMN);\n                        if( (stind>=edind-1) && (edind==MINMN) )\n                            blklastind=MINMN;\n                        else\n                            blklastind=0;\n                    }\n                    if(blklastind >= (MINMN-1))  stt=stt+1;\n                } /* END for sweepid=st:ed    */\n            } /* END for m=1:stepercol */\n        } /* END for i=1:MINMN-2      */\n    } /* END for thgrid=1:thgrnb     */\n\n     /*\n     * Barrier used only for now, to be sure that everything\n     * is done before copying the D and E and free workspace.\n     * this will be removed later when D and E are directly filled\n     * during the bulge process.\n     */\n    QUARK_Barrier(plasma->quark);\n    printf(\"converting back to tile\\n\");\n    \n    plasma_zooplap2tile( A, AB, NB, NB, A.lm, A.ln, 0, 0, M, N, sequence, request, plasma_desc_mat_free(&A));\n/*\n    A = plasma_desc_init(PlasmaComplexDouble, NB,NB, NB*NB, M, N, 0, 0, M, N);\n        if ( plasma_desc_mat_alloc( &(A) ) ) {                         \n        plasma_error( __func__, \"plasma_shared_alloc() failed\");        \n        {free;};                                                        \n        return PLASMA_ERR_OUT_OF_RESOURCES;\n        }\n        */\n    /*\n    plasma_parallel_call_5( plasma_pzlapack_to_tile,   \n        PLASMA_Complex64_t*, AB,                                      \n        int,                 MINMN,                                      \n        PLASMA_desc,         A,                                   \n        PLASMA_sequence*,    sequence,                                     \n        PLASMA_request*,     request);\n\n*/\n\n    QUARK_Barrier(plasma->quark);\n    printf(\"converting done\\n\");\n\n    plasma_shared_free(plasma, (void*) DEP);\n    plasma_shared_free(plasma, (void*) MAXID);\n    plasma_shared_free(plasma, (void*) VQ);\n    plasma_shared_free(plasma, (void*) TAUQ);\n    plasma_shared_free(plasma, (void*) VP);\n    plasma_shared_free(plasma, (void*) TAUP);\n\n    /*\n     * STORE THE RESULTING diagonal/off-diagonal in D AND E\n     */\n    memset(D, 0, MINMN*sizeof(double));\n    memset(E, 0, (MINMN-1)*sizeof(double));\n\n\n    /* Make diagonal and superdiagonal elements real,\n     * storing them in D and E\n     */\n    if(uplo==PlasmaUpper){\n        for (i=0; i < MINMN-1; i++) {\n            D[i] = *A(i, i  );\n            E[i] = *A(i, i+1);\n        }\n        D[i] = *A(i, i);\n    }\n    else{\n        for (i=0; i < MINMN-1; i++) {\n            D[i] = *A(i, i  );\n            E[i] = *A(i+1, i);\n        }\n        D[i] = *A(i, i);\n    }\n\n\n} /* END FUNCTION */\n", "meta": {"hexsha": "0275712d274a6bb97e357210800135f544f9cc12", "size": 13328, "ext": "c", "lang": "C", "max_stars_repo_path": "compute/pzgbrdb.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/pzgbrdb.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/pzgbrdb.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.3333333333, "max_line_length": 200, "alphanum_fraction": 0.5090786315, "num_tokens": 3923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3821494162566816}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Josef Gajdusek\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 <stdio.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_multifit.h>\n\n#include \"log.h\"\n\n#include \"coords.h\"\n\nstatic projPJ proj_wgs;\n\nvoid init_projs()\n{\n\tproj_wgs = pj_init_plus(\"+init=epsg:4326\");\n}\n\ncl_float2 wgs84_to_meters(cl_float2 wgs, projPJ proj_meters)\n{\n\tcl_float2 ret;\n\t// The X and Ys are switched intentionally\n\tdouble ry = wgs.x * DEG_TO_RAD;\n\tdouble rx = wgs.y * DEG_TO_RAD;\n\tint err = pj_transform(proj_wgs, proj_meters, 1, 1, &ry, &rx, NULL);\n\tif (err) {\n\t\tlog_error(\"Coordinate conversion failed: %s\", pj_strerrno(err));\n\t}\n\tret.x = rx;\n\tret.y = ry;\n\treturn ret;\n}\n\nvoid generate_translation_tile(int xtile, int ytile, int zoom, cl_float4 *out, projPJ proj_meters)\n{\n\tint side = 20;\n\tint npoints = side * side;\n\tgsl_multifit_linear_workspace *gwsp = gsl_multifit_linear_alloc(npoints, 3);\n\tgsl_vector *yx = gsl_vector_alloc(npoints);\n\tgsl_vector *yy = gsl_vector_alloc(npoints);\n\tgsl_matrix *X = gsl_matrix_alloc(npoints, 3);\n\tgsl_vector *cx = gsl_vector_alloc(3);\n\tgsl_vector *cy = gsl_vector_alloc(3);\n\tgsl_matrix *cov = gsl_matrix_alloc(npoints, npoints);\n\tdouble chisq;\n\n\t// Generate side x side training points\n\tfor (int x = 0; x < side; x++) {\n\t\tfor (int y = 0; y < side; y++) {\n\t\t\tcl_float2 tile = {.x = xtile + (double)x / side,\n\t\t\t\t\t\t\t  .y = ytile + (double)y / side};\n\t\t\tcl_float2 wgs = tile_to_wgs84(tile, zoom);\n\t\t\tcl_float2 mets = wgs84_to_meters(wgs, proj_meters);\n\n\t\t\tint pt = x * side + y;\n\t\t\t// Inputs\n\t\t\tgsl_matrix_set(X, pt, 0, tile.x - xtile);\n\t\t\tgsl_matrix_set(X, pt, 1, tile.y - ytile);\n\t\t\tgsl_matrix_set(X, pt, 2,\t 1);\n\n\t\t\t// Outputs\n\t\t\tgsl_vector_set(yx, pt, mets.x);\n\t\t\tgsl_vector_set(yy, pt, mets.y);\n\n\t\t}\n\t}\n\n\t// Fit\n\tgsl_multifit_linear(X, yx, cx, cov, &chisq, gwsp);\n\tgsl_multifit_linear(X, yy, cy, cov, &chisq, gwsp);\n\n\tgsl_matrix *mtrans = gsl_matrix_alloc(3, 2);\n\tgsl_matrix_set_col(mtrans, 0, cx);\n\tgsl_matrix_set_col(mtrans, 1, cy);\n\n\t// Output\n\n\tout[0].x = gsl_matrix_get(mtrans, 0, 0);\n\tout[0].y = gsl_matrix_get(mtrans, 1, 0);\n\tout[0].z = gsl_matrix_get(mtrans, 2, 0);\n\tout[1].x = gsl_matrix_get(mtrans, 0, 1);\n\tout[1].y = gsl_matrix_get(mtrans, 1, 1);\n\tout[1].z = gsl_matrix_get(mtrans, 2, 1);\n\n\tgsl_matrix_free(mtrans);\n\tgsl_matrix_free(cov);\n\tgsl_vector_free(cy);\n\tgsl_vector_free(cx);\n\tgsl_matrix_free(X);\n\tgsl_vector_free(yy);\n\tgsl_vector_free(yx);\n\tgsl_multifit_linear_free(gwsp);\n}\n", "meta": {"hexsha": "ffb7541524ccd66aa868a27a01e41b86bf9e8973", "size": 3557, "ext": "c", "lang": "C", "max_stars_repo_path": "src/coords.c", "max_stars_repo_name": "atalax/cl-heatmap", "max_stars_repo_head_hexsha": "84ce0fc1698fd7dd768f92ed3361b94ec9263773", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-09T04:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-09T04:17:17.000Z", "max_issues_repo_path": "src/coords.c", "max_issues_repo_name": "atalax/cl-heatmap", "max_issues_repo_head_hexsha": "84ce0fc1698fd7dd768f92ed3361b94ec9263773", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/coords.c", "max_forks_repo_name": "atalax/cl-heatmap", "max_forks_repo_head_hexsha": "84ce0fc1698fd7dd768f92ed3361b94ec9263773", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-29T06:28:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-29T06:28:25.000Z", "avg_line_length": 30.4017094017, "max_line_length": 98, "alphanum_fraction": 0.708743323, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3821494162566814}}
{"text": "#include <cblas.h>\n\nvoid openblas_mul_double(double *a, double *b, double *c, int m, int k, int n)\n{\n    cblas_dgemm(\n        CblasRowMajor, CblasNoTrans, CblasNoTrans,\n        m, n, k,\n        1.,\n        a, k,\n        b, n,\n        0.,\n        c, n\n    );\n}\n", "meta": {"hexsha": "7052e4bcdbc7f90082aabd961d57607b16775523", "size": 260, "ext": "c", "lang": "C", "max_stars_repo_path": "proj3/src/dnn_openblas.c", "max_stars_repo_name": "hsyis/object-detection-yolo2-tiny", "max_stars_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "proj3/src/dnn_openblas.c", "max_issues_repo_name": "hsyis/object-detection-yolo2-tiny", "max_issues_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proj3/src/dnn_openblas.c", "max_forks_repo_name": "hsyis/object-detection-yolo2-tiny", "max_forks_repo_head_hexsha": "507ac8aa2fc1cd9d2e12db9a720a68dceb3a85f0", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 78, "alphanum_fraction": 0.4923076923, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760727, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3816486362643724}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C code for the geometric coefficients entering the response for LISA-like detectors.\n *\n */\n\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n#include \"waveform.h\"\n#include \"LISAgeometry.h\"\n\n#include <time.h> /* for testing */\n\n//Named LISA-like constellation struct examples\n/*\nstruct tagLISAconstellation {\n  double OrbitOmega,OrbitPhi0,OrbitR;\n  double ConstOmega,ConstPhi0,ConstL;\n}\n*/\n\nLISAconstellation LISAProposal = {\n  EarthOrbitOmega_SI,\n  0,\n  AU_SI,\n  EarthOrbitOmega_SI,\n  0,\n  2.5e9,\n  LISAProposalnoise\n};\n\nLISAconstellation LISA2017 = {\n  EarthOrbitOmega_SI,\n  0,\n  AU_SI,\n  EarthOrbitOmega_SI,\n  0,\n  2.5e9,\n  LISA2017noise\n};\n\nLISAconstellation LISA2010 = {\n  EarthOrbitOmega_SI,\n  0,\n  AU_SI,\n  EarthOrbitOmega_SI,\n  0,\n  5e9,\n  LISA2010noise\n};\n\nLISAconstellation slowOrbitLISA = {\n  EarthOrbitOmega_SI/100.0,\n  0,\n  AU_SI,\n  EarthOrbitOmega_SI/100.0,\n  0,\n  2.5e9,\n  LISA2017noise\n};\n\nLISAconstellation tinyOrbitLISA = {\n  EarthOrbitOmega_SI,\n  0,\n  AU_SI/100,\n  EarthOrbitOmega_SI,\n  0,\n  2.5e9,\n  LISA2017noise\n};\n\nLISAconstellation fastOrbitLISA = {\n  EarthOrbitOmega_SI*10.0,\n  0,\n  AU_SI,\n  EarthOrbitOmega_SI*10.0,\n  0,\n  2.5e9,\n  LISA2017noise\n};\n\nLISAconstellation bigOrbitLISA = {\n  EarthOrbitOmega_SI/10.0,\n  0,\n  AU_SI,\n  EarthOrbitOmega_SI/10.0,\n  0,\n  2.5e9,\n  LISA2017noise\n};\n\n\n\n/****************************************************************/\n/********* Coefficients for the geometric response **************/\n\n/* External storage for cos, sin and coefficients */\nstatic double coeffn1Hn1crossconst, coeffn1Hn1plusconst, coeffn2Hn2crossconst, coeffn2Hn2plusconst, coeffn3Hn3crossconst, coeffn3Hn3plusconst;\nstatic double coeffn1Hn1pluscos[4];\nstatic double coeffn1Hn1plussin[4];\nstatic double coeffn2Hn2pluscos[4];\nstatic double coeffn2Hn2plussin[4];\nstatic double coeffn3Hn3pluscos[4];\nstatic double coeffn3Hn3plussin[4];\nstatic double coeffn1Hn1crosscos[4];\nstatic double coeffn1Hn1crosssin[4];\nstatic double coeffn2Hn2crosscos[4];\nstatic double coeffn2Hn2crosssin[4];\nstatic double coeffn3Hn3crosscos[4];\nstatic double coeffn3Hn3crosssin[4];\nstatic double coeffkn1const, coeffkn2const, coeffkn3const, coeffkp1plusp2const, coeffkp2plusp3const, coeffkp3plusp1const, coeffkp1const, coeffkp2const, coeffkp3const, coeffkRconst;\nstatic double coeffkn1cos[2];\nstatic double coeffkn1sin[2];\nstatic double coeffkn2cos[2];\nstatic double coeffkn2sin[2];\nstatic double coeffkn3cos[2];\nstatic double coeffkn3sin[2];\nstatic double coeffkp1plusp2cos[2];\nstatic double coeffkp1plusp2sin[2];\nstatic double coeffkp2plusp3cos[2];\nstatic double coeffkp2plusp3sin[2];\nstatic double coeffkp3plusp1cos[2];\nstatic double coeffkp3plusp1sin[2];\nstatic double coeffkp1cos[2];\nstatic double coeffkp1sin[2];\nstatic double coeffkp2cos[2];\nstatic double coeffkp2sin[2];\nstatic double coeffkp3cos[2];\nstatic double coeffkp3sin[2];\nstatic double coeffkRcos[2];\nstatic double coeffkRsin[2];\n\nstatic double cosarray[4];\nstatic double sinarray[4];\n\n#pragma omp threadprivate(coeffn1Hn1crossconst, coeffn1Hn1plusconst, coeffn2Hn2crossconst, coeffn2Hn2plusconst, coeffn3Hn3crossconst, coeffn3Hn3plusconst)\n#pragma omp threadprivate(coeffn1Hn1pluscos,coeffn1Hn1plussin,coeffn2Hn2pluscos,coeffn2Hn2plussin,coeffn3Hn3pluscos,coeffn3Hn3plussin)\n#pragma omp threadprivate(coeffn1Hn1crosscos,coeffn1Hn1crosssin,coeffn2Hn2crosscos,coeffn2Hn2crosssin,coeffn3Hn3crosscos,coeffn3Hn3crosssin)\n#pragma omp threadprivate(coeffkn1const, coeffkn2const, coeffkn3const, coeffkp1plusp2const, coeffkp2plusp3const, coeffkp3plusp1const, coeffkp1const, coeffkp2const, coeffkp3const, coeffkRconst)\n#pragma omp threadprivate(coeffkn1cos,coeffkn1sin,coeffkn2cos,coeffkn2sin,coeffkn3cos,coeffkn3sin)\n#pragma omp threadprivate(coeffkp1cos,coeffkp1sin,coeffkp2cos,coeffkp2sin,coeffkp3cos,coeffkp3sin)\n#pragma omp threadprivate(coeffkp1plusp2cos,coeffkp1plusp2sin,coeffkp2plusp3cos,coeffkp2plusp3sin,coeffkp3plusp1cos,coeffkp3plusp1sin)\n#pragma omp threadprivate(coeffkRcos,coeffkRsin,cosarray,sinarray)\n\n/*************************************************************/\n/********* Functions for the geometric response **************/\n\n/* Function to convert string input TDI string to TDItag */\nTDItag ParseTDItag(char* string) {\n  TDItag tag;\n  if(strcmp(string, \"delayO\")==0) tag = delayO;\n  else if(strcmp(string, \"y12L\")==0) tag = y12L;\n  else if(strcmp(string, \"y12\")==0) tag = y12;\n  else if(strcmp(string, \"TDIXYZ\")==0) tag = TDIXYZ;\n  else if(strcmp(string, \"TDIalphabetagamma\")==0) tag = TDIalphabetagamma;\n  else if(strcmp(string, \"TDIAETXYZ\")==0) tag = TDIAETXYZ;\n  else if(strcmp(string, \"TDIAETalphabetagamma\")==0) tag = TDIAETalphabetagamma;\n  else if(strcmp(string, \"TDIX\")==0) tag = TDIX;\n  else if(strcmp(string, \"TDIalpha\")==0) tag = TDIalpha;\n  else if(strcmp(string, \"TDIAXYZ\")==0) tag = TDIAXYZ;\n  else if(strcmp(string, \"TDIEXYZ\")==0) tag = TDIEXYZ;\n  else if(strcmp(string, \"TDITXYZ\")==0) tag = TDITXYZ;\n  else if(strcmp(string, \"TDIAalphabetagamma\")==0) tag = TDIAalphabetagamma;\n  else if(strcmp(string, \"TDIEalphabetagamma\")==0) tag = TDIEalphabetagamma;\n  else if(strcmp(string, \"TDITalphabetagamma\")==0) tag = TDITalphabetagamma;\n  else {\n    printf(\"Error in ParseTDItag: string not recognized.\\n\");\n    exit(1);\n  }\n  return tag;\n}\n\n/* Function to convert string input ResponseApprox to tag */\nResponseApproxtag ParseResponseApproxtag(char* string) {\n  ResponseApproxtag tag;\n  if(strcmp(string, \"full\")==0) tag = full;\n  else if(strcmp(string, \"lowfL\")==0) tag = lowfL;\n  else if(strcmp(string, \"lowf\")==0) tag = lowf;\n  else {\n    printf(\"Error in ParseResponseApproxtag: string not recognized.\\n\");\n    exit(1);\n  }\n  return tag;\n}\n\n/* Compute Solar System Barycenter time tSSB from retarded time at the center of the LISA constellation tL */\n/* NOTE: depends on the sky position given in SSB parameters */\ndouble tSSBfromLframe(const LISAconstellation *variant, const double tL, const double lambdaSSB, const double betaSSB) {\n  double phase = variant->ConstOmega*tL + variant->ConstPhi0 - lambdaSSB;\n  double RoC = variant->OrbitR/C_SI;\n return tL + RoC*cos(betaSSB)*cos(phase) - 1./2*variant->ConstOmega*pow(RoC*cos(betaSSB), 2)*sin(2.*phase);\n}\n/* Compute retarded time at the center of the LISA constellation tL from Solar System Barycenter time tSSB */\ndouble tLfromSSBframe(const LISAconstellation *variant, const double tSSB, const double lambdaSSB, const double betaSSB) {\n  double phase = variant->ConstOmega*tSSB + variant->ConstPhi0 - lambdaSSB;\n  double RoC = variant->OrbitR/C_SI;\n  return tSSB - RoC*cos(betaSSB)*cos(phase);\n}\n/* Convert L-frame params to SSB-frame params */\n/* NOTE: no transformation of the phase -- approximant-dependence with e.g. EOBNRv2HMROM setting phiRef at fRef, and freedom in definition */\nint ConvertLframeParamsToSSBframe(\n  double* tSSB,\n  double* lambdaSSB,\n  double* betaSSB,\n  double* psiSSB,\n  const double tL,\n  const double lambdaL,\n  const double betaL,\n  const double psiL,\n  const LISAconstellation *variant)\n{\n  double alpha = 0., cosalpha = 0, sinalpha = 0., coslambdaL = 0, sinlambdaL = 0., cosbetaL = 0., sinbetaL = 0., cospsiL = 0., sinpsiL = 0.;\n  double coszeta = cos(PI/3.);\n  double sinzeta = sin(PI/3.);\n  coslambdaL = cos(lambdaL);\n  sinlambdaL = sin(lambdaL);\n  cosbetaL = cos(betaL);\n  sinbetaL = sin(betaL);\n  cospsiL = cos(psiL);\n  sinpsiL = sin(psiL);\n  double lambdaSSB_approx = 0.;\n  double betaSSB_approx = 0.;\n  /* Initially, approximate alpha using tL instead of tSSB - then iterate */\n  double tSSB_approx = tL;\n  for(int k=0; k<3; k++) {\n    alpha = variant->ConstOmega * (tSSB_approx) + variant->ConstPhi0;\n    cosalpha = cos(alpha);\n    sinalpha = sin(alpha);\n    lambdaSSB_approx = atan2(cosalpha*cosalpha*cosbetaL*sinlambdaL -sinalpha*sinbetaL*sinzeta + cosbetaL*coszeta*sinalpha*sinalpha*sinlambdaL -cosalpha*cosbetaL*coslambdaL*sinalpha + cosalpha*cosbetaL*coszeta*coslambdaL*sinalpha, cosbetaL*coslambdaL*sinalpha*sinalpha -cosalpha*sinbetaL*sinzeta + cosalpha*cosalpha*cosbetaL*coszeta*coslambdaL -cosalpha*cosbetaL*sinalpha*sinlambdaL + cosalpha*cosbetaL*coszeta*sinalpha*sinlambdaL);\n    betaSSB_approx = asin(coszeta*sinbetaL + cosalpha*cosbetaL*coslambdaL*sinzeta + cosbetaL*sinalpha*sinzeta*sinlambdaL);\n    tSSB_approx = tSSBfromLframe(variant, tL, lambdaSSB_approx, betaSSB_approx);\n  }\n  *tSSB = tSSB_approx;\n  *lambdaSSB = lambdaSSB_approx;\n  *betaSSB = betaSSB_approx;\n  /* Polarization */\n  *psiSSB = modpi(psiL + atan2(cosalpha*sinzeta*sinlambdaL -coslambdaL*sinalpha*sinzeta, cosbetaL*coszeta -cosalpha*coslambdaL*sinbetaL*sinzeta -sinalpha*sinbetaL*sinzeta*sinlambdaL));\n  \n  return SUCCESS;\n}\n/* Convert SSB-frame params to L-frame params */\n/* NOTE: no transformation of the phase -- approximant-dependence with e.g. EOBNRv2HMROM setting phiRef at fRef, and freedom in definition */\nint ConvertSSBframeParamsToLframe(\n  double* tL,\n  double* lambdaL,\n  double* betaL,\n  double* psiL,\n  const double tSSB,\n  const double lambdaSSB,\n  const double betaSSB,\n  const double psiSSB,\n  const LISAconstellation *variant)\n{\n  double alpha = 0., cosalpha = 0, sinalpha = 0., coslambda = 0, sinlambda = 0., cosbeta = 0., sinbeta = 0., cospsi = 0., sinpsi = 0.;\n  double coszeta = cos(PI/3.);\n  double sinzeta = sin(PI/3.);\n  coslambda = cos(lambdaSSB);\n  sinlambda = sin(lambdaSSB);\n  cosbeta = cos(betaSSB);\n  sinbeta = sin(betaSSB);\n  cospsi = cos(psiSSB);\n  sinpsi = sin(psiSSB);\n  alpha = variant->ConstOmega * (tSSB) + variant->ConstPhi0;\n  cosalpha = cos(alpha);\n  sinalpha = sin(alpha);\n  *tL = tLfromSSBframe(variant, tSSB, lambdaSSB, betaSSB);\n  *lambdaL = atan2(cosalpha*cosalpha*cosbeta*sinlambda + sinalpha*sinbeta*sinzeta + cosbeta*coszeta*sinalpha*sinalpha*sinlambda -cosalpha*cosbeta*coslambda*sinalpha + cosalpha*cosbeta*coszeta*coslambda*sinalpha, cosalpha*sinbeta*sinzeta + cosbeta*coslambda*sinalpha*sinalpha + cosalpha*cosalpha*cosbeta*coszeta*coslambda -cosalpha*cosbeta*sinalpha*sinlambda + cosalpha*cosbeta*coszeta*sinalpha*sinlambda);\n  *betaL = asin(coszeta*sinbeta -cosalpha*cosbeta*coslambda*sinzeta -cosbeta*sinalpha*sinzeta*sinlambda);\n  *psiL = modpi(psiSSB + atan2(coslambda*sinalpha*sinzeta -cosalpha*sinzeta*sinlambda, cosbeta*coszeta + cosalpha*coslambda*sinbeta*sinzeta + sinalpha*sinbeta*sinzeta*sinlambda));\n\n  return SUCCESS;\n}\n\n/* Function cardinal sine */\ndouble sinc(const double x) {\n  if (x==0)\n    return 1;\n  else return sin(x)/x;\n}\n\n/* Function to compute, given a value of a sky position and polarization, all the complicated time-independent trigonometric coefficients entering the response */\nvoid SetCoeffsG(const double lambda, const double beta, const double psi) {\n  /* Precomputing cosines and sines */\n  double coslambda = cos(lambda);\n  double sinlambda = sin(lambda);\n  double cosbeta = cos(beta);\n  double sinbeta = sin(beta);\n  double cospsi = cos(psi);\n  double sinpsi = sin(psi);\n\n  /* Projection coefficients for hplus in n3.H.n3 */\n  /**/\n  coeffn3Hn3plusconst = 1./128 * (-4*cospsi*cospsi + 4*sinpsi*sinpsi -27*coslambda*coslambda*cospsi*cospsi -27*sinlambda*sinlambda*sinpsi*sinpsi -4*cosbeta*cosbeta*cospsi*cospsi -4*sinbeta*sinbeta*sinpsi*sinpsi + 4*cosbeta*cosbeta*sinpsi*sinpsi + 4*cospsi*cospsi*sinbeta*sinbeta + 27*coslambda*coslambda*sinpsi*sinpsi + 27*cospsi*cospsi*sinlambda*sinlambda -9*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -9*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -9*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -9*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 9*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + 9*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + 9*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + 9*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -54*sqrt3*coslambda*sinlambda*sinpsi*sinpsi + 54*sqrt3*coslambda*cospsi*cospsi*sinlambda -144*coslambda*cospsi*sinbeta*sinlambda*sinpsi -72*sqrt3*coslambda*coslambda*cospsi*sinbeta*sinpsi -18*sqrt3*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi -18*sqrt3*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 18*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda + 18*sqrt3*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 72*sqrt3*cospsi*sinbeta*sinlambda*sinlambda*sinpsi);\n  /**/\n  coeffn3Hn3pluscos[0] = 1./16*cosbeta * (-9*cospsi*cospsi*sinbeta*sinlambda + 9*sinbeta*sinlambda*sinpsi*sinpsi + 18*coslambda*cospsi*sinpsi -7*sqrt3*coslambda*sinbeta*sinpsi*sinpsi + 7*sqrt3*coslambda*cospsi*cospsi*sinbeta + 14*sqrt3*cospsi*sinlambda*sinpsi);\n  /**/\n  coeffn3Hn3pluscos[1] = -3./64 * (-3*sinpsi*sinpsi + 3*cospsi*cospsi -6*coslambda*coslambda*cospsi*cospsi -6*sinlambda*sinlambda*sinpsi*sinpsi -3*cosbeta*cosbeta*sinpsi*sinpsi -3*cospsi*cospsi*sinbeta*sinbeta + 3*cosbeta*cosbeta*cospsi*cospsi + 3*sinbeta*sinbeta*sinpsi*sinpsi + 6*coslambda*coslambda*sinpsi*sinpsi + 6*cospsi*cospsi*sinlambda*sinlambda -2*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -2*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -2*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -2*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 2*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + 2*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + 2*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + 2*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -32*coslambda*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn3Hn3pluscos[2] = -1./16*cosbeta * (-6*coslambda*cospsi*sinpsi -3*sinbeta*sinlambda*sinpsi*sinpsi + 3*cospsi*cospsi*sinbeta*sinlambda + sqrt3*coslambda*cospsi*cospsi*sinbeta -sqrt3*coslambda*sinbeta*sinpsi*sinpsi + 2*sqrt3*cospsi*sinlambda*sinpsi);\n  /**/\n  coeffn3Hn3pluscos[3] = 1./128 * (-3*coslambda*coslambda*cospsi*cospsi -3*sinlambda*sinlambda*sinpsi*sinpsi + 3*coslambda*coslambda*sinpsi*sinpsi + 3*cospsi*cospsi*sinlambda*sinlambda + cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -6*sqrt3*coslambda*cospsi*cospsi*sinlambda + 6*sqrt3*coslambda*sinlambda*sinpsi*sinpsi -16*coslambda*cospsi*sinbeta*sinlambda*sinpsi -8*sqrt3*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -2*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -2*sqrt3*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 2*sqrt3*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + 2*sqrt3*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 8*sqrt3*coslambda*coslambda*cospsi*sinbeta*sinpsi);\n  /**/\n  coeffn3Hn3plussin[0] = -1./16*cosbeta * (-9*coslambda*sinbeta*sinpsi*sinpsi + 9*coslambda*cospsi*cospsi*sinbeta + 18*cospsi*sinlambda*sinpsi + sqrt3*sinbeta*sinlambda*sinpsi*sinpsi -sqrt3*cospsi*cospsi*sinbeta*sinlambda + 2*sqrt3*coslambda*cospsi*sinpsi);\n  /**/\n  coeffn3Hn3plussin[1] = 3./64 * (-3*sqrt3*sinpsi*sinpsi + 3*sqrt3*cospsi*cospsi -12*coslambda*sinlambda*sinpsi*sinpsi -3*sqrt3*cosbeta*cosbeta*sinpsi*sinpsi -3*sqrt3*cospsi*cospsi*sinbeta*sinbeta + 3*sqrt3*cosbeta*cosbeta*cospsi*cospsi + 3*sqrt3*sinbeta*sinbeta*sinpsi*sinpsi + 12*coslambda*cospsi*cospsi*sinlambda -16*coslambda*coslambda*cospsi*sinbeta*sinpsi -4*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi -4*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 4*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda + 4*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 16*cospsi*sinbeta*sinlambda*sinlambda*sinpsi);\n  /**/\n  coeffn3Hn3plussin[2] = 1./16*cosbeta * (-3*coslambda*sinbeta*sinpsi*sinpsi + 3*coslambda*cospsi*cospsi*sinbeta + 6*cospsi*sinlambda*sinpsi + sqrt3*sinbeta*sinlambda*sinpsi*sinpsi -sqrt3*cospsi*cospsi*sinbeta*sinlambda + 2*sqrt3*coslambda*cospsi*sinpsi);\n  /**/\n  coeffn3Hn3plussin[3] = 1./128 * (-6*coslambda*cospsi*cospsi*sinlambda -3*sqrt3*coslambda*coslambda*sinpsi*sinpsi -3*sqrt3*cospsi*cospsi*sinlambda*sinlambda + 3*sqrt3*coslambda*coslambda*cospsi*cospsi + 3*sqrt3*sinlambda*sinlambda*sinpsi*sinpsi + 6*coslambda*sinlambda*sinpsi*sinpsi + sqrt3*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi + sqrt3*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda + sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta + sqrt3*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -8*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -2*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -2*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi -sqrt3*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi -sqrt3*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi -sqrt3*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi -sqrt3*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda + 2*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + 2*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 8*coslambda*coslambda*cospsi*sinbeta*sinpsi + 16*sqrt3*coslambda*cospsi*sinbeta*sinlambda*sinpsi);\n\n  /* Projection coefficients for hcross in n3.H.n3 */\n  /**/\n  coeffn3Hn3crossconst = 1./64 * (4*cospsi*sinpsi -27*cospsi*sinlambda*sinlambda*sinpsi -4*cospsi*sinbeta*sinbeta*sinpsi + 4*cosbeta*cosbeta*cospsi*sinpsi + 27*coslambda*coslambda*cospsi*sinpsi -36*coslambda*cospsi*cospsi*sinbeta*sinlambda -18*sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta -18*sqrt3*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -9*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -9*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 9*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + 9*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 18*sqrt3*coslambda*coslambda*sinbeta*sinpsi*sinpsi + 18*sqrt3*cospsi*cospsi*sinbeta*sinlambda*sinlambda + 36*coslambda*sinbeta*sinlambda*sinpsi*sinpsi -54*sqrt3*coslambda*cospsi*sinlambda*sinpsi -18*sqrt3*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi + 18*sqrt3*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi);\n  /**/\n  coeffn3Hn3crosscos[0] = 1./16*cosbeta * (-9*coslambda*sinpsi*sinpsi + 9*coslambda*cospsi*cospsi -7*sqrt3*sinlambda*sinpsi*sinpsi + 7*sqrt3*cospsi*cospsi*sinlambda + 18*cospsi*sinbeta*sinlambda*sinpsi -14*sqrt3*coslambda*cospsi*sinbeta*sinpsi);\n  /**/\n  coeffn3Hn3crosscos[1] = -3./32 * (-3*cospsi*sinpsi -6*cospsi*sinlambda*sinlambda*sinpsi -3*cosbeta*cosbeta*cospsi*sinpsi + 3*cospsi*sinbeta*sinbeta*sinpsi + 6*coslambda*coslambda*cospsi*sinpsi -8*coslambda*cospsi*cospsi*sinbeta*sinlambda -2*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -2*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 2*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + 2*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 8*coslambda*sinbeta*sinlambda*sinpsi*sinpsi);\n  /**/\n  coeffn3Hn3crosscos[2] = 1./16*cosbeta * (-3*coslambda*sinpsi*sinpsi + 3*coslambda*cospsi*cospsi + sqrt3*sinlambda*sinpsi*sinpsi -sqrt3*cospsi*cospsi*sinlambda + 6*cospsi*sinbeta*sinlambda*sinpsi + 2*sqrt3*coslambda*cospsi*sinbeta*sinpsi);\n  /**/\n  coeffn3Hn3crosscos[3] = 1./64 * (-3*cospsi*sinlambda*sinlambda*sinpsi + 3*coslambda*coslambda*cospsi*sinpsi + cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi -4*coslambda*cospsi*cospsi*sinbeta*sinlambda -2*sqrt3*coslambda*coslambda*sinbeta*sinpsi*sinpsi -2*sqrt3*cospsi*cospsi*sinbeta*sinlambda*sinlambda -cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 2*sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta + 2*sqrt3*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 4*coslambda*sinbeta*sinlambda*sinpsi*sinpsi + 6*sqrt3*coslambda*cospsi*sinlambda*sinpsi -2*sqrt3*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi + 2*sqrt3*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn3Hn3crosssin[0] = -1./16*cosbeta * (-9*sinlambda*sinpsi*sinpsi + 9*cospsi*cospsi*sinlambda + sqrt3*coslambda*cospsi*cospsi -sqrt3*coslambda*sinpsi*sinpsi -18*coslambda*cospsi*sinbeta*sinpsi + 2*sqrt3*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn3Hn3crosssin[1] = -3./32 * (-4*coslambda*coslambda*sinbeta*sinpsi*sinpsi -4*cospsi*cospsi*sinbeta*sinlambda*sinlambda + 3*sqrt3*cospsi*sinpsi + 4*coslambda*coslambda*cospsi*cospsi*sinbeta + 4*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -3*sqrt3*cospsi*sinbeta*sinbeta*sinpsi + 3*sqrt3*cosbeta*cosbeta*cospsi*sinpsi + 12*coslambda*cospsi*sinlambda*sinpsi -4*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi + 4*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn3Hn3crosssin[2] = 1./16*cosbeta * (-3*sinlambda*sinpsi*sinpsi + 3*cospsi*cospsi*sinlambda + sqrt3*coslambda*cospsi*cospsi -sqrt3*coslambda*sinpsi*sinpsi -6*coslambda*cospsi*sinbeta*sinpsi + 2*sqrt3*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn3Hn3crosssin[3] = 1./64 * (-2*coslambda*coslambda*sinbeta*sinpsi*sinpsi -2*cospsi*cospsi*sinbeta*sinlambda*sinlambda + 2*coslambda*coslambda*cospsi*cospsi*sinbeta + 2*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -3*sqrt3*coslambda*coslambda*cospsi*sinpsi + 3*sqrt3*cospsi*sinlambda*sinlambda*sinpsi + 6*coslambda*cospsi*sinlambda*sinpsi + sqrt3*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi + sqrt3*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi -4*sqrt3*coslambda*sinbeta*sinlambda*sinpsi*sinpsi -2*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi -sqrt3*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi -sqrt3*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 2*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi + 4*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinlambda);\n\n  /* Projection coefficients for hplus in n2.H.n2 */\n  /**/\n  coeffn2Hn2plusconst = 1./128 * (-4*cospsi*cospsi + 4*sinpsi*sinpsi -27*coslambda*coslambda*cospsi*cospsi -27*sinlambda*sinlambda*sinpsi*sinpsi -4*cosbeta*cosbeta*cospsi*cospsi -4*sinbeta*sinbeta*sinpsi*sinpsi + 4*cosbeta*cosbeta*sinpsi*sinpsi + 4*cospsi*cospsi*sinbeta*sinbeta + 27*coslambda*coslambda*sinpsi*sinpsi + 27*cospsi*cospsi*sinlambda*sinlambda -9*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -9*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -9*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -9*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 9*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + 9*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + 9*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + 9*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -54*sqrt3*coslambda*cospsi*cospsi*sinlambda + 54*sqrt3*coslambda*sinlambda*sinpsi*sinpsi -144*coslambda*cospsi*sinbeta*sinlambda*sinpsi -72*sqrt3*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -18*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -18*sqrt3*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 18*sqrt3*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + 18*sqrt3*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 72*sqrt3*coslambda*coslambda*cospsi*sinbeta*sinpsi);\n  /**/\n  coeffn2Hn2pluscos[0] = 1./16*cosbeta * (-18*coslambda*cospsi*sinpsi -9*sinbeta*sinlambda*sinpsi*sinpsi + 9*cospsi*cospsi*sinbeta*sinlambda -7*sqrt3*coslambda*sinbeta*sinpsi*sinpsi + 7*sqrt3*coslambda*cospsi*cospsi*sinbeta + 14*sqrt3*cospsi*sinlambda*sinpsi);\n  /**/\n  coeffn2Hn2pluscos[1] = -3./64 * (-3*sinpsi*sinpsi + 3*cospsi*cospsi -6*coslambda*coslambda*cospsi*cospsi -6*sinlambda*sinlambda*sinpsi*sinpsi -3*cosbeta*cosbeta*sinpsi*sinpsi -3*cospsi*cospsi*sinbeta*sinbeta + 3*cosbeta*cosbeta*cospsi*cospsi + 3*sinbeta*sinbeta*sinpsi*sinpsi + 6*coslambda*coslambda*sinpsi*sinpsi + 6*cospsi*cospsi*sinlambda*sinlambda -2*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -2*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -2*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -2*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 2*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + 2*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + 2*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + 2*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -32*coslambda*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn2Hn2pluscos[2] = -1./16*cosbeta * (-3*cospsi*cospsi*sinbeta*sinlambda + 3*sinbeta*sinlambda*sinpsi*sinpsi + 6*coslambda*cospsi*sinpsi + sqrt3*coslambda*cospsi*cospsi*sinbeta -sqrt3*coslambda*sinbeta*sinpsi*sinpsi + 2*sqrt3*cospsi*sinlambda*sinpsi);\n  /**/\n  coeffn2Hn2pluscos[3] = 1./128 * (-3*coslambda*coslambda*cospsi*cospsi -3*sinlambda*sinlambda*sinpsi*sinpsi + 3*coslambda*coslambda*sinpsi*sinpsi + 3*cospsi*cospsi*sinlambda*sinlambda + cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -6*sqrt3*coslambda*sinlambda*sinpsi*sinpsi + 6*sqrt3*coslambda*cospsi*cospsi*sinlambda -16*coslambda*cospsi*sinbeta*sinlambda*sinpsi -8*sqrt3*coslambda*coslambda*cospsi*sinbeta*sinpsi -2*sqrt3*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi -2*sqrt3*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 2*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda + 2*sqrt3*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 8*sqrt3*cospsi*sinbeta*sinlambda*sinlambda*sinpsi);\n  /**/\n  coeffn2Hn2plussin[0] = 1./16*cosbeta * (-9*coslambda*sinbeta*sinpsi*sinpsi + 9*coslambda*cospsi*cospsi*sinbeta + 18*cospsi*sinlambda*sinpsi + sqrt3*cospsi*cospsi*sinbeta*sinlambda -2*sqrt3*coslambda*cospsi*sinpsi -sqrt3*sinbeta*sinlambda*sinpsi*sinpsi);\n  /**/\n  coeffn2Hn2plussin[1] = -3./64 * (-3*sqrt3*sinpsi*sinpsi + 3*sqrt3*cospsi*cospsi -12*coslambda*cospsi*cospsi*sinlambda -3*sqrt3*cosbeta*cosbeta*sinpsi*sinpsi -3*sqrt3*cospsi*cospsi*sinbeta*sinbeta + 3*sqrt3*cosbeta*cosbeta*cospsi*cospsi + 3*sqrt3*sinbeta*sinbeta*sinpsi*sinpsi + 12*coslambda*sinlambda*sinpsi*sinpsi -16*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -4*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -4*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 4*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + 4*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 16*coslambda*coslambda*cospsi*sinbeta*sinpsi);\n  /**/\n  coeffn2Hn2plussin[2] = -1./16*cosbeta * (-3*coslambda*sinbeta*sinpsi*sinpsi + 3*coslambda*cospsi*cospsi*sinbeta + 6*cospsi*sinlambda*sinpsi + sqrt3*cospsi*cospsi*sinbeta*sinlambda -2*sqrt3*coslambda*cospsi*sinpsi -sqrt3*sinbeta*sinlambda*sinpsi*sinpsi);\n  /**/\n  coeffn2Hn2plussin[3] = 1./128 * (-6*coslambda*cospsi*cospsi*sinlambda -3*sqrt3*coslambda*coslambda*cospsi*cospsi -3*sqrt3*sinlambda*sinlambda*sinpsi*sinpsi + 3*sqrt3*coslambda*coslambda*sinpsi*sinpsi + 3*sqrt3*cospsi*cospsi*sinlambda*sinlambda + 6*coslambda*sinlambda*sinpsi*sinpsi + sqrt3*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + sqrt3*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + sqrt3*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + sqrt3*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -8*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -2*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -2*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi -sqrt3*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -sqrt3*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -sqrt3*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 2*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + 2*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 8*coslambda*coslambda*cospsi*sinbeta*sinpsi -16*sqrt3*coslambda*cospsi*sinbeta*sinlambda*sinpsi);\n\n  /* Projection coefficients for hcross in n2.H.n2 */\n  /**/\n  coeffn2Hn2crossconst = 1./64 * (4*cospsi*sinpsi -27*cospsi*sinlambda*sinlambda*sinpsi -4*cospsi*sinbeta*sinbeta*sinpsi + 4*cosbeta*cosbeta*cospsi*sinpsi + 27*coslambda*coslambda*cospsi*sinpsi -36*coslambda*cospsi*cospsi*sinbeta*sinlambda -18*sqrt3*coslambda*coslambda*sinbeta*sinpsi*sinpsi -18*sqrt3*cospsi*cospsi*sinbeta*sinlambda*sinlambda -9*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -9*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 9*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + 9*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 18*sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta + 18*sqrt3*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 36*coslambda*sinbeta*sinlambda*sinpsi*sinpsi + 54*sqrt3*coslambda*cospsi*sinlambda*sinpsi -18*sqrt3*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi + 18*sqrt3*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn2Hn2crosscos[0] = -1./16*cosbeta * (-9*coslambda*sinpsi*sinpsi + 9*coslambda*cospsi*cospsi -7*sqrt3*cospsi*cospsi*sinlambda + 7*sqrt3*sinlambda*sinpsi*sinpsi + 18*cospsi*sinbeta*sinlambda*sinpsi + 14*sqrt3*coslambda*cospsi*sinbeta*sinpsi);\n  /**/\n  coeffn2Hn2crosscos[1] = -3./32 * (-3*cospsi*sinpsi -6*cospsi*sinlambda*sinlambda*sinpsi -3*cosbeta*cosbeta*cospsi*sinpsi + 3*cospsi*sinbeta*sinbeta*sinpsi + 6*coslambda*coslambda*cospsi*sinpsi -8*coslambda*cospsi*cospsi*sinbeta*sinlambda -2*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -2*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 2*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + 2*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 8*coslambda*sinbeta*sinlambda*sinpsi*sinpsi);\n  /**/\n  coeffn2Hn2crosscos[2] = -1./16*cosbeta * (-3*coslambda*sinpsi*sinpsi + 3*coslambda*cospsi*cospsi + sqrt3*cospsi*cospsi*sinlambda -sqrt3*sinlambda*sinpsi*sinpsi + 6*cospsi*sinbeta*sinlambda*sinpsi -2*sqrt3*coslambda*cospsi*sinbeta*sinpsi);\n  /**/\n  coeffn2Hn2crosscos[3] = 1./64 * (-3*cospsi*sinlambda*sinlambda*sinpsi + 3*coslambda*coslambda*cospsi*sinpsi + cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi -4*coslambda*cospsi*cospsi*sinbeta*sinlambda -2*sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta -2*sqrt3*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 2*sqrt3*coslambda*coslambda*sinbeta*sinpsi*sinpsi + 2*sqrt3*cospsi*cospsi*sinbeta*sinlambda*sinlambda + 4*coslambda*sinbeta*sinlambda*sinpsi*sinpsi -6*sqrt3*coslambda*cospsi*sinlambda*sinpsi -2*sqrt3*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi + 2*sqrt3*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi);\n  /**/\n  coeffn2Hn2crosssin[0] = -1./16*cosbeta * (-9*cospsi*cospsi*sinlambda + 9*sinlambda*sinpsi*sinpsi + sqrt3*coslambda*cospsi*cospsi -sqrt3*coslambda*sinpsi*sinpsi + 18*coslambda*cospsi*sinbeta*sinpsi + 2*sqrt3*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn2Hn2crosssin[1] = -3./32 * (-4*coslambda*coslambda*sinbeta*sinpsi*sinpsi -4*cospsi*cospsi*sinbeta*sinlambda*sinlambda -3*sqrt3*cospsi*sinpsi + 4*coslambda*coslambda*cospsi*cospsi*sinbeta + 4*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -3*sqrt3*cosbeta*cosbeta*cospsi*sinpsi + 3*sqrt3*cospsi*sinbeta*sinbeta*sinpsi + 12*coslambda*cospsi*sinlambda*sinpsi -4*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi + 4*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn2Hn2crosssin[2] = 1./16*cosbeta * (-3*cospsi*cospsi*sinlambda + 3*sinlambda*sinpsi*sinpsi + sqrt3*coslambda*cospsi*cospsi -sqrt3*coslambda*sinpsi*sinpsi + 6*coslambda*cospsi*sinbeta*sinpsi + 2*sqrt3*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn2Hn2crosssin[3] = 1./64 * (-2*coslambda*coslambda*sinbeta*sinpsi*sinpsi -2*cospsi*cospsi*sinbeta*sinlambda*sinlambda + 2*coslambda*coslambda*cospsi*cospsi*sinbeta + 2*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -3*sqrt3*cospsi*sinlambda*sinlambda*sinpsi + 3*sqrt3*coslambda*coslambda*cospsi*sinpsi + 6*coslambda*cospsi*sinlambda*sinpsi + sqrt3*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + sqrt3*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi -4*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinlambda -2*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi -sqrt3*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -sqrt3*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 2*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi + 4*sqrt3*coslambda*sinbeta*sinlambda*sinpsi*sinpsi);\n\n  /* Projection coefficients for hplus in n1.H.n1 */\n  /**/\n  coeffn1Hn1plusconst = 1./64 * (-2*cospsi*cospsi + 2*sinpsi*sinpsi -27*coslambda*coslambda*sinpsi*sinpsi -27*cospsi*cospsi*sinlambda*sinlambda -2*cosbeta*cosbeta*cospsi*cospsi -2*sinbeta*sinbeta*sinpsi*sinpsi + 2*cosbeta*cosbeta*sinpsi*sinpsi + 2*cospsi*cospsi*sinbeta*sinbeta + 27*coslambda*coslambda*cospsi*cospsi + 27*sinlambda*sinlambda*sinpsi*sinpsi -9*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi -9*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi -9*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi -9*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda + 9*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi + 9*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda + 9*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta + 9*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 144*coslambda*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn1Hn1pluscos[0] = -1./8*sqrt3*cosbeta * (coslambda*cospsi*cospsi*sinbeta -coslambda*sinbeta*sinpsi*sinpsi + 2*cospsi*sinlambda*sinpsi);\n  /**/\n  coeffn1Hn1pluscos[1] = -3./32 * (-3*cospsi*cospsi + 3*sinpsi*sinpsi -3*cosbeta*cosbeta*cospsi*cospsi -3*coslambda*coslambda*cospsi*cospsi -3*sinbeta*sinbeta*sinpsi*sinpsi -3*sinlambda*sinlambda*sinpsi*sinpsi + 3*cosbeta*cosbeta*sinpsi*sinpsi + 3*coslambda*coslambda*sinpsi*sinpsi + 3*cospsi*cospsi*sinbeta*sinbeta + 3*cospsi*cospsi*sinlambda*sinlambda + cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -16*coslambda*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn1Hn1pluscos[2] = 1./8*sqrt3*cosbeta * (coslambda*cospsi*cospsi*sinbeta -coslambda*sinbeta*sinpsi*sinpsi + 2*cospsi*sinlambda*sinpsi);\n  /**/\n  coeffn1Hn1pluscos[3] = 1./64 * (-3*coslambda*coslambda*sinpsi*sinpsi -3*cospsi*cospsi*sinlambda*sinlambda + 3*coslambda*coslambda*cospsi*cospsi + 3*sinlambda*sinlambda*sinpsi*sinpsi + cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi + cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda + coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta + sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi -cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi -coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi -cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda + 16*coslambda*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn1Hn1plussin[0] = 5./8*sqrt3*cosbeta * (cospsi*cospsi*sinbeta*sinlambda -2*coslambda*cospsi*sinpsi -sinbeta*sinlambda*sinpsi*sinpsi);\n  /**/\n  coeffn1Hn1plussin[1] = -3./16 * (-3*coslambda*cospsi*cospsi*sinlambda + 3*coslambda*sinlambda*sinpsi*sinpsi + coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda -4*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 4*coslambda*coslambda*cospsi*sinbeta*sinpsi);\n  /**/\n  coeffn1Hn1plussin[2] = 1./8*sqrt3*cosbeta * (cospsi*cospsi*sinbeta*sinlambda -2*coslambda*cospsi*sinpsi -sinbeta*sinlambda*sinpsi*sinpsi);\n  /**/\n  coeffn1Hn1plussin[3] = 1./32 * (-3*coslambda*sinlambda*sinpsi*sinpsi + 3*coslambda*cospsi*cospsi*sinlambda + coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda + cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi -4*coslambda*coslambda*cospsi*sinbeta*sinpsi -coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi -cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 4*cospsi*sinbeta*sinlambda*sinlambda*sinpsi);\n\n  /* Projection coefficients for hcross in n1.H.n1 */\n  /**/\n  coeffn1Hn1crossconst = 1./32 * (2*cospsi*sinpsi -27*coslambda*coslambda*cospsi*sinpsi -2*cospsi*sinbeta*sinbeta*sinpsi + 2*cosbeta*cosbeta*cospsi*sinpsi + 27*cospsi*sinlambda*sinlambda*sinpsi -36*coslambda*sinbeta*sinlambda*sinpsi*sinpsi -9*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi -9*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 9*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi + 9*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 36*coslambda*cospsi*cospsi*sinbeta*sinlambda);\n  /**/\n  coeffn1Hn1crosscos[0] = -1./8*sqrt3*cosbeta * (cospsi*cospsi*sinlambda -sinlambda*sinpsi*sinpsi -2*coslambda*cospsi*sinbeta*sinpsi);\n  /**/\n  coeffn1Hn1crosscos[1] = -3./16 * (3*cospsi*sinpsi -3*cospsi*sinbeta*sinbeta*sinpsi -3*cospsi*sinlambda*sinlambda*sinpsi + 3*cosbeta*cosbeta*cospsi*sinpsi + 3*coslambda*coslambda*cospsi*sinpsi + cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi -4*coslambda*cospsi*cospsi*sinbeta*sinlambda -cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 4*coslambda*sinbeta*sinlambda*sinpsi*sinpsi);\n  /**/\n  coeffn1Hn1crosscos[2] = 1./8*sqrt3*cosbeta * (cospsi*cospsi*sinlambda -sinlambda*sinpsi*sinpsi -2*coslambda*cospsi*sinbeta*sinpsi);\n  /**/\n  coeffn1Hn1crosscos[3] = 1./32 * (-3*coslambda*coslambda*cospsi*sinpsi + 3*cospsi*sinlambda*sinlambda*sinpsi + cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi + cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi -4*coslambda*sinbeta*sinlambda*sinpsi*sinpsi -cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi -coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 4*coslambda*cospsi*cospsi*sinbeta*sinlambda);\n  /**/\n  coeffn1Hn1crosssin[0] = -5./8*sqrt3*cosbeta * (coslambda*cospsi*cospsi -coslambda*sinpsi*sinpsi + 2*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn1Hn1crosssin[1] = -3./8 * (coslambda*coslambda*cospsi*cospsi*sinbeta + sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -coslambda*coslambda*sinbeta*sinpsi*sinpsi -cospsi*cospsi*sinbeta*sinlambda*sinlambda + 3*coslambda*cospsi*sinlambda*sinpsi + coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi -cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi);\n  /**/\n  coeffn1Hn1crosssin[2] = -1./8*sqrt3*cosbeta * (coslambda*cospsi*cospsi -coslambda*sinpsi*sinpsi + 2*cospsi*sinbeta*sinlambda*sinpsi);\n  /**/\n  coeffn1Hn1crosssin[3] = 1./16 * (coslambda*coslambda*sinbeta*sinpsi*sinpsi + cospsi*cospsi*sinbeta*sinlambda*sinlambda -coslambda*coslambda*cospsi*cospsi*sinbeta -sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -3*coslambda*cospsi*sinlambda*sinpsi + cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi -coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi);\n\n  /* Coefficients in k.n3 */\n  /**/\n  coeffkn3const = 3./8*cosbeta * (sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkn3cos[0] = 3./4 * (-sinbeta);\n  /**/\n  coeffkn3cos[1] = -1./8*cosbeta * (-sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkn3sin[0] = -1./4*sqrt3 * (-sinbeta);\n  /**/\n  coeffkn3sin[1] = 1./8*cosbeta * (-coslambda + sqrt3*sinlambda);\n\n  /* Coefficients in k.n2 */\n  /**/\n  coeffkn2const = -3./8*cosbeta * (-sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkn2cos[0] = -3./4 * (-sinbeta);\n  /**/\n  coeffkn2cos[1] = 1./8*cosbeta * (sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkn2sin[0] = -1./4*sqrt3 * (-sinbeta);\n  /**/\n  coeffkn2sin[1] = 1./8*cosbeta * (-coslambda -sqrt3*sinlambda);\n\n  /* Coefficients in k.n1 */\n  /**/\n  coeffkn1const = 3./4*cosbeta * (-sinlambda);\n  /**/\n  coeffkn1cos[0] =  0. ;\n  /**/\n  coeffkn1cos[1] = 1./4*cosbeta * (-sinlambda);\n  /**/\n  coeffkn1sin[0] = 1./2*sqrt3 * (-sinbeta);\n  /**/\n  coeffkn1sin[1] = -1./4*cosbeta * (-coslambda);\n\n  /* Coefficients in k.(p1+p2) */\n  /**/\n  coeffkp1plusp2const = -1./8*cosbeta * (-3*sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkp1plusp2cos[0] = -1./4 * (-sinbeta);\n  /**/\n  coeffkp1plusp2cos[1] = 1./24*cosbeta * (3*sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkp1plusp2sin[0] = -1./4*sqrt3 * (-sinbeta);\n  /**/\n  coeffkp1plusp2sin[1] = 1./24*cosbeta * (-3*coslambda -sqrt3*sinlambda);\n\n  /* Coefficients in k.(p2+p3) */\n  /**/\n  coeffkp2plusp3const = 1./4*sqrt3*cosbeta * (-coslambda);\n  /**/\n  coeffkp2plusp3cos[0] = 1./2 * (-sinbeta);\n  /**/\n  coeffkp2plusp3cos[1] = -1./4/sqrt3 * (-cosbeta*coslambda);\n  /**/\n  coeffkp2plusp3sin[0] =  0. ;\n  /**/\n  coeffkp2plusp3sin[1] = -1./4/sqrt3 * (-cosbeta*sinlambda);\n\n  /* Coefficients in k.(p3+p1) */\n  /**/\n  coeffkp3plusp1const = -1./8*cosbeta * (3*sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkp3plusp1cos[0] = -1./4 * (-sinbeta);\n  /**/\n  coeffkp3plusp1cos[1] = 1./24*cosbeta * (-3*sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkp3plusp1sin[0] = 1./4*sqrt3 * (-sinbeta);\n  /**/\n  coeffkp3plusp1sin[1] = -1./24*cosbeta * (-3*coslambda + sqrt3*sinlambda);\n\n  /* Coefficients in k.p1 */\n  /**/\n  coeffkp1const = -1./4*sqrt3 * (-cosbeta*coslambda);\n  /**/\n  coeffkp1cos[0] = -1./2 * (-sinbeta);\n  /**/\n  coeffkp1cos[1] = 1./(4*sqrt3) * (-cosbeta*coslambda);\n  /**/\n  coeffkp1sin[0] =  0. ;\n  /**/\n  coeffkp1sin[1] = 1./(4*sqrt3) * (-cosbeta*sinlambda);\n\n  /* Coefficients in k.p2 */\n  /**/\n  coeffkp2const = 1./8*cosbeta * (3*sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkp2cos[0] = 1./4 * (-sinbeta);\n  /**/\n  coeffkp2cos[1] = -1./24*cosbeta * (-3*sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkp2sin[0] = -1./4*sqrt3 * (-sinbeta);\n  /**/\n  coeffkp2sin[1] = 1./24*cosbeta * (-3*coslambda + sqrt3*sinlambda);\n\n  /* Coefficients in k.p3 */\n  /**/\n  coeffkp3const = 1./8*cosbeta * (-3*sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkp3cos[0] = 1./4 * (-sinbeta);\n  /**/\n  coeffkp3cos[1] = -1./24*cosbeta * (3*sinlambda -sqrt3*coslambda);\n  /**/\n  coeffkp3sin[0] = 1./4*sqrt3 * (-sinbeta);\n  /**/\n  coeffkp3sin[1] = -1./24*cosbeta * (-3*coslambda -sqrt3*sinlambda);\n\n  /* Coefficients in k.R */\n  /**/\n  coeffkRconst = 0.;\n  coeffkRcos[0] = 1. * (-cosbeta*coslambda);\n  coeffkRsin[0] = 1. * (-cosbeta*sinlambda);\n  coeffkRcos[1] = 0.;\n  coeffkRsin[1] = 0.;\n\n}\n\n/*********************** Fourier-domain response ************************/\n\n/* Individual functions GABmode: older version, does not include the orbital delay (was treated separately as Bessel phase) */\n/* Collective function EvaluateGABmode: orbital delay included */\n/* Conventions changed: now MLDC conventions */\n\n/* Function evaluating G21, combining the two polarization with the spherical harmonics factors */\ndouble complex G21mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross)\n{\n\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  double n3Pn3plus = coeffn3Hn3plusconst;\n  double n3Pn3cross = coeffn3Hn3crossconst;\n  for(int j=0; j<4; j++) {\n    n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j];\n    n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j];\n  }\n  double kn3 = coeffkn3const;\n  double kp1plusp2 = coeffkp1plusp2const;\n  for(int j=0; j<2; j++) {\n    kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j];\n    kp1plusp2 += cosarray[j] * coeffkp1plusp2cos[j] + sinarray[j] * coeffkp1plusp2sin[j];\n  }\n  return I*PI*f*variant->ConstL/C_SI * (n3Pn3plus*Yfactorplus + n3Pn3cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.+kn3)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp1plusp2) );\n}\n/* Function evaluating G12, combining the two polarization with the spherical harmonics factors */\ndouble complex G12mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross)\n{\n\n  double phase = variant->ConstOmega*t + variant->ConstPhi0;\n\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  double n3Pn3plus = coeffn3Hn3plusconst;\n  double n3Pn3cross = coeffn3Hn3crossconst;\n  for(int j=0; j<4; j++) {\n    n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j];\n    n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j];\n  }\n  double kn3 = coeffkn3const;\n  double kp1plusp2 = coeffkp1plusp2const;\n  for(int j=0; j<2; j++) {\n    kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j];\n    kp1plusp2 += cosarray[j] * coeffkp1plusp2cos[j] + sinarray[j] * coeffkp1plusp2sin[j];\n  }\n\n  return I*PI*f*variant->ConstL/C_SI * (n3Pn3plus*Yfactorplus + n3Pn3cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.-kn3)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp1plusp2) );\n}\n/* Function evaluating G32, combining the two polarization with the spherical harmonics factors */\ndouble complex G32mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross)\n{\n\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  double n1Pn1plus = coeffn1Hn1plusconst;\n  double n1Pn1cross = coeffn1Hn1crossconst;\n  for(int j=0; j<4; j++) {\n    n1Pn1plus += cosarray[j] * coeffn1Hn1pluscos[j] + sinarray[j] * coeffn1Hn1plussin[j];\n    n1Pn1cross += cosarray[j] * coeffn1Hn1crosscos[j] + sinarray[j] * coeffn1Hn1crosssin[j];\n  }\n  double kn1 = coeffkn1const;\n  double kp2plusp3 = coeffkp2plusp3const;\n  for(int j=0; j<2; j++) {\n    kn1 += cosarray[j] * coeffkn1cos[j] + sinarray[j] * coeffkn1sin[j];\n    kp2plusp3 += cosarray[j] * coeffkp2plusp3cos[j] + sinarray[j] * coeffkp2plusp3sin[j];\n  }\n\n  return I*PI*f*variant->ConstL/C_SI * (n1Pn1plus*Yfactorplus + n1Pn1cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.+kn1)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp2plusp3) );\n}\n/* Function evaluating G23, combining the two polarization with the spherical harmonics factors */\ndouble complex G23mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross)\n{\n\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1)* phase);\n    sinarray[j] = sin((j+1)* phase);\n  }\n  double n1Pn1plus = coeffn1Hn1plusconst;\n  double n1Pn1cross = coeffn1Hn1crossconst;\n  for(int j=0; j<4; j++) {\n    n1Pn1plus += cosarray[j] * coeffn1Hn1pluscos[j] + sinarray[j] * coeffn1Hn1plussin[j];\n    n1Pn1cross += cosarray[j] * coeffn1Hn1crosscos[j] + sinarray[j] * coeffn1Hn1crosssin[j];\n  }\n  double kn1 = coeffkn1const;\n  double kp2plusp3 = coeffkp2plusp3const;\n  for(int j=0; j<2; j++) {\n    kn1 += cosarray[j] * coeffkn1cos[j] + sinarray[j] * coeffkn1sin[j];\n    kp2plusp3 += cosarray[j] * coeffkp2plusp3cos[j] + sinarray[j] * coeffkp2plusp3sin[j];\n  }\n\n  return I*PI*f*variant->ConstL/C_SI * (n1Pn1plus*Yfactorplus + n1Pn1cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.-kn1)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp2plusp3) );\n}\n/* Function evaluating G13, combining the two polarization with the spherical harmonics factors */\ndouble complex G13mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross)\n{\n\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  double n2Pn2plus = coeffn2Hn2plusconst;\n  double n2Pn2cross = coeffn2Hn2crossconst;\n  for(int j=0; j<4; j++) {\n    n2Pn2plus += cosarray[j] * coeffn2Hn2pluscos[j] + sinarray[j] * coeffn2Hn2plussin[j];\n    n2Pn2cross += cosarray[j] * coeffn2Hn2crosscos[j] + sinarray[j] * coeffn2Hn2crosssin[j];\n  }\n  double kn2 = coeffkn2const;\n  double kp3plusp1 = coeffkp3plusp1const;\n  for(int j=0; j<2; j++) {\n    kn2 += cosarray[j] * coeffkn2cos[j] + sinarray[j] * coeffkn2sin[j];\n    kp3plusp1 += cosarray[j] * coeffkp3plusp1cos[j] + sinarray[j] * coeffkp3plusp1sin[j];\n  }\n\n  return I*PI*f*variant->ConstL/C_SI * (n2Pn2plus*Yfactorplus + n2Pn2cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.+kn2)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp3plusp1) );\n}\n/* Function evaluating G31, combining the two polarization with the spherical harmonics factors */\ndouble complex G31mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross)\n{\n\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  double n2Pn2plus = coeffn2Hn2plusconst;\n  double n2Pn2cross = coeffn2Hn2crossconst;\n  for(int j=0; j<4; j++) {\n    n2Pn2plus += cosarray[j] * coeffn2Hn2pluscos[j] + sinarray[j] * coeffn2Hn2plussin[j];\n    n2Pn2cross += cosarray[j] * coeffn2Hn2crosscos[j] + sinarray[j] * coeffn2Hn2crosssin[j];\n  }\n  double kn2 = coeffkn2const;\n  double kp3plusp1 = coeffkp3plusp1const;\n  for(int j=0; j<2; j++) {\n    kn2 += cosarray[j] * coeffkn2cos[j] + sinarray[j] * coeffkn2sin[j];\n    kp3plusp1 += cosarray[j] * coeffkp3plusp1cos[j] + sinarray[j] * coeffkp3plusp1sin[j];\n  }\n\n  return I*PI*f*variant->ConstL/C_SI * (n2Pn2plus*Yfactorplus + n2Pn2cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.-kn2)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp3plusp1) );\n}\n\n/* Function evaluating all coefficients G12, G21, G23, G32, G31, G13, combining the two polarization with the spherical harmonics factors */\n/* Note: includes orbital delay */\nint EvaluateGABmode(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  double complex* G12,                     /* Output for G12 */\n  double complex* G21,                     /* Output for G21 */\n  double complex* G23,                     /* Output for G23 */\n  double complex* G32,                     /* Output for G32 */\n  double complex* G31,                     /* Output for G31 */\n  double complex* G13,                     /* Output for G13 */\n  const double f,                          /* Frequency */\n  const double t,                          /* Time */\n  const double complex Yfactorplus,        /* Spin-weighted spherical harmonic factor for plus */\n  const double complex Yfactorcross,       /* Spin-weighted spherical harmonic factor for cross */\n  const int tagdelayR,                     /* Tag: when 1, include the phase term of the R-delay */\n  const ResponseApproxtag responseapprox)  /* Tag to select possible low-f approximation level in FD response */\n{\n  double phase = variant->ConstOmega*t + variant->ConstPhi0;\n\n  /* Precompute array of sine/cosine */\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  /* Scalar products with k */\n  double n1Pn1plus = coeffn1Hn1plusconst;\n  double n1Pn1cross = coeffn1Hn1crossconst;\n  double n2Pn2plus = coeffn2Hn2plusconst;\n  double n2Pn2cross = coeffn2Hn2crossconst;\n  double n3Pn3plus = coeffn3Hn3plusconst;\n  double n3Pn3cross = coeffn3Hn3crossconst;\n  for(int j=0; j<4; j++) {\n    n1Pn1plus += cosarray[j] * coeffn1Hn1pluscos[j] + sinarray[j] * coeffn1Hn1plussin[j];\n    n1Pn1cross += cosarray[j] * coeffn1Hn1crosscos[j] + sinarray[j] * coeffn1Hn1crosssin[j];\n    n2Pn2plus += cosarray[j] * coeffn2Hn2pluscos[j] + sinarray[j] * coeffn2Hn2plussin[j];\n    n2Pn2cross += cosarray[j] * coeffn2Hn2crosscos[j] + sinarray[j] * coeffn2Hn2crosssin[j];\n    n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j];\n    n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j];\n  }\n  /* Scalar products with k */\n  double kn1 = coeffkn1const;\n  double kn2 = coeffkn2const;\n  double kn3 = coeffkn3const;\n  double kp1plusp2 = coeffkp1plusp2const;\n  double kp2plusp3 = coeffkp2plusp3const;\n  double kp3plusp1 = coeffkp3plusp1const;\n  double kR = coeffkRconst;\n  for(int j=0; j<2; j++) {\n    kn1 += cosarray[j] * coeffkn1cos[j] + sinarray[j] * coeffkn1sin[j];\n    kn2 += cosarray[j] * coeffkn2cos[j] + sinarray[j] * coeffkn2sin[j];\n    kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j];\n    kp1plusp2 += cosarray[j] * coeffkp1plusp2cos[j] + sinarray[j] * coeffkp1plusp2sin[j];\n    kp2plusp3 += cosarray[j] * coeffkp2plusp3cos[j] + sinarray[j] * coeffkp2plusp3sin[j];\n    kp3plusp1 += cosarray[j] * coeffkp3plusp1cos[j] + sinarray[j] * coeffkp3plusp1sin[j];\n    kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j];\n  }\n  /* Common factors */\n  double complex factn1Pn1 = n1Pn1plus*Yfactorplus + n1Pn1cross*Yfactorcross;\n  double complex factn2Pn2 = n2Pn2plus*Yfactorplus + n2Pn2cross*Yfactorcross;\n  double complex factn3Pn3 = n3Pn3plus*Yfactorplus + n3Pn3cross*Yfactorcross;\n  double prefactor = PI*f*variant->ConstL/C_SI;\n  double prefactorR = 2*PI*f*variant->OrbitR/C_SI;\n  double complex factorcexp12 = cexp(I*prefactor * (1.+kp1plusp2));\n  double complex factorcexp23 = cexp(I*prefactor * (1.+kp2plusp3));\n  double complex factorcexp31 = cexp(I*prefactor * (1.+kp3plusp1));\n  double factorsinc12 = sinc( prefactor * (1.-kn3));\n  double factorsinc21 = sinc( prefactor * (1.+kn3));\n  double factorsinc23 = sinc( prefactor * (1.-kn1));\n  double factorsinc32 = sinc( prefactor * (1.+kn1));\n  double factorsinc31 = sinc( prefactor * (1.-kn2));\n  double factorsinc13 = sinc( prefactor * (1.+kn2));\n  /* The tag tagdelayR allows to choose to include or not the R-delay phase term (here leading order) */\n  double complex factorcexpkR;\n  if(tagdelayR) factorcexpkR = cexp(I*prefactorR * kR);\n  else factorcexpkR = 1.;\n\n  /* Take into account level of approximation in for low-f response - choices are full, lowfL or lowf */\n  if(responseapprox==lowf) {\n    factorcexpkR = 1.;\n  }\n  if((responseapprox==lowfL)||(responseapprox==lowf)) {\n    factorsinc12 = 1.;\n    factorsinc21 = 1.;\n    factorsinc23 = 1.;\n    factorsinc32 = 1.;\n    factorsinc31 = 1.;\n    factorsinc13 = 1.;\n    factorcexp12 = 1.;\n    factorcexp23 = 1.;\n    factorcexp31 = 1.;\n  }\n\n  /* Output result */\n  *G12 = I*prefactor * factorcexpkR * factn3Pn3 * factorsinc12 * factorcexp12;\n  *G21 = I*prefactor * factorcexpkR * factn3Pn3 * factorsinc21 * factorcexp12;\n  *G23 = I*prefactor * factorcexpkR * factn1Pn1 * factorsinc23 * factorcexp23;\n  *G32 = I*prefactor * factorcexpkR * factn1Pn1 * factorsinc32 * factorcexp23;\n  *G31 = I*prefactor * factorcexpkR * factn2Pn2 * factorsinc31 * factorcexp31;\n  *G13 = I*prefactor * factorcexpkR * factn2Pn2 * factorsinc13 * factorcexp31;\n\n  return SUCCESS;\n}\n\n/*********************** Fourier-domain TDI factors ************************/\n\n/* Functions evaluating the Fourier-domain factors (combinations of the GAB's) for TDI observables */\n/* NOTE: factors have been scaled out, in parallel of what is done for the noise function */\n/* Note: in case only one channel is considered, amplitudes for channels 2 and 3 are simply set to 0 */\n/* (allows minimal changes from the old structure that assumed KTV A,E,T - but probably not optimal) */\nint EvaluateTDIfactor3Chan(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  double complex* factor1,                       /* Output for factor for TDI channel 1 */\n  double complex* factor2,                       /* Output for factor for TDI channel 2 */\n  double complex* factor3,                       /* Output for factor for TDI channel 3 */\n  const double complex G12,                      /* Input for G12 */\n  const double complex G21,                      /* Input for G21 */\n  const double complex G23,                      /* Input for G23 */\n  const double complex G32,                      /* Input for G32 */\n  const double complex G31,                      /* Input for G31 */\n  const double complex G13,                      /* Input for G13 */\n  const double f,                                /* Frequency */\n  const TDItag tditag,                           /* Selector for the TDI observables */\n  const ResponseApproxtag responseapprox)        /* Tag to select possible low-f approximation level in FD response */\n{\n  /* Notation: x=pifL, z=e^2ix*/\n  double x = PI*f*variant->ConstL/C_SI;\n  double complex z = cexp(2*I*x);\n  /* In both lowf and lowf-L approximations, ignore z factors - consitently ignore all TDI delays */\n  if((responseapprox==lowf)||(responseapprox==lowfL)) {\n    x = 0.;\n    z = 1.;\n  }\n  switch(tditag) {\n    /* For testing purposes: basic yAB observable - no factor */\n  case y12:\n    *factor1 = G12;\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n    /* For testing purposes: basic yABL observable - no factor, same as for yAB */\n  case y12L:\n    *factor1 = G12;\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n    /* First-generation rescaled TDI aet from X,Y,Z */\n    /* With x=pifL, factors scaled out: A,E I*sqrt2*sin2x*e2ix - T 2*sqrt2*sin2x*sinx*e3ix */\n  case TDIAETXYZ:\n    *factor1 = 0.5 * ( (1.+z)*(G31+G13) - G23 - z*G32 - G21 - z*G12 );\n    *factor2 = 0.5*invsqrt3 * ( (1.-z)*(G13-G31) + (2.+z)*(G12-G32) + (1.+2*z)*(G21-G23) );\n    *factor3 = invsqrt6 * ( G21-G12 + G32-G23 + G13-G31);\n    break;\n    /* First-generation rescaled TDI aet from alpha, beta, gamma */\n    /* With x=pifL, factors scaled out: A,E -I*2sqrt2*sinx*eix - T sinx/(sin3x*eix) */\n  case TDIAETalphabetagamma:\n    *factor1 = 0.5 * (G13+G31 + z*(G12+G32) - (1.+z)*(G21+G13));\n    *factor2 = 0.5*invsqrt3 * ((2.+z)*(G12-G32) + (1.+z)*(G21-G23) + (1.+2*z)*(G13-G31));\n    *factor3 = invsqrt3 * (G21-G12 + G32-G23 + G13-G31);\n    break;\n    /* First-generation TDI XYZ */\n    /* With x=pifL, factor scaled out: 2I*sin2x*e2ix */\n  case TDIXYZ:\n    *factor1 = G21 + z*G12 - G31 - z*G13;\n    *factor2 = G32 + z*G23 - G12 - z*G21;\n    *factor3 = G13 + z*G31 - G23 - z*G32;\n    break;\n    /* First-generation TDI alpha beta gamma */\n  case TDIalphabetagamma:\n    *factor1 = G21-G31 + z*(G13-G12) + z*z*(G32-G23);\n    *factor2 = G32-G12 + z*(G21-G23) + z*z*(G13-G31);\n    *factor3 = G13-G23 + z*(G32-G31) + z*z*(G21-G12);\n    break;\n  /* First-generation TDI XYZ */\n  case TDIX:\n    *factor1 = G21 + z*G12 - G31 - z*G13;\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  /* First-generation TDI alpha beta gamma */\n  case TDIalpha:\n    *factor1 = G21-G31 + z*(G13-G12) + z*z*(G32-G23);\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  /* First-generation rescaled TDI aet from X,Y,Z */\n  /* With x=pifL, factors scaled out: A,E I*sqrt2*sin2x*eix - T 2*sqrt2*sin2x*sinx*e2ix */\n  case TDIAXYZ:\n    *factor1 = 0.5 * ( (1.+z)*(G31+G13) - G23 - z*G32 - G21 - z*G12 );\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  case TDIEXYZ:\n    *factor1 = 0.5*invsqrt3 * ( (1.-z)*(G13-G31) + (2.+z)*(G12-G32) + (1.+2*z)*(G12-G23) );\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  case TDITXYZ:\n    *factor1 = invsqrt6 * ( G21-G12 + G32-G23 + G13-G31);\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  /* First-generation rescaled TDI aet from alpha, beta, gamma */\n  /* With x=pifL, factors scaled out: A,E -I*2sqrt2*sinx*eix - T sinx/(sin3x*eix) */\n  case TDIAalphabetagamma:\n    *factor1 = 0.5 * (G13+G31 + z*(G12+G32) - (1.+z)*(G21+G13));\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  case TDIEalphabetagamma:\n    *factor1 = 0.5*invsqrt3 * ((2.+z)*(G12-G32) + (1.+z)*(G21-G23) + (1.+2*z)*(G13-G31));\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  case TDITalphabetagamma:\n    *factor1 = invsqrt3 * (G21-G12 + G32-G23 + G13-G31);\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  default:\n    printf(\"Error in EvaluateTDIfactor3Chan: tditag not recognized.\\n\");\n    exit(1);\n  }\n  return SUCCESS;\n}\n\n/* Function evaluating the Fourier-domain factors that have been scaled out of TDI observables */\n/* The factors scaled out, parallel what is done for the noise functions */\n/* Note: in case only one channel is considered, factors for channels 2 and 3 are simply set to 0 */\nint ScaledTDIfactor3Chan(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  double complex* factor1,                       /* Output for factor for TDI factor 1 */\n  double complex* factor2,                       /* Output for factor for TDI factor 2 */\n  double complex* factor3,                       /* Output for factor for TDI factor 3 */\n  const double f,                                /* Frequency */\n  const TDItag tditag)                           /* Selector for the TDI observables */\n{\n  /* Notation: x=pifL */\n  double x = PI*f*variant->ConstL/C_SI;\n  switch(tditag) {\n    /* First-generation rescaled TDI aet from X,Y,Z */\n  case TDIAETXYZ:\n    *factor1 = I*sqrt(2)*sin(2*x)*cexp(2*I*x);\n    *factor2 = I*sqrt(2)*sin(2*x)*cexp(2*I*x);\n    *factor3 = 2*sqrt(2)*sin(x)*sin(2*x)*cexp(3*I*x);\n    break;\n    /* First-generation rescaled TDI aet from alpha, beta, gamma */\n  case TDIAETalphabetagamma:\n    *factor1 = -I*2*sqrt(2)*sin(x)*cexp(I*x);\n    *factor2 = -I*2*sqrt(2)*sin(x)*cexp(I*x);\n    *factor3 = sin(3*x)/sin(x)*cexp(I*x);\n    break;\n    /* First-generation TDI XYZ */\n  case TDIXYZ:\n    *factor1 = 2*I*sin(2*x)*cexp(2*I*x);\n    *factor2 = 2*I*sin(2*x)*cexp(2*I*x);\n    *factor3 = 2*I*sin(2*x)*cexp(2*I*x);\n    break;\n    /* First-generation TDI alpha beta gamma */\n  case TDIalphabetagamma:\n    *factor1 = 1.;\n    *factor2 = 1.;\n    *factor3 = 1.;\n    break;\n  /* First-generation TDI XYZ */\n  case TDIX:\n    *factor1 = 2*I*sin(2*x)*cexp(2*I*x);\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  /* First-generation TDI alpha beta gamma */\n  case TDIalpha:\n    *factor1 = 1.;\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  /* First-generation rescaled TDI aet from X,Y,Z */\n  /* With x=pifL, factors scaled out: A,E I*sqrt2*sin2x*eix - T 2*sqrt2*sin2x*sinx*e2ix */\n  case TDIAXYZ:\n    *factor1 = I*sqrt(2)*sin(2*x)*cexp(2*I*x);\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  case TDIEXYZ:\n    *factor1 = I*sqrt(2)*sin(2*x)*cexp(2*I*x);\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  case TDITXYZ:\n    *factor1 = 2*sqrt(2)*sin(x)*sin(2*x)*cexp(3*I*x);\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  /* First-generation rescaled TDI aet from alpha, beta, gamma */\n  /* With x=pifL, factors scaled out: A,E -I*2sqrt2*sinx*eix - T sinx/(sin3x*eix) */\n  case TDIAalphabetagamma:\n    *factor1 = -I*2*sqrt(2)*sin(x)*cexp(I*x);\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  case TDIEalphabetagamma:\n    *factor1 = -I*2*sqrt(2)*sin(x)*cexp(I*x);\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  case TDITalphabetagamma:\n    *factor1 = sin(3*x)/sin(x)*cexp(I*x);\n    *factor2 = 0.;\n    *factor3 = 0.;\n    break;\n  default:\n    printf(\"Error in EvaluateTDIfactor3Chan: tditag not recognized.\\n\");\n    exit(1);\n  }\n  return SUCCESS;\n}\n\n/* Function restoring the factor that have been scaled out of the TDI observables */\n/* NOTE: the operation is made in-place, and the input is overwritten */\nint RestoreInPlaceScaledFactorTDI(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  ListmodesCAmpPhaseFrequencySeries* listtdi,     /* Output/Input: list of mode contributions to TDI observable */\n  TDItag tditag,                                  /* Tag selecting the TDI observable */\n  int nchannel)                                   /* TDI channel number */\n{\n  double complex factor1 = 0;\n  double complex factor2 = 0;\n  double complex factor3 = 0;\n  double complex factor;\n  double complex camp;\n  ListmodesCAmpPhaseFrequencySeries* listelement = listtdi;\n  /* Going throug the list of modes */\n  while(listelement) {\n    gsl_vector* freq = listelement->freqseries->freq;\n    gsl_vector* ampreal = listelement->freqseries->amp_real;\n    gsl_vector* ampimag = listelement->freqseries->amp_imag;\n    for(int i=0; i<freq->size; i++) {\n      ScaledTDIfactor3Chan(variant,&factor1, &factor2, &factor3, gsl_vector_get(freq, i), tditag);\n      switch(nchannel) {\n      case 1: factor = factor1; break;\n      case 2: factor = factor2; break;\n      case 3: factor = factor3; break;\n      }\n      camp = factor * (gsl_vector_get(ampreal, i) + I*gsl_vector_get(ampimag, i));\n      gsl_vector_set(ampreal, i, creal(camp));\n      gsl_vector_set(ampimag, i, cimag(camp));\n    }\n    listelement = listelement->next;\n  }\n  return SUCCESS;\n}\n\n\n/* Functions evaluating the Fourier-domain factors (combinations of the GAB's) for TDI observables */\n/* int EvaluateTDIfactor1Chan( */\n/*   double complex* factor,                        /\\* Output for factor for TDI channel *\\/ */\n/*   const double complex G12,                      /\\* Input for G12 *\\/ */\n/*   const double complex G21,                      /\\* Input for G21 *\\/ */\n/*   const double complex G23,                      /\\* Input for G23 *\\/ */\n/*   const double complex G32,                      /\\* Input for G32 *\\/ */\n/*   const double complex G31,                      /\\* Input for G31 *\\/ */\n/*   const double complex G13,                      /\\* Input for G13 *\\/ */\n/*   const double f,                                /\\* Frequency *\\/ */\n/*   const TDItag tditag)                           /\\* Selector for the TDI observables *\\/ */\n/* { */\n/*   /\\* Notation: x=pifL, z = e^2ix*\\/ */\n/*   double x = PI*f*variant->ConstL/C_SI; */\n/*   double complex z = cexp(2*I*x); */\n/*   double sin2x = sin(2*x); */\n/*   double complex commonfac; */\n/*   switch(tditag) { */\n/*   /\\* First-generation TDI XYZ *\\/ */\n/*   case TDIX: { */\n/*     commonfac = 2*I*z*sin2x; */\n/*     *factor = commonfac * (G21 + z*G12 - G31 - z*G13); } */\n/*   case TDIY: { */\n/*     commonfac = 2*I*z*sin2x; */\n/*     *factor = commonfac * (G32 + z*G23 - G12 - z*G21); } */\n/*   case TDIZ: { */\n/*     commonfac = 2*I*z*sin2x; */\n/*     *factor = commonfac * (G13 + z*G31 - G23 - z*G32); } */\n/*   /\\* First-generation TDI alpha beta gamma *\\/ */\n/*   case TDIalpha: { */\n/*     *factor = G21-G31 + z*(G13-G12) + z*z*(G32-G23); } */\n/*   case TDIbeta: { */\n/*     *factor = G32-G12 + z*(G21-G23) + z*z*(G13-G31); } */\n/*   case TDIgamma: { */\n/*     *factor = G13-G23 + z*(G32-G31) + z*z*(G21-G12); } */\n/*   /\\* First-generation rescaled TDI aet from X,Y,Z *\\/ */\n/*   /\\* With x=pifL, factors scaled out: A,E I*sqrt2*sin2x*eix - T 2*sqrt2*sin2x*sinx*e2ix *\\/ */\n/*   case TDIAXYZ: { */\n/*     *factor = 0.5 * ( (1.+z)*(G31+G13) - G23 - z*G32 - G21 - z*G12 ); } */\n/*   case TDIEXYZ: { */\n/*     *factor = 0.5*invsqrt3 * ( (1.-z)*(G13-G31) + (2.+z)*(G12-G32) + (1.+2*z)*(G12-G23) ); } */\n/*   case TDITXYZ: { */\n/*     *factor = invsqrt6 * ( G21-G12 + G32-G23 + G13-G31); } */\n/*   /\\* First-generation rescaled TDI aet from alpha, beta, gamma *\\/ */\n/*   /\\* With x=pifL, factors scaled out: A,E -I*2sqrt2*sinx*eix - T sinx/(sin3x*eix) *\\/ */\n/*   case TDIAalphabetagamma: { */\n/*     *factor = 0.5 * (G13+G31 + z*(G12+G32) - (1.+z)*(G21+G13)); } */\n/*   case TDIEalphabetagamma: { */\n/*     *factor = 0.5*invsqrt3 * ((2+z)*(G12-G32) + (1+z)*(G21-G23) + (1.+2*z)*(G13-G31)); } */\n/*   case TDITalphabetagamma: { */\n/*     *factor = invsqrt3 * (G21-G12 + G32-G23 + G13-G31); } */\n/*   default: { */\n/*     printf(\"Error in EvaluateTDIfactor3Chan: tditag not recognized.\"); */\n/*     exit(1); } */\n/*   } */\n/* } */\n\n/*********************** Time-domain response ************************/\n\n/* Processing single mode in amp/phase form through orbital time delay */\nstatic double hOTDAmpPhase(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  double* amp,                             /* Output: amplitude */\n  double* phase,                           /* Output: phase */\n  gsl_spline* splineamp,                   /* Input spline for TD mode amplitude */\n  gsl_spline* splinephase,                 /* Input spline for TD mode phase */\n  gsl_interp_accel* accelamp,              /* Accelerator for amp spline */\n  gsl_interp_accel* accelphase,            /* Accelerator for phase spline */\n  const double t)                          /* Time */\n{\n  double tphase=variant->ConstOmega*t + variant->ConstPhi0;\n  /* Precompute array of sine/cosine */\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * tphase);\n    sinarray[j] = sin((j+1) * tphase);\n  }\n  /* Scalar product k.R */\n  double kR = coeffkRconst;\n  for(int j=0; j<2; j++) {\n    kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j];\n  }\n  /* Common factor and delay */\n  double delay = -(kR*variant->OrbitR)/C_SI;\n\n  /* Output result */\n  *amp = gsl_spline_eval(splineamp, t+delay, accelamp);\n  *phase = gsl_spline_eval(splinephase, t+delay, accelphase);\n}\n\n/* Functions evaluating yAB observables in time domain - constellation response only */\n/* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */\nstatic double y12LTDfromh22AmpPhase(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  gsl_spline* splineamp,                   /* Input spline for h22 TD amp */\n  gsl_spline* splinephase,                 /* Input spline for h22 TD phase */\n  gsl_interp_accel* accelamp,              /* Accelerator for amp spline */\n  gsl_interp_accel* accelphase,            /* Accelerator for phase spline */\n  double complex Y22,                      /* Y22 factor needed to convert h22 to hplus, hcross */\n  double complex Y2m2,                     /* Y2-2 factor needed to convert h2-2 to hplus, hcross */\n  const double t)                          /* Time */\n{\n  /* Precompute array of sine/cosine */\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  /* Scalar products with k */\n  double n3Pn3plus = coeffn3Hn3plusconst;\n  double n3Pn3cross = coeffn3Hn3crossconst;\n  for(int j=0; j<4; j++) {\n    n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j];\n    n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j];\n  }\n  /* Scalar products with k */\n  double kn3 = coeffkn3const;\n  double kp1 = coeffkp1const;\n  double kp2 = coeffkp2const;\n  for(int j=0; j<2; j++) {\n    kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j];\n    kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j];\n    kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j];\n  }\n  /* Common factor and delay */\n  double factorp = (1./(1.-kn3)) * 0.5*n3Pn3plus;\n  double factorc = (1./(1.-kn3)) * 0.5*n3Pn3cross;\n  double firstdelay = -((kp1 + 1)*variant->ConstL)/C_SI;\n  double seconddelay = -(kp2*variant->ConstL)/C_SI;\n\n  /* Values of Y22*h22 + Y2-2*h2-2 at 1 and 2 with delays, and hplus, hcross */\n  /* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */\n  double A22at1 = gsl_spline_eval(splineamp, t+firstdelay, accelamp);\n  double phi22at1 = gsl_spline_eval(splinephase, t+firstdelay, accelphase);\n  double A22at2 = gsl_spline_eval(splineamp, t+seconddelay, accelamp);\n  double phi22at2 = gsl_spline_eval(splinephase, t+seconddelay, accelphase);\n  double complex Y22h22at1 = Y22 * A22at1 * cexp(I*phi22at1);\n  double complex Y22h22at2 = Y22 * A22at2 * cexp(I*phi22at2);\n  double complex Y2m2h2m2at1 = Y2m2 * A22at1 * cexp(-I*phi22at1);\n  double complex Y2m2h2m2at2 = Y2m2 * A22at2 * cexp(-I*phi22at2);\n  double hp1 = creal(Y22h22at1 + Y2m2h2m2at1);\n  double hc1 = -cimag(Y22h22at1 + Y2m2h2m2at1);\n  double hp2 = creal(Y22h22at2 + Y2m2h2m2at2);\n  double hc2 = -cimag(Y22h22at2 + Y2m2h2m2at2);\n\n  /* Result */\n  double y12 = factorp*(hp1 - hp2) + factorc*(hc1 - hc2);\n  return y12;\n}\n\n/* Functions evaluating yAB observables in time domain - orbital and constellation response */\n/* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */\nstatic double y12TDfromh22AmpPhase(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  gsl_spline* splineamp,                   /* Input spline for h22 TD amp */\n  gsl_spline* splinephase,                 /* Input spline for h22 TD phase */\n  gsl_interp_accel* accelamp,              /* Accelerator for amp spline */\n  gsl_interp_accel* accelphase,            /* Accelerator for phase spline */\n  double complex Y22,                      /* Y22 factor needed to convert h22 to hplus, hcross */\n  double complex Y2m2,                     /* Y2-2 factor needed to convert h2-2 to hplus, hcross */\n  const double t)                          /* Time */\n{\n  /* Precompute array of sine/cosine */\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  /* Scalar product k.R */\n  double kR = coeffkRconst;\n  for(int j=0; j<2; j++) {\n    kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j];\n  }\n  /* Common factor and delay */\n  double delay0 = -(kR*variant->OrbitR)/C_SI;\n  /* Scalar products with k */\n  double n3Pn3plus = coeffn3Hn3plusconst;\n  double n3Pn3cross = coeffn3Hn3crossconst;\n  for(int j=0; j<4; j++) {\n    n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j];\n    n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j];\n  }\n  /* Scalar products with k */\n  double kn3 = coeffkn3const;\n  double kp1 = coeffkp1const;\n  double kp2 = coeffkp2const;\n  for(int j=0; j<2; j++) {\n    kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j];\n    kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j];\n    kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j];\n  }\n  /* Common factor and delay */\n  double factorp = (1./(1.-kn3)) * 0.5*n3Pn3plus;\n  double factorc = (1./(1.-kn3)) * 0.5*n3Pn3cross;\n  double firstdelay = delay0 - ((kp1 + 1)*variant->ConstL)/C_SI;\n  double seconddelay = delay0 - (kp2*variant->ConstL)/C_SI;\n\n  /* Values of Y22*h22 + Y2-2*h2-2 at 1 and 2 with delays, and hplus, hcross */\n  /* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */\n  double A22at1 = gsl_spline_eval(splineamp, t+firstdelay, accelamp);\n  double phi22at1 = gsl_spline_eval(splinephase, t+firstdelay, accelphase);\n  double A22at2 = gsl_spline_eval(splineamp, t+seconddelay, accelamp);\n  double phi22at2 = gsl_spline_eval(splinephase, t+seconddelay, accelphase);\n  double complex Y22h22at1 = Y22 * A22at1 * cexp(I*phi22at1);\n  double complex Y22h22at2 = Y22 * A22at2 * cexp(I*phi22at2);\n  double complex Y2m2h2m2at1 = Y2m2 * A22at1 * cexp(-I*phi22at1);\n  double complex Y2m2h2m2at2 = Y2m2 * A22at2 * cexp(-I*phi22at2);\n  double hp1 = creal(Y22h22at1 + Y2m2h2m2at1);\n  double hc1 = -cimag(Y22h22at1 + Y2m2h2m2at1);\n  double hp2 = creal(Y22h22at2 + Y2m2h2m2at2);\n  double hc2 = -cimag(Y22h22at2 + Y2m2h2m2at2);\n\n  /* Result */\n  double y12 = factorp*(hp1 - hp2) + factorc*(hc1 - hc2);\n  return y12;\n}\n\n/* Functions evaluating yAB observables in time domain */\ndouble y12TD(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  gsl_spline* splinehp,                    /* Input spline for TD hplus */\n  gsl_spline* splinehc,                    /* Input spline for TD hcross */\n  gsl_interp_accel* accelhp,               /* Accelerator for hp spline */\n  gsl_interp_accel* accelhc,               /* Accelerator for hc spline */\n  const double t)                          /* Time */\n{\n  /* Precompute array of sine/cosine */\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  /* Scalar products with k */\n  double n3Pn3plus = coeffn3Hn3plusconst;\n  double n3Pn3cross = coeffn3Hn3crossconst;\n  for(int j=0; j<4; j++) {\n    n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j];\n    n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j];\n  }\n  /* Scalar products with k */\n  double kn3 = coeffkn3const;\n  double kp1 = coeffkp1const;\n  double kp2 = coeffkp2const;\n  double kR = coeffkRconst;\n  for(int j=0; j<2; j++) {\n    kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j];\n    kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j];\n    kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j];\n    kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j];\n  }\n  /* Common factor and delay */\n  double factorp = (1./(1.-kn3)) * 0.5*n3Pn3plus;\n  double factorc = (1./(1.-kn3)) * 0.5*n3Pn3cross;\n  double firstdelay = -(kR*variant->OrbitR + (kp1 + 1)*variant->ConstL)/C_SI;\n  double seconddelay = -(kR*variant->OrbitR + kp2*variant->ConstL)/C_SI;\n\n  /* Result */\n  double y12 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc));\n  return y12;\n}\n\ndouble y21TD(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  gsl_spline* splinehp,                    /* Input spline for TD hplus */\n  gsl_spline* splinehc,                    /* Input spline for TD hcross */\n  gsl_interp_accel* accelhp,               /* Accelerator for hp spline */\n  gsl_interp_accel* accelhc,               /* Accelerator for hc spline */\n  const double t)                          /* Time */\n{\n  /* Precompute array of sine/cosine */\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  /* Scalar products with k */\n  double n3Pn3plus = coeffn3Hn3plusconst;\n  double n3Pn3cross = coeffn3Hn3crossconst;\n  for(int j=0; j<4; j++) {\n    n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j];\n    n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j];\n  }\n  /* Scalar products with k */\n  double kn3 = coeffkn3const;\n  double kp1 = coeffkp1const;\n  double kp2 = coeffkp2const;\n  double kR = coeffkRconst;\n  for(int j=0; j<2; j++) {\n    kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j];\n    kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j];\n    kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j];\n    kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j];\n  }\n  /* Common factor and delay */\n  double factorp = (1./(1.+kn3)) * 0.5*n3Pn3plus;\n  double factorc = (1./(1.+kn3)) * 0.5*n3Pn3cross;\n  double firstdelay = -(kR*variant->OrbitR + (kp2 + 1)*variant->ConstL)/C_SI;\n  double seconddelay = -(kR*variant->OrbitR + kp1*variant->ConstL)/C_SI;\n\n  /* Result */\n  double y21 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc));\n  return y21;\n}\ndouble y23TD(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  gsl_spline* splinehp,                    /* Input spline for TD hplus */\n  gsl_spline* splinehc,                    /* Input spline for TD hcross */\n  gsl_interp_accel* accelhp,               /* Accelerator for hp spline */\n  gsl_interp_accel* accelhc,               /* Accelerator for hc spline */\n  const double t)                          /* Time */\n{\n  /* Precompute array of sine/cosine */\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  /* Scalar products with k */\n  double n1Pn1plus = coeffn1Hn1plusconst;\n  double n1Pn1cross = coeffn1Hn1crossconst;\n  for(int j=0; j<4; j++) {\n    n1Pn1plus += cosarray[j] * coeffn1Hn1pluscos[j] + sinarray[j] * coeffn1Hn1plussin[j];\n    n1Pn1cross += cosarray[j] * coeffn1Hn1crosscos[j] + sinarray[j] * coeffn1Hn1crosssin[j];\n  }\n  /* Scalar products with k */\n  double kn1 = coeffkn1const;\n  double kp2 = coeffkp2const;\n  double kp3 = coeffkp3const;\n  double kR = coeffkRconst;\n  for(int j=0; j<2; j++) {\n    kn1 += cosarray[j] * coeffkn1cos[j] + sinarray[j] * coeffkn1sin[j];\n    kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j];\n    kp3 += cosarray[j] * coeffkp3cos[j] + sinarray[j] * coeffkp3sin[j];\n    kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j];\n  }\n  /* Common factor and delay */\n  double factorp = (1./(1.-kn1)) * 0.5*n1Pn1plus;\n  double factorc = (1./(1.-kn1)) * 0.5*n1Pn1cross;\n  double firstdelay = -(kR*variant->OrbitR + (kp2 + 1)*variant->ConstL)/C_SI;\n  double seconddelay = -(kR*variant->OrbitR + kp3*variant->ConstL)/C_SI;\n\n  /* Result */\n  double y23 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc));\n  return y23;\n}\ndouble y32TD(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  gsl_spline* splinehp,                    /* Input spline for TD hplus */\n  gsl_spline* splinehc,                    /* Input spline for TD hcross */\n  gsl_interp_accel* accelhp,               /* Accelerator for hp spline */\n  gsl_interp_accel* accelhc,               /* Accelerator for hc spline */\n  const double t)                          /* Time */\n{\n  /* Precompute array of sine/cosine */\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  /* Scalar products with k */\n  double n1Pn1plus = coeffn1Hn1plusconst;\n  double n1Pn1cross = coeffn1Hn1crossconst;\n  for(int j=0; j<4; j++) {\n    n1Pn1plus += cosarray[j] * coeffn1Hn1pluscos[j] + sinarray[j] * coeffn1Hn1plussin[j];\n    n1Pn1cross += cosarray[j] * coeffn1Hn1crosscos[j] + sinarray[j] * coeffn1Hn1crosssin[j];\n  }\n  /* Scalar products with k */\n  double kn1 = coeffkn1const;\n  double kp2 = coeffkp2const;\n  double kp3 = coeffkp3const;\n  double kR = coeffkRconst;\n  for(int j=0; j<2; j++) {\n    kn1 += cosarray[j] * coeffkn1cos[j] + sinarray[j] * coeffkn1sin[j];\n    kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j];\n    kp3 += cosarray[j] * coeffkp3cos[j] + sinarray[j] * coeffkp3sin[j];\n    kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j];\n  }\n  /* Common factor and delay */\n  double factorp = (1./(1.+kn1)) * 0.5*n1Pn1plus;\n  double factorc = (1./(1.+kn1)) * 0.5*n1Pn1cross;\n  double firstdelay = -(kR*variant->OrbitR + (kp3 + 1)*variant->ConstL)/C_SI;\n  double seconddelay = -(kR*variant->OrbitR + kp2*variant->ConstL)/C_SI;\n\n  /* Result */\n  double y32 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc));\n  return y32;\n}\ndouble y31TD(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  gsl_spline* splinehp,                    /* Input spline for TD hplus */\n  gsl_spline* splinehc,                    /* Input spline for TD hcross */\n  gsl_interp_accel* accelhp,               /* Accelerator for hp spline */\n  gsl_interp_accel* accelhc,               /* Accelerator for hc spline */\n  const double t)                          /* Time */\n{\n  /* Precompute array of sine/cosine */\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  /* Scalar products with k */\n  double n2Pn2plus = coeffn2Hn2plusconst;\n  double n2Pn2cross = coeffn2Hn2crossconst;\n  for(int j=0; j<4; j++) {\n    n2Pn2plus += cosarray[j] * coeffn2Hn2pluscos[j] + sinarray[j] * coeffn2Hn2plussin[j];\n    n2Pn2cross += cosarray[j] * coeffn2Hn2crosscos[j] + sinarray[j] * coeffn2Hn2crosssin[j];\n  }\n  /* Scalar products with k */\n  double kn2 = coeffkn2const;\n  double kp3 = coeffkp3const;\n  double kp1 = coeffkp1const;\n  double kR = coeffkRconst;\n  for(int j=0; j<2; j++) {\n    kn2 += cosarray[j] * coeffkn2cos[j] + sinarray[j] * coeffkn2sin[j];\n    kp3 += cosarray[j] * coeffkp3cos[j] + sinarray[j] * coeffkp3sin[j];\n    kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j];\n    kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j];\n  }\n  /* Common factor and delay */\n  double factorp = (1./(1.-kn2)) * 0.5*n2Pn2plus;\n  double factorc = (1./(1.-kn2)) * 0.5*n2Pn2cross;\n  double firstdelay = -(kR*variant->OrbitR + (kp3 + 1)*variant->ConstL)/C_SI;\n  double seconddelay = -(kR*variant->OrbitR + kp1*variant->ConstL)/C_SI;\n\n  /* Result */\n  double y31 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc));\n  return y31;\n}\ndouble y13TD(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  gsl_spline* splinehp,                    /* Input spline for TD hplus */\n  gsl_spline* splinehc,                    /* Input spline for TD hcross */\n  gsl_interp_accel* accelhp,               /* Accelerator for hp spline */\n  gsl_interp_accel* accelhc,               /* Accelerator for hc spline */\n  const double t)                          /* Time */\n{\n  /* Precompute array of sine/cosine */\n  double phase=variant->ConstOmega*t + variant->ConstPhi0;\n  for(int j=0; j<4; j++) {\n    cosarray[j] = cos((j+1) * phase);\n    sinarray[j] = sin((j+1) * phase);\n  }\n  /* Scalar products with k */\n  double n2Pn2plus = coeffn2Hn2plusconst;\n  double n2Pn2cross = coeffn2Hn2crossconst;\n  for(int j=0; j<4; j++) {\n    n2Pn2plus += cosarray[j] * coeffn2Hn2pluscos[j] + sinarray[j] * coeffn2Hn2plussin[j];\n    n2Pn2cross += cosarray[j] * coeffn2Hn2crosscos[j] + sinarray[j] * coeffn2Hn2crosssin[j];\n  }\n  /* Scalar products with k */\n  double kn2 = coeffkn2const;\n  double kp3 = coeffkp3const;\n  double kp1 = coeffkp1const;\n  double kR = coeffkRconst;\n  for(int j=0; j<2; j++) {\n    kn2 += cosarray[j] * coeffkn2cos[j] + sinarray[j] * coeffkn2sin[j];\n    kp3 += cosarray[j] * coeffkp3cos[j] + sinarray[j] * coeffkp3sin[j];\n    kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j];\n    kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j];\n  }\n  /* Common factor and delay */\n  double factorp = (1./(1.+kn2)) * 0.5*n2Pn2plus;\n  double factorc = (1./(1.+kn2)) * 0.5*n2Pn2cross;\n  double firstdelay = -(kR*variant->OrbitR + (kp1 + 1)*variant->ConstL)/C_SI;\n  double seconddelay = -(kR*variant->OrbitR + kp3*variant->ConstL)/C_SI;\n\n  /* Result */\n  double y13 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc));\n  return y13;\n}\n\n/**/\nint EvaluateTDIXYZTD(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  double* TDIX,                            /* Output: value of TDI observable X */\n  double* TDIY,                            /* Output: value of TDI observable Y */\n  double* TDIZ,                            /* Output: value of TDI observable Z */\n  gsl_spline* splinehp,                    /* Input spline for TD hplus */\n  gsl_spline* splinehc,                    /* Input spline for TD hcross */\n  gsl_interp_accel* accelhp,               /* Accelerator for hp spline */\n  gsl_interp_accel* accelhc,               /* Accelerator for hc spline */\n  const double t)                          /* Time */\n{\n  double armdelay = variant->ConstL/C_SI;\n  double X = (y31TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y21TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay));\n  double Y = (y12TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y32TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay));\n  double Z = (y23TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y13TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay));\n\n  /* Output */\n  *TDIX = X;\n  *TDIY = Y;\n  *TDIZ = Z;\n\n  return SUCCESS;\n}\n\n/**/\nint EvaluateTDIAETXYZTD(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  double* TDIA,                            /* Output: value of TDI observable X */\n  double* TDIE,                            /* Output: value of TDI observable Y */\n  double* TDIT,                            /* Output: value of TDI observable Z */\n  gsl_spline* splinehp,                    /* Input spline for TD hplus */\n  gsl_spline* splinehc,                    /* Input spline for TD hcross */\n  gsl_interp_accel* accelhp,               /* Accelerator for hp spline */\n  gsl_interp_accel* accelhc,               /* Accelerator for hc spline */\n  const double t)                          /* Time */\n{\n  double armdelay = variant->ConstL/C_SI;\n  double X = (y31TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y21TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay));\n  double Y = (y12TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y32TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay));\n  double Z = (y23TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y13TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay));\n\n  /* Output */\n  *TDIA = 1./(2*sqrt(2)) * (Z-X);\n  *TDIE = 1./(2*sqrt(6)) * (X-2*Y+Z);\n  *TDIT = 1./(2*sqrt(3)) * (X+Y+Z);\n\n  return SUCCESS;\n}\n\n/**/\nint GenerateTDITD3Chanhphc(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  RealTimeSeries** TDI1,                   /* Output: real time series for TDI channel 1 */\n  RealTimeSeries** TDI2,                   /* Output: real time series for TDI channel 2 */\n  RealTimeSeries** TDI3,                   /* Output: real time series for TDI channel 3 */\n  gsl_spline* splinehp,                    /* Input spline for TD hplus */\n  gsl_spline* splinehc,                    /* Input spline for TD hcross */\n  gsl_interp_accel* accelhp,               /* Accelerator for hp spline */\n  gsl_interp_accel* accelhc,               /* Accelerator for hc spline */\n  gsl_vector* times,                       /* Vector of times to evaluate */\n  int nbptmargin,                          /* Margin set to 0 on both side to avoid problems with delays out of the domain */\n  TDItag tditag)                           /* Tag selecting the TDI observables */\n{\n  /* Initialize output */\n  int nbpt = times->size;\n  RealTimeSeries_Init(TDI1, nbpt);\n  RealTimeSeries_Init(TDI2, nbpt);\n  RealTimeSeries_Init(TDI3, nbpt);\n  gsl_vector_memcpy((*TDI1)->times, times);\n  gsl_vector_memcpy((*TDI2)->times, times);\n  gsl_vector_memcpy((*TDI3)->times, times);\n  gsl_vector_set_zero((*TDI1)->h);\n  gsl_vector_set_zero((*TDI2)->h);\n  gsl_vector_set_zero((*TDI3)->h);\n\n  /* Loop over time samples - we take a margin to avoid problems with the domain */\n  double t;\n  double* tval = times->data;\n  double* tdi1 = (*TDI1)->h->data;\n  double* tdi2 = (*TDI2)->h->data;\n  double* tdi3 = (*TDI3)->h->data;\n  double tdi1val = 0, tdi2val = 0, tdi3val = 0;\n\n  /* For testing purposes: basic observable yAB */\n  if(tditag==y12) {\n    for(int i=nbptmargin; i<nbpt-nbptmargin; i++) {\n      t = tval[i];\n      tdi1[i] = y12TD(variant, splinehp, splinehc, accelhp, accelhc, t);\n      tdi2[i] = 0.;\n      tdi3[i] = 0.;\n    }\n  }\n  else if(tditag==TDIXYZ) {\n    for(int i=nbptmargin; i<nbpt-nbptmargin; i++) {\n      t = tval[i];\n      EvaluateTDIXYZTD(variant, &tdi1val, &tdi2val, &tdi3val, splinehp, splinehc, accelhp, accelhc, t);\n      tdi1[i] = tdi1val;\n      tdi2[i] = tdi2val;\n      tdi3[i] = tdi3val;\n    }\n  }\n  else if(tditag==TDIAETXYZ) {\n    for(int i=nbptmargin; i<nbpt-nbptmargin; i++) {\n      t = tval[i];\n      EvaluateTDIAETXYZTD(variant, &tdi1val, &tdi2val, &tdi3val, splinehp, splinehc, accelhp, accelhc, t);\n      tdi1[i] = tdi1val;\n      tdi2[i] = tdi2val;\n      tdi3[i] = tdi3val;\n    }\n  }\n  else {\n    printf(\"Error: in GenerateTDITD3Chan, TDI tag not recognized.\\n\");\n  }\n\n  return SUCCESS;\n}\n\n/* Generate hO orbital-delayed for one mode contribution from amp, phase */\nint Generateh22TDO(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  AmpPhaseTimeSeries** h22tdO,             /* Output: amp/phase time series for h22TDO */\n  gsl_spline* splineamp,                   /* Input spline for TD mode amplitude */\n  gsl_spline* splinephase,                 /* Input spline for TD mode phase */\n  gsl_interp_accel* accelamp,              /* Accelerator for amp spline */\n  gsl_interp_accel* accelphase,            /* Accelerator for phase spline */\n  gsl_vector* times,                       /* Vector of times to evaluate */\n  int nbptmargin)                          /* Margin set to 0 on both side to avoid problems with delays out of the domain */\n{\n  /* Initialize output */\n  int nbpt = times->size;\n  AmpPhaseTimeSeries_Init(h22tdO, nbpt);\n  gsl_vector_memcpy((*h22tdO)->times, times);\n  gsl_vector_set_zero((*h22tdO)->h_amp);\n  gsl_vector_set_zero((*h22tdO)->h_phase);\n\n  /* Loop over time samples - we take a margin to avoid problems with the domain */\n  double t;\n  double* tval = times->data;\n  double* amp = (*h22tdO)->h_amp->data;\n  double* phase = (*h22tdO)->h_phase->data;\n\n  /* Loop over time samples */\n  for(int i=nbptmargin; i<nbpt-nbptmargin; i++) {\n    t = tval[i];\n    hOTDAmpPhase(variant,&(amp[i]), &(phase[i]), splineamp, splinephase, accelamp, accelphase, t);\n  }\n\n  return SUCCESS;\n}\n\n/* Generate y12L from orbital-delayed h22 in amp/phase form */\n/* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */\n/* BEWARE: this ignores the fact that processing through orbital delay breaks the h2-2 = h22* symmetry */\nint Generatey12LTD(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  RealTimeSeries** y12Ltd,                 /* Output: real time series for y12L */\n  gsl_spline* splineamp,                   /* Input spline for h22 TD amplitude */\n  gsl_spline* splinephase,                 /* Input spline for h22 TD phase */\n  gsl_interp_accel* accelamp,              /* Accelerator for h22 amp spline */\n  gsl_interp_accel* accelphase,            /* Accelerator for h22 phase spline */\n  gsl_vector* times,                       /* Vector of times to evaluate */\n  double Theta,                            /* Inclination */\n  double Phi,                              /* Phase */\n  int nbptmargin)                          /* Margin set to 0 on both side to avoid problems with delays out of the domain */\n{\n  /* Initialize output */\n  int nbpt = times->size;\n  RealTimeSeries_Init(y12Ltd, nbpt);\n  gsl_vector_memcpy((*y12Ltd)->times, times);\n  gsl_vector_set_zero((*y12Ltd)->h);\n\n  /* Spin-weighted spherical harmonic Y22 and Y2-2 */\n  double complex Y22 = SpinWeightedSphericalHarmonic(Theta, Phi, -2, 2, 2);\n  double complex Y2m2 = SpinWeightedSphericalHarmonic(Theta, Phi, -2, 2, -2);\n\n  /* Loop over time samples - we take a margin to avoid problems with the domain */\n  double t;\n  double* tval = times->data;\n  double* y12val = (*y12Ltd)->h->data;\n\n  /* Loop over time samples */\n  for(int i=nbptmargin; i<nbpt-nbptmargin; i++) {\n    t = tval[i];\n    y12val[i] = y12LTDfromh22AmpPhase(variant, splineamp, splinephase, accelamp, accelphase, Y22, Y2m2, t);\n  }\n\n  return SUCCESS;\n}\n\n/* Generate y12 from original h22 in amp/phase form, including both  */\n/* Here no approximation made as to the decomposition of the response in two steps, all the response is evaluated at once */\n/* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */\nint Generatey12TD(\n  const LISAconstellation *variant,    /* Description of LISA variant */\n  RealTimeSeries** y12td,                 /* Output: real time series for y12L */\n  gsl_spline* splineamp,                   /* Input spline for h22 TD amplitude */\n  gsl_spline* splinephase,                 /* Input spline for h22 TD phase */\n  gsl_interp_accel* accelamp,              /* Accelerator for h22 amp spline */\n  gsl_interp_accel* accelphase,            /* Accelerator for h22 phase spline */\n  gsl_vector* times,                       /* Vector of times to evaluate */\n  double Theta,                            /* Inclination */\n  double Phi,                              /* Phase */\n  int nbptmargin)                          /* Margin set to 0 on both side to avoid problems with delays out of the domain */\n{\n  /* Initialize output */\n  int nbpt = times->size;\n  RealTimeSeries_Init(y12td, nbpt);\n  gsl_vector_memcpy((*y12td)->times, times);\n  gsl_vector_set_zero((*y12td)->h);\n\n  /* Spin-weighted spherical harmonic Y22 and Y2-2 */\n  double complex Y22 = SpinWeightedSphericalHarmonic(Theta, Phi, -2, 2, 2);\n  double complex Y2m2 = SpinWeightedSphericalHarmonic(Theta, Phi, -2, 2, -2);\n\n  /* Loop over time samples - we take a margin to avoid problems with the domain */\n  double t;\n  double* tval = times->data;\n  double* y12val = (*y12td)->h->data;\n\n  /* Loop over time samples */\n  for(int i=nbptmargin; i<nbpt-nbptmargin; i++) {\n    t = tval[i];\n    y12val[i] = y12TDfromh22AmpPhase(variant, splineamp, splinephase, accelamp, accelphase, Y22, Y2m2, t);\n  }\n\n  return SUCCESS;\n}\n", "meta": {"hexsha": "ae1a058cf546f69e8af0e422d187284bc5f32ab1", "size": 99961, "ext": "c", "lang": "C", "max_stars_repo_path": "LISAsim/LISAgeometry.c", "max_stars_repo_name": "JohnGBaker/flare", "max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "LISAsim/LISAgeometry.c", "max_issues_repo_name": "JohnGBaker/flare", "max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LISAsim/LISAgeometry.c", "max_forks_repo_name": "JohnGBaker/flare", "max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 56.7315550511, "max_line_length": 1269, "alphanum_fraction": 0.6913396225, "num_tokens": 32496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.38153595472740087}}
{"text": "#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <gsl/gsl_statistics_double.h>\n#include \"tz_error.h\"\n#include \"tz_constant.h\"\n#include \"tz_iarray.h\"\n#include \"tz_image_lib.h\"\n#include \"tz_objdetect.h\"\n#include \"tz_imatrix.h\"\n#include \"tz_stack_math.h\"\n#include \"tz_stack_bwdist.h\"\n#include \"tz_pixel_array.h\"\n#include \"tz_stack_bwmorph.h\"\n#include \"tz_dimage_lib.h\"\n#include \"tz_darray.h\"\n#include \"tz_u8array.h\"\n#include \"tz_stack_objlabel.h\"\n#include \"tz_voxel_linked_list.h\"\n#include \"tz_voxel_graphics.h\"\n#include \"tz_dmatrix.h\"\n#include \"tz_stack_sampling.h\"\n#include \"tz_stack_threshold.h\"\n\nINIT_EXCEPTION_MAIN(e)\n\nint main(int argc, char* argv[]) \n{\n  char neuron_name[100];\n  if (argc == 1) {\n    strcpy(neuron_name, \"fly_neuron\");\n  } else {\n    strcpy(neuron_name, argv[1]);\n  }\n\n  char file_path[100];\n  sprintf(file_path, \"../data/%s/mask.tif\", neuron_name);\n\n  Stack *mask = Read_Stack(file_path);\n\n  sprintf(file_path, \"../data/%s/seeds.pa\", neuron_name);\n  Pixel_Array *pa = Pixel_Array_Read(file_path);\n  double *pa_array = (double *) pa->array;\n  \n  sprintf(file_path, \"../data/%s/seed_offset.ar\", neuron_name);\n  int seed_number = pa->size;\n  int *seed_offset = (int *) malloc(sizeof(int) * seed_number);\n  iarray_read(file_path, seed_offset, &seed_number);\n\n  int max_idx;\n  double max_dist = darray_max(pa_array, pa->size, &max_idx);\n  max_idx = seed_offset[max_idx];\n\n  Stack_Label_Object_Dist_N(mask, NULL, max_idx, 1, 2, max_dist * 2.0, 26);\n\n  Stack_Threshold_Binarize(mask, 1);\n\n  sprintf(file_path, \"../data/%s/blobmask.tif\", neuron_name);\n  Write_Stack(file_path, mask);\n  \n  free(seed_offset);\n  Kill_Stack(mask);\n\n  return 0;\n}\n", "meta": {"hexsha": "34e231d2b300ef35f48151e6d6dbc57beb946f2d", "size": 1676, "ext": "c", "lang": "C", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/single_neuron_blobmask.c", "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/single_neuron_blobmask.c", "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/single_neuron_blobmask.c", "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": ["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.3939393939, "max_line_length": 75, "alphanum_fraction": 0.7153937947, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.38137377759292146}}
{"text": "/**\n * @file bblas_ztesting.c\n *\n * @brief BBLAS testing  for double _Complex routines.\n *\n * BBLAS is a software package provided by Univ. of Manchester,\n * Univ. of Tennessee.\n *\n * @version 1.0.0\n * @author  Samuel  D. Relton\n * @author  Pedro   V. Lara\n * @author  Mawussi Zounon\n * @date    2016-02-20\n *\n */\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n/**\n * Code generation\n * @precisions normal z -> c d s\n **/\n#endif\n\n#include \"bblas_common.h\"\n#if defined(BBLAS_WITH_MKL)\n#include <mkl_lapacke.h>\n#else\n#include <lapacke.h>\n#endif\n#include <cblas.h>\n\n\n\n#define COMPLEX\n\n/**\n * Initialize test parameters to their default values.\n **/\n\nvoid bblas_zinit_config (bblas_ztest_t *test)\n{\n    test->gen_uplo       =1;\n    test->gen_transA     =1;\n    test->gen_transB     =1;\n    test->gen_trans      =1;\n    test->gen_side       =1;\n    test->gen_diag       =1;\n    test->minM           = 0;\n    test->minN           = 0;\n    test->minK           = 0;\n    test->maxM           = 0;\n    test->maxN           = 0;\n    test->maxK           = 0;\n    test->minbatch_count = 1;\n    test->maxbatch_count = 1;\n    test->batch_opts     = 0;\n    test->routine        = 1;\n    test->nb_test        = 1;\n    test->set_error      = 0;\n    test->global_error   = 0;\n    test->faulty_iter    = 0;\n    test->mkl_sequential = 0;\n    test->new_accuracy   = 1;\n}\n\n/**\n * Set the values of all the BBLAS parameters inside the test structure.\n **/\n\nvoid bblas_zsettest(bblas_ztest_t *test)\n{\n\n    enum BBLAS_ROUTINE routine = test->routine;\n\n    /*\n     * Set the value of batch count\n     */\n    bblas_zset_batch_count(test);\n\n    /*\n     * Allocate memory and set values for uplo\n     */\n    if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||\n\t(routine == BBLAS_SYRK) || (routine == BBLAS_HERK) ||\n\t(routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)||\n\t(routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n    {\n\tbblas_zsetuplo(test);\n    }\n\n    /*\n     * Allocate memory and set values for transA\n     */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_TRMM) ||\n\t(routine == BBLAS_TRSM))\n    {\n\tbblas_zsettransA(test);\n    }\n\n    /*\n     * Allocate memory and set values for transB\n     */\n    if (routine == BBLAS_GEMM)\n    {\n\tbblas_zsettransB(test);\n    }\n\n    /*\n     * Allocate memory and set values for trans\n     */\n    if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) ||\n\t(routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))\n    {\n\tbblas_zsettrans(test);\n    }\n\n    /*\n     * Allocate memory and set values for side\n     */\n    if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||\n\t(routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n    {\n\tbblas_zsetside(test);\n    }\n\n    /*\n     * Allocate memory and set values for diag\n     */\n    if  ((routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n    {\n\tbblas_zsetdiag(test);\n    }\n\n    /*\n     * Allocate memory and set values for  M\n     */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) ||\n\t(routine == BBLAS_TRSM))\n    {\n\tbblas_zsetM(test);\n    }\n\n    /*\n     * Allocate memory and set values for N, all routines\n     */\n    bblas_zsetN(test);\n\n    /*\n     * Allocate memory and set values for K\n     */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK)  ||\n\t(routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) ||\n\t(routine == BBLAS_HER2K))\n    {\n\tbblas_zsetK(test);\n    }\n\n    /*\n     * Allocate memory and set values for lda, all routines\n     */\n    bblas_zsetlda(test);\n\n    /*\n     * Allocate memory and set values for ldb, all routines\n     */\n    if ((routine == BBLAS_GEMM)  || (routine == BBLAS_SYMM)  ||\n\t(routine == BBLAS_HEMM)  || (routine == BBLAS_SYR2K) ||\n\t(routine == BBLAS_HER2K) || (routine == BBLAS_TRMM)  ||\n\t(routine == BBLAS_TRSM))\n    {\n\tbblas_zsetldb(test);\n    }\n\n    /*\n     * Allocate memory and set values for ldc, all routines\n     */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) ||\n\t(routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)||\n\t(routine == BBLAS_HER2K))\n    {\n\tbblas_zsetldc(test);\n    }\n\n    /*\n     * Allocate memory and set values for alpha, all routines\n     */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) || (routine == BBLAS_SYRK)  ||\n\t(routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)||\n\t(routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n    {\n\tbblas_zsetalpha(test);\n    }\n\n    /*\n     * Allocate memory and set values for alpha\n     */\n    if (routine == BBLAS_HERK)\n    {\n\tbblas_zsetalpha_herk(test);\n    }\n\n\n    /*\n     * Allocate memory and set values for beta\n     */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) ||\n        (routine == BBLAS_SYR2K))\n    {\n\tbblas_zsetbeta(test);\n    }\n\n    /*\n     * Allocate memory and set values for beta_herk\n     */\n    if ((routine == BBLAS_HERK) || (routine == BBLAS_HER2K))\n    {\n\tbblas_zsetbeta_herk(test);\n    }\n\n    /*\n     * Allocate memory and set values for arrayA\n     */\n    bblas_zsetarrayA(test);\n\n    /*\n     * Allocate memory and set values for arrayB\n     */\n    if ((routine == BBLAS_GEMM)  || (routine == BBLAS_SYMM)  ||\n\t(routine == BBLAS_HEMM)  || (routine == BBLAS_SYR2K) ||\n\t(routine == BBLAS_HER2K) || (routine == BBLAS_TRMM)  ||\n\t(routine == BBLAS_TRSM))\n    {\n\tbblas_zsetarrayB(test);\n    }\n\n\n    /*\n     * Allocate memory and set values for arrayC\n     */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) ||\n\t(routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)||\n\t(routine == BBLAS_HER2K))\n    {\n\tbblas_zsetarrayC(test);\n    }\n\n    /* Memory allocation for result and error variables */\n    bblas_zmalloc_result_error(test);\n}\n\n/**\n * Allocate memory and set the values of uplo\n **/\n\nvoid bblas_zsetuplo(bblas_ztest_t *test)\n{\n    int batch_iter;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"uplo\";\n    int random_number;\n    /*Initialize random number generation */\n    srand ( time(NULL) ) ;\n\n    /*Memory allocation */\n    test->uplo =  (enum BBLAS_UPLO*) malloc(nb_data*sizeof(enum BBLAS_UPLO));\n\n    /*Malloc checking */\n    bblas_malloc_check(test->uplo, ptr_name);\n\n    /*set UPLO values */\n    switch (test->gen_uplo)\n    {\n\tcase UPLO_LOWER:\n\n\t    for( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t    {\n\t\ttest->uplo[batch_iter] = BblasLower;\n\t    }\n\t    break;\n\n\tcase UPLO_UPPER:\n\n\t    for( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t    {\n\t\ttest->uplo[batch_iter] = BblasUpper;\n\t    }\n\t    break;\n\n\tdefault:\n\t    for( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t    {\n\t\t/*Generate a random number */\n\t\trandom_number = rand() % 100;\n\n\t\tif (random_number < 50 )\n\t\t{\n\t\t    test->uplo[batch_iter] = BblasLower;\n\n\t\t}else\n\t\t{\n\t\t    test->uplo[batch_iter] = BblasUpper;\n\t\t}\n\t\tbreak;\n\t    }\n    }\n}\n\n\n/**\n * Allocate memory and set the values of transA\n **/\n\nvoid bblas_zsettransA(bblas_ztest_t *test)\n{\n    int batch_iter;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"transA\";\n    int random_number;\n\n    /*Initialize random number generation */\n    srand ( time(NULL) ) ;\n\n    /*Memory allocation */\n    test->transA =  (enum BBLAS_TRANS*) malloc(nb_data*sizeof(enum BBLAS_TRANS));\n\n    /*Malloc checking */\n    bblas_malloc_check(test->transA, ptr_name);\n\n    /*set transA */\n    switch (test->gen_transA)\n    {\n\tcase NO_TRANS:\n\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\ttest->transA[batch_iter] = BblasNoTrans;\n\t    }\n\t    break;\n\n\tcase TRANS:\n\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\ttest->transA[batch_iter] = BblasTrans;\n\t    }\n\t    break;\n\n\tcase CONJ:\n\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\ttest->transA[batch_iter] = BblasConjTrans;\n\t    }\n\t    break;\n\n\tdefault:\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\t/*Generate a random number */\n\t\trandom_number = rand() % 100;\n\n\t\tif (random_number < 50)\n\t\t{\n\t\t    test->transA[batch_iter] = BblasNoTrans;\n\n\t\t}else if (random_number < 80)\n\t\t{\n\t\t    test->transA[batch_iter] = BblasTrans;\n\t\t}else\n\t\t{\n\t\t    test->transA[batch_iter] = BblasConjTrans;\n\t\t}\n\t    }\n\t    break;\n    }\n}\n\n/**\n * Allocate memory and set the values of transB\n **/\n\nvoid bblas_zsettransB(bblas_ztest_t *test)\n{\n    int batch_iter;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"transB\";\n    int random_number;\n\n    /*Initialize random number generation */\n    srand ( time(NULL) ) ;\n\n    /*Memory allocation for transB */\n    test->transB =  (enum BBLAS_TRANS*) malloc(nb_data*sizeof(enum BBLAS_TRANS));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->transB, ptr_name);\n\n    /*set transB */\n    switch (test->gen_transB)\n    {\n\tcase NO_TRANS:\n\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\ttest->transB[batch_iter] = BblasNoTrans;\n\t    }\n\t    break;\n\n\tcase TRANS:\n\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\ttest->transB[batch_iter] = BblasTrans;\n\t    }\n\t    break;\n\n\tcase CONJ:\n\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\ttest->transB[batch_iter] = BblasConjTrans;\n\t    }\n\t    break;\n\n\tdefault:\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\t/*Generate a random number */\n\t\trandom_number = rand() % 100;\n\n\t\tif (random_number < 50)\n\t\t{\n\t\t    test->transB[batch_iter] = BblasNoTrans;\n\n\t\t}else if (random_number < 80)\n\t\t{\n\t\t    test->transB[batch_iter] = BblasTrans;\n\t\t}else\n\t\t{\n\t\t    test->transB[batch_iter] = BblasConjTrans;\n\t\t}\n\t    }\n\t    break;\n    }\n\n}\n\n\n/**\n * Allocate memory and set the values of trans\n **/\n\nvoid bblas_zsettrans(bblas_ztest_t *test)\n{\n    int batch_iter;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"trans\";\n    int random_number;\n\n    /*Initialize random number generation */\n    srand ( time(NULL) ) ;\n\n    /*Memory allocation for trans */\n    test->trans =  (enum BBLAS_TRANS*) malloc(nb_data*sizeof(enum BBLAS_TRANS));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->trans, ptr_name);\n\n    /*Set the values of trans */\n    switch (test->gen_trans)\n    {\n\tcase NO_TRANS:\n\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\ttest->trans[batch_iter] = BblasNoTrans;\n\t    }\n\t    break;\n\n\tcase TRANS:\n\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\ttest->trans[batch_iter] = BblasTrans;\n\t    }\n\t    break;\n\n\tcase CONJ:\n\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\ttest->trans[batch_iter] = BblasConjTrans;\n\t    }\n\t    break;\n\n\tdefault:\n\t    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t    {\n\t\t/*Generate a random number */\n\t\trandom_number = rand() % 100;\n\n\t\tif (random_number < 50)\n\t\t{\n\t\t    test->trans[batch_iter] = BblasNoTrans;\n\n\t\t}else if (random_number < 80)\n\t\t{\n\t\t    test->trans[batch_iter] = BblasTrans;\n\t\t}else\n\t\t{\n\t\t    test->trans[batch_iter] = BblasConjTrans;\n\t\t}\n\t    }\n\t    break;\n    }\n}\n\n\n\n/**\n * Allocate memory and set the values of side\n **/\n\nvoid bblas_zsetside(bblas_ztest_t *test)\n{\n\n    int batch_iter;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"side\";\n    int random_number;\n\n    /*Initialize random number generation */\n    srand ( time(NULL) ) ;\n\n    /*Memory allocation for side */\n    test->side =  (enum BBLAS_SIDE*) malloc(nb_data*sizeof(enum BBLAS_SIDE));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->side, ptr_name);\n\n    /*Set the values of side */\n    switch (test->gen_side)\n    {\n\tcase SIDE_LEFT:\n\n\t    for( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t    {\n\t\ttest->side[batch_iter] = BblasLeft;\n\t    }\n\t    break;\n\n\tcase SIDE_RIGHT:\n\n\t    for( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t    {\n\t\ttest->side[batch_iter] = BblasRight;\n\t    }\n\t    break;\n\n\tdefault:\n\t    for( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t    {\n\t\t/*Generate a random number */\n\t\trandom_number = rand() % 100;\n\n\t\tif (random_number < 50 )\n\t\t{\n\t\t    test->side[batch_iter] = BblasLeft;\n\n\t\t}else\n\t\t{\n\t\t    test->side[batch_iter] = BblasRight;\n\t\t}\n\t\tbreak;\n\t    }\n    }\n}\n\n\n\n/**\n * Allocate memory and set the values of diag\n **/\n\nvoid bblas_zsetdiag(bblas_ztest_t *test)\n{\n\n    int batch_iter;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"diag\";\n    int random_number;\n\n    /*Initialize random number generation */\n    srand ( time(NULL) ) ;\n\n    /*Memory allocation for diag */\n    test->diag =  (enum BBLAS_DIAG*) malloc(nb_data*sizeof(enum BBLAS_DIAG));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->diag, ptr_name);\n\n    /*Set the values of diag */\n    switch (test->gen_diag)\n    {\n\tcase DIAG_NO_U:\n\n\t    for( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t    {\n\t\ttest->diag[batch_iter] = BblasNonUnit;\n\t    }\n\t    break;\n\n\tcase DIAG_U:\n\n\t    for( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t    {\n\t\ttest->diag[batch_iter] = BblasUnit;\n\t    }\n\t    break;\n\n\tdefault:\n\t    for( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t    {\n\t\t/*Generate a random number */\n\t\trandom_number = rand() % 100;\n\n\t\tif (random_number < 50 )\n\t\t{\n\t\t    test->diag[batch_iter] = BblasNonUnit;\n\n\t\t}else\n\t\t{\n\t\t    test->diag[batch_iter] = BblasUnit;\n\t\t}\n\t\tbreak;\n\t    }\n    }\n}\n\n\n/**\n * Allocate memory and set the values of M\n **/\n\nvoid bblas_zsetM(bblas_ztest_t *test)\n{\n\n    int batch_iter;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"M\";\n\n    /*Memory allocation for M */\n    test->M = (int*) malloc(nb_data*sizeof(int));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->M, ptr_name);\n\n    /*Set the values of M */\n    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n    {\n\ttest->M[batch_iter] = irandRange(test->minM, test->maxM);\n    }\n}\n\n\n/**\n * Allocate memory and set the values of N\n **/\n\nvoid bblas_zsetN(bblas_ztest_t *test)\n{\n\n    int batch_iter;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"N\";\n\n    /*Memory allocation for N */\n    test->N = (int*) malloc(nb_data*sizeof(int));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->N, ptr_name);\n\n    /*Set the values of N */\n    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n    {\n\ttest->N[batch_iter] = irandRange(test->minN, test->maxN);\n    }\n}\n\n\n/**\n * Allocate memory and set the values of K\n **/\n\nvoid bblas_zsetK(bblas_ztest_t *test)\n{\n    int batch_iter;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"K\";\n\n    /*Memory allocation for K */\n    test->K = (int*) malloc(nb_data*sizeof(int));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->K, ptr_name);\n\n    /*Set the values of K */\n    for( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n    {\n\ttest->K[batch_iter] = irandRange(test->minK, test->maxK);\n    }\n}\n\n\n/**\n * Allocate memory and set the values of lda\n **/\n\nvoid bblas_zsetlda(bblas_ztest_t *test)\n{\n    int batch_iter;\n    int nb_data                 = bblas_znbdata(test);\n    int routine                 = test->routine;\n    char ptr_name[NAME_LENGTH]  = \"lda\";\n\n    /*Memory allocation for lda */\n    test->lda = (int*) malloc(nb_data*sizeof(int));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->lda, ptr_name);\n\n    /*LDA for GEMM */\n    if (routine == BBLAS_GEMM)\n    {\n\tfor( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t{\n\t    if (test->transA[batch_iter] == BblasNoTrans)\n\t    {\n\t\ttest->lda[batch_iter] = test->M[batch_iter];\n\t    }else\n\t    {\n\t\ttest->lda[batch_iter] =test->K[batch_iter] ;\n\t    }\n\t}\n    }\n\n    /*LDA for SYMM, HEMM, TRMM AND TRSM */\n    if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||\n\t(routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n    {\n\tfor( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t{\n\t    if (test->side[batch_iter] == BblasLeft)\n\t    {\n\t\ttest->lda[batch_iter] = test->M[batch_iter];\n\t    }else\n\t    {\n\t\ttest->lda[batch_iter] =test->N[batch_iter] ;\n\t    }\n\t}\n    }\n\n    /*LDA for SYRK, HERK, SYR2K, HER2K */\n    if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) ||\n\t(routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))\n    {\n\tfor( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t{\n\t    if (test->trans[batch_iter] == BblasNoTrans)\n\t    {\n\t\ttest->lda[batch_iter] = test->N[batch_iter];\n\t    }else\n\t    {\n\t\ttest->lda[batch_iter] =test->K[batch_iter] ;\n\t    }\n\t}\n    }\n}\n\n/**\n * Allocate memory and set the values of ldb\n **/\n\nvoid bblas_zsetldb(bblas_ztest_t *test)\n{\n    int batch_iter;\n    int routine                 = test->routine;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"ldb\";\n\n    /*Memory allocation for ldb */\n    test->ldb = (int*) malloc(nb_data*sizeof(int));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->ldb, ptr_name);\n\n    /*LDB for GEMM */\n    if ((routine == BBLAS_GEMM) )\n    {\n\tfor( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t{\n\t    if (test->transB[batch_iter] == BblasNoTrans)\n\t    {\n\t\ttest->ldb[batch_iter] = test->K[batch_iter];\n\t    }else\n\t    {\n\t\ttest->ldb[batch_iter] =test->N[batch_iter] ;\n\t    }\n\t}\n    }\n\n    /*LDB SYMM, HEMM, TRMM AND TRSM */\n    if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||\n\t(routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n    {\n\tfor( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t{\n\t    test->ldb[batch_iter] = test->M[batch_iter];\n\t}\n    }\n\n    /*LDB for SYR2K, HER2K */\n    if ((routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))\n    {\n\tfor( batch_iter =0; batch_iter < nb_data; batch_iter++)\n\t{\n\t    if (test->trans[batch_iter] == BblasNoTrans)\n\t    {\n\t\ttest->ldb[batch_iter] = test->N[batch_iter];\n\t    }else\n\t    {\n\t\ttest->ldb[batch_iter] =test->K[batch_iter] ;\n\t    }\n\t}\n    }\n}\n\n\n/**\n * Allocate memory and set the values of ldc\n **/\n\nvoid bblas_zsetldc(bblas_ztest_t *test)\n{\n    int batch_iter;\n    int routine                 = test->routine;\n    int nb_data                 = bblas_znbdata(test);\n    char ptr_name[NAME_LENGTH]  = \"ldc\";\n\n    /*Memory allocation for ldc */\n    test->ldc = (int*) malloc(nb_data*sizeof(int));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->ldc, ptr_name);\n\n    /*LDC for GEMM */\n    if (routine == BBLAS_GEMM)\n    {\n\tfor( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t{\n\t    test->ldc[batch_iter] = test->M[batch_iter];\n\t}\n    }\n\n    /*LDC for SYMM, HEMM */\n    if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM))\n    {\n\tfor( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t{\n\t    test->ldc[batch_iter] = test->M[batch_iter];\n\t}\n    }\n\n    /*LDC for SYRK, HERK, SYR2K, HER2K */\n    if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) ||\n\t(routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))\n    {\n\tfor( batch_iter =0; batch_iter < nb_data ; batch_iter++)\n\t{\n\t    test->ldc[batch_iter] = test->N[batch_iter];\n\t}\n    }\n}\n\n\n/**\n * Allocate memory and set the values of alpha\n **/\n\nvoid bblas_zsetalpha(bblas_ztest_t *test)\n{\n    int batch_iter;\n    int batch_count             = test->batch_count;\n    char ptr_name[NAME_LENGTH]  = \"alpha\";\n\n    /*Memory allocation for alpha */\n    test->alpha = (BBLAS_Complex64_t*) malloc(batch_count*sizeof(BBLAS_Complex64_t));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->alpha, ptr_name);\n\n    /* Set value of alpha */\n    for( batch_iter =0; batch_iter < batch_count; batch_iter++)\n    {\n\ttest->alpha[batch_iter] = ((BBLAS_Complex64_t)rand()/(BBLAS_Complex64_t)RAND_MAX);\n    }\n}\n\n\n/**\n * Allocate memory and set the values of alpha specifically for herk.\n **/\n\nvoid bblas_zsetalpha_herk(bblas_ztest_t *test)\n{\n\n    int batch_iter;\n    int batch_count             = test->batch_count;\n    char ptr_name[NAME_LENGTH]  = \"alpha_herk\";\n\n    /*Memory allocation for alpha_herk */\n    test->alpha_herk = (double*) malloc(batch_count*sizeof(double));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->alpha_herk, ptr_name);\n\n    /* Set value of alpha_herk */\n    for( batch_iter =0; batch_iter < batch_count; batch_iter++)\n    {\n\ttest->alpha_herk[batch_iter] = ((double)rand()/(double)RAND_MAX);\n    }\n}\n\n\n/**\n * Allocate memory and set the values of beta.\n **/\n\nvoid bblas_zsetbeta(bblas_ztest_t *test)\n{\n    int batch_iter;\n    int batch_count             = test->batch_count;\n    char ptr_name[NAME_LENGTH]  = \"beta\";\n\n    /*Memory allocation for beta */\n    test->beta = (BBLAS_Complex64_t*) malloc(batch_count*sizeof(BBLAS_Complex64_t));\n\n    /*checking memory allocation */\n    bblas_malloc_check(test->beta, ptr_name);\n\n    /* Set value of beta */\n    for( batch_iter =0; batch_iter < batch_count; batch_iter++)\n    {\n\ttest->beta[batch_iter] = ((BBLAS_Complex64_t)rand()/(BBLAS_Complex64_t)RAND_MAX);\n    }\n}\n\n/**\n * Allocate memory and set the values of beta specifically for herk.\n **/\n\nvoid bblas_zsetbeta_herk(bblas_ztest_t *test)\n{\n     int batch_iter;\n     int batch_count             = test->batch_count;\n     char ptr_name[NAME_LENGTH]  = \"beta_herk\";\n\n     /*Memory allocation for beta_herk */\n     test->beta_herk = (double*) malloc(batch_count*sizeof(double));\n\n     /*checking memory allocation */\n     bblas_malloc_check(test->beta_herk, ptr_name);\n\n     /* Set value of beta_herk */\n     for( batch_iter =0; batch_iter < batch_count; batch_iter++)\n     {\n\t test->beta_herk[batch_iter] = ((double)rand()/(double)RAND_MAX);\n     }\n}\n\n\n/**\n * Allocate memory and set the values of arrayA.\n **/\n\nvoid bblas_zsetarrayA(bblas_ztest_t *test)\n{\n    int batch_iter, nb_row, nb_col;\n     int first_index             = 0;\n     int routine                 = test->routine;\n     int batch_count             = test->batch_count;\n     char ptr_name[NAME_LENGTH]  = \"arrayA\";\n\n     int IONE     = 1;\n     int ISEED[4] ={0,0,0,1};\n\n     /*Memory allocation for **arrayA  */\n     test->arrayA = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*));\n     bblas_malloc_check(test->arrayA, ptr_name);\n\n     if( test->batch_opts == BBLAS_VARIABLE )\n     {\n\t for( batch_iter =0; batch_iter < batch_count; batch_iter++)\n\t {\n\t     nb_row = test->lda[batch_iter];\n\n\t     /* nb_col  for GEMM */\n\t     if (routine == BBLAS_GEMM)\n\t     {\n\t\t if (test->transA[batch_iter] == BblasNoTrans)\n\t\t {\n\t\t     nb_col =test->K[batch_iter];\n\t\t }else\n\t\t {\n\t\t     nb_col =test->M[batch_iter];\n\t\t }\n\t     }\n\n\t     /*  nb_col  SYMM, HEMM, TRMM AND TRSM */\n\t     if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||\n\t\t (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n\t     {\n\t\t if(test->side[batch_iter] == BblasLeft )\n\t\t {\n\t\t     nb_col = test->M[batch_iter];\n\t\t }else\n\t\t {\n\t\t     nb_col = test->N[batch_iter];\n\t\t }\n\t     }\n\n\t     /* nb_col for SYRK, HERK, SYR2K, HER2K */\n\t     if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) ||\n\t\t (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))\n\t     {\n\t\t if (test->trans[batch_iter] == BblasNoTrans)\n\t\t {\n\t\t     nb_col = test->K[batch_iter];\n\t\t }else\n\t\t {\n\t\t     nb_col = test->N[batch_iter];\n\t\t }\n\t     }\n\n\t     /*Matrix filling */\n\t     test->arrayA[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t ));\n\t     bblas_malloc_check(test->arrayA[batch_iter], ptr_name);\n\n#if defined(BBLAS_WITH_MKL)\n\t     LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayA[batch_iter]);\n#else\n\t\t LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayA[batch_iter]);\n#endif\n\n\t     if( (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n\t       {\n\t\t for(int i=0; i<max(nb_row,nb_col); i++)\n\t\t   {\n\t\t     test->arrayA[batch_iter][nb_col*i+i] = test->arrayA[batch_iter][nb_col*i+i] + 1.0;\n\t\t   }\n\t       }\n\n\t     if(routine == BBLAS_HEMM )\n\t       {\n\t\t for(int i=0; i< nb_row; i++)\n\t\t   {\n\t\t     test->arrayA[batch_iter][nb_col*i+i] = creal(test->arrayA[batch_iter][nb_col*i+i]);\n\t\t   }\n\t       }\n\t }\n\n     }else if( test->batch_opts == BBLAS_FIXED )\n     {\n\t nb_row = test->lda[first_index];\n\n\t /* nb_col  for GEMM */\n\t if (routine == BBLAS_GEMM)\n\t {\n\t     if (test->transA[first_index] == BblasNoTrans)\n\t     {\n\t\t nb_col =test->K[first_index];\n\t     }else\n\t     {\n\t\t nb_col =test->M[first_index];\n\t     }\n\t }\n\n\t /*  nb_col  SYMM, HEMM, TRMM AND TRSM */\n\t if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||\n\t     (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n\t {\n\t     if(test->side[first_index] == BblasLeft )\n\t     {\n\t\t nb_col = test->M[first_index];\n\t     }else\n\t     {\n\t\t nb_col = test->N[first_index];\n\t     }\n\t }\n\n\t /* nb_col for SYRK, HERK, SYR2K, HER2K */\n\t if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) ||\n\t     (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))\n\t {\n\t     if (test->trans[first_index] == BblasNoTrans)\n\t     {\n\t\t nb_col = test->K[first_index];\n\t     }else\n\t     {\n\t\t nb_col = test->N[first_index];\n\t     }\n\t }\n\n\t /*Matrix filling */\n\t for( batch_iter =0; batch_iter < batch_count; batch_iter++)\n\t {\n\t     test->arrayA[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t ));\n\t     bblas_malloc_check(test->arrayA[batch_iter], ptr_name);\n\n#if defined(BBLAS_WITH_MKL)\n\t     LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayA[batch_iter]);\n#else\n\t\t LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayA[batch_iter]);\n#endif\n\n\t     if( (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n\t       {\n\t\t for(int i=0; i<max(nb_row,nb_col); i++)\n\t\t   {\n\t\t     test->arrayA[batch_iter][nb_col*i+i] = test->arrayA[batch_iter][nb_col*i+i] + 1.0;\n\t\t   }\n\t       }\n\n\t     if(routine == BBLAS_HEMM )\n\t       {\n\t\t for(int i=0; i<max(nb_row,nb_col); i++)\n\t\t   {\n\t\t     test->arrayA[batch_iter][nb_col*i+i] = creal(test->arrayA[batch_iter][nb_col*i+i]);\n\t\t   }\n\t       }\n\t }\n     }else\n     {\n\t bblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n     }\n}\n\n/**\n * Allocate memory and set the values of arrayB.\n **/\n\nvoid bblas_zsetarrayB(bblas_ztest_t *test)\n{\n    int batch_iter, nb_row, nb_col;\n    int first_index             = 0;\n    int routine                 = test->routine;\n    int batch_count             = test->batch_count;\n    char ptr_name[NAME_LENGTH]  = \"arrayB\";\n    int max_work_size = max(test->maxK, max(test->maxM, test->maxN));\n    int IONE     = 1;\n    int ISEED[4] ={0,0,0,1};\n\n    /*Memory allocation for arrayB */\n    test->arrayB = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*));\n    bblas_malloc_check(test->arrayB, ptr_name);\n\n    test->Binitnorm = (double *)malloc(batch_count*sizeof(double));\n    bblas_malloc_check(test->Binitnorm, \"Binitnorm\");\n\n    double *work = (double *)malloc(max_work_size*sizeof(double));\n    bblas_malloc_check(work, \"work\");\n\n    if( test->batch_opts == BBLAS_VARIABLE )\n    {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    nb_row =test->ldb[batch_iter];\n\n\t    /* nb_col  for GEMM */\n\t    if (routine == BBLAS_GEMM)\n\t    {\n\t\tif (test->transB[batch_iter] == BblasNoTrans)\n\t\t{\n\t\t    nb_col = test->N[batch_iter];\n\t\t}else\n\t\t{\n\t\t    nb_col = test->K[batch_iter];\n\t\t}\n\t    }\n\n\t    /* nb_col for SYMM, HEMM, TRMM AND TRSM */\n\t    if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||\n\t\t(routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n\t    {\n\t\tnb_col =test->N[batch_iter];\n\t    }\n\n\t    /* nb_col for SYR2K, HER2K */\n\t    if ((routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))\n\t    {\n\t\tif (test->trans[batch_iter] == BblasNoTrans)\n\t\t{\n\t\t    nb_col = test->K[batch_iter];\n\t\t}else\n\t\t{\n\t\t    nb_col = test->N[batch_iter];\n\t\t}\n\t    }\n\n\t    test->arrayB[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t ));\n\t    bblas_malloc_check(test->arrayB[batch_iter], ptr_name);\n\n#if defined(BBLAS_WITH_MKL)\n\t    LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayB[batch_iter]);\n#else\n\t\tLAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayB[batch_iter]);\n#endif\n\n\t    /*Compute the infinity norm of B  */\n\t    if( (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n\t    {\n#if defined(BBLAS_WITH_MKL)\n\t\ttest->Binitnorm[batch_iter] = (BBLAS_Complex64_t) LAPACKE_zlange_work(LAPACK_COL_MAJOR,\n\t\t\t\t\t\t\t\t  'I', nb_row, nb_col,\n\t\t\t\t\t\t\t\t  (MKL_Complex16*) test->arrayB[batch_iter],\n\t\t\t\t\t\t\t\t  test->ldb[batch_iter], work);\n#else\n\t\ttest->Binitnorm[batch_iter] = LAPACKE_zlange_work(LAPACK_COL_MAJOR,\n\t\t\t\t\t\t\t\t  'I', nb_row, nb_col,\n\t\t\t\t\t\t\t\t  test->arrayB[batch_iter],\n\t\t\t\t\t\t\t\t  test->ldb[batch_iter], work);\n#endif\n\t    }\n\t}\n\n    }else if( test->batch_opts == BBLAS_FIXED )\n    {\n\tnb_row =test->ldb[first_index];\n\n\t/* nb_col  for GEMM */\n\tif (routine == BBLAS_GEMM)\n\t{\n\t    if (test->transB[first_index] == BblasNoTrans)\n\t    {\n\t\tnb_col = test->N[first_index];\n\t    }else\n\t    {\n\t\tnb_col = test->K[first_index];\n\t    }\n\t}\n\n\t/* nb_col for SYMM, HEMM, TRMM AND TRSM */\n\tif ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||\n\t    (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n\t{\n\t    nb_col =test->N[first_index];\n\t}\n\n\t/* nb_col for SYR2K, HER2K */\n\tif ((routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))\n\t{\n\t    if (test->trans[first_index] == BblasNoTrans)\n\t    {\n\t\tnb_col = test->K[first_index];\n\t    }else\n\t    {\n\t\tnb_col = test->N[first_index];\n\t    }\n\t}\n\t/*Matrix filling */\n\tfor( batch_iter =0; batch_iter < batch_count; batch_iter++)\n\t{\n\t     test->arrayB[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t ));\n#if defined(BBLAS_WITH_MKL)\n\t     LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayB[batch_iter]);\n#else\n\t\t LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayB[batch_iter]);\n#endif\n\n\t     /*Compute the infinity norm of B  */\n\t     if( (routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n\t     {\n#if defined(BBLAS_WITH_MKL)\n\t\t test->Binitnorm[batch_iter] = (BBLAS_Complex64_t) LAPACKE_zlange_work(LAPACK_COL_MAJOR,\n\t\t\t\t\t\t\t\t   'I', nb_row, nb_col,\n\t\t\t\t\t\t\t\t   (MKL_Complex16*) test->arrayB[batch_iter],\n\t\t\t\t\t\t\t\t   test->ldb[first_index], work);\n#else\n\t\t test->Binitnorm[batch_iter] = LAPACKE_zlange_work(LAPACK_COL_MAJOR,\n\t\t\t\t\t\t\t\t   'I', nb_row, nb_col,\n\t\t\t\t\t\t\t\t   test->arrayB[batch_iter],\n\t\t\t\t\t\t\t\t   test->ldb[first_index], work);\n#endif\n\t     }\n\t }\n    }else\n    {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n    }\n    /*Free work */\n    free(work);\n}\n\n\n/**\n * Allocate memory and set the values of arrayC.\n **/\n\nvoid bblas_zsetarrayC(bblas_ztest_t *test)\n{\n    int batch_iter, nb_row, nb_col;\n    int first_index             = 0;\n    int batch_count             = test->batch_count;\n    int max_work_size = max(test->maxK, max(test->maxM, test->maxN));\n    char ptr_name[NAME_LENGTH]  = \"arrayC\";\n\n    int IONE     = 1;\n    int ISEED[4] ={0,0,0,1};\n\n    test->arrayC = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*));\n    bblas_malloc_check(test->arrayC, ptr_name);\n\n    test->Cinitnorm = (double *)malloc(batch_count*sizeof(double));\n    bblas_malloc_check(test->Cinitnorm, \"Cinitnorm\");\n\n    double *work = (double *)malloc(max_work_size*sizeof(double));\n    bblas_malloc_check(work, \"work\");\n\n\n    if( test->batch_opts == BBLAS_VARIABLE )\n    {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    nb_row =test->ldc[batch_iter];\n\t    nb_col =test->N[batch_iter];\n\n\t    test->arrayC[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t ));\n\t    bblas_malloc_check(test->arrayC[batch_iter], ptr_name);\n#if defined(BBLAS_WITH_MKL)\n\t    LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayC[batch_iter]);\n#else\n\t\tLAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayC[batch_iter]);\n#endif\n\n\t    if( (test->routine == BBLAS_HERK) || (test->routine == BBLAS_HER2K))\n\t      {\n\t\tfor(int i=0; i<max(nb_row,nb_col); i++)\n\t\t  {\n\t\t    test->arrayC[batch_iter][nb_col*i+i] = creal(test->arrayC[batch_iter][nb_col*i+i]);\n\t\t  }\n\t      }\n\n\t    /*Compuptation of the norm of C */\n#if defined(BBLAS_WITH_MKL)\n\t    test->Cinitnorm[batch_iter] = (BBLAS_Complex64_t) LAPACKE_zlange_work(LAPACK_COL_MAJOR,\n\t\t\t\t\t\t\t\t  'I', nb_row, nb_col, (MKL_Complex16*) test->arrayC[batch_iter],\n\t\t\t\t\t\t\t\t  test->ldc[batch_iter], work);\n#else\n\t\ttest->Cinitnorm[batch_iter] = LAPACKE_zlange_work(LAPACK_COL_MAJOR,\n\t\t\t\t\t\t\t      'I', nb_row, nb_col, test->arrayC[batch_iter],\n\t\t\t\t\t\t\t\t  test->ldc[batch_iter], work);\n#endif\n\t}\n\n    }else if( test->batch_opts == BBLAS_FIXED )\n    {\n\tnb_row =test->ldc[first_index];\n\tnb_col =test->N[first_index];\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    test->arrayC[batch_iter] = (BBLAS_Complex64_t *) malloc(nb_row*nb_col* sizeof(BBLAS_Complex64_t ));\n\t    bblas_malloc_check(test->arrayC[batch_iter], ptr_name);\n\n#if defined(BBLAS_WITH_MKL)\n\t    LAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, (MKL_Complex16*) test->arrayC[batch_iter]);\n#else\n\t\tLAPACKE_zlarnv_work(IONE, ISEED, nb_row*nb_col, test->arrayC[batch_iter]);\n#endif\n\n\t    if( (test->routine == BBLAS_HERK) || (test->routine == BBLAS_HER2K))\n\t      {\n\t\tfor(int i=0; i<max(nb_row,nb_col); i++)\n\t\t  {\n\t\t    test->arrayC[batch_iter][nb_col*i+i] = creal(test->arrayC[batch_iter][nb_col*i+i]);\n\t\t  }\n\t      }\n\n\t    /*Compuptation of the norm of C */\n#if defined(BBLAS_WITH_MKL)\n\t    test->Cinitnorm[batch_iter] = (BBLAS_Complex64_t) LAPACKE_zlange_work(LAPACK_COL_MAJOR,\n\t\t\t\t\t\t\t\t\t  'I', nb_row, nb_col,\n\t\t\t\t\t\t\t\t\t  (MKL_Complex16*) test->arrayC[batch_iter],\n\t\t\t\t\t\t\t\t\t  test->ldc[first_index], work);\n\t\t#else\n\t\ttest->Cinitnorm[batch_iter] = LAPACKE_zlange_work(LAPACK_COL_MAJOR,\n\t\t\t\t\t\t\t      'I',nb_row, nb_col, test->arrayC[batch_iter],\n\t\t\t\t\t\t\t\t  test->ldc[first_index], work);\n\t\t#endif\n\t}\n    } else\n    {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n    }\n\n    /*Free work */\n    free(work);\n}\n\n/**\n * Allocate memory for error checking.\n **/\n\nvoid bblas_zmalloc_result_error(bblas_ztest_t *test)\n{\n\n    int batch_count             = test->batch_count;\n\n    /*Memory for error computation  */\n    switch(test->target)\n    {\n\tcase BBLAS_MKL:\n\t    test->mkl_result  = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*));\n\t    bblas_malloc_check(test->mkl_result, \"mkl_result\");\n\n\t    test->mkl_error = (double*) malloc(batch_count*sizeof(double));\n\t    bblas_malloc_check(test->mkl_error, \"mkl_error\");\n\t    break;\n\n\tcase BBLAS_CUBLAS:\n\tcase BBLAS_MAGMA:\n\t    test->device_result = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*));\n\t    bblas_malloc_check(test->device_result, \"device_result\");\n\n\t    test->device_error = (double*) malloc(batch_count*sizeof(double));\n\t    bblas_malloc_check(test->device_error, \"device_error\");\n\t    break;\n\n\tcase BBLAS_OTHER:\n\t    test->other_result  = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*));\n\t    bblas_malloc_check(test->other_result, \"other_result\");\n\n\t    test->other_error = (double*) malloc(batch_count*sizeof(double));\n\t    bblas_malloc_check(test->other_error, \"other_error\");\n\t    break;\n\n\tcase BBLAS_CUMKL:\n\t    test->mkl_result    = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*));\n\t    bblas_malloc_check(test->mkl_result, \"mkl_result\");\n\n\t    test->device_result = (BBLAS_Complex64_t**) malloc(batch_count*sizeof(BBLAS_Complex64_t*));\n\t    bblas_malloc_check(test->device_result, \"device_result\");\n\n\t    test->mkl_error = (double*) malloc(batch_count*sizeof(double));\n\t    bblas_malloc_check(test->mkl_error, \"mkl_error\");\n\n\t    test->device_error = (double*) malloc(batch_count*sizeof(double));\n\t    bblas_malloc_check(test->device_error, \"device_error\");\n\t    break;\n\n\tdefault:\n\t    printf(\"Memory alloation for error: Target no defined\\n\");\n\t    exit(EXIT_FAILURE);\n    }\n\n    /*Memory for info  */\n    test->info = (int*) malloc(batch_count*sizeof(int));\n}\n\n\n/**\n * Allocate memory and copy the initial arrayC values.\n * This is required to take norms after the computation is complete.\n **/\n\nvoid bblas_zcopy_Cinit(bblas_ztest_t *test, BBLAS_Complex64_t **C_copy)\n{\n    /*Local variables */\n    enum BBLAS_ROUTINE routine  = test->routine;\n    int batch_count = test->batch_count;\n    int batch_iter, first_index = 0;\n    int ldc, N;\n\n    if (!((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t  (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) ||\n\t  (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)||\n\t  (routine == BBLAS_HER2K)))\n    {\n\tprintf(\"BBLAS FATAL ERROR: bblas_ztesting.c():\\n\");\n\tprintf(\"\\t bblas_zcopy_Cinit not defined for %s \\n\", bblas_getroutine(test->routine));\n\texit(EXIT_FAILURE);\n    }\n\n    if( test->batch_opts == BBLAS_VARIABLE ) // Varible size\n    {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    ldc = test->ldc[batch_iter];\n\t    N   = test->N[batch_iter];\n\t    C_copy[batch_iter] = (BBLAS_Complex64_t *) malloc(ldc*N* sizeof(BBLAS_Complex64_t ));\n\n\t    /*Copy the matrix {C}_i */\n\t    cblas_zcopy (ldc*N, test->arrayC[batch_iter], 1, C_copy[batch_iter], 1);\n\t}\n\n    }else if( test->batch_opts == BBLAS_FIXED ) //fixed  size\n    {\n\tldc = test->ldc[first_index];\n\tN = test->N[first_index];\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    C_copy[batch_iter] = (BBLAS_Complex64_t *) malloc(ldc*N* sizeof(BBLAS_Complex64_t ));\n\n\t    /*Copy the matrix {C}_i */\n\t    cblas_zcopy (ldc*N, test->arrayC[batch_iter], 1,  C_copy[batch_iter], 1);\n\t}\n    }else\n    {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\\n\");\n    }\n}\n\n/**\n * Allocate memory and copy the initial arrayB values.\n * This is required to take norms after the computation is complete.\n **/\n\nvoid bblas_zcopy_Binit(bblas_ztest_t *test, BBLAS_Complex64_t **B_copy)\n{\n    /*Local variables */\n    enum BBLAS_ROUTINE routine  = test->routine;\n    int batch_count = test->batch_count;\n    int batch_iter, first_index = 0;\n    int ldb, N;\n\n    if (!((routine == BBLAS_TRMM) || (routine == BBLAS_TRSM)))\n    {\n\tprintf(\"BBLAS FATAL ERROR: bblas_ztesting.c():\\n\");\n\tprintf(\"\\t bblas_zcopy_Binit not defined for %s \\n\", bblas_getroutine(test->routine));\n\texit(EXIT_FAILURE);\n    }\n\n    if( test->batch_opts == BBLAS_VARIABLE )\n    {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    ldb = test->ldb[batch_iter];\n\t    N   = test->N[batch_iter];\n\n\t    B_copy[batch_iter] = (BBLAS_Complex64_t *) malloc(ldb*N* sizeof(BBLAS_Complex64_t ));\n\n\t    /*Copy the matrix {B}_i */\n\t    cblas_zcopy (ldb*N, test->arrayB[batch_iter], 1, B_copy[batch_iter], 1);\n\t}\n\n    }else if( test->batch_opts == BBLAS_FIXED ) //fixed  size\n    {\n\tldb = test->ldb[first_index];\n\tN = test->N[first_index];\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    B_copy[batch_iter] = (BBLAS_Complex64_t *) malloc(ldb*N* sizeof(BBLAS_Complex64_t ));\n\n\t    /*Copy the matrix {B}_i */\n\t    cblas_zcopy (ldb*N, test->arrayB[batch_iter], 1, B_copy[batch_iter], 1);\n\t}\n    }else\n    {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\\n\");\n    }\n}\n\n/**\n * Compute the relative error of each batch operation.\n **/\n\nvoid bblas_zcheck_Cfinal(bblas_ztest_t *test, BBLAS_Complex64_t **C_final)\n{\n\n    /*Local variables */\n    enum BBLAS_ROUTINE routine  = test->routine;\n    int batch_count = test->batch_count;\n    int batch_iter, first_index = 0;\n    int ldc, N;\n\n    /* Error calculation variables */\n    double Cnorm, Error_norm;\n    BBLAS_Complex64_t alpha =-1;\n\n    /*Check if the call has been made by the correct routine */\n    if (!((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t  (routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) ||\n\t  (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)||\n\t  (routine == BBLAS_HER2K)))\n    {\n\tprintf(\"BBLAS FATAL ERROR: bblas_ztesting.c():\\n\");\n\tprintf(\"\\t bblas_zcheck_Cfinal not defined for %s \\n\", bblas_getroutine(test->routine));\n\texit(EXIT_FAILURE);\n    }\n\n    /*Temporary buffer to save (test-arrayC -C_final) */\n    BBLAS_Complex64_t **C_diff;\n    C_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));\n\n    /*Make a copy of test->arrayC in C_diff */\n    bblas_zcopy_Cinit(test, C_diff);\n\n    /*Variable size */\n    if( test->batch_opts == BBLAS_VARIABLE )\n    {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    ldc = test->ldc[batch_iter];\n\t    N   = test->N[batch_iter];\n\n\t    /*Computation of the Frobenus norm of  {C}_batch_iter */\n\t    Cnorm = cblas_dznrm2(ldc*N, test->arrayC[batch_iter], 1);\n\n\t    /*Compute the error */\n\t    cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t    /*Compute  the norm assoicated  with the error */\n\t    Error_norm = cblas_dznrm2(ldc*N, C_diff[batch_iter], 1);\n\n\t    /*Compute the relative error */\n\t    switch(test->target)\n\t    {\n\t\tcase BBLAS_MKL:\n\t\t    test->mkl_error[batch_iter] = Error_norm/Cnorm;\n\t\t    break;\n\n\t\tcase BBLAS_CUBLAS:\n                case BBLAS_MAGMA:\n  \t\t    test->device_error[batch_iter] = Error_norm/Cnorm;\n\t\t    break;\n\n\t\tcase BBLAS_OTHER:\n\t\t    test->other_error[batch_iter] = Error_norm/Cnorm;\n\t\t    break;\n\t\tdefault:\n\t\t    printf(\"In bblas_zcheck_Cfinal, Variable: Target no defined\\n\");\n\t\t    exit(EXIT_FAILURE);\n\t    }\n\t}\n\n    }else  if( test->batch_opts == BBLAS_FIXED ) //fixed  size\n    {\n\tldc = test->ldc[first_index];\n\tN   = test->N[first_index];\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    /*Computation of the Frobenus norm of  {C}_batch_iter */\n\t    Cnorm = cblas_dznrm2(ldc*N, test->arrayC[batch_iter], 1);\n\n\t    /*Compute the error */\n\t    cblas_zaxpy (ldc*N, CBLAS_SADDR(alpha), C_final[batch_iter], 1, C_diff[batch_iter], 1);\n\n\t    /*Compute  the norm assoicated  with the error */\n\t    Error_norm = cblas_dznrm2(ldc*N, C_diff[batch_iter], 1);\n\n\t    /*Compute the relative error */\n\t    switch(test->target)\n\t    {\n\t\tcase BBLAS_MKL:\n\t\t    test->mkl_error[batch_iter] = Error_norm/Cnorm;\n\t\t    break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t    test->device_error[batch_iter] = Error_norm/Cnorm;\n\t\t    break;\n\n\t\tcase BBLAS_OTHER:\n\t\t    test->other_error[batch_iter] = Error_norm/Cnorm;\n\t\t    break;\n\t\tdefault:\n\t\t    printf(\"In bblas_zcheck_Cfinal: Fixed, Target no defined\\n\");\n\t\t    exit(EXIT_FAILURE);\n\t    }\n\t}\n    }else\n    {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n    }\n\n    /*Free  C_diff */\n    for(batch_iter=0; batch_iter < batch_count ; batch_iter++)\n    {\n\tfree(C_diff[batch_iter]);\n    }\n    free(C_diff);\n}\n\n/**\n * Compute the relative error of each batch operation.\n **/\n\nvoid bblas_zcheck_Bfinal(bblas_ztest_t *test, BBLAS_Complex64_t **B_final)\n{\n\n    /*Local variables */\n    enum BBLAS_ROUTINE routine  = test->routine;\n    int batch_count = test->batch_count;\n    int batch_iter, first_index = 0;\n    int ldb, N;\n\n    /* Error calculation variables */\n    double Bnorm, Error_norm;\n    BBLAS_Complex64_t alpha =-1;\n\n    /*Check if the call has been made by the correct routine */\n    if (!((routine == BBLAS_TRSM) || (routine == BBLAS_TRMM)))\n    {\n\tprintf(\"BBLAS FATAL ERROR: bblas_ztesting.c():\\n\");\n\tprintf(\"\\t bblas_zcheck_Bfinal not defined for %s \\n\", bblas_getroutine(test->routine));\n\texit(EXIT_FAILURE);\n    }\n\n    /*Temporary buffer to save (test-arrayB -B_final) */\n    BBLAS_Complex64_t **B_diff;\n    B_diff = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t *));\n\n    /*Make a copy of test->arrayB in B_diff */\n    bblas_zcopy_Binit(test, B_diff);\n\n    /*Variable size */\n    if( test->batch_opts == BBLAS_VARIABLE )\n    {\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    ldb = test->ldb[batch_iter];\n\t    N   = test->N[batch_iter];\n\n\t    /*Computation of the Frobenus norm of  {B}_batch_iter */\n\t    Bnorm = cblas_dznrm2(ldb*N, test->arrayB[batch_iter], 1);\n\n\t    /*Compute the error */\n\t    cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1);\n\n\t    /*Compute  the norm assoicated  with the error */\n\t    Error_norm = cblas_dznrm2(ldb*N, B_diff[batch_iter], 1);\n\n\t    /*Compute the relative error */\n\t    switch(test->target)\n\t    {\n\t\tcase BBLAS_MKL:\n\t\t    test->mkl_error[batch_iter] = Error_norm/Bnorm;\n\t\t    break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t    test->device_error[batch_iter] = Error_norm/(Bnorm);\n\t\t    break;\n\n\t\tcase BBLAS_OTHER:\n\t\t    test->other_error[batch_iter] = Error_norm/(Bnorm);\n\t\t    break;\n\t\tdefault:\n\t\t    printf(\"In bblas_zcheck_Bfinal(): Target no defined\\n\");\n\t\t    exit(EXIT_FAILURE);\n\t    }\n\t}\n\n    }else  if( test->batch_opts == BBLAS_FIXED )\n    {\n\tldb = test->ldb[first_index];\n\tN = test->N[first_index];\n\n\tfor( batch_iter =0; batch_iter < batch_count ; batch_iter++)\n\t{\n\t    /*Computation of the Frobenus norm of  {B}_batch_iter */\n\t    Bnorm = cblas_dznrm2(ldb*N, test->arrayB[batch_iter], 1);\n\n\t    /*Compute the error */\n\t    cblas_zaxpy (ldb*N, CBLAS_SADDR(alpha), B_final[batch_iter], 1, B_diff[batch_iter], 1);\n\n\t    /*Compute  the norm assoicated  with the error */\n\t    Error_norm = cblas_dznrm2(ldb*N, B_diff[batch_iter], 1);\n\n\t    /*Compute the relative error */\n\t    switch(test->target)\n\t    {\n\t\tcase BBLAS_MKL:\n\t\t    test->mkl_error[batch_iter] = Error_norm/(Bnorm);\n\t\t    break;\n\n\t\tcase BBLAS_CUBLAS:\n\t\tcase BBLAS_MAGMA:\n\t\t    test->device_error[batch_iter] = Error_norm/(Bnorm);\n\t\t    break;\n\n\t\tcase BBLAS_OTHER:\n\t\t    test->other_error[batch_iter] = Error_norm/(Bnorm);\n\t\t    break;\n\t\tdefault:\n\t\t    printf(\"In bblas_zcheck_Bfinal(): Target no defined\\n\");\n\t\t    exit(EXIT_FAILURE);\n\t    }\n\t}\n    }else\n    {\n\tbblas_error(\"bblas_ztesting.c\", \"wrong batch_opts value\");\n    }\n\n    /*Free  B_diff */\n    for(batch_iter=0; batch_iter < batch_count ; batch_iter++)\n    {\n\tfree(B_diff[batch_iter]);\n    }\n    free(B_diff);\n}\n\n/**\n * Free the memory associated with the test structure.\n **/\n\nvoid bblas_zfreetest( bblas_ztest_t *test )\n{\n    enum BBLAS_ROUTINE routine  = test->routine;\n    /*Free uplo */\n    if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||\n\t(routine == BBLAS_SYRK) || (routine == BBLAS_HERK) ||\n\t(routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)||\n\t(routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n    {\n\tfree(test->uplo);\n    }\n\n    /*Free TRANSA */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_TRMM) ||\n\t(routine == BBLAS_TRSM))\n    {\n\tfree( test->transA );\n    }\n\n    /*Free TRANSB */\n    if (routine == BBLAS_GEMM)\n    {\n\tfree( test->transB );\n    }\n\n    /*Free TRANS */\n    if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) ||\n\t(routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))\n    {\n\tfree( test->trans );\n    }\n\n    /*Free SIDE*/\n    if ((routine == BBLAS_SYMM) || (routine == BBLAS_HEMM) ||\n\t(routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n    {\n\tfree( test->side );\n    }\n\n    /*Free DIAG*/\n    if  ((routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n    {\n\tfree(test->diag);\n    }\n\n\n    /* Free M  memory*/\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) ||\n\t(routine == BBLAS_TRSM))\n    {\n\tfree( test->M );\n    }\n\n    /* Free N memory*/\n    free( test->N );\n\n    /* Free K memory*/\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK)  ||\n\t(routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) ||\n\t(routine == BBLAS_HER2K))\n    {\n\tfree( test->K );\n    }\n\n    /*Free LDA memory */\n    free( test->lda );\n\n    /*Free LDB memory */\n    if ((routine == BBLAS_GEMM)  || (routine == BBLAS_SYMM)  ||\n\t(routine == BBLAS_HEMM)  || (routine == BBLAS_SYR2K) ||\n\t(routine == BBLAS_HER2K) || (routine == BBLAS_TRMM)  ||\n\t(routine == BBLAS_TRSM))\n    {\n\tfree( test->ldb );\n    }\n\n    /*Free LDC memory */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) ||\n\t(routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)||\n\t(routine == BBLAS_HER2K))\n    {\n\tfree( test->ldc );\n    }\n\n    /*Free ALPHA memory */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) ||(routine == BBLAS_SYRK)  ||\n\t(routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K)||\n\t(routine == BBLAS_TRMM) || (routine == BBLAS_TRSM))\n    {\n\tfree(test->alpha);\n\n    }else if (routine == BBLAS_HERK)\n    {\n\tfree(test->alpha_herk);\n    }\n\n    /*Free ALPHA BETA memory */\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) ||\n\t(routine == BBLAS_SYR2K))\n    {\n\tfree( test->beta  );\n\n    }else if ((routine == BBLAS_HERK) || (routine == BBLAS_HER2K))\n    {\n\tfree(test->beta_herk);\n    }\n\n    /*Free matrices {A}_i  */\n    for ( int batch_iter = 0; batch_iter < test->batch_count; batch_iter++ )\n    {\n\tfree( test->arrayA[batch_iter] );\n    }\n    free( test->arrayA );\n\n    /*Free matrices  {B}_i*/\n    if ((routine == BBLAS_GEMM)  || (routine == BBLAS_SYMM)  ||\n\t(routine == BBLAS_HEMM)  || (routine == BBLAS_SYR2K) ||\n\t(routine == BBLAS_HER2K) || (routine == BBLAS_TRMM)  ||\n\t(routine == BBLAS_TRSM))\n    {\n\tfor ( int batch_iter = 0; batch_iter < test->batch_count; batch_iter++ )\n\t{\n\t    free( test->arrayB[batch_iter] );\n\t}\n\tfree( test->arrayB );\n    }\n\n\n    /*Free matrices  {C}_i*/\n    if ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) ||\n\t(routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)||\n\t(routine == BBLAS_HER2K))\n    {\n\tfor ( int batch_iter = 0; batch_iter < test->batch_count; batch_iter++ )\n\t{\n\t    free( test->arrayC[batch_iter] );\n\t}\n\tfree( test->arrayC );\n    }\n\n    /*Free memory allocated for error computation */\n    switch(test->target)\n    {\n\tcase BBLAS_MKL:\n\t    free(test->mkl_error);\n\t    //free(test->group_size);\n\t    for ( int batch_iter = 0; batch_iter < test->batch_count; batch_iter++ )\n\t    {\n\t\tfree( test->mkl_result[batch_iter] );\n\t    }\n\t    free( test->mkl_result );\n\n\t    break;\n\n\tcase BBLAS_CUBLAS:\n\tcase BBLAS_MAGMA:\n\t    free(test->device_error);\n\n\t    for (int batch_iter =0; batch_iter < test->batch_count; batch_iter++)\n\t    {\n\t\tfree(test->device_result[batch_iter]);\n\t    }\n\n\t    free(test->device_result);\n\n\t    break;\n\n\tcase BBLAS_OTHER:\n\n\t    free(test->other_error);\n\n\t    for (int batch_iter =0; batch_iter < test->batch_count; batch_iter++)\n\t    {\n\t\tfree(test->other_result[batch_iter]);\n\t    }\n\t    free(test->other_result);\n\n\t    break;\n\n\tcase BBLAS_CUMKL:\n\t    free(test->mkl_error);\n\t    free(test->device_error);\n\t    free(test->group_size);\n\n\t    for (int batch_iter =0; batch_iter < test->batch_count; batch_iter++)\n\t    {\n\t\tfree(test->device_result[batch_iter]);\n\t\tfree(test->mkl_result[batch_iter]);\n\t    }\n\t    free(test->device_result);\n\t    free(test->mkl_result);\n\n\t    break;\n\n\tdefault:\n\t    printf(\"In bblas_zfreetest(): Target no defined\\n\");\n\t    exit(EXIT_FAILURE);\n    }\n    /*Free INFO */\n    free( test->info );\n\n    /*Free cuda memory */\n    if( (test->target == BBLAS_CUBLAS) || (test->target == BBLAS_MAGMA))\n    {\n\tbblas_zcudaFree(test);\n    }\n\n\tif ((routine == BBLAS_GEMM)  || (routine == BBLAS_SYMM)  ||\n\t(routine == BBLAS_HEMM)  || (routine == BBLAS_SYR2K) ||\n\t(routine == BBLAS_HER2K) || (routine == BBLAS_TRMM)  ||\n\t(routine == BBLAS_TRSM))\n\t{\n\t\tfree(test->Binitnorm);\n    }\n\n    /*Free memory allocated for norm computing */\n\tif ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t(routine == BBLAS_HEMM) || (routine == BBLAS_SYRK) ||\n\t(routine == BBLAS_HERK) || (routine == BBLAS_SYR2K)||\n\t(routine == BBLAS_HER2K))\n    {\n\t\tfree(test->Cinitnorm);\n    }\n}\n\n#undef COMPLEX\n", "meta": {"hexsha": "17e183abdde810a384d7767994f1f20fc2ee3aa6", "size": 51573, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/bblas_ztesting.c", "max_stars_repo_name": "NLAFET/BBLAS-ref", "max_stars_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "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": "testing/bblas_ztesting.c", "max_issues_repo_name": "NLAFET/BBLAS-ref", "max_issues_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/bblas_ztesting.c", "max_forks_repo_name": "NLAFET/BBLAS-ref", "max_forks_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "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.0841439689, "max_line_length": 105, "alphanum_fraction": 0.6192969189, "num_tokens": 15834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.38116318985101105}}
{"text": "#ifndef __Q_INCS\n#define __Q_INCS\n#include <alloca.h>\n#include <assert.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <float.h>\n// #include <gsl/gsl_vector.h>\n// #include <gsl/gsl_matrix.h>\n// #include <gsl/gsl_blas.h>\n// #include <gsl/gsl_linalg.h>\n#include <inttypes.h>\n#include <limits.h>\n// TODO P4 do not think this is needed:#include <malloc.h>\n#include <math.h>\n#include <memory.h>\n#include <omp.h>\n#include <stdbool.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#ifndef MAC_OSX\n// TODO P1 Is this needed?#include <sys/sysinfo.h>\n#endif\n#include <sys/time.h>\n#include <time.h>\n#include <unistd.h>\n#include \"q_macros.h\"\n#endif\n", "meta": {"hexsha": "e8002a17807ccfc6e4436a08bc56fe64386b947a", "size": 755, "ext": "h", "lang": "C", "max_stars_repo_path": "UTILS/inc/q_incs.h", "max_stars_repo_name": "subramon/qlu", "max_stars_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_stars_repo_licenses": ["MIT"], "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/inc/q_incs.h", "max_issues_repo_name": "subramon/qlu", "max_issues_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-07-29T16:48:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-26T23:47:22.000Z", "max_forks_repo_path": "UTILS/inc/q_incs.h", "max_forks_repo_name": "subramon/qlu", "max_forks_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-05-14T22:34:13.000Z", "max_forks_repo_forks_event_max_datetime": "2015-05-14T22:34:13.000Z", "avg_line_length": 21.5714285714, "max_line_length": 58, "alphanum_fraction": 0.7006622517, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.38116318608964034}}
{"text": "#ifndef MATH_FNS_H\n#define MATH_FNS_H\n\n#ifdef USE_OPENBLAS\nextern \"C\" \n{\n#include <cblas.h>\n}\n#endif\n\n\nstruct QuantizationParams\n{\n\tfloat scale;\n\tuint8_t zero_point;\n};\n\ntemplate<typename Dtype>\nvoid cpu_gemm(bool transA, bool transB, uint64_t M, uint64_t N, uint64_t K, Dtype alpha, Dtype* A, Dtype* B, Dtype beta, Dtype* C);\n\ntemplate<typename Dtype>\nvoid cpu_axpy(uint64_t N, Dtype alpha, Dtype* X, Dtype* Y, Dtype* C); // c = alpha * x + y\n\ntemplate<typename Dtype>\nvoid cpu_axpby(uint64_t N, Dtype alpha, Dtype* X_ptr, Dtype beta, Dtype* Y_ptr, Dtype* C_ptr); // c = alpha * x + beta * y\n\ntemplate<typename Dtype>\nvoid cpu_mul(uint64_t N, Dtype* A_ptr, Dtype* B_ptr, Dtype* C_ptr); // c = a * b\n\ntemplate<typename Dtype>\nvoid cpu_mul(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr, Dtype beta, Dtype* C_ptr); // c = beta * c + alpha * a * b\n\ntemplate<typename Dtype>\nvoid cpu_mul(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha * a\n\ntemplate<typename Dtype>\nvoid cpu_add(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha + a\n\ntemplate<typename Dtype>\nvoid cpu_div(uint64_t N, Dtype* A_ptr, Dtype* B_ptr, Dtype* C_ptr); // c += a / b\n\ntemplate<typename Dtype>\nvoid cpu_div(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr, Dtype beta, Dtype* C_ptr); // c = (beta * c) +  (alpha * a / b)\n\ntemplate<typename Dtype>\nvoid cpu_div_back(uint64_t N, Dtype* A_ptr, Dtype* B_ptr, Dtype* C_ptr, Dtype* D_ptr); // special function for processing div_backward during backpropagation (calculates d += a * (-b) / (c * c))\n\ntemplate<typename Dtype>\nvoid cpu_sig(uint64_t N, const Dtype* A_ptr, Dtype* B_ptr); // b = sig(a)\n\ntemplate<typename Dtype>\nvoid cpu_tanh(uint64_t N, const Dtype* A_ptr, Dtype* B_ptr); // b = tanh(a)\n\ntemplate<typename Dtype>\nvoid cpu_powx(uint64_t N, const Dtype* A_ptr, Dtype x, Dtype* B_ptr); // b = pow(a,x)\n\ntemplate<typename Dtype>\nvoid cpu_copy(uint64_t N, Dtype* A_ptr, Dtype* B_ptr); // b = a\n\ntemplate<typename Dtype>\nvoid cpu_max(const Dtype* src, Dtype* dst, uint64_t* indices, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid cpu_max_backward(Dtype* dst, const Dtype* src, const uint64_t* indices, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid cpu_sum(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid cpu_sum_backward(Dtype* dst, const Dtype* src, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid cpu_mean(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid cpu_mean_backward(Dtype* dst, const Dtype* src, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid cpu_var(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid cpu_var_backward(Dtype* dst, const Dtype* src, const Dtype* op1, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid cpu_std(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride, bool sample_mode = true);\n\ntemplate<typename Dtype>\nvoid cpu_std_backward(Dtype* dst, const Dtype* src, const Dtype* op1, const Dtype* std, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride, bool sample_mode = true);\n\ntemplate<typename Dtype>\nvoid cpu_dropout(Dtype* dst, Dtype* src, unsigned int* mask, unsigned int threshold, Dtype scale, uint64_t len);\n\ntemplate<typename Dtype>\nvoid cpu_sig_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels);\n\ntemplate<typename Dtype>\nvoid cpu_tanh_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels);\n\nvoid cpu_transpose(float* src, float* dst, int dim_1, int dim_2,\n\tint stride_src_dim_1, int stride_src_dim_1_minus_1, int stride_src_dim_2, int stride_src_dim_2_minus_1,\n\tint stride_trn_dim_1, int stride_trn_dim_1_minus_1, int stride_trn_dim_2, int stride_trn_dim_2_minus_1, uint64_t numels);\n\n\nvoid quantized_matmul(bool traspose_A, bool traspose_B, uint64_t M, uint64_t N, uint64_t K, uint8_t alpha, uint8_t* A, uint8_t* B, uint8_t beta, uint8_t* C, QuantizationParams* qparms, int* bias, int* workspace); // workspace must be at least (M + N) * sizeof(int) bytes\n\n\n\n\n\n//-------------------------------------CUDA functions----------------------------------------------------------------\n\ntemplate<typename Dtype>\nvoid gpu_sum(Dtype* A, Dtype* B, Dtype* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B);\n\ntemplate<typename Dtype>\nvoid gpu_sub(Dtype* A, Dtype* B, Dtype* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B);\n\n// C =  A * B\ntemplate<typename Dtype>\nvoid gpu_mul(uint64_t N, Dtype* A_ptr, Dtype* B_ptr, Dtype* C_ptr);\n\n// C = beta * C + A * B\n// supports broadcast semantics\n// use this when C dims >= both A and B dims (avoid atomics)\ntemplate<typename Dtype>\nvoid gpu_mul(Dtype* A, Dtype* B, Dtype* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B, Dtype beta);\n\n// C = C + A * B\n// supports broadcast semantics\n// use this when C dims < either A or B dims (uses atomics, but no support for uint8_t)\nvoid gpu_mul(float* A, float* B, float* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B, uint64_t height_C, uint64_t width_C);\n\ntemplate<typename Dtype>\nvoid gpu_mul(uint64_t N, Dtype alpha, Dtype* A, Dtype* B, Dtype beta, Dtype* C); // c = beta * c + alpha * a * b\n\ntemplate<typename Dtype>\nvoid gpu_mul(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha * a\n\n// C =  A / B\n// supports broadcast semantics\n// use this when C dims >= both A and B dims (avoid atomics)\ntemplate<typename Dtype>\nvoid gpu_div(Dtype* A, Dtype* B, Dtype* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B);\n\n// C = C + A / B\n// use this when C numels == A numels == B numels (no broadcast therefore fastest)\ntemplate<typename Dtype>\nvoid gpu_div(uint64_t N, Dtype* A, Dtype* B, Dtype* C);\n\n// C = A / B\n// use this when C numels == A numels == B numels (no broadcast therefore fastest)\n//template<typename Dtype>\n//void gpu_div2(uint64_t N, Dtype* A, Dtype* B, Dtype* C);\n\n// C = C + A / B\n// supports broadcast semantics\n// use this when C dims < either A or B dims (uses atomics, but no support for uint8_t)\nvoid gpu_div(float* A, float* B, float* C, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B, uint64_t height_C, uint64_t width_C);\n\n// special function for processing div_backward during backpropagation (calculates d += a * (-b) / (c * c))\n// supports broadcast semantics\n// use this when D dims < A or B or C dims (uses atomics, but no support for uint8_t)\n//template<typename Dtype>\nvoid gpu_div_back(float* A, float* B, float* C, float* D, uint64_t height_A, uint64_t width_A, uint64_t height_B, uint64_t width_B, uint64_t height_C, uint64_t width_C, uint64_t height_D, uint64_t width_D);\n\ntemplate<typename Dtype>\nvoid gpu_sum(Dtype* data, Dtype* sum, uint64_t len);\n\ntemplate<typename Dtype>\nvoid gpu_nll(Dtype* input, Dtype* target, Dtype* loss, uint64_t len, uint64_t batches);\n\ntemplate<typename Dtype>\nvoid gpu_scalar_mul(Dtype* A, Dtype* B, Dtype scalar, uint64_t len); // B = scaler * A\n\n// C += alpha * A\n// supports broadcast semantics\n// use this when C dims < A dims (uses atomics, but no support for uint8_t)\nvoid gpu_scalar_mul(float alpha, float* A, float* C, uint64_t height_A, uint64_t width_A, uint64_t height_C, uint64_t width_C);\n\ntemplate<typename Dtype>\nvoid gpu_fill(Dtype* memory, uint64_t size, Dtype value);\n\ntemplate<typename Dtype>\nvoid gpu_fill(Dtype* memory, uint64_t len, Dtype* value);\n\nvoid gpu_sgd_step(float* weight_ptr, float* weight_grad_ptr, float* velocity_ptr, int64_t numels, float mo, float wd, float lr);\n\ntemplate<typename Dtype>\nvoid gpu_max(const Dtype* src, Dtype* dst, uint64_t* indices, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid gpu_max_backward(Dtype* dst, const Dtype* src, const uint64_t* indices, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid gpu_powx(uint64_t N, const Dtype* A, Dtype x, Dtype* B); // b = pow(a,x)\n\ntemplate<typename Dtype>\nvoid gpu_exp(Dtype* dst, const Dtype* src, const uint64_t numels);\n\ntemplate<typename Dtype>\nvoid gpu_log(Dtype* dst, const Dtype* src, const uint64_t numels);\n\ntemplate<typename Dtype>\nvoid gpu_sig(Dtype* dst, const Dtype* src, const uint64_t numels);\n\ntemplate<typename Dtype>\nvoid gpu_sig_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels);\n\ntemplate<typename Dtype>\nvoid gpu_tanh(Dtype* dst, const Dtype* src, const uint64_t numels);\n\ntemplate<typename Dtype>\nvoid gpu_tanh_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels);\n\ntemplate<typename Dtype>\nvoid gpu_sum(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid gpu_sum_backward(Dtype* dst, const Dtype* src, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid gpu_add(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha + a\n\ntemplate<typename Dtype>\nvoid gpu_axpy(uint64_t N, Dtype alpha, Dtype* X_ptr, Dtype* Y_ptr, Dtype* C_ptr);\n\ntemplate<typename Dtype>\nvoid gpu_axpby(uint64_t N, Dtype alpha, Dtype* X_ptr, Dtype beta, Dtype* Y_ptr, Dtype* C_ptr); // c = alpha * x + beta * y\n\ntemplate<typename Dtype>\nvoid gpu_relu(Dtype* dst, Dtype* src, uint64_t len);\n\ntemplate<typename Dtype>\nvoid gpu_relu_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t len);\n\n\ntemplate<typename Dtype>\nvoid gpu_dropout(Dtype* dst, Dtype* src, unsigned int* mask, unsigned int threshold, Dtype scale, uint64_t len);\n\ntemplate<typename Dtype>\nvoid gpu_transpose(Dtype* src, Dtype* dst, int dim_1, int dim_2,\n\tint stride_src_dim_1, int stride_src_dim_1_minus_1, int stride_src_dim_2, int stride_src_dim_2_minus_1,\n\tint stride_trn_dim_1, int stride_trn_dim_1_minus_1, int stride_trn_dim_2, int stride_trn_dim_2_minus_1, uint64_t numels);\n\ntemplate<typename Dtype>\nvoid gpu_cat(Dtype* dest, Dtype* op1, Dtype* op2, uint64_t dest_stride_1, uint64_t dest_stride_2, uint64_t op1_stride, uint64_t op2_stride_1, uint64_t op2_stride_2, uint64_t dim_offset, uint64_t op1_numels, uint64_t op2_numels);\n\n\ntemplate<typename Dtype>\nvoid gpu_cat_backward(Dtype* dest, Dtype* src, uint64_t dest_stride, uint64_t src_stride, uint64_t dest_numels);\n\ntemplate<typename Dtype>\nvoid gpu_cat_backward(Dtype* dest, Dtype* src, uint64_t dest_stride_1, uint64_t dest_stride_2, uint64_t src_stride_1, uint64_t src_stride_2, uint64_t dim_offset, uint64_t op1_numels, uint64_t dest_numels);\n\ntemplate<typename Dtype>\nvoid gpu_embedding(Dtype* dst, Dtype* wts, int* indices, uint64_t numels, uint64_t indices_per_batch, unsigned int embedding_dim);\n\ntemplate<typename Dtype>\nvoid gpu_embedding_backward(Dtype* dst, Dtype* wts, int* indices, uint64_t numels, uint64_t indices_per_batch, unsigned int embedding_dim);\n\ntemplate<typename Dtype>\nvoid gpu_sqrt(Dtype* dst, const Dtype* src, const uint64_t numels);\n\ntemplate<typename Dtype>\nvoid gpu_sqrt_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels);\n\ntemplate<typename Dtype>\nvoid gpu_mean(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid gpu_mean_backward(Dtype* dst, const Dtype* src, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid gpu_var(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid gpu_var_backward(Dtype* dst, const Dtype* src, const Dtype* op1, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride);\n\ntemplate<typename Dtype>\nvoid gpu_std(const Dtype* src, Dtype* dst, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride, bool sample_mode = true);\n\ntemplate<typename Dtype>\nvoid gpu_std_backward(Dtype* dst, const Dtype* src, const Dtype* op1, const Dtype* std, const uint64_t numels, const uint64_t ratio, const uint64_t dim_size, const uint64_t stride, bool sample_mode = true);\n\n#endif // MATH_FNS_H\n", "meta": {"hexsha": "36ef3008f89d4c7161ee97929d043a66e0b4535c", "size": 13084, "ext": "h", "lang": "C", "max_stars_repo_path": "l-ten/math_fns.h", "max_stars_repo_name": "adeobootpin/light-tensor", "max_stars_repo_head_hexsha": "dfc2d19495848e773b7367427cf848e4ac30b29d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "l-ten/math_fns.h", "max_issues_repo_name": "adeobootpin/light-tensor", "max_issues_repo_head_hexsha": "dfc2d19495848e773b7367427cf848e4ac30b29d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "l-ten/math_fns.h", "max_forks_repo_name": "adeobootpin/light-tensor", "max_forks_repo_head_hexsha": "dfc2d19495848e773b7367427cf848e4ac30b29d", "max_forks_repo_licenses": ["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.7482517483, "max_line_length": 270, "alphanum_fraction": 0.7582543565, "num_tokens": 3651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3811143226035598}}
{"text": "/* fft/gsl_fft_halfcomplex.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_FFT_HALFCOMPLEX_H__\n#define __GSL_FFT_HALFCOMPLEX_H__\n\n#if !defined( GSL_FUN )\n#  if !defined( GSL_DLL )\n#    define GSL_FUN extern\n#  elif defined( BUILD_GSL_DLL )\n#    define GSL_FUN extern __declspec(dllexport)\n#  else\n#    define GSL_FUN extern __declspec(dllimport)\n#  endif\n#endif\n\n#include <stddef.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_fft.h>\n#include <gsl/gsl_fft_real.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\nGSL_FUN int gsl_fft_halfcomplex_radix2_backward (double data[], const size_t stride, const size_t n);\nGSL_FUN int gsl_fft_halfcomplex_radix2_inverse (double data[], const size_t stride, const size_t n);\nGSL_FUN int gsl_fft_halfcomplex_radix2_transform (double data[], const size_t stride, const size_t n);\n\ntypedef struct\n  {\n    size_t n;\n    size_t nf;\n    size_t factor[64];\n    gsl_complex *twiddle[64];\n    gsl_complex *trig;\n  }\ngsl_fft_halfcomplex_wavetable;\n\nGSL_FUN gsl_fft_halfcomplex_wavetable * gsl_fft_halfcomplex_wavetable_alloc (size_t n);\n\nGSL_FUN void\ngsl_fft_halfcomplex_wavetable_free (gsl_fft_halfcomplex_wavetable * wavetable);\n\n\nGSL_FUN int gsl_fft_halfcomplex_backward (double data[], const size_t stride, const size_t n,\n                                  const gsl_fft_halfcomplex_wavetable * wavetable,\n                                  gsl_fft_real_workspace * work);\n\nGSL_FUN int gsl_fft_halfcomplex_inverse (double data[], const size_t stride, const size_t n,\n                                 const gsl_fft_halfcomplex_wavetable * wavetable,\n                                 gsl_fft_real_workspace * work);\n\nGSL_FUN int gsl_fft_halfcomplex_transform (double data[], const size_t stride, const size_t n,\n                                   const gsl_fft_halfcomplex_wavetable * wavetable,\n                                   gsl_fft_real_workspace * work);\n\nGSL_FUN int\ngsl_fft_halfcomplex_unpack (const double halfcomplex_coefficient[],\n                            double complex_coefficient[],\n                            const size_t stride, const size_t n);\n\nGSL_FUN int\ngsl_fft_halfcomplex_radix2_unpack (const double halfcomplex_coefficient[],\n                                   double complex_coefficient[],\n                                   const size_t stride, const size_t n);\n\n__END_DECLS\n\n#endif /* __GSL_FFT_HALFCOMPLEX_H__ */\n", "meta": {"hexsha": "f80611da2ea7b27eef8568cc30d3b4b025bd8b17", "size": 3341, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_fft_halfcomplex.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_fft_halfcomplex.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_fft_halfcomplex.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 34.4432989691, "max_line_length": 102, "alphanum_fraction": 0.7024842861, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.381099341546705}}
{"text": "#include <mpi.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_math.h>\n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n#ifdef CR_DIFFUSION_GREEN\n#include \"cosmic_rays.h\"\n\nvoid compute_diff_weights(int target, int mode);\nvoid scatter_diffusion(int target, int mode);\n\n#define m_p (PROTONMASS * All.HubbleParam / All.UnitMass_in_g)\n\nvoid greenf_diffusion(void)\n{\n  int *noffset, *nbuffer, *nsend, *nsend_local, *numlist, *ndonelist;\n  int i, j, n;\n  int ndone;\n  long long ntot, ntotleft;\n  int maxfill, source;\n  int level, ngrp, sendTask, recvTask;\n  int place, nexport;\n  double cr_efac_i, kappa_egy;\n  double kappa, a3inv, egysum, egytot, egytot_before;\n  double meanKineticEnergy, qmeanKin;\n  double CR_q_i;\n  MPI_Status status;\n\n\n  if(ThisTask == 0)\n    {\n      printf(\"Doing diffusion step with Green function method\\n\");\n      fflush(stdout);\n    }\n\n  for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)\n    {\n      \n      noffset = mymalloc(sizeof(int) * NTask);\t/* offsets of bunches in common list */\n      nbuffer = mymalloc(sizeof(int) * NTask);\n      nsend_local = mymalloc(sizeof(int) * NTask);\n      nsend = mymalloc(sizeof(int) * NTask * NTask);\n      ndonelist = mymalloc(sizeof(int) * NTask);\n      \n      \n      if(All.ComovingIntegrationOn)\n\ta3inv = 1 / (All.Time * All.Time * All.Time);\n      else\n\ta3inv = 1;\n      \n      \n      egysum = 0;\n      \n      for(n = 0, NumSphUpdate = 0; n < N_gas; n++)\n\t{\n\t  if(P[n].Type == 0)\n\t    {\n\t      NumSphUpdate++;\n\t      \n\t      egysum += SphP[n].CR_E0[CRpop];\n\t      \n\t      SphP[n].CR_DeltaE[CRpop] = 0;\n\t      SphP[n].CR_DeltaN[CRpop] = 0;\n\t      \n\t      kappa = All.CR_DiffusionCoeff;\n\t      \n\t      if(All.CR_DiffusionDensScaling != 0.0)\n\t\tkappa *= pow(SphP[n].d.Density * a3inv / All.CR_DiffusionDensZero, All.CR_DiffusionDensScaling);\n\t      \n\t      if(All.CR_DiffusionEntropyScaling != 0.0)\n\t\tkappa *= pow(SphP[n].Entropy / All.CR_DiffusionEntropyZero, All.CR_DiffusionEntropyScaling);\n\t      \n\t      if(SphP[n].CR_E0[CRpop] > 0)\n\t\t{\n\t\t  CR_q_i = SphP[n].CR_q0[CRpop] * pow(SphP[n].d.Density * a3inv, 0.33333);\n\t\t  \n\t\t  cr_efac_i =\n\t\t    CR_Tab_MeanEnergy(CR_q_i, All.CR_Alpha[CRpop] - 0.3333, CRpop) \n\t\t    / CR_Tab_MeanEnergy(CR_q_i, All.CR_Alpha[CRpop], CRpop);\n\t\t  \n\t\t  kappa *= (All.CR_Alpha[CRpop] - 1) / (All.CR_Alpha[CRpop] - 1.33333) * pow(CR_q_i, 0.3333);\n\t\t  \n\t\t  kappa_egy = kappa * cr_efac_i;\n\t\t}\n\t      else\n\t\tkappa_egy = kappa;\n\n\t      \n\t      SphP[n].CR_Kappa[CRpop] = kappa;\n\t      SphP[n].CR_Kappa_egy[CRpop] = kappa_egy;\n\t    }\n\t}\n      \n      \n      MPI_Allreduce(&egysum, &egytot_before, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n      \n      numlist = mymalloc(NTask * sizeof(int) * NTask);\n      MPI_Allgather(&NumSphUpdate, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);\n      for(i = 0, ntot = 0; i < NTask; i++)\n\tntot += numlist[i];\n      myfree(numlist);\n      \n      \n      /* first, sum the weights */\n      \n      \n      i = 0;\t\t\t/* beginn with this index */\n      ntotleft = ntot;\t\t/* particles left for all tasks together */\n      \n      while(ntotleft > 0)\n\t{\n\t  for(j = 0; j < NTask; j++)\n\t    nsend_local[j] = 0;\n\t  \n\t  /* do local particles and prepare export list */\n\t  \n\t  for(nexport = 0, ndone = 0; i < NumPart && nexport < All.BunchSizeDensity - NTask; i++)\n\t    if(P[i].Type == 0)\n\t      {\n\t\tndone++;\n\t\t\n\t\tfor(j = 0; j < NTask; j++)\n\t\t  Exportflag[j] = 0;\n\t\t\n\t\tcompute_diff_weights(i, 0);\n\t\t\n\t\tfor(j = 0; j < NTask; j++)\n\t\t  {\n\t\t    if(Exportflag[j])\n\t\t      {\n\t\t\tDensDataIn[nexport].Pos[0] = P[i].Pos[0];\n\t\t\tDensDataIn[nexport].Pos[1] = P[i].Pos[1];\n\t\t\tDensDataIn[nexport].Pos[2] = P[i].Pos[2];\n\t\t\tDensDataIn[nexport].Hsml = PPP[i].Hsml;\n\t\t\tDensDataIn[nexport].CR_Kappa[CRpop] = SphP[i].CR_Kappa[CRpop];\n\t\t\tDensDataIn[nexport].CR_Kappa_egy[CRpop] = SphP[i].CR_Kappa_egy[CRpop];\n\t\t\t\n\t\t\tDensDataIn[nexport].Index = i;\n\t\t\tDensDataIn[nexport].Task = j;\n\t\t\tnexport++;\n\t\t\tnsend_local[j]++;\n\t\t      }\n\t\t  }\n\t      }\n\n\n\t  qsort(DensDataIn, nexport, sizeof(struct densdata_in), dens_compare_key);\n\t  \n\t  for(j = 1, noffset[0] = 0; j < NTask; j++)\n\t    noffset[j] = noffset[j - 1] + nsend_local[j - 1];\n\t  \n\t  MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD);\n\t  \n\t  \n\t  /* now do the particles that need to be exported */\n\t  \n\t  for(level = 1; level < (1 << PTask); level++)\n\t    {\n\t      for(j = 0; j < NTask; j++)\n\t\tnbuffer[j] = 0;\n\t      for(ngrp = level; ngrp < (1 << PTask); ngrp++)\n\t\t{\n\t\t  maxfill = 0;\n\t\t  for(j = 0; j < NTask; j++)\n\t\t    {\n\t\t      if((j ^ ngrp) < NTask)\n\t\t\tif(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])\n\t\t\t  maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];\n\t\t    }\n\t\t  if(maxfill >= All.BunchSizeDensity)\n\t\t    break;\n\t\t  \n\t\t  sendTask = ThisTask;\n\t\t  recvTask = ThisTask ^ ngrp;\n\t\t  \n\t\t  if(recvTask < NTask)\n\t\t    {\n\t\t      if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)\n\t\t\t{\n\t\t\t  /* get the particles */\n\t\t\t  MPI_Sendrecv(&DensDataIn[noffset[recvTask]],\n\t\t\t\t       nsend_local[recvTask] * sizeof(struct densdata_in), MPI_BYTE,\n\t\t\t\t       recvTask, TAG_CONDUCT_A,\n\t\t\t\t       &DensDataGet[nbuffer[ThisTask]],\n\t\t\t\t       nsend[recvTask * NTask + ThisTask] * sizeof(struct densdata_in),\n\t\t\t\t       MPI_BYTE, recvTask, TAG_CONDUCT_A, MPI_COMM_WORLD, &status);\n\t\t\t}\n\t\t    }\n\t\t  \n\t\t  for(j = 0; j < NTask; j++)\n\t\t    if((j ^ ngrp) < NTask)\n\t\t      nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];\n\t\t}\n\t      \n\t      \n\t      for(j = 0; j < nbuffer[ThisTask]; j++)\n\t\tcompute_diff_weights(j, 1);\n\t      \n\t      \n\t      for(j = 0; j < NTask; j++)\n\t\tnbuffer[j] = 0;\n\t      for(ngrp = level; ngrp < (1 << PTask); ngrp++)\n\t\t{\n\t\t  maxfill = 0;\n\t\t  for(j = 0; j < NTask; j++)\n\t\t    {\n\t\t      if((j ^ ngrp) < NTask)\n\t\t\tif(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])\n\t\t\t  maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];\n\t\t    }\n\t\t  if(maxfill >= All.BunchSizeDensity)\n\t\t    break;\n\t\t  \n\t\t  sendTask = ThisTask;\n\t\t  recvTask = ThisTask ^ ngrp;\n\t\t  \n\t\t  if(recvTask < NTask)\n\t\t    {\n\t\t      if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)\n\t\t\t{\n\t\t\t  /* send the results */\n\t\t\t  MPI_Sendrecv(&DensDataResult[nbuffer[ThisTask]],\n\t\t\t\t       nsend[recvTask * NTask + ThisTask] * sizeof(struct densdata_out),\n\t\t\t\t       MPI_BYTE, recvTask, TAG_CONDUCT_B,\n\t\t\t\t       &DensDataPartialResult[noffset[recvTask]],\n\t\t\t\t       nsend_local[recvTask] * sizeof(struct densdata_out),\n\t\t\t\t       MPI_BYTE, recvTask, TAG_CONDUCT_B, MPI_COMM_WORLD, &status);\n\t\t\t  \n\t\t\t  /* add the result to the particles */\n\t\t\t  for(j = 0; j < nsend_local[recvTask]; j++)\n\t\t\t    {\n\t\t\t      source = j + noffset[recvTask];\n\t\t\t      place = DensDataIn[source].Index;\n\t\t\t      \n\t\t\t      SphP[place].CR_WeightSum += DensDataPartialResult[source].CR_WeightSum;\n\t\t\t      SphP[place].CR_WeightSum_egy += DensDataPartialResult[source].CR_WeightSum_egy;\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\t\t  \n\t\t  for(j = 0; j < NTask; j++)\n\t\t    if((j ^ ngrp) < NTask)\n\t\t      nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];\n\t\t}\n\t      level = ngrp - 1;\n\t    }\n\t  \n\t  MPI_Allgather(&ndone, 1, MPI_INT, ndonelist, 1, MPI_INT, MPI_COMM_WORLD);\n\t  for(j = 0; j < NTask; j++)\n\t    ntotleft -= ndonelist[j];\n\t}\n      \n\n\n  /*************** now do the diffusion step itself */\n\n\n\n\n\n      numlist = mymalloc(NTask * sizeof(int) * NTask);\n      MPI_Allgather(&NumSphUpdate, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);\n      for(i = 0, ntot = 0; i < NTask; i++)\n\tntot += numlist[i];\n      myfree(numlist);\n      \n      /* first, sum the weights */\n      \n      i = 0;\t\t\t/* beginn with this index */\n      ntotleft = ntot;\t\t/* particles left for all tasks together */\n      \n      while(ntotleft > 0)\n\t{\n\t  for(j = 0; j < NTask; j++)\n\t    nsend_local[j] = 0;\n\t  \n\t  /* do local particles and prepare export list */\n\t  \n\t  for(nexport = 0, ndone = 0; i < NumPart && nexport < All.BunchSizeDensity - NTask; i++)\n\t    if(P[i].Type == 0)\n\t      {\n\t\tndone++;\n\t\t\n\t\tfor(j = 0; j < NTask; j++)\n\t\t  Exportflag[j] = 0;\n\t\t\n\t\tscatter_diffusion(i, 0);\n\t\t\n\t\tfor(j = 0; j < NTask; j++)\n\t\t  {\n\t\t    if(Exportflag[j])\n\t\t      {\n\t\t\tDensDataIn[nexport].Pos[0] = P[i].Pos[0];\n\t\t\tDensDataIn[nexport].Pos[1] = P[i].Pos[1];\n\t\t\tDensDataIn[nexport].Pos[2] = P[i].Pos[2];\n\t\t\t\n\t\t\tDensDataIn[nexport].CR_Kappa[CRpop] = SphP[i].CR_Kappa[CRpop];\n\t\t\tDensDataIn[nexport].CR_Kappa_egy[CRpop] = SphP[i].CR_Kappa_egy[CRpop];\n\t\t\tDensDataIn[nexport].CR_WeightSum = SphP[i].CR_WeightSum;\n\t\t\tDensDataIn[nexport].CR_WeightSum_egy = SphP[i].CR_WeightSum_egy;\n\t\t\tDensDataIn[nexport].Hsml = PPP[i].Hsml;\n\t\t\tDensDataIn[nexport].CR_E0[CRpop] = SphP[i].CR_E0[CRpop];\n\t\t\tDensDataIn[nexport].CR_n0[CRpop] = SphP[i].CR_n0[CRpop];\n\t\t\t\n\t\t\tDensDataIn[nexport].Index = i;\n\t\t\tDensDataIn[nexport].Task = j;\n\t\t\tnexport++;\n\t\t\tnsend_local[j]++;\n\t\t      }\n\t\t  }\n\t      }\n\t  \n\t  \n\t  qsort(DensDataIn, nexport, sizeof(struct densdata_in), dens_compare_key);\n\t  \n\t  for(j = 1, noffset[0] = 0; j < NTask; j++)\n\t    noffset[j] = noffset[j - 1] + nsend_local[j - 1];\n\t  \n\t  MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD);\n\t  \n\t  \n\t  /* now do the particles that need to be exported */\n\t  \n\t  for(level = 1; level < (1 << PTask); level++)\n\t    {\n\t      for(j = 0; j < NTask; j++)\n\t\tnbuffer[j] = 0;\n\t      for(ngrp = level; ngrp < (1 << PTask); ngrp++)\n\t\t{\n\t\t  maxfill = 0;\n\t\t  for(j = 0; j < NTask; j++)\n\t\t    {\n\t\t      if((j ^ ngrp) < NTask)\n\t\t\tif(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])\n\t\t\t  maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];\n\t\t    }\n\t\t  if(maxfill >= All.BunchSizeDensity)\n\t\t    break;\n\t\t  \n\t\t  sendTask = ThisTask;\n\t\t  recvTask = ThisTask ^ ngrp;\n\t\t  \n\t\t  if(recvTask < NTask)\n\t\t    {\n\t\t      if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)\n\t\t\t{\n\t\t\t  /* get the particles */\n\t\t\t  MPI_Sendrecv(&DensDataIn[noffset[recvTask]],\n\t\t\t\t       nsend_local[recvTask] * sizeof(struct densdata_in), MPI_BYTE,\n\t\t\t\t       recvTask, TAG_CONDUCT_A,\n\t\t\t\t       &DensDataGet[nbuffer[ThisTask]],\n\t\t\t\t       nsend[recvTask * NTask + ThisTask] * sizeof(struct densdata_in),\n\t\t\t\t       MPI_BYTE, recvTask, TAG_CONDUCT_A, MPI_COMM_WORLD, &status);\n\t\t\t}\n\t\t    }\n\t\t  \n\t\t  for(j = 0; j < NTask; j++)\n\t\t    if((j ^ ngrp) < NTask)\n\t\t      nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];\n\t\t}\n\t      \n\t      \n\t      for(j = 0; j < nbuffer[ThisTask]; j++)\n\t\tscatter_diffusion(j, 1);\n\t      \n\t      \n\t      level = ngrp - 1;\n\t    }\n\t  \n\t  MPI_Allgather(&ndone, 1, MPI_INT, ndonelist, 1, MPI_INT, MPI_COMM_WORLD);\n\t  for(j = 0; j < NTask; j++)\n\t    ntotleft -= ndonelist[j];\n\t}\n      \n      \n      \n      /* now set the new cosmic ray prorperties */\n      \n      \n      egysum = 0;\n      \n      for(n = 0; n < N_gas; n++)\n\t{\n\t  if(P[n].Type == 0)\n\t    {\n\t      SphP[n].CR_E0[CRpop] = SphP[n].CR_DeltaE[CRpop];\n\t      SphP[n].CR_n0[CRpop] = SphP[n].CR_DeltaN[CRpop];\n\t      \n\t      egysum += SphP[n].CR_E0[CRpop];\n\t      \n\t      SphP[n].CR_DeltaE[CRpop] = 0;\n\t      SphP[n].CR_DeltaN[CRpop] = 0;\n\t      \n\t      if(SphP[n].CR_n0[CRpop] > 1.0e-12 && SphP[n].CR_E0[CRpop] > 0)\n\t\t{\n\t\t  meanKineticEnergy = SphP[n].CR_E0[CRpop] * m_p / SphP[n].CR_n0[CRpop];\n\t\t  \n\t\t  qmeanKin = CR_q_from_mean_kinetic_energy(meanKineticEnergy[CRpop], CRpop);\n\t\t  \n\t\t  SphP[n].CR_q0[CRpop] = qmeanKin * pow(SphP[n].d.Density * a3inv, -(1.0 / 3.0));\n\t\t  SphP[n].CR_C0[CRpop] = SphP[n].CR_n0[CRpop] * (All.CR_Alpha[CRpop] - 1.0) * \n\t\t    pow(SphP[n].CR_q0[CRpop], All.CR_Alpha[CRpop] - 1.0);\n\t\t}\n\t      else\n\t\t{\n\t\t  SphP[n].CR_E0[CRpop] = 0.0;\n\t\t  SphP[n].CR_n0[CRpop] = 0.0;\n\t\t  \n\t\t  SphP[n].CR_q0[CRpop] = 1.0e10;\n\t\t  SphP[n].CR_C0[CRpop] = 0.0;\n\t\t}\n\t    }\n\t}\n      \n      MPI_Allreduce(&egysum, &egytot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n      if(ThisTask == 0)\n\t{\n\t  printf(\"Energy before/after= %g | %g\\n\", egytot_before, egytot);\n\t  fflush(stdout);\n\t}\n      \n      \n      myfree(ndonelist);\n      myfree(nsend);\n      myfree(nsend_local);\n      myfree(nbuffer);\n      myfree(noffset);\n      \n      \n      All.TimeOfLastDiffusion = All.Time;\n    }\n}\n\n\n\n\nvoid compute_diff_weights(int target, int mode)\n{\n  int j, n;\n  int startnode, numngb_inbox;\n  double h;\n  double weightsum, weightsum_egy, kappa, kappa_egy, kappaeff, kappaeff_egy;;\n  double dx, dy, dz, r, r2;\n  MyFloat *pos;\n\n  if(mode == 0)\n    {\n      pos = P[target].Pos;\n      h = PPP[target].Hsml;\n      kappa = SphP[target].CR_Kappa;\n      kappa_egy = SphP[target].CR_Kappa_egy;\n    }\n  else\n    {\n      pos = DensDataGet[target].Pos;\n      h = DensDataGet[target].Hsml;\n      kappa = DensDataGet[target].CR_Kappa;\n      kappa_egy = DensDataGet[target].CR_Kappa_egy;\n    }\n\n\n  weightsum = weightsum_egy = 0;\n\n  startnode = All.MaxPart;\n\n  kappaeff = 4 * kappa * (All.Time - All.TimeOfLastDiffusion);\n  kappaeff_egy = 4 * kappa_egy * (All.Time - All.TimeOfLastDiffusion);\n\n  if(kappaeff > 0)\n    {\n      do\n\t{\n\t  numngb_inbox = ngb_treefind_variable(&pos[0], h, &startnode);\n\n\t  for(n = 0; n < numngb_inbox; n++)\n\t    {\n\t      j = Ngblist[n];\n\n\t      dx = pos[0] - P[j].Pos[0];\n\t      dy = pos[1] - P[j].Pos[1];\n\t      dz = pos[2] - P[j].Pos[2];\n\n#ifdef PERIODIC\t\t\t/*  now find the closest image in the given box size  */\n\t      if(dx > boxHalf_X)\n\t\tdx -= boxSize_X;\n\t      if(dx < -boxHalf_X)\n\t\tdx += boxSize_X;\n\t      if(dy > boxHalf_Y)\n\t\tdy -= boxSize_Y;\n\t      if(dy < -boxHalf_Y)\n\t\tdy += boxSize_Y;\n\t      if(dz > boxHalf_Z)\n\t\tdz -= boxSize_Z;\n\t      if(dz < -boxHalf_Z)\n\t\tdz += boxSize_Z;\n#endif\n\t      r2 = dx * dx + dy * dy + dz * dz;\n\n\t      if(r2 < h * h)\n\t\t{\n\t\t  r = sqrt(r2);\n\n\t\t  weightsum += P[j].Mass * exp(-r2 / kappaeff);\n\t\t  weightsum_egy += P[j].Mass * exp(-r2 / kappaeff_egy);\n\t\t}\n\t    }\n\t}\n      while(startnode >= 0);\n    }\n\n  if(mode == 0)\n    {\n      SphP[target].CR_WeightSum = weightsum;\n      SphP[target].CR_WeightSum_egy = weightsum_egy;\n    }\n  else\n    {\n      DensDataResult[target].CR_WeightSum = weightsum;\n      DensDataResult[target].CR_WeightSum_egy = weightsum_egy;\n    }\n\n}\n\n\n\nvoid scatter_diffusion(int target, int mode)\n{\n  int j, n;\n  int startnode, numngb_inbox;\n  double h, weight;\n  double weightsum, kappa, kappaeff, CR_E0, CR_n0;\n  double weightsum_egy, kappa_egy, kappaeff_egy;\n  double dx, dy, dz, r, r2;\n  MyFloat *pos;\n\n  if(mode == 0)\n    {\n      pos = P[target].Pos;\n      h = PPP[target].Hsml;\n      kappa = SphP[target].CR_Kappa;\n      kappa_egy = SphP[target].CR_Kappa_egy;\n      weightsum = SphP[target].CR_WeightSum;\n      weightsum_egy = SphP[target].CR_WeightSum_egy;\n      CR_E0 = SphP[target].CR_E0;\n      CR_n0 = SphP[target].CR_n0;\n    }\n  else\n    {\n      pos = DensDataGet[target].Pos;\n      h = DensDataGet[target].Hsml;\n      kappa = DensDataGet[target].CR_Kappa;\n      kappa_egy = DensDataGet[target].CR_Kappa_egy;\n      weightsum = DensDataGet[target].CR_WeightSum;\n      weightsum_egy = DensDataGet[target].CR_WeightSum_egy;\n      CR_E0 = DensDataGet[target].CR_E0;\n      CR_n0 = DensDataGet[target].CR_n0;\n    }\n\n\n  startnode = All.MaxPart;\n\n  kappaeff = 4 * kappa * (All.Time - All.TimeOfLastDiffusion);\n  kappaeff_egy = 4 * kappa_egy * (All.Time - All.TimeOfLastDiffusion);\n\n  if(kappaeff > 0)\n    {\n      do\n\t{\n\t  numngb_inbox = ngb_treefind_variable(&pos[0], h, &startnode);\n\n\t  for(n = 0; n < numngb_inbox; n++)\n\t    {\n\t      j = Ngblist[n];\n\n\t      dx = pos[0] - P[j].Pos[0];\n\t      dy = pos[1] - P[j].Pos[1];\n\t      dz = pos[2] - P[j].Pos[2];\n\n#ifdef PERIODIC\t\t\t/*  now find the closest image in the given box size  */\n\t      if(dx > boxHalf_X)\n\t\tdx -= boxSize_X;\n\t      if(dx < -boxHalf_X)\n\t\tdx += boxSize_X;\n\t      if(dy > boxHalf_Y)\n\t\tdy -= boxSize_Y;\n\t      if(dy < -boxHalf_Y)\n\t\tdy += boxSize_Y;\n\t      if(dz > boxHalf_Z)\n\t\tdz -= boxSize_Z;\n\t      if(dz < -boxHalf_Z)\n\t\tdz += boxSize_Z;\n#endif\n\t      r2 = dx * dx + dy * dy + dz * dz;\n\n\t      if(r2 < h * h)\n\t\t{\n\t\t  r = sqrt(r2);\n\n\t\t  weight = P[j].Mass * exp(-r2 / kappaeff) / weightsum;\n\t\t  SphP[j].CR_DeltaN += CR_n0 * weight;\n\n\t\t  weight = P[j].Mass * exp(-r2 / kappaeff_egy) / weightsum_egy;\n\t\t  SphP[j].CR_DeltaE += CR_E0 * weight;\n\n\t\t}\n\t    }\n\t}\n      while(startnode >= 0);\n    }\n}\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "2d51081502288f4c4b2ad4bf99a5f20b5acf95b9", "size": 16094, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/greenf_diffusion.c", "max_stars_repo_name": "egpbos/egp", "max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/greenf_diffusion.c", "max_issues_repo_name": "egpbos/egp", "max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/greenf_diffusion.c", "max_forks_repo_name": "egpbos/egp", "max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f", "max_forks_repo_licenses": ["Apache-2.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.8330658106, "max_line_length": 98, "alphanum_fraction": 0.5685348577, "num_tokens": 5622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.38107049897686995}}
{"text": "\ufeff/*! \\file vhartree.h\n    \\brief Hartree\u30dd\u30c6\u30f3\u30b7\u30e3\u30eb\u3092\u6c42\u3081\u308b\u30af\u30e9\u30b9\u306e\u5ba3\u8a00\n\n    Copyright \u00a9  2015 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n\n#ifndef _VHARTREE_H_\n#define _VHARTREE_H_\n\n#pragma once\n\n#include \"diffdata.h\"\n#include \"property.h\"\n#include <memory>           // for std::unique_ptr\n#include <gsl/gsl_spline.h> // for gsl_interp_accel, gsl_interp_accel_free, gsl_spline, gsl_spline_free\n\nnamespace schrac {\n    //! A class.\n    /*!\n        Hartree\u30dd\u30c6\u30f3\u30b7\u30e3\u30eb\u3092\u6c42\u3081\u308b\u30af\u30e9\u30b9\n    */\n    class Vhartree final {\n        // #region \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u30fb\u30c7\u30b9\u30c8\u30e9\u30af\u30bf\n\n    public:\n        //! A constructor.\n        /*!\n            \u552f\u4e00\u306e\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n            \\param r_mesh_ r\u306e\u30e1\u30c3\u30b7\u30e5\n        */\n        Vhartree(std::vector<double> const & r_mesh);\n\n        //! A private copy constructor.\n        /*!\n            \u30b3\u30d4\u30fc\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n        */\n        Vhartree(Vhartree const & rhs);\n\n        //! A destructor.\n        /*!\n            \u30c7\u30d5\u30a9\u30eb\u30c8\u30c7\u30b9\u30c8\u30e9\u30af\u30bf\n        */\n        ~Vhartree() = default;\n\n        // #region \u30e1\u30f3\u30d0\u95a2\u6570\n        \n        //!  A public member function (const).\n        /*!\n            Hartree\u30dd\u30c6\u30f3\u30b7\u30e3\u30eb\u306e\u5fae\u5206\u5024\u3092\u8fd4\u3059\n            \\param r \u6975\u5ea7\u6a19\u306er\n            \\return Hartree\u30dd\u30c6\u30f3\u30b7\u30e3\u30eb\u306e\u5fae\u5206\u5024\n        */\n        double dvhartree_dr(double r) const;\n\n        //!  A public member function.\n        /*!\n            Hartree\u30dd\u30c6\u30f3\u30b7\u30e3\u30eb\u304c\u5883\u754c\u6761\u4ef6\u3092\u6e80\u305f\u3059\u3088\u3046\u306b\u30bb\u30c3\u30c8\u3059\u308b\n            \\param Z \u539f\u5b50\u6838\u306e\u96fb\u8377\n        */\n        void set_vhartree_boundary_condition(double Z);\n\n        //!  A public member function.\n        /*!\n            Hartree\u30dd\u30c6\u30f3\u30b7\u30e3\u30eb\u3092\u521d\u671f\u5316\u3059\u308b\n        */\n        void vhart_init();\n\n        //!  A public member function (const).\n        /*!\n            Hartree\u30dd\u30c6\u30f3\u30b7\u30e3\u30eb\u306e\u5024\u3092\u8fd4\u3059\n            \\param r \u6975\u5ea7\u6a19\u306er\n            \\return Hartree\u30dd\u30c6\u30f3\u30b7\u30e3\u30eb\u306e\u5024\n        */\n        double vhartree(double r) const;\n\n        // #endregion \u30e1\u30f3\u30d0\u95a2\u6570\n\n        // #region \u30d7\u30ed\u30d1\u30c6\u30a3\n\n    public:\n        //! A property.\n        /*!\n            Hartree\u30dd\u30c6\u30f3\u30b7\u30e3\u30eb\u304c\u683c\u7d0d\u3055\u308c\u305f\u53ef\u5909\u9577\u914d\u5217\u3078\u306e\u30d7\u30ed\u30d1\u30c6\u30a3\n        */\n        Property<std::vector<double>> Vhart;\n\n        // #endregion \u30d7\u30ed\u30d1\u30c6\u30a3\n\n        // #region \u30e1\u30f3\u30d0\u5909\u6570\n\n    private:\n        //! A private member variable.\n        /*!\n            gsl_interp_accel\u3078\u306e\u30b9\u30de\u30fc\u30c8\u30dd\u30a4\u30f3\u30bf\n        */\n        std::unique_ptr<gsl_interp_accel, decltype(&gsl_interp_accel_free)> const acc_;\n        \n        //! A private member variable.\n        /*!\n            r\u306e\u30e1\u30c3\u30b7\u30e5\u304c\u683c\u7d0d\u3055\u308c\u305f\u53ef\u5909\u9577\u914d\u5217\n        */\n        std::vector<double> const r_mesh_;\n\n        //! A private member variable.\n        /*!\n            gsl_interp_type\u3078\u306e\u30b9\u30de\u30fc\u30c8\u30dd\u30a4\u30f3\u30bf\n        */\n        std::unique_ptr<gsl_spline, decltype(&gsl_spline_free)> const spline_;\n\n        //! A private member variable.\n        /*!\n            Hartree\u30dd\u30c6\u30f3\u30b7\u30e3\u30eb\u304c\u683c\u7d0d\u3055\u308c\u305f\u53ef\u5909\u9577\u914d\u5217\n        */\n        std::vector<double> vhart_;\n\n        // #endregion \u30e1\u30f3\u30d0\u5909\u6570\n\n        // #region \u7981\u6b62\u3055\u308c\u305f\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u30fb\u30e1\u30f3\u30d0\u95a2\u6570\n\n    private:\n        //! A private constructor (deleted).\n        /*!\n            \u30c7\u30d5\u30a9\u30eb\u30c8\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\uff08\u7981\u6b62\uff09\n        */\n        Vhartree() = delete;\n\n        //! A private member function (deleted).\n        /*!\n            operator=()\u306e\u5ba3\u8a00\uff08\u7981\u6b62\uff09\n            \\param \u30b3\u30d4\u30fc\u5143\u306e\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\uff08\u672a\u4f7f\u7528\uff09\n            \\return \u30b3\u30d4\u30fc\u5143\u306e\u30aa\u30d6\u30b8\u30a7\u30af\u30c8\n        */\n        Vhartree & operator=(Vhartree const &) = delete;\n\n        // #endregion \u7981\u6b62\u3055\u308c\u305f\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u30fb\u30e1\u30f3\u30d0\u95a2\u6570\n    };\n}\n\n#endif  // _VHARTREE_H_\n", "meta": {"hexsha": "4be0331943e1053b70b04e947c46d355571318b5", "size": 3180, "ext": "h", "lang": "C", "max_stars_repo_path": "src/vhartree.h", "max_stars_repo_name": "dc1394/Schrac", "max_stars_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T23:35:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T07:10:30.000Z", "max_issues_repo_path": "src/vhartree.h", "max_issues_repo_name": "dc1394/schrac", "max_issues_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vhartree.h", "max_forks_repo_name": "dc1394/schrac", "max_forks_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5531914894, "max_line_length": 103, "alphanum_fraction": 0.5311320755, "num_tokens": 1022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.38069233003885883}}
{"text": "#include <stdio.h>\n#include <math.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_odeiv.h>\n#define DIM 1\n#define NPTS 100\n\n#define abserr 1e-5\n#define relerr 1e-5\n#define mem 10000\ntypedef double (* function) (double x, void * params); \ndouble integrate(function f, void * params, double lower_bound, double upper_bound);\n\n//int func (double t, const double y[], double f[], void *params);\n//void gsl_ode(gsl_odeiv_system sys, double Xo, double maxtime);\n", "meta": {"hexsha": "e1a9fdf1c96a6a46473e09a91c8c60f761dbeca8", "size": 569, "ext": "h", "lang": "C", "max_stars_repo_path": "src/integrate.h", "max_stars_repo_name": "cboettig/AdaptiveDynamics", "max_stars_repo_head_hexsha": "3b0711e06a05b4808b16688ab68c745365005ec3", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/integrate.h", "max_issues_repo_name": "cboettig/AdaptiveDynamics", "max_issues_repo_head_hexsha": "3b0711e06a05b4808b16688ab68c745365005ec3", "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/integrate.h", "max_forks_repo_name": "cboettig/AdaptiveDynamics", "max_forks_repo_head_hexsha": "3b0711e06a05b4808b16688ab68c745365005ec3", "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": 28.45, "max_line_length": 84, "alphanum_fraction": 0.7346221441, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.38050696159143704}}
{"text": "/// based on https://mklimenko.github.io/english/2018/06/04/constexpr-random/\n#pragma once\n\n#include <atomic>\n#include <cstdint>\n#include <gsl/gsl>\n#include <limits>\n#include <random>\n\n#include \"HyperionUtils/Concepts.h\"\n\nnamespace hyperion::math {\n\tusing gsl::narrow_cast;\n#ifndef _MSC_VER\n\tusing std::size_t;\n#endif //_MSC_VER\n\n// clang-format off\n#ifndef _MSC_VER\n\t// NOLINTNEXTLINE\n\t#define IGNORE_DATETIME_START \\\n\t\t_Pragma(\"GCC diagnostic push\") \\\n\t\t_Pragma(\"GCC diagnostic ignored \\\"-Wdate-time\\\"\")\n#else\n\t// NOLINTNEXTLINE\n\t#define IGNORE_DATETIME_START\n#endif\n// clang-format on\n\n// clang-format off\n#ifndef _MSC_VER\n\t// NOLINTNEXTLINE\n\t#define IGNORE_DATETIME_STOP \\\n\t\t_Pragma(\"GCC diagnostic pop\")\n#else\n\t// NOLINTNEXTLINE\n\t#define IGNORE_DATETIME_STOP\n#endif\n\t// clang-format on\n\n// clang-format off\n#ifndef _MSC_VER\n\t// NOLINTNEXTLINE\n\t#define IGNORE_WEAK_VTABLES_START \\\n\t\t_Pragma(\"GCC diagnostic push\") \\\n\t\t_Pragma(\"GCC diagnostic ignored \\\"-Wweak-vtables\\\"\")\n#else\n\t// NOLINTNEXTLINE\n\t#define IGNORE_WEAK_VTABLES_START\n#endif\n// clang-format on\n\n// clang-format off\n#ifndef _MSC_VER\n\t// NOLINTNEXTLINE\n\t#define IGNORE_WEAK_VTABLES_STOP \\\n\t\t_Pragma(\"GCC diagnostic pop\")\n#else\n\t// NOLINTNEXTLINE\n\t#define IGNORE_WEAK_VTABLES_STOP\n#endif\n\t// clang-format on\n\n\tIGNORE_WEAK_VTABLES_START\n\tclass Engine {\n\t  public:\n\t\tconstexpr Engine() noexcept = default;\n\t\tconstexpr Engine(const Engine& engine) noexcept = default;\n\t\tconstexpr Engine(Engine&& engine) noexcept = default;\n\t\tvirtual constexpr ~Engine() noexcept = default;\n\n\t\t[[nodiscard]] virtual constexpr auto get_seed() const noexcept -> size_t = 0;\n\t\tvirtual constexpr auto seed(size_t seed) noexcept -> void = 0;\n\t\tvirtual constexpr auto generate() noexcept -> size_t = 0;\n\n\t\ttemplate<size_t size>\n\t\tinline constexpr auto generate_array() noexcept -> std::array<size_t, size> {\n\t\t\tauto array = std::array<size_t, size>();\n\t\t\tfor(auto& element : array) {\n\t\t\t\telement = generate();\n\t\t\t}\n\t\t}\n\n\t\t[[nodiscard]] virtual constexpr auto max_value() const noexcept -> size_t = 0;\n\n\t\tconstexpr auto operator=(const Engine& engine) noexcept -> Engine& = default;\n\t\tconstexpr auto operator=(Engine&& engine) noexcept -> Engine& = default;\n\n\t\tvirtual constexpr auto operator()() noexcept -> size_t = 0;\n\t};\n\tIGNORE_WEAK_VTABLES_STOP\n\n\ttemplate<size_t max = 714025>\n\tclass LinearCongruentialEngine final : public Engine {\n\t  public:\n\t\tconstexpr LinearCongruentialEngine() noexcept = default;\n\t\tconstexpr LinearCongruentialEngine(\n\t\t\tconst LinearCongruentialEngine& engine) noexcept = default;\n\t\tconstexpr LinearCongruentialEngine(LinearCongruentialEngine&& engine) noexcept = default;\n\t\tconstexpr ~LinearCongruentialEngine() noexcept final = default;\n\n\t\tIGNORE_DATETIME_START\n\t\t[[nodiscard]] inline constexpr auto get_seed() const noexcept -> size_t final {\n\t\t\tconst auto* t = __TIME__;\n\t\t\treturn time_from_string(t, 0) * 60 * 60 + time_from_string(t, 3) * 60\n\t\t\t\t   + time_from_string(t, 6);\n\t\t}\n\t\tIGNORE_DATETIME_STOP\n\n\t\tinline constexpr auto seed(size_t seed) noexcept -> void final {\n\t\t\tm_previous = seed;\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto generate() noexcept -> size_t final {\n\t\t\tm_previous = (m_a * m_previous + m_c) % max;\n\t\t\treturn m_previous;\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto max_value() const noexcept -> size_t final {\n\t\t\treturn max;\n\t\t}\n\n\t\tconstexpr auto operator=(const LinearCongruentialEngine& engine) noexcept\n\t\t\t-> LinearCongruentialEngine& = default;\n\t\tconstexpr auto operator=(LinearCongruentialEngine&& engine) noexcept\n\t\t\t-> LinearCongruentialEngine& = default;\n\n\t\tinline constexpr auto operator()() noexcept -> size_t final {\n\t\t\treturn generate();\n\t\t}\n\n\t  private:\n\t\tsize_t m_a = 4096;\n\t\tsize_t m_c = 150889;\n\t\tsize_t m_previous = get_seed();\n\n\t\t[[nodiscard]] static inline constexpr auto\n\t\ttime_from_string(const char* string, int offset) noexcept -> size_t {\n\t\t\treturn narrow_cast<size_t>(string[offset] - '0') * 10\t// NOLINT\n\t\t\t\t   + narrow_cast<size_t>(string[offset + 1] - '0'); // NOLINT\n\t\t}\n\t};\n\n\tIGNORE_WEAK_VTABLES_START\n\ttemplate<typename EngineType, utils::concepts::Numeric T = int>\n\trequires utils::concepts::Derived<EngineType, Engine>\n\tclass Distribution {\n\t  public:\n\t\tconstexpr Distribution() noexcept = default;\n\t\tconstexpr Distribution(const Distribution& distribution) noexcept = default;\n\t\tconstexpr Distribution(Distribution&& distribution) noexcept = default;\n\t\tvirtual constexpr ~Distribution() noexcept = default;\n\n\t\tvirtual constexpr auto normalized_random_value() noexcept -> double = 0;\n\t\tvirtual constexpr auto random_value() noexcept -> T = 0;\n\t\ttemplate<size_t size>\n\t\tinline constexpr auto normalized_random_values() noexcept -> std::array<double, size> {\n\t\t\tauto array = std::array<double, size>();\n\t\t\tfor(auto& element : array) {\n\t\t\t\telement = normalized_random_value();\n\t\t\t}\n\n\t\t\treturn array;\n\t\t}\n\t\ttemplate<size_t size>\n\t\tinline constexpr auto random_values() noexcept -> std::array<T, size> {\n\t\t\tauto array = std::array<T, size>();\n\t\t\tfor(auto& element : array) {\n\t\t\t\telement = random_value();\n\t\t\t}\n\n\t\t\treturn array;\n\t\t}\n\t\tvirtual constexpr auto seed(size_t seed) noexcept -> void = 0;\n\t\t[[nodiscard]] virtual constexpr auto get_seed() noexcept -> size_t = 0;\n\n\t\t[[nodiscard]] virtual constexpr auto get_min() const noexcept -> T = 0;\n\t\tvirtual constexpr auto set_min(T min) noexcept -> void = 0;\n\t\t[[nodiscard]] virtual constexpr auto get_max() const noexcept -> T = 0;\n\t\tvirtual constexpr auto set_max(T max) noexcept -> void = 0;\n\n\t\tconstexpr auto\n\t\toperator=(const Distribution& distribution) noexcept -> Distribution& = default;\n\t\tconstexpr auto operator=(Distribution&& distribution) noexcept -> Distribution& = default;\n\n\t\tvirtual constexpr auto operator()() noexcept -> T = 0;\n\t};\n\tIGNORE_WEAK_VTABLES_STOP\n\n\ttemplate<typename EngineType, utils::concepts::Numeric T = int>\n\trequires utils::concepts::Derived<EngineType, Engine>\n\tclass UniformDistribution final : public Distribution<EngineType, T> {\n\t  public:\n\t\tconstexpr UniformDistribution() noexcept requires\n\t\t\tutils::concepts::DefaultConstructible<EngineType>\n\t\t\t: m_engine(std::make_unique<EngineType>()) {\n\t\t\tm_engine->seed(m_engine->get_seed());\n\t\t}\n\t\tconstexpr UniformDistribution(T min, T max) noexcept requires\n\t\t\tutils::concepts::DefaultConstructible<EngineType>\n\t\t\t: m_min(min), m_max(max), m_engine(std::make_unique<EngineType>()) {\n\t\t\tm_engine->seed(m_engine->get_seed());\n\t\t}\n\t\tconstexpr UniformDistribution(T min, T max, std::unique_ptr<EngineType>&& engine) noexcept\n\t\t\t: m_min(min), m_max(max), m_engine(engine) {\n\t\t\tm_engine->seed(m_engine->get_seed());\n\t\t}\n\t\texplicit constexpr UniformDistribution(std::unique_ptr<EngineType>&& engine) noexcept\n\t\t\t: m_engine(std::move(engine)) {\n\t\t\tm_engine->seed(m_engine->get_seed());\n\t\t}\n\t\ttemplate<typename... Args>\n\t\trequires utils::concepts::Derived<EngineType, Engine> && utils::concepts::\n\t\t\tConstructibleFrom<EngineType, Args...>\n\t\texplicit constexpr UniformDistribution(Args&&... args) noexcept\n\t\t\t: m_engine(std::make_unique<EngineType>(args...)) {\n\t\t\tm_engine->seed(m_engine->get_seed());\n\t\t}\n\t\ttemplate<typename... Args>\n\t\trequires utils::concepts::Derived<EngineType, Engine> && utils::concepts::\n\t\t\tConstructibleFrom<EngineType, Args...>\n\t\texplicit constexpr UniformDistribution(T min, T max, Args&&... args) noexcept\n\t\t\t: m_min(min), m_max(max), m_engine(std::make_unique<EngineType>(args...)) {\n\t\t\tm_engine->seed(m_engine->get_seed());\n\t\t}\n\t\tconstexpr UniformDistribution(const UniformDistribution& distribution) noexcept = default;\n\t\tconstexpr UniformDistribution(UniformDistribution&& distribution) noexcept = default;\n\n\t\tconstexpr ~UniformDistribution() noexcept final = default;\n\n\t\tinline constexpr auto normalized_random_value() noexcept -> double final {\n\t\t\treturn narrow_cast<double>(m_engine->generate())\n\t\t\t\t   / narrow_cast<double>(m_engine->max_value());\n\t\t}\n\n\t\tinline constexpr auto random_value() noexcept -> T final {\n\t\t\treturn narrow_cast<T>(this->normalized_random_value()) * (m_max - m_min) + m_min;\n\t\t}\n\n\t\tinline constexpr auto seed(size_t seed) noexcept -> void final {\n\t\t\tm_engine->seed(seed);\n\t\t}\n\n\t\t[[nodiscard]] inline constexpr auto get_seed() noexcept -> size_t final {\n\t\t\treturn m_engine->get_seed();\n\t\t}\n\n\t\tinline constexpr auto set_min(T min) noexcept -> void final {\n\t\t\tm_min = min;\n\t\t}\n\t\t[[nodiscard]] inline constexpr auto get_min() const noexcept -> T final {\n\t\t\treturn m_min;\n\t\t}\n\n\t\tinline constexpr auto set_max(T max) noexcept -> void final {\n\t\t\tm_max = max;\n\t\t}\n\t\t[[nodiscard]] inline constexpr auto get_max() const noexcept -> T final {\n\t\t\treturn m_max;\n\t\t}\n\n\t\tconstexpr auto operator=(const UniformDistribution& distribution) noexcept\n\t\t\t-> UniformDistribution& = default;\n\t\tconstexpr auto\n\t\toperator=(UniformDistribution&& distribution) noexcept -> UniformDistribution& = default;\n\n\t\tinline constexpr auto operator()() noexcept -> T final {\n\t\t\treturn random_value();\n\t\t}\n\n\t  private:\n\t\tT m_min = narrow_cast<T>(0);\n\t\tT m_max = narrow_cast<T>(1);\n\t\tstd::unique_ptr<EngineType> m_engine;\n\t};\n\n\ttemplate<utils::concepts::Numeric T = float>\n\t[[clang::no_destroy]] static math::UniformDistribution<math::LinearCongruentialEngine<>, T>\n\t\tGLOBAL_UNIFORM_DISTRIBUTION;\n\n\ttemplate<utils::concepts::Numeric T = float>\n\tstatic std::atomic_bool GLOBAL_UNIFORM_DISTRIBUTION_INITIALIZED;\n\n\ttemplate<utils::concepts::Numeric T = float>\n\tinline static constexpr auto initialize_global_uniform_distribution() noexcept -> void {\n\t\tbool initialized = false;\n\t\tif(GLOBAL_UNIFORM_DISTRIBUTION_INITIALIZED<T>.compare_exchange_strong(\n\t\t\t   initialized,\n\t\t\t   true,\n\t\t\t   std::memory_order_seq_cst))\n\t\t{\n\t\t\tGLOBAL_UNIFORM_DISTRIBUTION<\n\t\t\t\tT> = math::UniformDistribution<math::LinearCongruentialEngine<>, T>();\n\t\t}\n\t}\n\n\ttemplate<utils::concepts::FloatingPoint T = float>\n\tinline auto random_value() noexcept -> T {\n\t\tinitialize_global_uniform_distribution<T>();\n\t\tGLOBAL_UNIFORM_DISTRIBUTION<T>.set_min(narrow_cast<T>(0));\n\t\tGLOBAL_UNIFORM_DISTRIBUTION<T>.set_max(narrow_cast<T>(1));\n\n\t\treturn GLOBAL_UNIFORM_DISTRIBUTION<T>();\n\t}\n\n\ttemplate<utils::concepts::Numeric T = float>\n\tinline auto random_value(T min, T max) noexcept -> T {\n\t\tinitialize_global_uniform_distribution<T>();\n\n\t\tGLOBAL_UNIFORM_DISTRIBUTION<T>.set_min(min);\n\t\tGLOBAL_UNIFORM_DISTRIBUTION<T>.set_max(max);\n\n\t\treturn GLOBAL_UNIFORM_DISTRIBUTION<T>();\n\t}\n} // namespace hyperion::math\n", "meta": {"hexsha": "840d8e553fe4f6c20abd26a21a7b3122276ba3f3", "size": 10332, "ext": "h", "lang": "C", "max_stars_repo_path": "include/HyperionMath/Random.h", "max_stars_repo_name": "braxtons12/Hyperion-Math", "max_stars_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/HyperionMath/Random.h", "max_issues_repo_name": "braxtons12/Hyperion-Math", "max_issues_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/HyperionMath/Random.h", "max_forks_repo_name": "braxtons12/Hyperion-Math", "max_forks_repo_head_hexsha": "77093e282b29747741fd4164b4e165fcef267471", "max_forks_repo_licenses": ["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.6962025316, "max_line_length": 92, "alphanum_fraction": 0.7282229965, "num_tokens": 2581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.38047260224356205}}
{"text": "#ifndef IBS_HPP\n#define IBS_HPP\n\n#include <array>\n#include <assert.h>\n#include <memory>\n#include <vector>\n\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_errno.h>\n\n#include \"jspec2/force.h\"\n#include \"jspec2/rate.h\"\n\nclass Lattice;\nclass IonBeam;\n\nenum class IBSModel {MARTINI, BM, BMC, BMZ};\n\nclass IBSSolver {\nprotected:\n    double log_c_ = 0.0;     //Coulomb logarithm.\n    double k_ = 0.0;          //Coupling rate in transverse directions.\n    bool cache_invalid = true;\n    bool ibs_by_element = false; //Calculate and output the ibs rate contribution element by element.\n\n    void ibs_coupling(double &rx, double &ry, double k, double emit_x, double emit_y);\n    void ibs_by_element_sddshead(std::ofstream& outfile, int n_element);\npublic:\n    double log_c() const { return log_c_; }\n    double k() const { return k_; }\n    void set_k(double x) { k_ = x; }\n    void set_log_c(double x) { log_c_ = x; }\n    void set_ibs_by_element(bool b) {ibs_by_element = b;}\n    void invalidate_cache() { cache_invalid = true; }\n\n    IBSSolver(double log_c, double k);\n\n    virtual rate3d rate(const Lattice &lattice, const IonBeam &beam) = 0;\n};\n\nclass IBSSolver_Martini : public IBSSolver {\nprivate:\n    struct TrigonometryStorageUV {\n        double sin_u2_cos_v2;\n        double g1;\n        double g2_1;\n        double g2_2;\n    };\n    struct TrigonometryStorageV {\n        double sin_v;\n        double cos_v;\n    };\n    struct TrigonometryStorageU {\n        double sin_u;\n        double sin_u2;\n        double cos_u2;\n        double g3;\n        std::vector<TrigonometryStorageUV> uv;\n    };\n    struct OpticalStorage {\n        double a;\n        double b2;\n        double c2;\n        double d2;\n        double dtld;\n        double k1;\n        double k2;\n        double k3;\n    };\n\n    int nu_ = 0;                //Grid number in u direction.\n    int nv_ = 0;                //Grid number in v direction.\n    int nz_ = 0;                //Grid number in z direction.\n\n    // Scratch variables for IBS calculation (Martini model)\n    std::vector<double> sigma_xbet, sigma_xbetp, sigma_y, sigma_yp;\n    std::vector<TrigonometryStorageU> storage_u;\n    std::vector<TrigonometryStorageV> storage_v;\n    std::vector<OpticalStorage> storage_opt;\n    std::vector<double> f1, f2, f3;\n\n    void bunch_size(const Lattice &lattice, const IonBeam &beam);\n    void abcdk(const Lattice &lattice, const IonBeam &beam);\n    void coef_f();\n    void f();\n    double coef_a(const Lattice &lattice, const IonBeam &beam) const;\npublic:\n    int nu() const { return nu_; }\n    int nv() const { return nv_; }\n    int nz() const { return nz_; }\n    void set_nu(int nu) { assert(nu>0&&\"Wrong value of nu in IBS parameters!\"); nu_ = nu; invalidate_cache(); }\n    void set_nv(int nv) { assert(nv>0&&\"Wrong value of nv in IBS parameters!\"); nv_ = nv; invalidate_cache(); }\n    void set_nz(int nz) { assert(nz>0&&\"Wrong value of nz in IBS parameters!\"); nz_ = nz; invalidate_cache(); }\n    IBSSolver_Martini(int nu, int nv, int nz, double log_c, double k);\n    virtual rate3d rate(const Lattice &lattice, const IonBeam &beam) override;\n};\n\nclass IBSSolver_BM : public IBSSolver {\n private:\n     struct OpticalStorage { //variables only depends on the TWISS parameters and the energy.\n         double phi;\n         double dx2; //D_x * D_x\n         double dx_betax_phi_2; // D_x * D_x / (beta_x * beta_x) + phi * phi\n         double sqrt_betay; // sqrt(beta_y)\n         double gamma_phi_2; // gamma * gamma * phi * phi\n     };\n     struct Kernels {\n         double  psi;\n         double sx;\n         double sp;\n         double sxp;\n         double inv_sigma;\n     };\n\n     // Scratch variables for IBS calculation (Bjorken-Mtingwa model using Sergei Nagitsev's formula)\n     std::vector<OpticalStorage> optical_strage;\n     std::vector<Kernels> kernels;\n     void init_fixed_var(const Lattice &lattice, const IonBeam &beam);\n     void calc_kernels(const Lattice &lattice, const IonBeam &beam);\n     double coef_bm(const Lattice &lattice, const IonBeam &beam) const;\n public:\n     IBSSolver_BM(double log_c, double k);\n     virtual rate3d rate(const Lattice &lattice, const IonBeam &beam) override;\n\n};\n\nclass IBSSolver_BMZ : public IBSSolver {\nprivate:\n    int nt_;     //Number of steps for integration.\n    struct optcl{\n        double phi_x2;\n        double phi_y2;\n        double hx;\n        double hy;\n        double dx_2_over_beta_x;\n        double dy_2_over_beta_y;\n        double beta_x_over_hx;\n        double hy_beta_x_over_hx;\n        double beta_phi_x2;\n        double beta_phi_y2;\n        double hy_over_beta_y;\n    };\n    std::vector<optcl> optical;\n    double factor = 3;\n    void init_optical(const Lattice &lattice);\n    double calc_abc(const Lattice &lattice, const IonBeam& beam, int i, double& a, double& b, double& c,\n                               double& ax, double& bx, double& ay, double& by,double& al, double& bl);\n    double coef(const Lattice &lattice, const IonBeam &beam) const;\n    void calc_integral(double a, double b, double c, double ax, double bx, double ay, double by, double al,\n                                  double bl, double& ix, double& iy, double& is, int nt, double u);\npublic:\n    IBSSolver_BMZ(int nt, double log_c, double k);\n    void set_nt(int n){assert(n>0&&\"Wrong value of nt in IBS parameters!\"); nt_ = n; invalidate_cache();}\n    virtual rate3d rate(const Lattice &lattice, const IonBeam &beam) override;\n    void set_factor(double x){factor = x;}\n};\n\n\nclass IBSSolver_BM_Complete : public IBSSolver {\nprivate:\n    int nt_;\n    double inv_ex;\n    double inv_ey;\n    double inv_dp2;\n    double gamma;\n    double gamma2;\n    double factor = 3;\n    struct Itgrl{\n        double lambda;\n        double lambda_sqrt;\n        double ct;   // ct = 1/(1-t)^2\n    };\n    struct Optc {\n        double phix;\n        double phiy;\n        double hx;\n        double hy;\n    };\n\n    std::vector<Optc> optc;\n    std::vector<Itgrl> itgrl;\n    void init_optc(const Lattice &lattice);\n    double det(std::array<std::array<double, 3>,3>& l);\n    double inv(std::array<std::array<double, 3>,3>& l, std::array<std::array<double, 3>,3>& v);\n    double trace(std::array<std::array<double, 3>,3>& l){return l[0][0]+l[1][1]+l[2][2];}\n    void calc_l(const Lattice& lattice, int i, std::array<std::array<double, 3>,3>& lh,\n                std::array<std::array<double, 3>,3>& lv, std::array<std::array<double, 3>,3>& ls);\n    void calc_itgl(int i, std::array<std::array<double, 3>,3>& ii, std::array<std::array<double, 3>,3>& l,\n                  std::array<std::array<double, 3>,3>& ll, std::array<std::array<double, 3>,3>& lh,\n                  std::array<std::array<double, 3>,3>& lv, std::array<std::array<double, 3>,3>& ls);\n    void calc_beam_const(const IonBeam& beam);\n    double coef(const Lattice &lattice, const IonBeam &beam) const;\npublic:\n     IBSSolver_BM_Complete(int nt, double log_c, double k);\n     void set_factor(double x){factor = x;}\n     virtual rate3d rate(const Lattice &lattice, const IonBeam &beam) override;\n\n};\n//\n//class IBSSolver_BMZ2 : public IBSSolver {\n//private:\n//    int nt_;     //Number of steps for integration.\n//    struct itgrl{\n//        double lambda;\n////        double lambda_2;\n////        double lambda_3;\n//        double lambda_sqrt;\n//        double ct;   // ct = 1/(1-t)^2\n//    };\n//    double gamma_2;\n//    double gamma_2_inv;\n//    double gamma_4;\n//    double emit_x_inv;\n//    double emit_y_inv;\n//    double emit_x2_inv;\n//    double emit_y2_inv;\n//\n//    struct optcl{\n//        double phi_x;\n//        double phi_y;\n//        double dx_2_over_beta_x;\n//        double dy_2_over_beta_y;\n//    };\n//    std::vector<itgrl> integral;\n//    std::vector<optcl> optical;\n//    struct debug {\n//        double  a, b, c, ax, bx, ay, by, al, bl, ix, iy, is;\n//    };\n//    std::vector<debug> my_debug;\n//\n//    gsl_integration_workspace *gw;\n//\n//    size_t limit = 100;\n//    double espabs = 1e-12;\n//    double esprel = 1e-3;\n//    struct P{\n//        double a;\n//        double b;\n//        double c;\n//        double ai;\n//        double bi;\n//    }p;\n////    double core(double q, void* params);\n//\n////    void init_integral(int n);\n//    void init_optical(const Lattice &lattice);\n//    double calc_abc(const Lattice &lattice, const Beam& beam, int i, double& a, double& b, double& c,\n//                               double& ax, double& bx, double& ay, double& by,double& al, double& bl, double& scale);\n//    double coef(const Lattice &lattice, const Beam &beam) const;\n//    void calc_integral(double a, double b, double c, double ax, double bx, double ay, double by, double al,\n//                                  double bl, double& ix, double& iy, double& is, int nt, std::vector<itgrl>& g);\n//public:\n//    IBSSolver_BMZ(int nt, double log_c, double k);\n//    set_nt(int n){assert(n>0&&\"Wrong value of nt in IBS parameters!\"); nt_ = n; invalidate_cache();}\n//    virtual void rate(const Lattice &lattice, const Beam &beam, double &rx, double &ry, double &rs);\n//\n//    ~IBSSolver_BMZ(){gsl_integration_workspace_free(gw);};\n//\n//};\n//\n//\n//\n//};\n#endif\n", "meta": {"hexsha": "90cc444633f6fec3f8dd31558572ae6bd80811ca", "size": 9114, "ext": "h", "lang": "C", "max_stars_repo_path": "include/jspec2/ibs.h", "max_stars_repo_name": "mbruker/jspec2-python", "max_stars_repo_head_hexsha": "c82b41cf0a314f15eb84ab15b0de96ac2992bf9c", "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/jspec2/ibs.h", "max_issues_repo_name": "mbruker/jspec2-python", "max_issues_repo_head_hexsha": "c82b41cf0a314f15eb84ab15b0de96ac2992bf9c", "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/jspec2/ibs.h", "max_forks_repo_name": "mbruker/jspec2-python", "max_forks_repo_head_hexsha": "c82b41cf0a314f15eb84ab15b0de96ac2992bf9c", "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.2631578947, "max_line_length": 119, "alphanum_fraction": 0.6212420452, "num_tokens": 2570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3803953798885321}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C header for structures representing a waveform as a list of modes in amplitude/phase form.\n *\n */\n\n#ifndef _STRUCT_H\n#define _STRUCT_H\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n\n\n#if defined(__cplusplus)\nextern \"C\" {\n#elif 0\n} /* so that editors will match preceding brace */\n#endif\n\n/***************************************************/\n/*************** Type definitions ******************/\n\n/* Type for real functions */\ntypedef double (*RealFunctionPtr)(double);\ntypedef double (*RealObjectFunctionPtr)(const void *, double);\n\n/* Type for real functions that reference an object */\ntypedef struct tagObjectFunction\n{\n  const void * object;\n  RealObjectFunctionPtr function;\n} ObjectFunction ;\ndouble ObjectFunctionCall(const ObjectFunction*,double);\n\n/* Complex frequency series in amplitude and phase representation (for one mode) */\ntypedef struct tagCAmpPhaseFrequencySeries\n{\n  gsl_vector* freq;\n  gsl_vector* amp_real; /* We authorize complex amplitudes - will be used for the LISA response */\n  gsl_vector* amp_imag; /* We authorize complex amplitudes - will be used for the LISA response */\n  gsl_vector* phase;\n} CAmpPhaseFrequencySeries;\n/* GSL splines for complex amplitude and phase representation (for one mode) */\ntypedef struct tagCAmpPhaseGSLSpline\n{\n  gsl_vector* freq;\n  gsl_spline* spline_amp_real; /* We authorize complex amplitudes - will be used for the LISA response */\n  gsl_spline* spline_amp_imag; /* We authorize complex amplitudes - will be used for the LISA response */\n  gsl_spline* spline_phase;\n  gsl_interp_accel* accel_amp_real;\n  gsl_interp_accel* accel_amp_imag;\n  gsl_interp_accel* accel_phase;\n} CAmpPhaseGSLSpline;\n/* Splines in matrix form for complex amplitude and phase representation (for one mode) */\ntypedef struct tagCAmpPhaseSpline\n{\n  gsl_matrix* spline_amp_real; /* We authorize complex amplitudes - will be used for the LISA response */\n  gsl_matrix* spline_amp_imag; /* We authorize complex amplitudes - will be used for the LISA response */\n  gsl_matrix* quadspline_phase;\n} CAmpPhaseSpline;\n\n/* Complex frequency series in real/imaginary part representation (for one mode, or their sum) */\ntypedef struct tagReImFrequencySeries\n{\n  gsl_vector* freq;\n  gsl_vector* h_real;\n  gsl_vector* h_imag;\n} ReImFrequencySeries;\n\n/* Complex frequency series in real/imaginary part representation (for one mode, or their sum) */\n/* NOTE: for now, exact duplicata of ReImFrequencySeries - differentiated for readability of the code */\ntypedef struct tagReImTimeSeries\n{\n  gsl_vector* times;\n  gsl_vector* h_real;\n  gsl_vector* h_imag;\n} ReImTimeSeries;\n\n/* Complex frequency series in amplitude/phase representation (representing one mode) */\n/* NOTE: for now, exact duplicata of ReImFrequencySeries - differentiated for readability of the code */\ntypedef struct tagAmpPhaseTimeSeries\n{\n  gsl_vector* times;\n  gsl_vector* h_amp;\n  gsl_vector* h_phase;\n} AmpPhaseTimeSeries;\n\n/* Real time series */\n/* NOTE: could change the h to something more general, like values - also used for TD 22 amplitude, for instance  */\ntypedef struct tagRealTimeSeries\n{\n  gsl_vector* times;\n  gsl_vector* h;\n} RealTimeSeries;\n\n/* List structure, for a list of modes, each in amplitude and phase form */\ntypedef struct tagListmodesCAmpPhaseFrequencySeries\n{\n  CAmpPhaseFrequencySeries*                      freqseries; /* The frequencies series with amplitude and phase */\n  int                                            l; /* Node mode l  */\n  int                                            m; /* Node submode m  */\n  struct tagListmodesCAmpPhaseFrequencySeries*    next; /* Next pointer */\n} ListmodesCAmpPhaseFrequencySeries;\n\n/* List structure, for a list of modes, each with interpolated splines in amplitude and phase form */\ntypedef struct tagListmodesCAmpPhaseSpline\n{\n  CAmpPhaseSpline*                       splines; /* The frequencies series with amplitude and phase */\n  int                                    l;       /* Node mode l  */\n  int                                    m;       /* Node submode m  */\n  struct tagListmodesCAmpPhaseSpline*    next;    /* Next pointer */\n} ListmodesCAmpPhaseSpline;\n\n/**************************************************************/\n/* Functions computing the max and min between two int */\nint max (int a, int b);\nint min (int a, int b);\n\n/**************************************************************/\n/************** GSL error handling and I/O ********************/\n\n/* GSL error handler */\nvoid Err_Handler(const char *reason, const char *file, int line, int gsl_errno);\n\n/* Functions to read/write data from files */\nint Read_Vector(const char dir[], const char fname[], gsl_vector *v);\nint Read_Matrix(const char dir[], const char fname[], gsl_matrix *m);\nint Read_Text_Vector(const char dir[], const char fname[], gsl_vector *v);\nint Read_Text_Matrix(const char dir[], const char fname[], gsl_matrix *m);\nint Write_Vector(const char dir[], const char fname[], gsl_vector *v);\nint Write_Matrix(const char dir[], const char fname[], gsl_matrix *m);\nint Write_Text_Vector(const char dir[], const char fname[], gsl_vector *v);\nint Write_Text_Matrix(const char dir[], const char fname[], gsl_matrix *m);\n\n/**********************************************************/\n/**************** Internal functions **********************/\n\n/* Functions for list manipulations */\nListmodesCAmpPhaseFrequencySeries* ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(\n\t   ListmodesCAmpPhaseFrequencySeries* appended,  /* List structure to prepend to */\n\t   CAmpPhaseFrequencySeries* freqseries,  /* data to contain */\n\t   int l, /*< major mode number */\n\t   int m  /*< minor mode number */\n);\nListmodesCAmpPhaseFrequencySeries* ListmodesCAmpPhaseFrequencySeries_GetMode(\n\t   ListmodesCAmpPhaseFrequencySeries* const list,  /* List structure to get a particular mode from */\n\t   int l, /*< major mode number */\n\t   int m  /*< minor mode number */\n);\nvoid ListmodesCAmpPhaseFrequencySeries_Destroy(\n\t   ListmodesCAmpPhaseFrequencySeries* list  /* List structure to destroy; notice that the data is destroyed too */\n);\nListmodesCAmpPhaseSpline* ListmodesCAmpPhaseSpline_AddModeNoCopy(\n\t   ListmodesCAmpPhaseSpline* appended,  /* List structure to prepend to */\n\t   CAmpPhaseSpline* freqseries,  /* data to contain */\n\t   int l, /*< major mode number */\n\t   int m  /*< minor mode number */\n);\nListmodesCAmpPhaseSpline* ListmodesCAmpPhaseSpline_GetMode(\n\t   ListmodesCAmpPhaseSpline* const list,  /* List structure to get a particular mode from */\n\t   int l, /*< major mode number */\n\t   int m  /*< minor mode number */\n);\nvoid ListmodesCAmpPhaseSpline_Destroy(\n\t   ListmodesCAmpPhaseSpline* list  /* List structure to destroy; notice that the data is destroyed too */\n);\n\n/* Functions to initialize and clean up data structure */\nvoid CAmpPhaseFrequencySeries_Init(\n\t CAmpPhaseFrequencySeries** freqseries, /* double pointer for initialization */\n\t const int n );                         /* length of the frequency series */\nvoid CAmpPhaseFrequencySeries_Cleanup(CAmpPhaseFrequencySeries* freqseries);\nvoid CAmpPhaseSpline_Init(\n\t CAmpPhaseSpline** splines,             /* double pointer for initialization */\n\t const int n );                         /* length of the frequency series setting the splines */\nvoid CAmpPhaseSpline_Cleanup(CAmpPhaseSpline* splines);\nvoid CAmpPhaseGSLSpline_Init(\n\t CAmpPhaseGSLSpline** splines,          /* double pointer for initialization */\n\t const int n );                         /* length of the frequency series setting the splines */\nvoid CAmpPhaseGSLSpline_Cleanup(CAmpPhaseGSLSpline* splines);\nvoid ReImFrequencySeries_Init(\n\t ReImFrequencySeries** freqseries,      /* double pointer for initialization */\n\t const int n );                         /* length of the frequency series */\nvoid ReImFrequencySeries_Cleanup(ReImFrequencySeries* freqseries);\nvoid ReImTimeSeries_Init(\n\t ReImTimeSeries** timeseries,           /* double pointer for initialization */\n\t const int n );                         /* length of the time series */\nvoid ReImTimeSeries_Cleanup(ReImTimeSeries* timeseries);\nvoid AmpPhaseTimeSeries_Init(\n\t AmpPhaseTimeSeries** timeseries,       /* double pointer for initialization */\n\t const int n );                         /* length of the time series */\nvoid AmpPhaseTimeSeries_Cleanup(AmpPhaseTimeSeries* timeseries);\nvoid RealTimeSeries_Init(\n\t RealTimeSeries** timeseries,      /* double pointer for initialization */\n\t const int n );                /* length of the time series */\nvoid RealTimeSeries_Cleanup(RealTimeSeries* timeseries);\n\n/***********************************************************************/\n/**************** I/O functions for internal structures ****************/\n\n/* Note: at the moment, requires external input for the number of lines in the data */\nint Read_RealTimeSeries(RealTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary);\nint Read_AmpPhaseTimeSeries(AmpPhaseTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary);\nint Read_ReImTimeSeries(ReImTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary);\nint Write_ReImFrequencySeries(const char dir[], const char file[], ReImFrequencySeries* freqseries, const int binary);\nint Write_RealTimeSeries(const char dir[], const char file[], RealTimeSeries* timeseries, int binary);\nint Write_AmpPhaseTimeSeries(const char dir[], const char file[], AmpPhaseTimeSeries* timeseries, int binary);\nint Write_ReImTimeSeries(const char dir[], const char file[], ReImTimeSeries* timeseries, int binary);\n\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _STRUCT_H */\n", "meta": {"hexsha": "fad94798f994e19e3695d54c956140b6ba9af4d3", "size": 10258, "ext": "h", "lang": "C", "max_stars_repo_path": "tools/struct.h", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "tools/struct.h", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "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/struct.h", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 42.2139917695, "max_line_length": 135, "alphanum_fraction": 0.6952622344, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3803253317644918}}
{"text": "/** @file */\n\n#ifndef __CCL_LSST_SPECS_INCLUDED__\n#define __CCL_LSST_SPECS_INCLUDED__\n\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_spline.h>\n\n/**\n * We assume no relevant source redshift distributions exceed z= 5\n */\n#define Z_MIN_SOURCES 0.\n#define Z_MAX_SOURCES 5.0\n\nCCL_BEGIN_DECLS\n/** \n * P(z) function.\n * This is a P(z) function (which can be user defined) \n * with a void* field to contain the parameters to that function.\n */\ntypedef struct {\n        double (* your_pz_func)(double, double, void *, int*); /*< Function returns the likelihood of measuring a z_ph\n        * (first double) given a z_spec (second double), with a pointer to additonal arguments and a status flag.*/\n        void *  your_pz_params; /*< Additional parameters to be passed into your_pz_func */\n} pz_info;\n\n/** \n * dNdz function.\n * This is a dNdz function (which can be user defined)\n * with a void* field to contain the parameters to that function.\n */\ntypedef struct {\n        double (* your_dN_func)(double, void *, int*); /*< Function returns the differential number density of galaxies wrt redshifts, \n        * with a pointer to additonal arguments and a status flag.*/\n        void *  your_dN_params; /*< Additional parameters to be passed into your_dN_func */\n} dNdz_info;\n\n/**\n * dNdz smail parmas structure.\n * This is a convenience parameters structure\n * to hold the three parameters of the Smail et al. analytic dNdz\n */\n typedef struct{\n\t\tdouble alpha;\n\t\tdouble beta;\n\t\tdouble z0;\n\t} smail_params;\n\n/** \n * Return dNdz in a particular tomographic bin, \n    convolved with a photo-z model (defined by the user), and normalized.\n * @param z redshift \n * @param dNdz_type the choice of dN/dz from Chang+\n * @param bin_zmin the minimum redshift of the tomorgraphic bin\n * @param bin_zmax the maximum redshift of the tomographic bin\n * @param photo_info the P(z) info struct\n * @param tomoout the output dN/dz\n * @param status Status flag. 0 if there are no errors, nonzero otherwise.\n * @return void \n */\nvoid ccl_dNdz_tomog(double z, double bin_zmin, double bin_zmax, pz_info * photo_info,  dNdz_info * dN_info, double *tomoout, int *status);\n\n/** \n * This function creates a structure amalgamating the information on an analytic true dNdz, plus some parameters.\n * @param params parameters for the analytic dNdz form\n * @param dNdz_func dNdz function\n * @return a structure with the dNdz and parameters\n */\n \ndNdz_info* ccl_create_dNdz_info(void * params, double(*dNdz_func)(double,void*,int*));\n\n/** \n * This function creates a structure containing the true dNdz for the built-in Smail-type analytic form:\n * dNdz ~ z^alpha exp(- (z/z0)^beta)\n * @param alpha \n * @param z0 \n * @param beta\n * @return a structure with the built-in Smail-type dNdz and parameters\n */\n dNdz_info* ccl_create_Smail_dNdz_info(double alpha, double beta, double z0);\n\n\n/** Free memory holding the structure containing dNdz information.\n * @param dN_info that holds user-defined dNdz and parameters\n * @return void\n */\nvoid ccl_free_dNdz_info(dNdz_info * dN_info);\n\n/** \n * This function creates a structure amalgamating the information on the photo-z model, P(z) plus some parameters.\n * @param params parameters for the P(z) function\n * @param pz_func P(z) function\n * @return a structure with the P(z) and parameters\n */\n \npz_info* ccl_create_photoz_info(void * params, double(*pz_func)(double, double,void*,int*));\n\n/** \n * This function creates a structure containing the photo-z model for the built-in Gaussian photo-z pdf.\n * @param sigma_z0 The photo-z uncertainty at z=0. The photo-z uncertainty is assumed to scale like (1 + z).\n * @return a structure with the built-in Gaussian P(z) and parameters\n */\npz_info* ccl_create_gaussian_photoz_info(double sigma_z0);\n\n\n/** Free memory holding the structure containing user-input photoz information.\n * @param my_photoz_info that holds user-defined P(z) and parameters\n * @return void\n */\nvoid ccl_free_photoz_info(pz_info *my_photoz_info);\n\nCCL_END_DECLS\n\n#endif\n", "meta": {"hexsha": "1710d3287c16183480bd2f4913770060cfd978b2", "size": 3997, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ccl_redshifts.h", "max_stars_repo_name": "vrastil/CCL", "max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ccl_redshifts.h", "max_issues_repo_name": "vrastil/CCL", "max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ccl_redshifts.h", "max_forks_repo_name": "vrastil/CCL", "max_forks_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_forks_repo_licenses": ["BSD-3-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.7565217391, "max_line_length": 138, "alphanum_fraction": 0.7320490368, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3802330471900901}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C header for the instrumental noise for LISA-type detectors.\n *\n * Formulas taken from Kr\u00f3lak&al gr-qc/0401108 (c.f. section III).\n *\n */\n\n#ifndef _LISANOISE_H\n#define _LISANOISE_H\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n#include \"LISAgeometry.h\"\n\n\n#if defined(__cplusplus)\nextern \"C\" {\n#elif 0\n} /* so that editors will match preceding brace */\n#endif\n\n/************************************************************************/\n/****** Global variables storing min and max f for the noise PSD  *******/\n\n/* Defines bounds in frequency beyond which we don't trust the instrument model anymore - all waveforms will be cut to this range */\n/* Here extended range - allows for instance to taper the FD signal for f>1Hz */\n#define __LISASimFD_Noise_fLow 1.e-6\n#define __LISASimFD_Noise_fHigh 5.\n/* Original, more conservative bounds */\n//#define __LISASimFD_Noise_fLow 1.e-5\n//#define __LISASimFD_Noise_fHigh 1.\n\n/**************************************************************/\n/****** Prototypes: functions evaluating the noise PSD  *******/\n\n/* Function returning the relevant noise function, given a set of TDI observables and a channel */\nObjectFunction NoiseFunction(const LISAconstellation *variant, const TDItag tditag, const int nchan);\n\n/* Noise Sn for TDI observables - factors have been scaled out both in the response and the noise */\ndouble SnXYZ(const LISAconstellation *variant, double f);\ndouble Snalphabetagamma(const LISAconstellation *variant, double f);\ndouble SnAXYZ(const LISAconstellation *variant, double f);\ndouble SnEXYZ(const LISAconstellation *variant, double f);\ndouble SnTXYZ(const LISAconstellation *variant, double f);\ndouble SnAalphabetagamma(const LISAconstellation *variant, double f);\ndouble SnEalphabetagamma(const LISAconstellation *variant, double f);\ndouble SnTalphabetagamma(const LISAconstellation *variant, double f);\n\n/* Noise functions for AET(XYZ) without rescaling */\ndouble SnAXYZNoRescaling(const LISAconstellation *variant, double f);\ndouble SnEXYZNoRescaling(const LISAconstellation *variant, double f);\ndouble SnTXYZNoRescaling(const LISAconstellation *variant, double f);\n\n/* Function returning the relevant noise function, given a set of TDI observables and a channel */\n/* double (*NoiseFunction(const TDItag tditag, const int chan))(double); */\n\n/* The noise functions themselves */\n/* double NoiseSnA(const double f); */\n/* double NoiseSnE(const double f); */\n/* double NoiseSnT(const double f); */\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _LISANOISE_H */\n", "meta": {"hexsha": "45656cc55bf8e018f9de98acfd036bb305ece997", "size": 3092, "ext": "h", "lang": "C", "max_stars_repo_path": "LISAsim/LISAnoise.h", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "LISAsim/LISAnoise.h", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LISAsim/LISAnoise.h", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 32.5473684211, "max_line_length": 132, "alphanum_fraction": 0.7208926261, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3800399324966877}}
{"text": "/* rstat/rquantile.c\n * \n * Copyright (C) 2015 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_statistics.h>\n#include <gsl/gsl_rstat.h>\n\n/*\n * Running quantile calculation based on the paper\n *\n * [1] R. Jain and I. Chlamtac, \"The P^2 algorithm for dynamic\n *     calculation of quantiles and histograms without storing\n *     observations\", Communications of the ACM, October 1985\n */\n\nstatic double calc_psq(const double qp1, const double q, const double qm1,\n                       const double d, const double np1, const double n, const double nm1);\n\ngsl_rstat_quantile_workspace *\ngsl_rstat_quantile_alloc(const double p)\n{\n  gsl_rstat_quantile_workspace *w;\n\n  w = calloc(1, sizeof(gsl_rstat_quantile_workspace));\n  if (w == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for workspace\", GSL_ENOMEM);\n    }\n\n  w->p = p;\n\n  gsl_rstat_quantile_reset(w);\n\n  return w;\n} /* gsl_rstat_quantile_alloc() */\n\nvoid\ngsl_rstat_quantile_free(gsl_rstat_quantile_workspace *w)\n{\n  free(w);\n} /* gsl_rstat_quantile_free() */\n\nint\ngsl_rstat_quantile_reset(gsl_rstat_quantile_workspace *w)\n{\n  const double p = w->p;\n  size_t i;\n\n  /* initialize positions n */\n  for (i = 0; i < 5; ++i)\n    w->npos[i] = i + 1;\n\n  /* initialize n' */\n  w->np[0] = 1.0;\n  w->np[1] = 1.0 + 2.0 * p;\n  w->np[2] = 1.0 + 4.0 * p;\n  w->np[3] = 3.0 + 2.0 * p;\n  w->np[4] = 5.0;\n\n  /* initialize dn' */\n  w->dnp[0] = 0.0;\n  w->dnp[1] = 0.5 * p;\n  w->dnp[2] = p;\n  w->dnp[3] = 0.5 * (1.0 + p);\n  w->dnp[4] = 1.0;\n\n  w->n = 0;\n\n  return GSL_SUCCESS;\n}\n\nint\ngsl_rstat_quantile_add(const double x, gsl_rstat_quantile_workspace *w)\n{\n  if (w->n < 5)\n    {\n      w->q[w->n] = x;\n    }\n  else\n    {\n      int i;\n      int k = -1;\n\n      if (w->n == 5)\n        {\n          /* initialization: sort the first five heights */\n          gsl_sort(w->q, 1, w->n);\n        }\n\n      /* step B1: find k such that q_k <= x < q_{k+1} */\n      if (x < w->q[0])\n        {\n          w->q[0] = x;\n          k = 0;\n        }\n      else if (x >= w->q[4])\n        {\n          w->q[4] = x;\n          k = 3;\n        }\n      else\n        {\n          for (i = 0; i <= 3; ++i)\n            {\n              if (w->q[i] <= x && x < w->q[i + 1])\n                {\n                  k = i;\n                  break;\n                }\n            }\n        }\n\n      if (k < 0)\n        {\n          /* we could get here if x is nan */\n          GSL_ERROR (\"invalid input argument x\", GSL_EINVAL);\n        }\n\n      /* step B2(a): update n_i */\n      for (i = k + 1; i <= 4; ++i)\n        ++(w->npos[i]);\n\n      /* step B2(b): update n_i' */\n      for (i = 0; i < 5; ++i)\n        w->np[i] += w->dnp[i];\n\n      /* step B3: update heights */\n      for (i = 1; i <= 3; ++i)\n        {\n          double ni = (double) w->npos[i];\n          double d = w->np[i] - ni;\n\n          if ((d >= 1.0 && (w->npos[i + 1] - w->npos[i] > 1)) ||\n              (d <= -1.0 && (w->npos[i - 1] - w->npos[i] < -1)))\n            {\n              int dsign = (d > 0.0) ? 1 : -1;\n              double qp1 = w->q[i + 1];\n              double qi = w->q[i];\n              double qm1 = w->q[i - 1];\n              double np1 = (double) w->npos[i + 1];\n              double nm1 = (double) w->npos[i - 1];\n              double qp = calc_psq(qp1, qi, qm1, (double) dsign,\n                                   np1, ni, nm1);\n\n              if (qm1 < qp && qp < qp1)\n                w->q[i] = qp;\n              else\n                {\n                  /* use linear formula */\n                  w->q[i] += dsign * (w->q[i + dsign] - qi) / ((double) w->npos[i + dsign] - ni);\n                }\n\n              w->npos[i] += dsign;\n            }\n        }\n    }\n\n  ++(w->n);\n\n  return GSL_SUCCESS;\n} /* gsl_rstat_quantile_add() */\n\ndouble\ngsl_rstat_quantile_get(gsl_rstat_quantile_workspace *w)\n{\n  if (w->n >= 5)\n    {\n      return w->q[2];\n    }\n  else\n    {\n      /* not yet initialized */\n      gsl_sort(w->q, 1, w->n);\n      return gsl_stats_quantile_from_sorted_data(w->q, 1, w->n, w->p);\n    }\n} /* gsl_rstat_quantile_get() */\n\nstatic double\ncalc_psq(const double qp1, const double q, const double qm1,\n         const double d, const double np1, const double n, const double nm1)\n{\n  double outer = d / (np1 - nm1);\n  double inner_left = (n - nm1 + d) * (qp1 - q) / (np1 - n);\n  double inner_right = (np1 - n - d) * (q - qm1) / (n - nm1);\n\n  return q + outer * (inner_left + inner_right);\n} /* calc_psq() */\n", "meta": {"hexsha": "0c4e84ad43c87d400e138d25345a727fa720e8b3", "size": 5225, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/rstat/rquantile.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rstat/rquantile.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rstat/rquantile.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 25.1201923077, "max_line_length": 97, "alphanum_fraction": 0.5150239234, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.37989897882337564}}
{"text": "#ifndef _SPC_FITTING_H\n#define _SPC_FITTING_H\n\n\n#include <math.h>\n#include <gsl/gsl_fit.h>\n#include <gsl/gsl_multifit.h>\n#include \"aXe_errors.h\"\n\n\nextern void\ncomp_vector_average (const double *xs, double *ys,\n\t\t       double *ws, double *yi, const int n, const int final);\nextern void\ncomp_vector_median (const double *xs, double *ys,\n\t\t      double *ws, double *yi, const int n, const int final);\n\nextern void\ncomp_vector_linear (const double *xs, double *ys,\n\t\t      double *ws, double *yi, const int n, const int final);\n\nextern void\ncomp_vector_polyN (const int m, const double *xs, double *ys,\n\t\t    double *ws, double *yi, const int n, const int final);\n\nextern void\nfill_const_value(double *ys, double *ws, double *yi, const int n,\n\t\t double cval, double stdev, const int final);\n\nextern void\ndet_vector_average (const double *xs, double *ys,\n\t\t    double *ws, const int n, double *avg, double *std);\nextern void\ndet_vector_median (const double *xs, double *ys,\n\t\t    double *ws, const int n, double *med, double *std);\n\nextern gsl_vector *\ndet_vector_linear(const double *xs, double *ys, double *ws,\n\t\t  const int n, const int weight);\n\nextern gsl_vector *\ndet_vector_poly_N (int m, const double *const xs, double *const ys,\n\t\t   double *const ws, const int n, gsl_vector *c,\n\t\t   gsl_matrix *cov);\n\nextern void\nfill_linear_interp(const double *const xs, double *const ys,\n\t\t   double *const ws, double *yi, const int n,\n\t\t   gsl_vector *interp, const int final);\n\nextern void\nfill_polyN_interp(const double *const xs, double *const ys,\n\t\t  double *const ws, double *yi, const int n,\n\t\t  gsl_vector *coeffs, gsl_matrix *cov, gsl_vector *interp,\n\t\t  const int final);\n#endif\n", "meta": {"hexsha": "971f39ea279c6b20de8202e3a035a4ba6fc77ad3", "size": 1683, "ext": "h", "lang": "C", "max_stars_repo_path": "cextern/src/spce_fitting.h", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spce_fitting.h", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spce_fitting.h", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-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.5263157895, "max_line_length": 67, "alphanum_fraction": 0.7106357695, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3798922071034066}}
{"text": "#ifndef ShapeBase_H\n#define ShapeBase_H\n\n\n#include <iostream>\n#include <ostream>\n#include <fstream>\n#include <stdio.h>\n#include <string>\n#include <vector>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n\n#include \"Node.h\"\n#include \"ReferenceShapeBase.h\"\n#include \"GrowthFunctionBase.h\"\n#include \"GrowthFunctionTypes.h\"\n\nclass ShapeBase{\nprivate:\n    void ParentErrorMessage(std::string functionName);\t\t\t\t///<Error message displayed when a virtual function is called through the ShapeBase(parent), while it should have been called through a child (eg. Prism). For functions taking in string inputs.\n    bool ParentErrorMessage(std::string functionName, bool returnValue); \t///<Error message displayed when a virtual function is called through the ShapeBase(parent), while it should have been called through a child (eg. Prism). For functions taking in string and bool inputs, returning bool.\n    double ParentErrorMessage(std::string functionName, double returnValue);\t///<Error message displayed when a virtual function is called through the ShapeBase(parent), while it should have been called through a child (eg. Prism). For functions taking in string and double inputs, returning double.\n    int ParentErrorMessage(std::string functionName, int returnValue);\t\t///<Error message displayed when a virtual function is called through the ShapeBase(parent), while it should have been called through a child (eg. Prism). For functions taking in string and int inputs, returning int.\nprotected:\n    int                         ShapeType;                      ///< The integer defining the type of the shape, Prisms shape type = 1;\n    size_t                      nNodes;                         ///< The number of nodes of the element, it is based on ShapeBase#ShapeType\n    size_t                      nDim;                           ///< The number of dimensions for the positions of each of the nodes of the element\n    std::array<int,3>           IdentifierColour;\t\t\t\t///< The unique identifier colour of the element, this is used for \"picking\" in the visual interface.\n    std::array<double,3>        GrowthRate;                     ///< Growth rate recording for display purposes only. The recorded growth rate in x, y, and z  coordinates, does not record shear deformation induced in growth. Recorded in exponential form through time step, converted to rate per hour for display within the visual interface\n    gsl_matrix*                 growthIncrement;\t\t\t\t///< The matrix (3,3) representing the incremental growth in current time step. Reset to identity at the beginning of each time step, updated in growth functions, and utilised to update Fg.\n    gsl_matrix*                 plasticDeformationIncrement;\t///< The matrix (3,3) representing the incremental plastic deformation (treated as growth) in current time step. Set in plastic deformation calculation at each step, and utilised to update Fg.\n    gsl_matrix*                 shapeChangeIncrement;           ///< The matrix (3,3) representing the incremental shape change in current time step. Reset to identity at the beginning of each time step, updated in shape change functions, and utilised to update Fg.\n    double                      zRemodellingSoFar;\t\t\t\t///< The z remodelling that have been applied to elemetn up to the current time step. This parameter is used to limit extreme thinning or elongation of elements.\n    double                      columnarGrowthWeight;\t\t\t///< The fraction defining how close to the columnar layer the element is. 1.0 for columnar layer, 0.0 for peripodial membrane elements, and scaled according to position in the elements surrounding the lumen.\n    double                      peripodialGrowthWeight;         ///< The fraction defining how close to the peripodial membrane the element is. 0.0 for columnar layer, 1.0 for peripodial membrane elements, and scaled according to position in the elements surrounding the lumen.\n    std::array<double,6>        ShapeChangeRate;\t\t\t\t///< Shape change rate of the elements, only orthagonal shape changes are allowed (x, y, z). Shape changes will be scaled to conserve volume, thus three values will not be independent.\n    bool                        rotatedGrowth;\t\t\t\t\t///< The boolean stating if the element has rotated from the growth axis, hence the calculated growth requires further rotation to follow tissue axes.\n    std::array<double,3>        relativePosInBoundingBox;\t\t///< The relative position on x-y plane, within the bounding box of the tissue(x,y).\n    std::array<double,3>        initialRelativePosInBoundingBox;///< The relative position on x-y plane, within the bounding box of the tissue(x,y) at the beginning of simulation. This is used when growth rates are pinned to the initial structure of the tissue.\n    double                      initialRelativePositionInZ;     ///< The relative position on z-height of tissue, taken not in z direction but in tissue layers, 0 being on the apical surface and 1 being on the basal surface.\n    size_t                      numberOfGaussPoints;            ///< The number of Gauss points used in numerical deforamtion calculation.\n    std::array<std::array<double,3>,6>\tgaussPoints;            ///< The array contianing all the Gauss points for element. Set up is for 6, can work for any number as loops are kept indexed up to numberOfGaussPoints.\n    std::array<double,6>        gaussWeights;                   ///< The array for storing the weights of each Gauss point for element.\n    std::vector<gsl_matrix*> \tShapeFuncDerivatives;           ///< The array of matrices for shape function derivatives. The array stores a ShapeBase#nDim by ShapeBase#nNodes matrix for each gauss point (there are 3 Gauss points for prisms).\n    std::vector<gsl_matrix*> \tShapeFuncDerStacks;                    \t\t///< The array of matrices of shape function derivatives in stacked format for ease of matrix operations. The array stores a (ShapeBase#nDim * ShapeBase#nDim) by (ShapeBase#nDim * ShapeBase#nNodes) matrix for each gauss point (there are 3 Gauss points for prisms).\n    std::vector<gsl_matrix*> \tInvdXdes;                              \t\t///< The array stores inverse of the matrix for derivatives of world coordinates with respect to barycentric coordinates (dX / de). The array stores an ShapeBase#nDim by ShapeBase#nDim  matrix for each gauss point (there are 3 Gauss points for prisms).\n    std::array<double,6>     \tdetdXdes;                              \t\t///< The array stores the determinants of the matrices for derivatives of world coordinates with respect to barycentric coordinates (dX / de). The array stores a double value for each gauss point (there are 3 Gauss points for prisms).\n    std::vector<gsl_matrix*> \tBmatrices;                             \t\t///< The array stores the B matrix for the calculation of stiffness matrix, see for ShapeBase#calculateBTforNodalForces calculation. The array stores an ShapeBase#nNodes by (ShapeBase#nDim*ShapeBase#nNodes)  matrix for each Gauss point (there are 3 Gauss points for prisms).\n    std::vector<gsl_matrix*> \tFeMatrices;\t\t\t\t\t///< The array stores the elastic part of the deformation matrix. The array stores an ShapeBase#nDim by ShapeBase#nDim  matrix for each Gauss point (there are 6 Gauss points for prisms).\n    std::vector<gsl_matrix*> \tinvJShapeFuncDerStack;\t\t\t\t///< The array stores the shape function derivatives multiplied by the inverse Jacobian stack, for each Gauss point. See ShapeBase#calculateBTforNodalForces for calculation.\n    std::vector<gsl_matrix*> \tinvJShapeFuncDerStackwithFe;\t\t\t///< See ShapeBase#calculateInvJShFuncDerSWithFe for calculation.\n    std::vector<gsl_matrix*> \telasticStress;\t\t\t\t\t///< The array of matrices for elastic stress of the element. The array stores a 6 by 6 matrix for each Gauss point (there are 6 Gauss points for prisms).\n    std::vector<gsl_matrix*> \tviscousStress;\t\t\t\t\t///< The array of matrices for internal viscous stress of the element. The array stores a 6 by 6 matrix for each Gauss point (there are 6 Gauss points for prisms).\n    gsl_matrix*              \tTriPointF;                             \t\t///< The deformation matrix of the element resulting from iteration over all Gauss points. The dimensions of the matrix is ShapeBase#nDim by ShapeBase#nDim.\n    gsl_matrix*              \tElementalElasticSystemForces;          \t\t///< The matrix stores the elemental elastic forces. The dimensions of the matrix is ShapeBase#nNodes by ShapeBase#nDim.\n    gsl_matrix*          \tElementalInternalViscousSystemForces;  \t\t///< The matrix stores the elemental internal viscous forces. The dimensions of the matrix is ShapeBase#nNodes by ShapeBase#nDim.\n    std::array<double,6> \tdetFs;                              \t\t///< The array stores the determinant of the deformation matrix for each Gauss point.\n    double \t\t\tZProjectedBasalArea;\t\t\t\t///< The z-projected area of the basal surface of the element.\n    double \t\t\tZProjectedApicalArea;\t\t\t    \t///< The z-projected area of the apical surface of the element.\n    double \t\t\tBasalArea;\t\t\t\t\t///< The area of the basal surface of the element.\n    double \t\t\tApicalArea;\t\t\t\t\t///< The area of the apical surface of the element.\n    double\t\t\texposedLateralAreaApicalSide;\t\t\t///< The area of the element on a linker position, and has lateral sides exposed to outside of the tissue, on the apical side, therefore should feel external viscosity.\n    double\t\t\texposedLateralAreaBasalSide;\t\t\t///< The area of the element on a linker position, and has lateral sides exposed to outside of the tissue, on the basal side, therefore should feel external viscosity.\n\n    bool \t\t\telementHasExposedApicalSurface;\t\t\t///< The boolean stating if the element has any apical surface exposed to the environment\n    bool \t\t\telementHasExposedBasalSurface;\t\t\t///< The boolean stating if the element has any basal surface exposed to the environment\n    int \t\t\texposedApicalSurfaceNodeIds[3];\t\t\t///< The int array of size 3, listing the node IDs of element that form the exposed apical surface. The IDs are the node IDs on the element (0-5 for prism), not the actual Node#Id.\n    int \t\t\texposedBasalSurfaceNodeIds[3];\t\t\t///< The int array of size 3, listing the node IDs of element that form the exposed basal surface. The IDs are the node IDs on the element (0-5 for prism), not the actual Node#Id.\n    int \t\t\texposedLateralAreaApicalSideNodeIds[4];\t\t///< The int array of size 4, listing the node IDs of element that form the lateral surface exposed apically. The IDs are the node IDs on the element (0-5 for prism), not the actual Node::Id.\n    int \t\t\texposedLateralAreaBasalSideNodeIds[4];\t\t///< The int array of size 4, listing the node IDs of element that form the lateral surface exposed basally. The IDs are the node IDs on the element (0-5 for prism), not the actual Node::Id.\n    size_t \t\t\tnLateralSurfaceAreaNodeNumber;\t\t\t///< Number of nodes that form the lateral surfaces for the element.\n    size_t \t\t\tnSurfaceAreaNodeNumber;\t\t\t\t///< Number of nodes that form the apical/basal surfaces for the element.\n\n    double \t\t\tstiffnessPerturbationRateInSec;         \t///< The rate at which the stiffness of the element will be perturbed, used with the model inputs from \"Stiffness_Perturbation:\" header in model input file\n    double \t\t\tminimumValueOfStiffnessMultiplier;\t\t///< The lower bound of stiffness modification multiplier, exists to prevent elements reaching unintended zero or negative stiffness values.\n    double \t\t\tmaximumValueOfStiffnessMultiplier;\t\t///< The upper bound of stiffness modification multiplier, exists to prevent elements reaching unrealistic hard stiffness values.\n    double \t\t\tmutationGrowthRatePerSec;\t\t\t///< The growth rate set by a mutant clone covering this element.\n    double \t\t\tmutationGrowthFold;\t\t\t\t///< The rate of fold change in growth rate set by a mutant clone covering this element.\n    void \t\t\tsetShapeType(std::string TypeName);\t\t///< The function sets the type of the shape.\n    void \t\t\treadNodeIds(const std::vector<int>& inpNodeIds);///< The function sets the Node#Id array that constructs the shape.\n    void \t\t\tsetPositionMatrix(const std::vector<std::unique_ptr<Node>>& Nodes);\t///< The function sets the ShapeBase#Positions matrix to define the locations of each constructing node.\n    void \t\t\tsetTissuePlacement(const std::vector<std::unique_ptr<Node>>& Nodes);\t///< The function sets the placement of the element within the tissue\n    void \t\t\tsetTissueType(const std::vector<std::unique_ptr<Node>>& Nodes);\t\t///< The function sets the tissue type of the element\n    void \t\t\tsetReferencePositionMatrix();\t\t\t\t\t\t///< The function sets the RefereneceShapeBase#Positions matrix to define the reference positions of the element.\n    void \t\t\tsetIdentificationColour();\t\t\t\t\t\t///< The function sets the unique ShapeBase#IdentifierColour colour for the element, which is used in element picking from the user interface.\n    void \t\t\trotateReferenceElementByRotationMatrix(std::array<double,9> rotMat);\t///< The function rotates the reference of the element (ShapeBase#ReferenceShape) by input rotation matrix, provided as a double pointer of 9 doubles.\n    bool \t\t\tInvertMatrix(boost::numeric::ublas::matrix<double>& input, boost::numeric::ublas::matrix<double>& inverse); ///< The function takes the first input matrix, and writes the inverse on the second input. False is returned if the matrix is not inverted. Input format is ublas matrices (slow).\n    bool \t\t\tInvertMatrix(gsl_matrix* input, gsl_matrix* inverse); \t\t\t///< The function takes the first input matrix, and writes the inverse on the second input. False is returned if the matrix is not inverted. Input format is gsl matrices (fast).\n\n    void \t\t\tupdateNodeIdsFromSave(std::ifstream& file);\t\t\t\t///< The function reads the ShapeBase#NodeIds of the current shape from save file provided as input.\n    void \t\t\tupdateReferencePositionMatrixFromSave(std::ifstream& file); \t\t///< The function reads and updates the ShapeBase#ReferenceShape positions (ReferenceShapeBase#Positions) of the current shape from save file provided as input.\n    virtual void \t\tcalculateReferenceVolume(){ParentErrorMessage(\"calculateReferenceVolume\");}  ///<Virtual function of the ShapeBase class to calculate volume of the ShapeBase#ReferenceShape\n\n    bool                calculateGrowthStrainsRotMat(double* v);\t\t\t\t///< The function calculates the rotation matrix to apply on growth strains to align growth with the current x axis of the tissue.\n    void                calculateForces3D(const std::vector<std::unique_ptr<Node>>& Nodes,  gsl_matrix* displacementPerDt); ///< The function calculates the viscous and elastic forces generated by the element.\n    gsl_matrix* \t\tcalculateEForNodalForcesKirshoff(gsl_matrix* C);\t\t\t///< This function calculates the green strains for a Kirshoff material model.\n    gsl_matrix* \t\tcalculateCauchyGreenDeformationTensor(gsl_matrix* Fe);\t\t\t///< This function calculates the Caucy-Green deformation tensor, from the elastic part of the deformation gradient\n    gsl_matrix* \t\tcalculateSForNodalForcesKirshoff(gsl_matrix* E);\t\t\t///< This function calculates the Secons order Piola-Kirshoff stress tensor for Kirshoff material model.\n    gsl_matrix* \t\tcalculateSForNodalForcesNeoHookean(gsl_matrix* invC, double lnJ);\t///< This function calculates the Secons order Piola-Kirshoff stress tensor for Neo-Hookean material model.v\n    void \t\t\tupdateLagrangianElasticityTensorNeoHookean(gsl_matrix* invC,double lnJ, int pointNo);\t///< This function calcualtes the Lagrangian elasticity tensor for Neo-Hookean material model.\n    gsl_matrix* \t\tcalculateCompactStressForNodalForces(double detFe,gsl_matrix* Fe, gsl_matrix* S, gsl_matrix *Stress); ///< This function calculates elemental stress in Voigt notation.\n    gsl_matrix* \t\tcalculateInverseJacobianStackForNodalForces(gsl_matrix* Jacobian);\t///< This function calculates the stack matrix of inverse Jacobians, used to calculate the nodal forces.\n    gsl_matrix* \t\tcalculateBTforNodalForces(gsl_matrix* InvJacobianStack, gsl_matrix* ShapeFuncDerStack, gsl_matrix *B, gsl_matrix* invJShFuncDerS); ///< This function calculates the B matrix, to calculate the nodal force.\n    void\t\t\tcalculateInvJShFuncDerSWithFe(gsl_matrix * currFe, gsl_matrix * InvDXde, gsl_matrix* ShapeFuncDerStack, gsl_matrix *invJShFuncDerSWithF); ///< This function calculates the collated matrix from inverse jaconians and shape function derivatives.\n    gsl_matrix* \t\tcalculateVelocityGradientTensor(gsl_matrix* B, gsl_matrix* displacementPerDt);  ///< This function calculates the velocity gradient tensor.\n    gsl_matrix* \t\tconstructElementalDisplacementMatrix(gsl_matrix* displacement); \t\t///< This function will assemble elemental node displacement matrix from the input displacement matrix for the whole system.\n    gsl_matrix* \t\tcalculateRateOfDeformationTensor(gsl_matrix* l);\t\t\t\t///< This function will calculate rate of deformation tensor from velocity gradient tensor\n    void \t\t\tcalculateViscousStress(gsl_matrix* d, gsl_matrix* viscousStress);\t\t///< This function will calculate internal viscous stress of the element from rate of deformation matrix.\n    void \t\t\tcalculateViscousForces(gsl_matrix*  gv, gsl_matrix*  BTdetFdetdXde, gsl_matrix* viscousStress); ///< This function  will calculate the elemental viscous forces from viscous stress.\n\n    void    \t\t\tconsturctBaTBb(gsl_matrix* B, gsl_matrix* BaT, gsl_matrix* Bb, int a, int b);\t///< This function constructs nodal subrange of B matrix for node couple a & b.\n    void   \t\t\tcalculateElasticKIntegral1(gsl_matrix* currElementalK,int pointNo);\t\t///< This function calcultes the first part of the integral for the stiffness matirx, the elastic part of the system Jacobian.\n    void\t\t\tcalculateElasticKIntegral2(gsl_matrix* currElementalK,int pointNo);             ///< This function calcultes the second part of the integral for the stiffness matirx, the elastic part of the system Jacobian.\n    void\t\t\tcalculateViscousKIntegral1(gsl_matrix* currElementalK, gsl_matrix* paranthesisTermForKv1, int pointNo);\t///< This function calcultes the first part of the integral for the internal viscous part of the system Jacobian.\n    void\t\t\tcalculateViscousKIntegral2(gsl_matrix* currElementalK,int pointNo);             ///< This function calcultes the second part of the integral for the viscous part of the system Jacobian.\n    void\t\t\tcalculateVelocityGradient( gsl_matrix* velocityGradient, gsl_matrix* displacementPerDt, int pointNo);\t///< This function calculates the velocity gradient.\n    void\t\t\tcalculateOuterProduct(gsl_matrix* a, gsl_matrix* b, gsl_matrix* outerProduct);\t///< Calculates the outer product, maths helper function.\n    gsl_matrix* \t\tcalculateSymmetricisedTensorProduct(gsl_matrix* a, gsl_matrix* b);          ///< Calculates the symetricised tensor product, maths helper function.\n\n    bool \t\t\tdisassembleRotationMatrixForZ(gsl_matrix* rotMat);\t\t\t///< This function extracts the z rotation from a rotation matrix.\n    bool \t\t\tcalculate3DRotMatFromF(gsl_matrix* rotMat);\t\t\t\t\t///< This function dissects the deformation gradient of the element into the rigid body rotation and deformation.\n\n    gsl_matrix* \t\tD;                                                      ///< elasticity tensor for Kirshoff material\n    gsl_matrix* \t\tCoeffMat;                                               ///< The coefficient matrix relating the shape function derivative stack to the Voigt notation of elemental stress nad strain.\n    //need to construct double array of size: D81[nGaussPoints][3][3][3][3];\n    std::vector<std::array<std::array<std::array<std::array<double,3>,3>,3>,3>> D81;\t\t\t\t///<Lagrangian elasticity tensor, vector for the number of Gauss points in simulaiton.\n    double \t\t\tE;                                                          ///< Young's modulus of the element.\n    double\t\t\tv;                                                          ///< Poisson's ratio of the element.\n    double \t\t\tinternalViscosity;                                          ///< Current internal viscosity of the element.\n    double \t\t\toriginalInternalViscosity;                                  ///< The internal viscosity of the element at the beginning of the simulation, prior to physical property perturbations.\n    double \t\t\tlambda;                                                     ///< Lame's second parameter, driven from Young's modulus and Poisson's ratio of the element\n    double\t\t\tmu;                                                         ///< Sheer modulus of the element.\n    gsl_matrix* \tInvFg;                                                      ///< Inverse of growth matrix\n    gsl_matrix* \tFsc;                                                        ///< Shape change matrix\n    gsl_matrix* \tInvFsc;                                                     ///< Inverse of shape change matrix\n    gsl_matrix* \tTriPointKe;                                                 ///< Current elastic part of the Jacobian (stiffness matrix) of the system, averaged over all Gauss Points.\n    gsl_matrix* \tTriPointKv;                                                 ///< Current viscous part of the Jacobian of the system, averaged over all Gauss Points.\npublic:\n    double \t\t\tstiffnessMultiplier;                                        ///< Current stiffness multiplier of the element, initially 1.0, modulated by stiffness perturbations\t\t\t\t\t\t///< The double for the multiplier that will define Young's modulus stress stiffening.\n    gsl_matrix*\t\tremodellingPlaneRotationMatrix;                             ///< The rotation matrix converting the xyz coordinate system to the plane of remodelling for the lateral elements.\n    gsl_matrix* \tFg;                                                         ///< Growth deformation gradient\n    int \t\t\tId;                                                         ///< The unique ID of the element, without remodelling, equal to its indes on the Simulation#Elements vector.\n    int\t\t\t\tShapeDim;                                                   ///< The dimension of the shape in workd coordiantes (2D vs 3D).\n    std::vector<int> NodeIds;                                                   ///< The vector storing the unique IDs (Node#Id) of nodes constructing this element. Their order is consistent for a given shape type.\n    virtual ~ShapeBase(){                                                       /// The ShapeBase destructor. This destructor should not be called uner healthy conditions.\n        //while deleting a ShapeBase* that happens to point a child, this destructor will be called after the child destructor\n    }\n    std::vector<std::array<double,3>> \tPositions;\t\t\t\t\t\t\t\t///< The vector storing the positions of the nodes constructing the element.\n    std::unique_ptr<ReferenceShapeBase> ReferenceShape;                         ///< The pointer to the reference shape object that defines th reference shape of this element.\n    gsl_matrix* \tStrain;                                                     ///< The gsl_matrix pointer, storing the address of the current strains on the element.\n\n    bool \t\t\tisFlipped;                                                  ///< Boolean stating if the element is flipped. The simulation will be stopped if there are flipped elements.\n    bool \t\t\tIsChangingShape;\n    //bool\t\t\twillBeRefined;\n    int \t\t\ttissuePlacement;                                            ///< 1 -> apical, 0 -> basal, 2->middle, 3 -> lateral\n    int \t\t\ttissueType;                                                 ///< The tissue type is 000 for columnar layer, 1 for peripodial membrane, and 2 for linker zone\n    bool\t\t\tspansWholeTissue;                                           ///< Boolean staing is the element spans the whole tissue. This is used to identify mid-layer tagged tissues (tissuePlacement = 2), that should still have apical abd basal responses\n    int \t\t\tcompartmentType;                                            ///< integer identifying the compartment of the tissue in DV axis, 0 pouch, 1 hinge, 2 notum\n    double \t\t\tcompartmentIdentityFraction;                                ///< The weight defining the constibution of each compartment to the physical identity of this element.\n    bool\t\t\tisECMMimicing;                                              ///< Boolean stating if the element is an ECM element.\n    bool\t\t\tisECMMimimcingAtCircumference;                              ///< Boolean stating if the element is an ECM element at the circumference of the tissue.\n    bool\t\t\tatBasalBorderOfECM;                                         ///< Boolean stating if the element is at the basal border of the cellular layer, linking to ECM elements.\n    bool\t\t\tisActinMimicing;                                            ///< Boolean stating if the element is forming the actin dense layer on the apical surface.\n    bool\t\t\tatApicalBorderOfActin;                                      ///< Boolean stating if the element is at the apical border of the soft cellular layer, linking to actin dense layer.\n    bool\t\t\tIsAblated;                                                  ///< Boolean stating if the element is laser ablated, therefore dead.\n    bool\t\t\tatSymetricityBoundary;                                      ///< Boolean stating if the element is at the symmetricity boundary.\n    //bool\t\t\tIsClippedInDisplay;\t\n    //bool \t\t\tIsXSymmetricClippedInDisplay;\n    //bool\t\t\tIsYSymmetricClippedInDisplay;\n    double \t\t\tCurrShapeChangeToAdd[3];                                    ///< The current shape change to be applied to the element, in form of 3D rates.\n    double  \t\tGrownVolume;                                                ///< Current volume of the element after growth.\n    double  \t\tVolumePerNode;                                              ///< Volume per node of the element.\n    bool \t\t\tcapElement;                                                 ///< Boolean stating if the element is capped at its remodelling due to restrictions in z remodelling (avoiding too thin ot too thick layers due to numerical error).\n    std::vector<int> elementsIdsOnSameColumn;                                   ///< The vector storing the unique element IDs of each element that is on the same columnar region of the tissue, i.e. the elements share apical/basal surfaces.\n    int \t\t\tbasalNeigElementId;                                         ///< This is recorded only for apical nodes of the columnar layer. If not recorded, id is -1.\n    bool \t\t\tinsideEllipseBand;                                          ///< Boolean stating if the element is marked by any identifier bands for physical perturbation.\n    int \t\t\tcoveringEllipseBandId;                                      ///< The unique ID of the covering perturbation band.\n\n    double \t\t\temergentShapeLongAxis[2];                                   ///< The long axis of the emergent shape. This is necessary for analysis of emergent growth orientations.\n    double \t\t\temergentShapeShortAxis[2];                                  ///< The short axis of the emergent shape. This is necessary for analysis of emergent growth orientations.\n\n    double\t\t\tplasticDeformationHalfLifeMultiplier;                       ///< The multiplier to modify the remodelling half-life upon physical property perturbation.\n    bool \t\t\tisMutated;                                                  ///< Boolean stating if the element is mutated.\n\n    bool \t\t\tthereIsGrowthRedistribution;                                ///< Boolean stating if there is redistribution of growth among mesh elements.\n    bool \t\t\tgrowthRedistributionShrinksElement;                         ///< Boolean stating if the growth distribution is taking material out of thes element to redistribute ot others.\n    double \t\t\tgrowthRedistributionScale;                                  ///< The extent of the redistribution of volume.\n    bool\t\t\tRotatedElement;                                             ///< The boolean stating if the elemetn has rigid body rotation.\n    gsl_matrix* \tGrowthStrainsRotMat;                                        ///< The rotation matrix needed to correct for the rigid body rotations of the element.\n\n    std::array<double,3> \tapicalNormalCurrentShape;\t\t\t\t\t\t\t///< The apical normal of the current shape.\n    int                         getId();                                        ///< The function returns the unique ID of the element.\n    std::string                 getName();                                      ///< The function returns the name of the element.\n    int                         getShapeType();\t\t\t\t\t\t\t\t\t///< The function returns the shape type of the element.\n    size_t                      getNodeNumber();\t\t\t\t\t\t\t\t///< The function returns the number of nodes o the element.\n    const std::vector<int>& \tgetNodeIds();\t\t\t\t\t\t\t\t\t///< The function returns the vector of node IDs.\n    int                         getNodeId(int i);\t\t\t\t\t\t\t\t///< The function returns the input i^{th} node's ID.\n    size_t                      getDim();                                       ///< The function returns the dimensions of the node, ShapeBase#Dim.\n    std::array<int,3>           getIdentifierColour();\t\t\t\t\t\t\t///< The unique [r,g,b] identifier colour of the element, utilised in picking in the user interface.\n    std::array<double,3>        getCentre();\t\t\t\t\t\t\t\t\t///< This function returns the centre of the element in world spave.\n    double                      getPeripodialness();\t\t\t\t\t\t\t///< This function returns the relative influence of the peripodial physical characteristics to this element.\n    double                      getColumnarness();\t\t\t\t\t\t\t\t///< This function returns the relative influence of the columnar  physical characteristics ot this element.\n    void                        getRelativePositionInTissueInGridIndex(int nGridX, int nGridY, int& IndexX, int& IndexY, double& FracX, double& FracY); \t///< Provides the relative position within the bounding box of the tissue, and calculates which point on the growth maps should be read.\n    void                        getInitialRelativePositionInTissueInGridIndex(int nGridX, int nGridY, int& IndexX, int& IndexY, double& FracX, double& FracY); \t///< The relative positions of the iitial configuration of the element within the bounding box of the tissue.\n    double                      getStiffnessMultiplier();\t\t\t\t\t\t\t///< This function returns the current stiffness multiplier as a result of perturbations to physical properties.\n    double                      getCurrentVolume();\t\t\t\t\t\t\t\t///< This function returns the current volume of the element.\n    double                      getElementalElasticForce(int nodeIndex, int dimIndex);\t\t\t\t///< This function returns the calculated elastic force for the node nodeIndex, in coordinate dimIndex.\n    void                        setElementalElasticForce(int nodeIndex, int dimIndex, double value);\t\t///< This functions sets the calculated elastic force for the node nodeIndex, dimension dimIndex, to the input value.\n\n    gsl_matrix*             getCurrentFe();\t\t\t\t\t\t\t\t\t///< This function returns the current elastic part of the deformation gradient.\n    double                  getApicalArea();\t\t\t\t\t\t\t\t///< This function returns the current apical area of the element.\n    void                    relaxElasticForces();\t\t\t\t\t\t\t\t///< This function relaxes all teh accumulated elastic forces in the system.\n    bool                    isGrowthRateApplicable(int sourceTissue, double& weight, double zmin, double zmax);\t///< The function checks if the element if affected by the current growth functions.\n    void                    updateGrowthWillBeScaledDueToApikobasalRedistribution(bool thisFunctionShrinksApical, std::vector<int>& ellipseBandIdsForGrowthRedistribution); ///< This function decide if the growth will be redistirbuted in the height of the tissue.\n    void                    scaleGrowthForZRedistribution( double& x, double& y, double& z);\t\t\t///< This function will modify the incremental growth deformation gradient of the element to reflect the volume redistribution in the height of the tissue.\n    void                    calculateFgFromRates(double dt, double x, double y, double z, gsl_matrix* rotMat, gsl_matrix* increment, int sourceTissue, double zMin, double zMax);\t///< This fucntion will calculate the incremental growth deformation gradient change for the current time step, from input growth rates\n    void                    calculateFgFromGridCorners(int gridGrowthsInterpolationType, double dt, GrowthFunctionBase* currGF, gsl_matrix* increment, int sourceTissue, int IndexX, int IndexY, double FracX, double dFracY); ///< This fucntion will calculate the incremental growth deformation gradient change for the current time step by reading it from the grid, and interpolating on 4 corners.\n    gsl_matrix*             getGrowthIncrement();\t\t\t\t\t\t\t\t///< This function will return the current growth deformation gradient increment\n    void                    updateGrowthIncrement(gsl_matrix* columnar, gsl_matrix* peripodial);\t\t///< This function will update the elemental growth deformation gradient from the current growth deformation gradient increment.\n    void                    updateGrowthByMutation(double dt);\t\t\t\t\t\t///< This function will update the growth growth deformaton gradient increment of the element due to a mutation.\n    void                    scaleGrowthIncrement(double multiuplier);\t\t\t\t\t///< This function will scale the growth growth deformaton gradient increment by input double.\n    void                    calculateShapeChangeIncrementFromRates(double dt, double rx, double ry, double rz, gsl_matrix* increment); ///< This function will calculate the current shape change deformation gradient increment due to elemental active shape change, from input rates.\n    void                    updateShapeChangeIncrement(gsl_matrix* columnarShapeChangeIncrement);\t\t///< This function updates the growth increment of the element with the current shape change increment\n    void                    calculateRelativePosInBoundingBox(double boundingBoxXMin, double boundingBoxYMin, double boundingBoxLength, double boundingBoxWidth); ///< This function will calculate the relative positions of the element in the xy-plane bounding box of the tissue.\n    void                    mutateElement(double growthFold, double growthRatePerHour);\t\t\t///< This function will set the element as a mutant, the mutant growth rates will be set.\n    void                    updateReferencePositionMatrixFromInput(double** input);\t\t\t\t///< This function will update the reference position matrix. Not used under healthy, continuous simulations, to preserve continuity of the mesh.\n    void                    displayRelativePosInBoundingBox();\t\t\t\t\t\t///< Helper function to display the relative position of the element in the bounding box of the tissue.\n    std::array<double,2>\tgetRelativePosInBoundingBox();\t\t\t\t\t\t\t///< This function will return the relative position of the element in the xy bounding box of the tissue\n    void \t\t\tsetRelativePosInBoundingBox(double x, double y);\t\t\t\t///< This functoin will set the relative position of the element in the bounding box of the tissue to the input coordinates.\n    void\t\t\tsetInitialRelativePosInBoundingBox();\t\t\t\t\t\t///< This function sets the initial relative position in bounding box of the tissue to current reference position.\n    void \t\t\tsetInitialZPosition(double zMax, double TissueHeight);\t\t\t\t///< This fucntion sets the initial relative z position of the tissue in tissue height.\n    std::array<double,2>\tgetInitialRelativePosInBoundingBox();\t\t\t\t\t\t///< This function will return the initial relative position of the element in the xy bounding box of the tissue\n    void \t\t\tconvertRelativePosToGridIndex(std::array<double,2> relpos, int& indexX, int &indexY, double &fracX, double &fracY, int nGridX, int nGridY); ///< This function will convert the relative position of the tissue in xy plane bounding box to growth map grid indices.\n    void \t\t\tgetStrain(int type, float &StrainMag);\t\t\t\t\t\t///< This function will return the selected strain component of the element.\n    void \t\t\tgetNodeBasedPysProp(int type, int NodeNo, const std::vector<std::unique_ptr<Node>>& Nodes, float& PysPropMag); ///< This function will return the selected physical properties of the element on a nodal basis.\n    void \t\t\tgetPysProp(int type, float &PysPropMag, double dt);\t\t\t\t///< This function will return the selected physical properties of the element.\n    double\t\t\tgetInternalViscosity();\t\t\t\t\t\t\t\t///< This function will return the internal viscosity of the element.\n    double\t\t\tgetOriginalInternalViscosity();\t\t\t\t\t\t\t///<  This function will return the internal viscosity of the element prior to any perturbations.\n    //void   \t\t\tupdateInternalViscosityTest();\n    double \t\t\tgetYoungModulus();\t\t\t\t\t\t\t\t///< This function will return the Young's modulus of the element\n    double \t\t\tgetPoissonRatio();\t\t\t\t\t\t\t\t///< This function will return the Poissons's ratio of the element\n    const std::array<double,3>& getGrowthRate();\t\t\t\t\t\t\t\t///< This function will return the current growth rate of the element.\n    const std::array<double,6>& getShapeChangeRate();\t\t\t\t\t\t\t\t///< This function will return the current shape change rate of the element.\n    const std::vector<std::array<double,3>>& getReferencePos();\t\t\t\t\t\t\t///< This function will return the reference positions of the element.\n    void    \t\t\tgetPos(gsl_matrix* Pos);\t\t\t\t\t\t\t///< This function will write the position of the element into input matrix.\n    gsl_matrix* \t\tgetFg();\t\t\t\t\t\t\t\t\t///< This function will return the growth component of the deformation gradient.\n    gsl_matrix* \t\tgetInvFg();\t\t\t\t\t\t\t\t\t///< This function calculates the inverse of the growth deformation gradient matrix.\n    gsl_matrix* \t\tgetFsc();\t\t\t\t\t\t\t\t\t///< This function will return the shape change component of the deformation gradient.\n    gsl_matrix* \t\tgetInvFsc();\t\t\t\t\t\t\t\t\t///< This function calculates the inverse of the shape change deformation gradient matrix. \n    gsl_matrix* \t\tgetFe();\t\t\t\t\t\t\t\t\t///< This function will return the elastic component of the deformation gradient.\n    double \t\t\tgetZRemodellingSoFar();\t\t\t\t\t\t\t\t///< This function will return the z remodelling applied to the element so far, to cap the z remodelling.\n    void \t\t\tsetZRemodellingSoFar(double zRemodellingSoFar); \t\t\t\t///< This function will set the z remodelling applied to the element so far to input value. This is needed during saved input reading.\n    void \t\t\tdisplayName();\t\t\t\t\t\t\t\t\t///< Helper function, display the name of the element\n    void\t\t\tdisplayNodeIds();\t\t\t\t\t\t\t\t///< Helper function, display the Ids of the nodes of the element\n    void \t\t\tdisplayPositions();\t\t\t\t\t\t\t\t///< Helper function, display the nodal positions of the element\n    void \t\t\tdisplayReferencePositions();\t\t\t\t\t\t\t///< Helper function, display the nodal positions of the reference element\n    void \t\t\tdisplayIdentifierColour();\t\t\t\t\t\t\t///< Helper function, display the unique identifier colour, for picking in user interface.\n    void  \t\t  \tsetFg(gsl_matrix* currFg);\t\t\t\t\t\t\t///< This function sets the current grwoth deformation gradient matrix equal to input matrix \n    void \t\t\tsetGrowthWeightsViaTissuePlacement (double periWeight);\t\t\t\t///< This function sets the weight for growth rate scaling depending on tissue type\n    void \t\t\tsetYoungsModulus(double E);\t\t\t\t\t\t\t///< This function sets the Young's modulus of the shape to inout double.\n    virtual void \t\tsetElasticProperties(double /*EApical*/,double /*EBasal*/, double /*EMid*/, double /*EECM*/, double /*v*/){ParentErrorMessage(\"setElasticProperties\");} ///< This is the parent virtual function for setting up the elasticity properties of the shape depending on its tissue type placement.\n    virtual void \t\tcheckEdgeLenghtsForBinding(std::vector<int>& /*masterIds*/, std::vector<int>& /*slaveIds*/){ParentErrorMessage(\"checkEdgeLenghtsForBinding\");} ///< The virt\n    void \t\t\tsetViscosity(double viscosityApical,double viscosityBasal, double viscosityMid);///< This function sets the viscosity of the element depending on its placement in the tissue.\n    void \t\t\tsetViscosity(double viscosityApical,double viscosityBasal);\t\t\t///< This function sets the viscosity of the element depending on its placement in the tissue.\n    void \t\t\tsetViscosity(double viscosity);\t\t\t\t\t\t\t///< This function sets the viscosity of the element depending on its placement in the tissue.\n    double\t\t\tcalculateEmergentShapeOrientation();\t\t\t\t\t\t///< This fucntion calculates the orientation of the emergent shape of an element in the xy plane of the tissue.\n    bool \t\t\tisActinStiffnessChangeAppliedToElement(bool ThereIsWholeTissueStiffnessPerturbation, bool ThereIsApicalStiffnessPerturbation, bool ThereIsBasalStiffnessPerturbation, bool ThereIsBasolateralWithApicalRelaxationStiffnessPerturbation, bool ThereIsBasolateralStiffnessPerturbation, std::vector <int> &stiffnessPerturbationEllipseBandIds, int numberOfStiffnessPerturbationAppliesEllipseBands ); ///< This function decides if the actin stiffness perturbation is applied to this element.\n    bool \t\t\tisECMChangeAppliedToElement(bool changeApicalECM, bool changeBasalECM, std::vector<int> &ECMChangeEllipseBandIds, int numberOfECMChangeEllipseBands);\t\t\t\t///< This function decides if the ECM perturbation is applied to this element\n    bool \t\t\tisShapeChangeAppliedToElement(std::vector<int> &ellipseBandIds, bool applyBasalECM, bool applyToLateralECM, bool applyApically, bool applyBasally, bool applyMidLayer );\t///< This function decides if the shape change perturbation is applied to this element\n    void \t\t\tcalculateStiffnessPerturbationRate(bool ThereIsBasolateralWithApicalRelaxationStiffnessPerturbation, double stiffnessPerturbationBeginTimeInSec, double stiffnessPerturbationEndTimeInSec, double stiffnessChangedToFractionOfOriginal); ///< This function will calciulate the stiffness perturbation rate.\n    void \t\t\tupdateStiffnessMultiplier(double dt); ///< The function will update the actin multiplier as a result of stiffness perturbations.\n    virtual std::array<double,3>  calculateBasalNormal(){ParentErrorMessage(\"calculateBasalNormal\"); std::array<double,3> dummy = {0.0, 0.0, 0.0}; return dummy;} \t///< The virtual function of the parent for basal normal calculation. The value is dependent on node topology of the element and defined for eac individual child class.\n    virtual void \t\tcalculateApicalNormalCurrentShape(){ParentErrorMessage(\"calculateApicalNormal\");}\t\t\t\t\t\t\t///< The virtual function of the parent for apical normal calculation. The value is dependent on node topology of the element and defined for eac individual child class.\n    void \t\t\tcalculateCurrentGrowthIncrement(gsl_matrix* resultingGrowthIncrement, double dt, double growthx, double growthy, double growthz, gsl_matrix* ShearAngleRotationMatrix); ///< The function calculates the current growth increment from the input of growth rate and the orientation rotation matrix.\n    void \t\t\tupdateShapeChangeRate(double x, double y, double z, double xy, double yz, double xz);\n    virtual void \t\tcalculateElementShapeFunctionDerivatives(){ParentErrorMessage(\"calculateElementShapeFunctionDerivatives\");}\t///< The virtual function of the parent for calculation of shape function derivatives. This is topology dependent and implemented in each child shape type.\n    virtual void \t\tcalculateCurrNodalForces(gsl_matrix */*gslcurrge*/, gsl_matrix */*gslcurrgv*/, gsl_matrix */*gslcurrF*/, gsl_matrix* /*displacementPerDt*/, int /*pointNo*/){ParentErrorMessage(\"calculateCurrNodalForces\");} ///< The virtual function to calculate nodal force. This is topology dependent and implemented in each child shape type.\n    virtual void \t\tcalculateCurrTriPointFForRotation(gsl_matrix */*currF*/,int /*pointNo*/){ParentErrorMessage(\"calculateCurrTriPointFForRotation\");}\n    virtual void \t\tcalculateApicalArea(){ParentErrorMessage(\"calculateApicalArea\");}                           ///< The virtual function to calculate apical area of element. This is topology dependent and implemented in each child shape type.\n    virtual void \t\tcalculateBasalArea(){ParentErrorMessage(\"calculateBasalArea\");}                             ///< The virtual function to calculate basal area of element. This is topology dependent and implemented in each child shape type.\n    double \t\t\tcalculateCurrentGrownAndEmergentVolumes();                                                      ///< This is the function to calculate hte current ideal volume of the element and its current apparent volume.\n    virtual void \t\tupdateElasticProperties(){ParentErrorMessage(\"updateElasticProperties\");}                   ///< This functions updates elastic propertiesand their dependent tensors upon alteration of a physical property.\n    void \t\t\twriteInternalForcesTogeAndgv(gsl_matrix* ge, gsl_matrix* gvInternal, std::vector<std::array<double,3>>& SystemForces, const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function writes the elemental elastic and viscous forces to the system scale force vector.\n    void \t\t\tcalculateForces(const std::vector<std::unique_ptr<Node>>& Nodes, gsl_matrix* displacementPerDt);\n    void \t\t\tupdatePositions(const std::vector<std::unique_ptr<Node>>& Nodes);                               ///< This function updates the position array of the element from the updated nodal posiitons.\n    void \t\t\tsetGrowthRate(double dt, double rx, double ry, double rz);                                      ///< This function sets the growth of the element from the tome step and the input rates\n    void \t\t\tsetGrowthRateViaInputTimeMultipliedMagnitude(double x, double y, double z);                     ///< This function sets the growht rate to pre-calculated rates given as input.\n    void \t\t\tupdateGrowthIncrementFromRate();                                                                ///< This function fills th egrowht increment matirx from the current growth rate matrix\n    double  \t\tcalculateVolumeForInputShapeStructure(std::vector<std::array<double,3>> shapePositions, size_t nTriangularFaces, std::vector<std::array<int,3>>  triangularFaces, std::array<double,3> midPoint ); ///< This function calculates the volume of the shape, it is generalised such that the shape is defined as an array of triengles forming a convex hull.\n    void \t\t\tcalculatePrincipalStrains3D(double& e1, double &e2,  double &e3, gsl_matrix* eigenVec);         ///< This function calculates the principal components of the strains through eigen values and eigen vectors in 3D.\n    void \t\t\tcalculatePrincipalStrains2D(double& e1, double &e2,  double &e3, gsl_matrix* eigenVec);         ///< This function calculates the principal components of the strains through eigen values and eigen vectors in 2D.\n    //void \t\t\tcalculatePrincipalStrainAxesOnXYPlane(double& e1, double &e2, double& tet);\t\t\t///< This function princial \n   // bool\t\t\tcheckIfXYPlaneStrainAboveThreshold(double thres);\n   // bool \t\t\tcalculateIfInsideActiveStripe(double initialPoint,double endPoint, double stripeSize1, double stripeSize2);\n    void \t\t\tsetShapeChangeRate(double x, double y, double z, double xy, double yz, double xz);                  ///< This function sets the shape change rate to pre-calculated rates given as input.\n    void  \t\t\tsetShapeChangeInrementToIdentity();                                                                 ///< This function sets the shape change deformation gradient increment to identity\n    void \t\t\tupdateElementVolumesAndTissuePlacementsForSave(const std::vector<std::unique_ptr<Node>>& Nodes);    ///< This function calculates the reference volume, tissue placement and tissue type from nodal information\n    bool \t\t\treadNodeIdData(std::ifstream& file);                                                                ///< This function reads in the node Ids for the element from save file\n    bool\t\t\treadReferencePositionData(std::ifstream& file);                                                     ///< This function reads the reference element positions from save file\n\n    bool \t\t\tareanyOfMyNodesAtCircumference(const std::vector<std::unique_ptr<Node> > &Nodes);                   ///< This function check if the element owns any node at tissue circumference\n\n    virtual void \t\t checkHealth(){ParentErrorMessage(\"checkHealth\");}                                              ///< The virtual function in parent to check if element is flipped, implemented for each child as it is node topology dependent.\n    void    \t\t\twriteKelasticToMainKatrix(gsl_matrix* K);                                                       ///< This function writes the elemental elastic component of the Jacobian to system Jacobian.\n    void    \t\t\twriteKviscousToMainKatrix(gsl_matrix* K);                                                       ///< This function writes the elemental viscous component of the Jacobian to system Jacobian.\n    void    \t\t\tcalculateImplicitKElastic();                                                                    ///< This function calculates the elemental elastic component of the Jacobian for implicit NR itaration.\n    void \t\t\tcalculateImplicitKViscous(gsl_matrix* displacementPerDt, double dt);                                ///< This function calculates the elemental viscous component of the Jacobian for implicit NR itaration.\n    void\t\t\tcalculateForceFromStress(int nodeId, gsl_matrix* Externalstress, gsl_matrix* ExternalNodalForces);  ///< This function calculates the elemental nodal forces from an input external stress matrix\n\n\n    void \t\t\tupdateShapeFromSave(std::ifstream& file);                                           ///< This function updates the element geometric poroerties from save file.\n    void \t\t\tdisplayMatrix(boost::numeric::ublas::matrix<double>& mat, std::string matname);     ///< Helper function, displays the input blas (double) matrix with the input name.\n    void \t\t\tdisplayMatrix(boost::numeric::ublas::matrix<int>& mat, std::string matname);        ///< Helper function, displays the input blas (int) matrix with the input name.\n    void \t\t\tdisplayMatrix(boost::numeric::ublas::vector<double>& vec, std::string matname);     ///< Helper function, displays the input blas (double) vector with the input name.\n    void \t\t\tdisplayMatrix(gsl_matrix* mat, std::string matname);                                ///< Helper function, displays the input gsl matrix with the input name.\n    void \t\t\tdisplayMatrix(gsl_vector* mat, std::string matname);                                ///< Helper function, displays the input gsl vector with the input name.\n    void \t\t\tcreateMatrixCopy(gsl_matrix *dest, gsl_matrix* src);                                ///< Helper function, creates a copy of the gsl matrix on new memory locaiton.\n    double  \t\tcalculateMagnitudeVector3D(std::array<double,3> v);                                 ///< Helper algebraic function, calculates norm of the vector defined in the array<double,3>;\n    void\t\t\tnormaliseVector3D(gsl_vector* v);                                                   ///< Helper algebraic function, normalises the input gsl vector (the input vector is modified)\n    double\t\t\tnormaliseVector3D(std::array<double,3>& v);                                         ///< Helper algebraic function, normalises the input array<double,3> (the input vector is modified)\n    double\t\t\tgetNormVector3D(gsl_vector* v);                                                     ///< Helper algebraic function, calculates norm of the vector defined in the gsl vector, the vector is not modified.\n    //double \t\t\tdeterminant3by3Matrix(double* rotMat);                                              ///< Helper algebraic function, calculates determinant of 3by3 matrix stored in the double array pointed by the input pointer\n    double \t\t\tdeterminant3by3Matrix(boost::numeric::ublas::matrix<double>& Mat);                  ///< Helper algebraic function, calculates determinant of 3by3 boost matrix\n    double \t\t\tdeterminant3by3Matrix(gsl_matrix* Mat);                                             ///< Helper algebraic function, calculates determinant of 3by3 gsl matrix\n    double \t\t\tdeterminant2by2Matrix(boost::numeric::ublas::matrix<double>& Mat);                  ///< Helper algebraic function, calculates determinant of 2by2 boost matrix\n    void\t\t\tcalculateRotationAngleSinCos(std::array<double,3>& u, std::array<double,3>& v, double& c, double& s);       /// Helper algebraic function calculates the sine and cosine of the rotation angle needed to align vector u onto v.\n    void    \t\tcalculateRotationAxis(const std::array<double,3>& u, const std::array<double,3> &v, std::array<double,3>& rotAx, double c); /// Helper algebraic function calculates the rotation axis needed to align vector u onto v.\n    void\t\t\tconstructRotationMatrix(double c, double s, double* rotAx, double* rotMat);         ///< Helper algebraic functio calculates the rotation matrix from input sine, cosine of the rotation angle and the rotation axis. Writes the matrix into the input rotMat\n    void\t\t\tconstructRotationMatrix(double c, double s, std::array<double,3>& rotAx, std::array<double,9>& rotMat); ///< Helper algebraic functio calculates the rotation matrix from input sine, cosine of the rotation angle and the rotation axis. Writes the matrix into the input rotMat\n    void\t\t\trotateVectorByRotationMatrix(double* u,double* rotMat);                             ///< Helper algebraic function rotates the input vector v by rotation matrix rotMat\n    void\t\t\trotateVectorByRotationMatrix(double* u,gsl_matrix* rotMat);                         ///< Helper algebraic function rotates the input vector v by rotation matrix rotMat\n    void\t\t\trotateVectorByRotationMatrix(std::array<double,3>& u, std::array<double,9> rotMat); ///< Helper algebraic function rotates the input vector v by rotation matrix rotMat\n    void    \t\tCalculateGrowthRotationByF();                                                       ///< This function calculates the rigid body rotation of the element around the z axis of the tissue from hte fecormation gradient.\n    void \t\t\tcalculateTriPointFForRatation();                                                    ///< This function calculates the current deformaiton gradient as averaged at all Gauss points, for rigid body rotation extraction\n    void \t\t\tsetPlasticDeformationIncrement(double xx, double yy, double zz);                    ///< This function sets diagonal of the plastic deformation gradient increment from input values\n    void \t\t\tgrowShapeByFg();                                                                    ///< This function updates the current growth deformaiton gradient with the growt/shape change/plastic deformation increments and their respective rotations.\n    void \t\t\tchangeShapeByFsc(double dt);                                                        ///< This function calculates the shape change increment from shape change rates\n    void\t\t\tcheckIfInsideEllipseBands(int nMarkerEllipseRanges, std::vector<double> markerEllipseBandXCentres, std::vector<double> markerEllipseBandR1Ranges, std::vector<double> markerEllipseBandR2Ranges, const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function checks if the element is inside any marker bands for perturbatins.\n    bool\t\t\tcheckZCappingInRemodelling(bool volumeConserved, double zRemodellingLowerThreshold, double zRemodellingUpperThreshold, gsl_matrix* increment, gsl_matrix* eigenVec);    ///< This function checks if the remodelling of the element in z axis have reached the specified cap.\n    void\t\t\tassignSoftHinge(double lowHingeLimit, double highHingeLimit,double softnessLevel);  ///< This function modulates the stiffness of the hinge domain of the tissue with the input level. The domain is defined in relative x position boundaries.\n\n    void\t\t\tcalculatePlasticDeformation3D(bool volumeConserved, double dt, double plasticDeformationHalfLife, double zRemodellingLowerThreshold, double zRemodellingUpperThreshold); ///< This function calculates the plastic deformation (remodelling) from the current elastic deformation gradient.\n    //void \t\t\taddMigrationIncrementToGrowthIncrement(gsl_matrix* migrationIncrement);\n    void \t\t\tdisplayDebuggingMatrices();                                                                     ///< This function displays a selected set of matricex for debugging purposes.\n    virtual double \t\tgetApicalSideLengthAverage(){return ParentErrorMessage(\"getApicalSideLengthAverage\",0.0);}  ///< The virtual function of the parent to calculate average apical side length, dependent on nodal topology, defined in each child.\n    virtual double \t\tgetBasalSideLengthAverage(){return ParentErrorMessage(\"getBasalSideLengthAverage\",0.0);}    ///< The virtual function of the parent to calculate average basal side length, dependent on nodal topology, defined in each child.\n    virtual int \t\tgetCorrecpondingApical(int /*currNodeId*/){return ParentErrorMessage(\"getCorrecpondingApical\", -100);}  ///< The virtual function of the parent to obtain the corresponding apical node of a basal node, dependent on nodal topology, defined in each child.\n    virtual bool \t\tIsThisNodeMyBasal(int /*currNodeId*/){return ParentErrorMessage(\"IsThisNodeMyBasal\", false);}   ///< The virtual function of the parent to check if the input node ID is a basal node of the element, dependent on nodal topology, defined in each child.\n    virtual bool \t\tIsThisNodeMyApical(int /*currNodeId*/){return ParentErrorMessage(\"IsThisNodeMyApical\", false);} ///< The virtual function of the parent to check if the input node ID is an apical node of the element, dependent on nodal topology, defined in each child.\n    virtual double \t\tgetElementHeight(){return ParentErrorMessage(\"getElementHeight\", 0.0);}                         ///< //< The virtual function of the parent to calculate z height of the element, dependent on nodal topology, defined in each child.\n    virtual void\t\tconstructElementStackList(const int /*discretisationLayers*/, const std::vector<std::unique_ptr<ShapeBase>>& /*elementsList*/){ParentErrorMessage(\"constructElementStackList\");}\n    virtual void \t\tcheckRotationConsistency3D(){ParentErrorMessage(\"checkRotationConsistency3D\");}                                         ///< The virtual function of the parent to check if the two input nodes of the element are directly connected on one of the elemental surfaces, dependent on nodal topology, defined in each child.\n    virtual bool \t\tareNodesDirectlyConnected(int /*node0*/, int /*node1*/){return ParentErrorMessage(\"areNodesDirectlyConnected\",false);} ///< The virtual function of the parent to check if the rotation of the nodes of the element are consistent, dependent on nodal topology, defined in each child.\n    bool \t\t\tDoesPointBelogToMe(int IdNode);                             ///< This function checks if the input node belogs to the element.\n    void \t\t\tassignVolumesToNodes(const std::vector<std::unique_ptr<Node>>& Nodes);  ///< This function distributes element's total volume among its owner nodes.\n    void \t\t\tcalculateZProjectedAreas();                                         ///< This function calculated the z-projected (to world xy plane) apical and basal areas of the element.\n    void \t\t\tassignZProjectedAreas(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function distributes element's z-projected areas among its owner nodes.\n    void \t\t\tassignElementToConnectedNodes(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function assigns the element to the nodes it owns, necessary to construc the owner and connectivity list of nodes.\n    void \t\t\tsetECMMimicing(bool IsECMMimicing);                         ///< This funciton sets the element as an ECM mimicking element (distinct domain in terms of physical characteristics).\n    void \t\t\tsetActinMimicing(bool isActinMimicing);                     ///< This funciton sets the element as an actin mimicking element (distinct domain in terms of physical characteristics).\n    virtual void \t\tassignExposedSurfaceAreaIndices(const std::vector<std::unique_ptr<Node>>& /*Nodes*/){ParentErrorMessage(\"assignExposedSurfaceAreaIndices\");} ///< The virtual function on parent assigns the nodes of the surfaces that are exposed to external world, dependent on topology, defined for each child.\n    void \t\t\tcalculateViscositySurfaces();                               ///< This function calls for the assignment of exposed surfaces if the element has viscosity\n    void \t\t\tassignViscositySurfaceAreaToNodes(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function distributes elemenbt's exposed surfaces to nodes.\n\n    void \t\t\tcalculateEmergentRotationAngles();                          ///< This function calculates the emergent rotation of the element in xy plane for display purposes\n    void \t\t\tupdateReferencePositionMatrixFromMeshInput(std::ifstream& file);    ///< This function updates the reference position of the element from save file\n    void\t\t\tfillNodeNeighbourhood(const std::vector<std::unique_ptr<Node>>& Nodes); ///< This function fills in the node neightbourhood, needed for constrction of the connectivity of nodes\n    double \t\t\tdotProduct3D(std::array<double,3>& u, std::array<double,3>& v); ///< Helper algebraic function, calculates dot product of two arrays <double,3>\n    void\t\t\tcrossProduct3D(gsl_vector* u, gsl_vector* v, gsl_vector* cross); ///< Helper algebraic function, calculates cross product of two gsl_vectors, writes into the third input gls vector.\n    std::array<double,3> \tcrossProduct3D(std::array<double,3> u, std::array<double,3> v); ///< Helper algebraic function, calculates cross product of two arrays <double,3>\n    virtual void \t\tsetBasalNeigElementId(const std::vector<std::unique_ptr<ShapeBase>>& /*elementsList*/){ParentErrorMessage(\"setBasalNeigElementId\");}\n    bool \t\t\tisElementFlippedInPotentialNewShape(int nodeId, double newX, double newY, double newZ); ///< This function checks if the element will plip in the case that its node (nodeID) is moved to the new x,y,z coordintes specified in the input. Necessary in node collapsing.\n    void \t\t\tcheckForCollapsedNodes(int TissueHeightDiscretisationLayers, const std::vector<std::unique_ptr<Node>>& Nodes, const std::vector<std::unique_ptr<ShapeBase>>& Elements); ///< This function checks if any of the edges of the element is shortened to the extent that it should be collapsed.\n    bool \t\t\thasEnoughNodesOnCurve(const std::vector<std::unique_ptr<Node> > &Nodes);    ///< This function checks if the majority of the nodes of teh element reside in a curved region, to assign it to specific curvature dependent perturbations.\n    void \t\t\tassignEllipseBandIdToWholeTissueColumn(size_t TissueHeightDiscretisationLayers, const std::vector<std::unique_ptr<Node>>& Nodes, const std::vector<std::unique_ptr<ShapeBase>>& Elements); ///< This function assigns the marker ID of the apical elemetn ot all its connected elements in the tissue hight (all column of the element).\n    void \t\t\tassignEllipseBandId(const std::vector<std::unique_ptr<Node>>& Nodes, int selectedEllipseBandId); ///< This function assigns the marking ellipse band ID of the element depending on the definition of nodes it is consturcted of.\n    void \t\t\tassignEllipseBandIdToNodes(const std::vector<std::unique_ptr<Node>>& Nodes);    ///< This function assigns the marker ID of the elemetn to all its nodes.\n    void \t\t\taddToElementalElasticSystemForces(int i,int j,double value); \t/// This function is to add the input value, to the (i,j)th element of the ElementalElasticSystemForces\n    void \t\t\taddToTriPointKe(int i,int j,double value); \t\t\t/// This function is to add the input value, to the (i,j)th element of the triPointKe\n};\n\n#endif\n", "meta": {"hexsha": "154d86d1b177f1683db627608bbb01521ce5592d", "size": 64142, "ext": "h", "lang": "C", "max_stars_repo_path": "TissueFolding/SourceCode/ShapeBase.h", "max_stars_repo_name": "meldatozluoglu/TissueFolding_Lite", "max_stars_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-18T14:13:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-25T16:18:45.000Z", "max_issues_repo_path": "TissueFolding/SourceCode/ShapeBase.h", "max_issues_repo_name": "meldatozluoglu/TissueFolding_Lite", "max_issues_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900", "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": "TissueFolding/SourceCode/ShapeBase.h", "max_forks_repo_name": "meldatozluoglu/TissueFolding_Lite", "max_forks_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-06T11:38:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T12:26:51.000Z", "avg_line_length": 163.6275510204, "max_line_length": 492, "alphanum_fraction": 0.6982008668, "num_tokens": 13539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.379832962471196}}
{"text": "/**\n * @file batchf_zdotu_sub.c\n *\n * Part of API test for Batched BLAS routines.\n *\n * @author  Samuel  D. Relton\n * @author  Pedro   V. Lara\n * @author  Mawussi Zounon\n * @date \n *\n * @precisions normal z -> c \n *\n **/\n\n#include <cblas.h>\n#include \"bblas.h\"\n\n#define COMPLEX\n\nvoid batchf_zdotu_sub(\n\t\t  const int n,\n\t\t  BBLAS_Complex64_t const * const * x,\n\t\t  const int incx,\n\t\t  BBLAS_Complex64_t const * const * y,\n\t\t  const int incy,\n\t\t  BBLAS_Complex64_t *dotu,\n\t\t  const int batch_count, int *info)\n{\n\t/* Local variables */\n\tint first_index = 0;\n\tint batch_iter = 0;\n\tchar func_name[15] = \"batchf_zdotu\";\n\n\t/*initialize the result */\n\tfor (batch_iter = 0; batch_iter < batch_count; batch_iter++)\n\t  {\n\t    dotu[batch_iter] = (BBLAS_Complex64_t)0.0;\n\t  }\n\t\n\t/* Check input arguments */\n\tif (batch_count < 0)\n\t{\n\t\txerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1);\n\t}\n\n\tif (n < 0)\n\t{\n\t\txerbla_batch(func_name, BBLAS_ERR_N, first_index);\n\t\tinfo[first_index] = BBLAS_ERR_N;\n\n\t}\n\n\n\tif (incx < 1)\n\t{\n\t\txerbla_batch(func_name, BBLAS_ERR_INCX, first_index);\n\t\tinfo[first_index] = BBLAS_ERR_INCX;\n\t}\n\tif (incy < 1)\n\t{\n\t\txerbla_batch(func_name, BBLAS_ERR_INCY, first_index);\n\t\tinfo[first_index] = BBLAS_ERR_INCY;\n\t}\n\t/* Call CBLAS */\n\tfor (batch_iter = 0; batch_iter < batch_count; batch_iter++)\n\t{\n\t  cblas_zdotu_sub(\n\t\t      n,\n\t\t      (void *)x[batch_iter],\n\t\t      incx,\n\t\t      (void *)y[batch_iter],\n\t\t      incy,\n\t\t      &dotu[batch_iter]);\n\t  /* Successful */\n\t} /* End fixed size for loop */\n\tinfo[first_index] = BBLAS_SUCCESS;\n}\n#undef COMPLEX\n", "meta": {"hexsha": "bddbfca8ded67b5e9a83974b8e9b24c033f9f1ec", "size": 1553, "ext": "c", "lang": "C", "max_stars_repo_path": "src/batchf_zdotu.c", "max_stars_repo_name": "mawussi/BBLAS-group", "max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z", "max_issues_repo_path": "src/batchf_zdotu.c", "max_issues_repo_name": "sdrelton/bblas_api_test", "max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/batchf_zdotu.c", "max_forks_repo_name": "sdrelton/bblas_api_test", "max_forks_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "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.6582278481, "max_line_length": 61, "alphanum_fraction": 0.6426271732, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3796834738966314}}
{"text": "#ifndef __UTILS_UTILS_H_INCLUDED__\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <gsl/gsl>\n#include <numeric>\n#include <random>\n#define __UTILS_UTILS_H_INCLUDED__\n\ntemplate<typename Matrix>\nvoid removeRow(Matrix& matrix, gsl::index rowToRemove)\n{\n    gsl::index numRows = matrix.rows()-1;\n    gsl::index numCols = matrix.cols();\n\n    if( rowToRemove < numRows )\n        matrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.block(rowToRemove+1,0,numRows-rowToRemove,numCols).eval();\n\n    matrix.conservativeResize(numRows,numCols);\n}\ntemplate<typename Matrix>\nvoid removeColumn(Matrix& matrix, gsl::index colToRemove)\n{\n    gsl::index numRows = matrix.rows();\n    gsl::index numCols = matrix.cols()-1;\n\n    if( colToRemove < numCols )\n        matrix.block(0,colToRemove,numRows,numCols-colToRemove) = matrix.block(0,colToRemove+1,numRows,numCols-colToRemove).eval();\n\n    matrix.conservativeResize(numRows,numCols);\n}\n\ntemplate <typename T>\nvoid select(std::vector<T>& result, const std::vector<T>& in, const std::vector<typename std::vector<T>::size_type>& s) {\n    result.reserve(s.size());\n    std::transform(s.begin(), s.end(), std::back_inserter(result),\n                   [&in](typename std::vector<T>::size_type idx) {\n                       return in.at(idx);\n                   });\n}\n\nstd::tuple<std::vector<gsl::index>,std::vector<gsl::index> > TrainTestSplit(gsl::index nrows,double testRatio=0.3){\n    assert(testRatio>=0 && testRatio<=1);\n    gsl::index ntest = (gsl::index) nrows*(testRatio);\n    gsl::index ntrain = nrows - ntest;\n    std::vector<int> idx(nrows);\n    std::iota(idx.begin(), idx.end(), 0);\n\n    std::vector<gsl::index> trainIdx, testIdx;\n    trainIdx.resize(ntrain);\n    testIdx.resize(ntest);\n    std::sample(idx.begin(), idx.end(), std::back_inserter(testIdx),\n                ntest, std::mt19937{std::random_device{}()});\n    std::sort(testIdx.begin(),testIdx.end());\n    std::set_difference(idx.begin(), idx.end(), trainIdx.begin(), trainIdx.end(),\n                        std::inserter(testIdx, testIdx.begin()));\n    return {trainIdx,testIdx};\n}\n\nstd::tuple<std::vector<gsl::index>,std::vector<gsl::index> > TrainTestSplit(std::vector<gsl::index> inputIdx,double testRatio=0.3){\n    assert(testRatio>=0 && testRatio<=1);\n    gsl::index nrows = inputIdx.size();\n    gsl::index ntest = (gsl::index) nrows*(testRatio);\n    gsl::index ntrain = nrows - ntest;\n    std::vector<int> idx(nrows);\n    std::iota(idx.begin(), idx.end(), 0);\n\n    std::vector<gsl::index> trainIdx, testIdx;\n    trainIdx.resize(ntrain);\n    testIdx.resize(ntest);\n    std::sample(inputIdx.begin(), inputIdx.end(), std::back_inserter(testIdx),\n                ntest, std::mt19937{std::random_device{}()});\n    std::sort(testIdx.begin(),testIdx.end());\n    std::sort(inputIdx.begin(),inputIdx.end());\n    std::set_difference(inputIdx.begin(), inputIdx.end(), trainIdx.begin(), trainIdx.end(),\n                        std::inserter(testIdx, testIdx.begin()));\n    return {trainIdx,testIdx};\n}\n\ntemplate<typename T>\nstd::vector<T> linspace(T start_in, T end_in, int num_in)\n{\n\n    std::vector<T> linspaced;\n\n    double start = static_cast<double>(start_in);\n    double end = static_cast<double>(end_in);\n    double num = static_cast<double>(num_in);\n\n    if (num == 0) { return linspaced; }\n    if (num == 1)\n    {\n        linspaced.push_back(start);\n        return linspaced;\n    }\n\n    double delta = (end - start) / (num - 1);\n    for(int i=0; i < num-1; ++i)\n    {\n        linspaced.push_back(start + delta * i);\n    }\n    linspaced.push_back(end);\n    return linspaced;\n}\n\ntemplate<typename T>\nvoid print_vector(std::vector<T> vec)\n{\n    std::cout << \"size: \" << vec.size() << std::endl;\n    for (T & d : vec)\n        std::cout << d << \" \";\n    std::cout << std::endl;\n}\n#endif\n", "meta": {"hexsha": "e984862f2f063253af01a5964f213738856b60f5", "size": 3822, "ext": "h", "lang": "C", "max_stars_repo_path": "cosan/utils/utils.h", "max_stars_repo_name": "zhxinyu/cosan", "max_stars_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cosan/utils/utils.h", "max_issues_repo_name": "zhxinyu/cosan", "max_issues_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cosan/utils/utils.h", "max_forks_repo_name": "zhxinyu/cosan", "max_forks_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T05:56:38.000Z", "avg_line_length": 33.2347826087, "max_line_length": 131, "alphanum_fraction": 0.6391941392, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.37953675673545423}}
{"text": "/* multiroots/gsl_multiroots.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MULTIROOTS_H__\n#define __GSL_MULTIROOTS_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/* Definition of vector-valued functions with parameters based on gsl_vector */\n\nstruct gsl_multiroot_function_struct\n{\n  int (* f) (const gsl_vector * x, void * params, gsl_vector * f);\n  size_t n;\n  void * params;\n};\n\ntypedef struct gsl_multiroot_function_struct gsl_multiroot_function ;\n\n#define GSL_MULTIROOT_FN_EVAL(F,x,y) (*((F)->f))(x,(F)->params,(y))\n\nint gsl_multiroot_fdjacobian (gsl_multiroot_function * F,\n                              const gsl_vector * x, const gsl_vector * f,\n                              double epsrel, gsl_matrix * jacobian);\n\n\ntypedef struct\n  {\n    const char *name;\n    size_t size;\n    int (*alloc) (void *state, size_t n);\n    int (*set) (void *state, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx);\n    int (*iterate) (void *state, gsl_multiroot_function * function, gsl_vector * x, gsl_vector * f, gsl_vector * dx);\n    void (*free) (void *state);\n  }\ngsl_multiroot_fsolver_type;\n\ntypedef struct\n  {\n    const gsl_multiroot_fsolver_type * type;\n    gsl_multiroot_function * function ;\n    gsl_vector * x ;\n    gsl_vector * f ;\n    gsl_vector * dx ;\n    void *state;\n  }\ngsl_multiroot_fsolver;\n\ngsl_multiroot_fsolver * \ngsl_multiroot_fsolver_alloc (const gsl_multiroot_fsolver_type * T, \n                                     size_t n); \n\nvoid gsl_multiroot_fsolver_free (gsl_multiroot_fsolver * s);\n\nint gsl_multiroot_fsolver_set (gsl_multiroot_fsolver * s, \n                               gsl_multiroot_function * f, gsl_vector * x);\n\nint gsl_multiroot_fsolver_iterate (gsl_multiroot_fsolver * s);\n\nconst char * gsl_multiroot_fsolver_name (const gsl_multiroot_fsolver * s);\ngsl_vector * gsl_multiroot_fsolver_root (const gsl_multiroot_fsolver * s);\ngsl_vector * gsl_multiroot_fsolver_dx (const gsl_multiroot_fsolver * s);\ngsl_vector * gsl_multiroot_fsolver_f (const gsl_multiroot_fsolver * s);\n\n/* Definition of vector-valued functions and gradient with parameters\n   based on gsl_vector */\n\nstruct gsl_multiroot_function_fdf_struct\n{\n  int (* f) (const gsl_vector * x, void * params, gsl_vector * f);\n  int (* df) (const gsl_vector * x, void * params, gsl_matrix * df);\n  int (* fdf) (const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix *df);\n  size_t n;\n  void * params;\n};\n\ntypedef struct gsl_multiroot_function_fdf_struct gsl_multiroot_function_fdf ;\n\n#define GSL_MULTIROOT_FN_EVAL_F(F,x,y) ((*((F)->f))(x,(F)->params,(y)))\n#define GSL_MULTIROOT_FN_EVAL_DF(F,x,dy) ((*((F)->df))(x,(F)->params,(dy)))\n#define GSL_MULTIROOT_FN_EVAL_F_DF(F,x,y,dy) ((*((F)->fdf))(x,(F)->params,(y),(dy)))\n\ntypedef struct\n  {\n    const char *name;\n    size_t size;\n    int (*alloc) (void *state, size_t n);\n    int (*set) (void *state, gsl_multiroot_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_matrix * J, gsl_vector * dx);\n    int (*iterate) (void *state, gsl_multiroot_function_fdf * fdf, gsl_vector * x, gsl_vector * f, gsl_matrix * J, gsl_vector * dx);\n    void (*free) (void *state);\n  }\ngsl_multiroot_fdfsolver_type;\n\ntypedef struct\n  {\n    const gsl_multiroot_fdfsolver_type * type;\n    gsl_multiroot_function_fdf * fdf ;\n    gsl_vector * x;\n    gsl_vector * f;\n    gsl_matrix * J;\n    gsl_vector * dx;\n    void *state;\n  }\ngsl_multiroot_fdfsolver;\n\ngsl_multiroot_fdfsolver *\ngsl_multiroot_fdfsolver_alloc (const gsl_multiroot_fdfsolver_type * T,\n                                      size_t n);\n\nint\ngsl_multiroot_fdfsolver_set (gsl_multiroot_fdfsolver * s, \n                             gsl_multiroot_function_fdf * fdf,\n                             gsl_vector * x);\n\nint\ngsl_multiroot_fdfsolver_iterate (gsl_multiroot_fdfsolver * s);\n\nvoid\ngsl_multiroot_fdfsolver_free (gsl_multiroot_fdfsolver * s);\n\nconst char * gsl_multiroot_fdfsolver_name (const gsl_multiroot_fdfsolver * s);\ngsl_vector * gsl_multiroot_fdfsolver_root (const gsl_multiroot_fdfsolver * s);\ngsl_vector * gsl_multiroot_fdfsolver_dx (const gsl_multiroot_fdfsolver * s);\ngsl_vector * gsl_multiroot_fdfsolver_f (const gsl_multiroot_fdfsolver * s);\n\nint gsl_multiroot_test_delta (const gsl_vector * dx, const gsl_vector * x, \n                              double epsabs, double epsrel);\n\nint gsl_multiroot_test_residual (const gsl_vector * f, double epsabs);\n\nGSL_VAR const gsl_multiroot_fsolver_type * gsl_multiroot_fsolver_dnewton;\nGSL_VAR const gsl_multiroot_fsolver_type * gsl_multiroot_fsolver_broyden;\nGSL_VAR const gsl_multiroot_fsolver_type * gsl_multiroot_fsolver_hybrid;\nGSL_VAR const gsl_multiroot_fsolver_type * gsl_multiroot_fsolver_hybrids;\n\nGSL_VAR const gsl_multiroot_fdfsolver_type * gsl_multiroot_fdfsolver_newton;\nGSL_VAR const gsl_multiroot_fdfsolver_type * gsl_multiroot_fdfsolver_gnewton;\nGSL_VAR const gsl_multiroot_fdfsolver_type * gsl_multiroot_fdfsolver_hybridj;\nGSL_VAR const gsl_multiroot_fdfsolver_type * gsl_multiroot_fdfsolver_hybridsj;\n\n\n__END_DECLS\n\n#endif /* __GSL_MULTIROOTS_H__ */\n", "meta": {"hexsha": "9e28897f7bd0e22726d0f95af11db5a1925b7143", "size": 6102, "ext": "h", "lang": "C", "max_stars_repo_path": "extern/include/gsl/gsl_multiroots.h", "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "extern/include/gsl/gsl_multiroots.h", "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extern/include/gsl/gsl_multiroots.h", "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": ["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.4745762712, "max_line_length": 132, "alphanum_fraction": 0.7274664045, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.3793771762963797}}
{"text": "/*\n * CARP/Kaczmarz sweep on diagonally banded matrix. The essential loop is:\n *\n * for each row i\n *     x = x + w*(b(i) - A(i,:)*x)*A(i,:)'\n * end\n *\n * The matrix is given in band storage format, where each row (stored\n * contiguously in memory) of the array R stores a diagonal of the matrix with\n * offset idx(j), such that \n *\n * \t   A(i,i+idx(j)) = R(i,j)\n *\n * use (from MATLAB):\n * \t\ty = sweepR_mex(R,idx,x,b,w,dir)\n *\n * \t\tR\t\t\t- matrix of diagonals of matrix A\n *\t\tidx\t\t\t- offsets of diagonals\n *\t\tx\t\t\t- initial guess\n * \t\tb \t\t\t- right hand side (source)\n *\t\tw \t\t\t- relaxation parameter (0 <= w <= 2)\n *\t\tdir \t\t- if dir > 0, go through matrix rows in ascending order.\n * \t\t\t  \t\t  if dir < 0, go through matrix rows in descending order.\n * \t\tn_threads\t- OPTIONAL argument to control the number of execution\n * \t\tthreads solving CARP blocks in parallel. The number of threads can also\n * \t\tbe defined via an environment variable (OMP_NUM_THREADS), but this\n * \t\toptional argument takes precedence. The default number of threads is\n * \t\tone. Take care if using more than one MATLAB worker per node: each\n * \t\tMATLAB worker will use OMP_NUM_THREADS, so if there are four workers on\n * \t\ta node, there will be 4 x OMP_NUM_THREADS parallel CARP sweeps.\n *\n * Author: Art Petrenko, Tristan van Leeuwen\n *         Seismic Laboratory for Imaging and Modeling\n *         Department of Earth, Ocean, and Atmosperic Sciences\n *         The University of British Columbia\n *         \n * Date: July, 2014\n \n * You may use this code only under the conditions and terms of the\n * license contained in the file LICENSE provided with this source\n * code. If you do not agree to these terms you may not use this\n * software.\n*/\n\n#include <stdlib.h> /* for getenv */\n#include <stddef.h> /* for size_t type */\n#include <string.h> /* for memcpy */\n#include <pthread.h> /* for threading */\n\n/* The following section allows this file to compile on Mac OS X 10.8.5. Pass\n * the flag -DARCH_MACI64 to the compiler to activate it. */\n#ifdef ARCH_MACI64\n#include \"pthread_barrier.h\"\n#include <mach/error.h>\ntypedef wchar_t char16_t;\n#else /* not ARCH_MACI64 */\n#include <error.h>\n#endif /* ARCH_MACI64 */\n\n#include <math.h>\n#include <mex.h>   \n#include <matrix.h>\n#include <blas.h>\n\nstruct copy_init_guess_data_t \n{\n\tdouble *copy_src_real, *copy_dst_real;\n\tdouble *copy_src_imag, *copy_dst_imag;\n\tlong n_to_copy;\n};\n\nstruct sweep_data_t \n{\n\tlong start_row, end_row, ncol, ny, nx, haloWidth, main_diagonal_offset;\n\tdouble *Rr, *Ri, *yr, *yi, *br, *bi;\n\tlong *idx;\n\tdouble w;\n\tint dir;\n};\n\nstruct average_data_t \n{\n\tdouble *copy_src_real, *copy_dst_real;\n\tdouble *copy_src_imag, *copy_dst_imag;\n\tdouble *halo_1_real, *halo_2_real;\n\tdouble *halo_1_imag, *halo_2_imag;\n\tdouble *halo_dst_real, *halo_dst_imag;\n\tlong n_to_copy, n_in_halo;\n};\n\nstruct thread_data_t \n{\n\tstruct copy_init_guess_data_t copy_init_guess_data;\n\tstruct sweep_data_t sweep_data;\n\tstruct average_data_t average_data;\n\tpthread_barrier_t *barrier;\n};\n\nvoid *do_sweep(void *thread_args_void)\n{\n    struct sweep_data_t *thread_args;\n\t/* Variables contained in thread_args_void struct */\n\tlong start_row, end_row, haloWidth, ncol, ny, nx;\n\t/* Rr and Ri are pointers to short fat ncol-by-N matrices */\n\tdouble *Rr, *Ri, *yr, *yi, *br, *bi;\n\tlong *idx;\n\tdouble w;\n\tint dir;\n\t/* Temporary storage variables */\n\tdouble cr = 0, ci = 0;\n\tlong offset, main_diagonal_offset;\n\n\t/* Assign local pointers to data locations in shared memory */\n\tthread_args = (struct sweep_data_t *) thread_args_void;\n\tstart_row \t= thread_args->start_row;\n\tend_row \t= thread_args->end_row;\n\tncol \t\t= thread_args->ncol;\n\tny \t\t\t= thread_args->ny;\n\tnx\t\t\t= thread_args->nx;\n\thaloWidth\t= thread_args->haloWidth;\n\tmain_diagonal_offset = thread_args->main_diagonal_offset;\n\tRr \t\t\t= thread_args->Rr;\n\tRi \t\t\t= thread_args->Ri;\n\tidx \t\t= thread_args->idx;\n\tyr \t\t\t= thread_args->yr;\n\tyi \t\t\t= thread_args->yi;\n\tbr \t\t\t= thread_args->br;\n\tbi \t\t\t= thread_args->bi;\n\tw \t\t\t= thread_args->w;\n\tdir \t\t= thread_args->dir;\n\n\toffset = (start_row == 0 ? 0 : haloWidth - main_diagonal_offset);\n\n\t/* Kaczmarz sweep on one row block */\n\tfor(long i = (dir > 0 ? start_row : end_row-1);\n\t\tdir > 0 ? i<end_row : i>=start_row;\n\t\tdir > 0 ? i++ : i--)\n\t{\n\n\t\tif (0 <= i + main_diagonal_offset && i + main_diagonal_offset < nx){\n\t\t\tcr = br[i + main_diagonal_offset];\n\t\t\tci = bi[i + main_diagonal_offset];\n\t\t}\n\t\telse{\n\t\t  //error(1,0,\"Discovery of whether the iterate vector is haloed failed.\");\n\t\t}\n\t\t/* First loop over non-zero row elements calculates inner product\n\t\t * of matrix row and CARP iterate */\n\t\tfor(long j=0, k; j<ncol;j++){\n\t\t\t/* i + idx[j] is the column index for the full Helmholtz matrix.\n\t\t\t * k is the index into the vector representing the CARP iterate\n\t\t\t * of the given block. */\n\t\t\tk = i + idx[j] - start_row + offset;\n\t\t\tif(0<=k && k<ny){\n\t\t\t\tcr -= Rr[i*ncol + j]*yr[k] - Ri[i*ncol + j]*yi[k];\n\t\t\t\tci -= Rr[i*ncol + j]*yi[k] + Ri[i*ncol + j]*yr[k];\n\t\t\t}\n\t\t}\n\t\t/* Second loop over non-zero row elements updates CARP iterate */\n\t\tcr *= w;\n\t\tci *= w;\n\t\tfor(long j=0, k; j<ncol;j++){\n\t\t\tk = i + idx[j] - start_row + offset;\n\t\t\tif(0<=k && k<ny){\n\t\t\t\tyr[k] +=   cr*Rr[i*ncol + j] + ci*Ri[i*ncol + j];\n\t\t\t\tyi[k] +=  -cr*Ri[i*ncol + j] + ci*Rr[i*ncol + j];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\nvoid *average_halos(void *thread_args_void)\n{\t\n\tstruct average_data_t *thread_args;\n\tdouble *copy_src_real, *copy_dst_real;\n\tdouble *copy_src_imag, *copy_dst_imag;\n\tdouble *halo_1_real, *halo_2_real;\n\tdouble *halo_1_imag, *halo_2_imag;\n\tdouble *halo_dst_real, *halo_dst_imag;\n\tsize_t n_to_copy, n_in_halo;\n\n\t/* Assign local pointer to data locations in shared memory */\n\tthread_args \t= (struct average_data_t *) thread_args_void;\n\tcopy_src_real\t= thread_args->copy_src_real;\n\tcopy_dst_real\t= thread_args->copy_dst_real;\n\tcopy_src_imag\t= thread_args->copy_src_imag;\n\tcopy_dst_imag\t= thread_args->copy_dst_imag;\n\tn_to_copy\t\t= thread_args->n_to_copy;\n\thalo_1_real     = thread_args->halo_1_real;\n\thalo_2_real\t\t= thread_args->halo_2_real;\n\thalo_dst_real\t= thread_args->halo_dst_real;\n\thalo_1_imag\t\t= thread_args->halo_1_imag;\n\thalo_2_imag\t\t= thread_args->halo_2_imag;\n\thalo_dst_imag   = thread_args->halo_dst_imag;\n\tn_in_halo\t\t= thread_args->n_in_halo;\n\n\t/* Copy the non-halo parts of the domain block directly to output array */\n\tmemcpy((void *)copy_dst_real, (void *)copy_src_real, sizeof(double)*n_to_copy);\n\tmemcpy((void *)copy_dst_imag, (void *)copy_src_imag, sizeof(double)*n_to_copy);\n\n\t/* Average the halo parts of the domain block and copy to output array.\n\t * NOTE: this assumes domain blocks overlap only with their nearest\n\t * neighbour segments. */\n\tfor (long i = 0; i < n_in_halo; i++){\n\t\thalo_dst_real[i] = (halo_1_real[i] + halo_2_real[i]) / 2;\n\t\thalo_dst_imag[i] = (halo_1_imag[i] + halo_2_imag[i]) / 2;\n\t}\n\n\treturn NULL;\n}\n\nvoid *sweep_and_average(void *thread_data_void)\n{\n\tstruct thread_data_t *thread_data = (struct thread_data_t *) thread_data_void;\n\n\t/* Copy the initial guess into the working arrays */\n\tmemcpy((void *)thread_data->copy_init_guess_data.copy_dst_real, (void *)thread_data->copy_init_guess_data.copy_src_real, sizeof(double)*thread_data->copy_init_guess_data.n_to_copy);\n\tmemcpy((void *)thread_data->copy_init_guess_data.copy_dst_imag, (void *)thread_data->copy_init_guess_data.copy_src_imag, sizeof(double)*thread_data->copy_init_guess_data.n_to_copy);\n\tdo_sweep((void *) &(thread_data->sweep_data));\n\n\tpthread_barrier_wait(thread_data->barrier);\n\n\taverage_halos((void *) &(thread_data->average_data));\n\n\treturn NULL;\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n\t/* structs to hold all arguments to each thread in one variable */\n\tstruct sweep_data_t **thread_args_sweep = NULL;\n\tstruct average_data_t **thread_args_average = NULL;\n\tstruct thread_data_t **thread_data = NULL;\n\tstruct copy_init_guess_data_t **copy_init_guess_data = NULL;\n\tpthread_barrier_t barrier_after_sweep_before_halo_average;\n\n\tmwSize ncol, nx;\n\tptrdiff_t ncolBlas, idxIncBlas = 1, maxIdxLoc = 0;\n\tmwSize haloWidth;\n\tmwSize n_threads = 1;\n\tchar *n_threads_str = NULL;\n\tdouble *Rr,*Ri,*idxd = NULL,*xr,*xi,*br,*bi,*yr,*yi;\n\tlong *idx = NULL;\n    double w = 0;\n\tint dir = 1;\n\tmwSize N=1, numGridPointsPerBlock, main_diagonal_offset;\n\n\t/* Flags that are set if memory is allocated within the MEX file */\n\tint Ri_alloc=0, xi_alloc=0, bi_alloc=0;\n\n\t/* a return code flag and segment demarcation arrays */ \n\tmwSize i_thread;\n\tmwSize *seg_bounds_hi, *seg_bounds_mid, *seg_bounds_row, *seg_bounds_lo;\n\n\t/* Threading variables */\n\tpthread_t *threadIDs = NULL;\n\tpthread_attr_t attr;\n\n\t/* Arrays to hold (overlapping) segments of yr and yi, a pair for each\n\t * thread */\n\tdouble **yr_seg = NULL, **yi_seg = NULL;\n\n\t/* Allow worker threads to join back to main thread once they are done */\n\tpthread_attr_init(&attr);\n\tpthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\t\n\t/* Read input arguments; initialize complex part to zero if input is real. */\n\tN = mxGetN(prhs[0]);\n    ncol = mxGetM(prhs[0]);\n\tncolBlas = (ptrdiff_t)ncol;\n\tRr  = mxGetPr(prhs[0]);\n    if(mxIsComplex(prhs[0])){\n        Ri  = mxGetPi(prhs[0]);\n    }\n    else{\n        Ri = mxCalloc(N*ncol,sizeof(double));\n\t\tRi_alloc = 1;\n    }\n\tidxd = mxGetPr(prhs[1]);\t\n    nx  = mxGetM(prhs[2]);\n\txr  = mxGetPr(prhs[2]);\n    if(mxIsComplex(prhs[2])){\n        xi  = mxGetPi(prhs[2]);\n    }\n    else{\n        xi = mxCalloc(nx,sizeof(double));\n\t\txi_alloc = 1;\n    }\n\tbr  = mxGetPr(prhs[3]);\n    if(mxIsComplex(prhs[3])){\n        bi  = mxGetPi(prhs[3]);\n    }\n    else{\n        bi = mxCalloc(nx,sizeof(double));\n\t\tbi_alloc = 1;\n    }\n\tif (mxGetM(prhs[3]) != nx){\n\t    mexPrintf('%d %d \\n',mxGetM(prhs[3]),nx);\n\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:NumElements\", \n\t\t\t\t\"The number of elements in the iterate and right hand side vectors must be equal.\");\n\t}\n\tw   = mxGetScalar(prhs[4]);\n\tdir = lrint(mxGetScalar(prhs[5]));\n\n\t/* The default value for the number of threads can be overridden by an\n\t * environment variable. */\n\tn_threads_str = getenv(\"OMP_NUM_THREADS\");\n\tif (n_threads_str == NULL){\n\t\tn_threads = 1;\n\t}\n\telse{\n\t\tn_threads = strtol(n_threads_str, NULL, 10);\n\t\tif(n_threads < 1){\n\t\t\tn_threads = 1;\n\t\t}\n\t}\n\t/* The environment variable can in turn be overridden by an optional\n\t * argument to the mexFunction. */ \n\tif (nrhs >= 7){\n\t\tif(1 <= lrint(mxGetScalar(prhs[6]))){\n\t\t\tn_threads = lrint(mxGetScalar(prhs[6]));\n\t\t}\n\t}\n\n\t/* Allocate the final output vector */\n\tplhs[0]  = mxCreateDoubleMatrix(nx, 1, mxCOMPLEX); \n\tyr       = mxGetPr(plhs[0]);\n    yi       = mxGetPi(plhs[0]);\n\n\t/* Check to make sure memory was allocated correctly */\n\tif (Rr==NULL || Ri==NULL || idxd==NULL || xr==NULL || xi==NULL || br==NULL || bi==NULL ||\n\t    yr==NULL || yi==NULL){\n\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:OutOfMemory\", \n\t\t\t\t\"Could not allocate memory for main computational variables.\");\n\t}\n\n\tif ((idx = (long *) mxCalloc(ncol, sizeof(long))) == NULL){\n\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:OutOfMemory\",\n\t\t\t\t\"Could not allocate memory for main computational variables.\");\n\t}\n\tfor (mwSize i=0; i < ncol; i++){\n\t\tidx[i] = lrint(idxd[i]); \n\t}\n\n\t/* Compute (half) halo width. Remember that BLAS routines like idamax\n\t * return FORTRAN-style indices. */\n\tmaxIdxLoc = idamax_(&ncolBlas, idxd, &idxIncBlas) - 1;\n\thaloWidth = (mwSize)labs(idx[maxIdxLoc]); \n\n\t/* Partition the iterate vector into blocks. Note that the below\n\t * partitioning scheme is slighlty different from that in pCARPCG.m in this\n\t * directory. The partitioning scheme of pCARPCG corresponds to\n\t * distributing a three dimensional array with dimensions given by n\n\t * according to Matlab's codistributor1d.defaultPartition(n(3)), and then\n\t * vectorizing it. The partition scheme of the present file instead uses\n\t * Matlab's codistributor1d.defaultPartion(prod(n)). In other words,\n\t * pCARPCG divides the iterate into blocks along the slow dimension,\n\t * whereas sweepR_mex.c does not take dimensionality into account, only the\n\t * total number of gridpoints. This is done to avoid needing an extra input\n\t * parameter with the the system dimensions. The seg_bounds_hi, _lo and\n\t * _mid arrays contain indices into non-haloed vectors, while the\n\t * seg_bounds_row array contains indices to the rows of the system matrix.\n\t *\n \t * yr_seg[i_thread-1]        overlap      yr_seg[i_thread]\n\t * ------------------------|-----|-----|-------------------------------\n\t *         .----------------^     |     ^-------------------.\n\t *    seg_bounds_lo[i_thread], seg_bounds_mid[i_thread], seg_bounds_hi[i_thread]\n\t */\n\tnumGridPointsPerBlock = N / n_threads;\n\tseg_bounds_hi  = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize));\n\tseg_bounds_mid = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize));\n\tseg_bounds_lo  = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize));\n\tseg_bounds_row = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize));\n\tif (N == nx){\n\t\tmain_diagonal_offset = 0;\n\t}\n\telse{\n\t\t/* The vector is haloed. We are only able to correctly process matrices\n\t\t * with a non-zero main diagonal and symmetric off-main diagonal offsets. */\n\t\tif (ncol % 2 != 1){\n\t\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:EvenNumberOfDiags\",\n\t\t\t\t\t\"Input iterate vector appears to be haloed but there is an even number of non-zero diagonals in the system matrix.\");\n\t\t}\n\t\tmain_diagonal_offset = idx[ncol/2];\n\t\tfor (mwSize i = 1; i <= ncol/2; i++){\n\t\t\tif (idx[ncol/2 + i] - main_diagonal_offset != -(idx[ncol/2 - i] - main_diagonal_offset)){\n\t\t\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:DiagsNotSymmetric\",\n\t\t\t\t\t\t\"Input iterate vector appears to be haloed but the pattern of non-zero diagonals in the system matrix is not symmetric.\");\n\t\t\t}\n\t\t}\n\t}\n\tfor (i_thread=0; i_thread<n_threads; i_thread++){\n\t\t/* First domain block */\n\t\tif (i_thread==0){\n\t\t\tseg_bounds_hi[i_thread]  = 0;\n\t\t\tseg_bounds_mid[i_thread] = 0;\n\t\t\tseg_bounds_row[i_thread] = 0;\n\t\t\tseg_bounds_lo[i_thread]  = 0;\n\t\t}\n\t\t/* Other domain blocks */\n\t\telse {\n\t\t\tif (i_thread <= N % n_threads) {\n\t\t\t\tseg_bounds_mid[i_thread] = (numGridPointsPerBlock+1)*i_thread + main_diagonal_offset;\n\t\t\t\tseg_bounds_row[i_thread] = (numGridPointsPerBlock+1)*i_thread;\n\t\t\t\tseg_bounds_hi[i_thread]  = (numGridPointsPerBlock+1)*i_thread + haloWidth + main_diagonal_offset;\t\n\t\t\t\tseg_bounds_lo[i_thread]  = (numGridPointsPerBlock+1)*i_thread - haloWidth + main_diagonal_offset;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tseg_bounds_mid[i_thread] = (N % n_threads) + numGridPointsPerBlock*i_thread + main_diagonal_offset;\n\t\t\t\tseg_bounds_row[i_thread] = (N % n_threads) + numGridPointsPerBlock*i_thread;\n\t\t\t\tseg_bounds_hi[i_thread]  = (N % n_threads) + numGridPointsPerBlock*i_thread + haloWidth + main_diagonal_offset;\t\n\t\t\t\tseg_bounds_lo[i_thread]  = (N % n_threads) + numGridPointsPerBlock*i_thread - haloWidth + main_diagonal_offset;\n\t\t\t}\n\t\t\t/* Check that halos do not overlap each other */\n\t\t\tif (seg_bounds_lo[i_thread] < seg_bounds_hi[i_thread-1]){\n\t\t\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:TooManyThreads\",\n\t\t\t\t\t\t\"Too many threads; non-adjacent domain blocks share nearest-neighbour grid points.\");\n\t\t\t}\n\t\t}\n\t}\n\tseg_bounds_lo[n_threads]  = nx;\n\tseg_bounds_hi[n_threads]  = nx;\n\tseg_bounds_mid[n_threads] = nx;\n\tseg_bounds_row[n_threads] = N;\n\n\t/* Allocate pointers to segments, to thread arguments and thread IDs */\n\tthread_args_sweep = (struct sweep_data_t **)mxCalloc(n_threads, sizeof(struct sweep_data_t *));\n\tif (n_threads > 1) {\n\t\t/* Set up a barrier for synchronization of all threads save the master that\n\t\t * executes mexFunction. Note that strictly speaking, only threads working\n\t\t * on domain blocks that share halos need to synchronize with each other.\n\t\t * */\n\t\tif (pthread_barrier_init(&barrier_after_sweep_before_halo_average, NULL, n_threads)){\n\t\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreads\",\n\t\t\t\t\t\"Could not initialize pthread barrier.\");\n\t\t}\n\n\t\tthread_data = (struct thread_data_t **)mxCalloc(n_threads, sizeof(struct thread_data_t *));\n\t\tthread_args_average = (struct average_data_t **)mxCalloc(n_threads, sizeof(struct average_data_t *));\n\t\tcopy_init_guess_data = (struct copy_init_guess_data_t **)mxCalloc(n_threads, sizeof(struct copy_init_guess_data_t *));\n\t\tyr_seg = (double **)mxCalloc(n_threads,sizeof(double *)); \n\t\tyi_seg = (double **)mxCalloc(n_threads,sizeof(double *));\n\t\tthreadIDs = (pthread_t *)mxCalloc(n_threads,sizeof(pthread_t));\n\t}\n\tfor (i_thread=0; i_thread<n_threads; i_thread++){\n\t\t/* Allocate the segments for each thread */\n\t\tif (n_threads > 1) {\n\t\t\tyr_seg[i_thread] = (double *)mxCalloc((seg_bounds_hi[i_thread+1]-seg_bounds_lo[i_thread]),sizeof(double));\n\t\t\tyi_seg[i_thread] = (double *)mxCalloc((seg_bounds_hi[i_thread+1]-seg_bounds_lo[i_thread]),sizeof(double));\n\t\t\t/* Check that segments were allocated correctly */\n\t\t\tif (yr_seg[i_thread]==NULL || yi_seg[i_thread]==NULL){\n\t\t\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreadsOutOfMemory\",\n\t\t\t\t\t\t\"Could not allocate memory for thread computational variables.\");\n\t\t\t}\n\t\t\tcopy_init_guess_data[i_thread] = (struct copy_init_guess_data_t *)mxCalloc(1,sizeof(struct copy_init_guess_data_t));\n\t\t\tcopy_init_guess_data[i_thread]->copy_src_real = &xr[seg_bounds_lo[i_thread]];\n\t\t\tcopy_init_guess_data[i_thread]->copy_src_imag = &xi[seg_bounds_lo[i_thread]];\n\t\t\tcopy_init_guess_data[i_thread]->copy_dst_real = yr_seg[i_thread];\n\t\t\tcopy_init_guess_data[i_thread]->copy_dst_imag = yi_seg[i_thread];\n\t\t\tcopy_init_guess_data[i_thread]->n_to_copy = (size_t) (seg_bounds_hi[i_thread+1] - seg_bounds_lo[i_thread]);\n\t\t}\n\n\t\t/* Set thread arguments */\n\t\tthread_args_sweep[i_thread] = (struct sweep_data_t *)mxCalloc(1,sizeof(struct sweep_data_t));\n\t\tthread_args_sweep[i_thread]->start_row \t= seg_bounds_row[i_thread];\n\t\tthread_args_sweep[i_thread]->end_row   \t= seg_bounds_row[i_thread+1];\n\t\tthread_args_sweep[i_thread]->ncol \t \t= ncol;\n\t\tthread_args_sweep[i_thread]->ny \t \t= seg_bounds_hi[i_thread+1]-seg_bounds_lo[i_thread];\n\t\tthread_args_sweep[i_thread]->nx\t\t\t= nx;\n\t\tthread_args_sweep[i_thread]->haloWidth \t= haloWidth*(i_thread ? 1 : 0);\n\t\tthread_args_sweep[i_thread]->main_diagonal_offset = main_diagonal_offset;\n\t\tthread_args_sweep[i_thread]->Rr  \t\t= Rr;\n\t\tthread_args_sweep[i_thread]->Ri  \t\t= Ri;\n\t\tthread_args_sweep[i_thread]->idx \t\t= idx;\n\t\tif (n_threads > 1){\n\t\t\tthread_args_sweep[i_thread]->yr \t= yr_seg[i_thread];\n\t\t\tthread_args_sweep[i_thread]->yi \t= yi_seg[i_thread];\n\t\t}\n\t\telse{\n\t\t\tthread_args_sweep[i_thread]->yr\t \t= yr;\n\t\t\tthread_args_sweep[i_thread]->yi\t \t= yi;\n\t\t}\n\t\tthread_args_sweep[i_thread]->br \t\t= br;\n\t\tthread_args_sweep[i_thread]->bi \t\t= bi;\n\t\tthread_args_sweep[i_thread]->w \t\t \t= w;\n\t\tthread_args_sweep[i_thread]->dir \t\t= dir;\n\n\t\tif (n_threads > 1){\n\t\t\t/* Set the arguments for the averaging threads. Note that each\n\t\t\t * thread is responsible for averaging the low end of its address\n\t\t\t * range. The middle of its address range is copied, while the high\n\t\t\t * end of its address range is left for the next thread. */\n\t\t\tthread_args_average[i_thread] = (struct average_data_t *)mxCalloc(1,sizeof(struct average_data_t));\n\t\t\tthread_args_average[i_thread]->copy_src_real = &(yr_seg[i_thread][seg_bounds_hi[i_thread] - seg_bounds_lo[i_thread]]);\n\t\t\tthread_args_average[i_thread]->copy_dst_real = &(yr[seg_bounds_hi[i_thread]]);\n\t\t\tthread_args_average[i_thread]->copy_src_imag = &(yi_seg[i_thread][seg_bounds_hi[i_thread] - seg_bounds_lo[i_thread]]);\n\t\t\tthread_args_average[i_thread]->copy_dst_imag = &(yi[seg_bounds_hi[i_thread]]);\n\t\t\tthread_args_average[i_thread]->n_to_copy \t = (size_t) (seg_bounds_lo[i_thread+1] - seg_bounds_hi[i_thread]);\n\t\t\tthread_args_average[i_thread]->halo_1_real   = &(yr_seg[i_thread-1 >= 0 ? i_thread-1 : 0][seg_bounds_lo[i_thread] - seg_bounds_lo[i_thread-1 >= 0 ? i_thread-1 : 0]]);\n\t\t\tthread_args_average[i_thread]->halo_2_real\t = yr_seg[i_thread];\n\t\t\tthread_args_average[i_thread]->halo_dst_real = &(yr[seg_bounds_lo[i_thread]]);\n\t\t\tthread_args_average[i_thread]->halo_1_imag   = &(yi_seg[i_thread-1 >= 0 ? i_thread-1 : 0][seg_bounds_lo[i_thread] - seg_bounds_lo[i_thread-1 >= 0 ? i_thread-1 : 0]]);\n\t\t\tthread_args_average[i_thread]->halo_2_imag\t = yi_seg[i_thread];\n\t\t\tthread_args_average[i_thread]->halo_dst_imag = &(yi[seg_bounds_lo[i_thread]]);\n\t\t\tthread_args_average[i_thread]->n_in_halo \t = (size_t) (seg_bounds_hi[i_thread] - seg_bounds_lo[i_thread]);\n\n\t\t\tthread_data[i_thread] = (struct thread_data_t *)mxCalloc(1,sizeof(struct thread_data_t));\n\t\t\tthread_data[i_thread]->copy_init_guess_data = *copy_init_guess_data[i_thread];\n\t\t\tthread_data[i_thread]->sweep_data = *thread_args_sweep[i_thread];\n\t\t\tthread_data[i_thread]->average_data = *thread_args_average[i_thread];\n\t\t\tthread_data[i_thread]->barrier = &barrier_after_sweep_before_halo_average;\n\t\t}\n\t}\n\n\tif (n_threads == 1) {\n\t\t/* Set the initial guess directly in the output array too */\n\t\tmemcpy((void *)yr, (void *)xr, sizeof(double)*nx);\n\t\tmemcpy((void *)yi, (void *)xi, sizeof(double)*nx);\n\t\tdo_sweep((void *)thread_args_sweep[0]);\n\t}\n\telse{\n\t\t/* Sweep and average, in separate worker threads */\n\t\tfor (i_thread=0; i_thread<n_threads; i_thread++){\n\t\t\tif (pthread_create(&threadIDs[i_thread], &attr, sweep_and_average, (void *)thread_data[i_thread])){\n\t\t\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreadCreate\", \n\t\t\t\t\t\t\"pthread_create returned non-zero.\");\n\t\t\t}\n\t\t}\n\n\t\t/* Wait for threads to finish */\n\t\tfor (i_thread=0; i_thread<n_threads; i_thread++){\n\t\t\tif (pthread_join(threadIDs[i_thread], NULL)){\n\t\t\t\tmexErrMsgIdAndTxt(\"SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreadCreate\", \n\t\t\t\t\t\t\"pthread_join returned non-zero.\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Free memory if it was allocated within the MEX file. */\n\tif (Ri_alloc){\n\t\tmxFree(Ri);\n\t}\n\tif (xi_alloc){\n\t\tmxFree(xi);\n\t}\n\tif (bi_alloc){\n\t\tmxFree(bi);\n\t}\n\tmxFree(seg_bounds_hi);\n\tmxFree(seg_bounds_mid);\n\tmxFree(seg_bounds_row);\n\tmxFree(seg_bounds_lo);\n\tif (n_threads > 1) {\n\t\tmxFree(threadIDs);\n\t}\n\tfor (i_thread=0; i_thread<n_threads; i_thread++){\n\t\tmxFree(thread_args_sweep[i_thread]);\n\t\tif (n_threads > 1){\n\t\t\tmxFree(thread_args_average[i_thread]);\n\t\t\tmxFree(thread_data[i_thread]);\n\t\t\tmxFree(copy_init_guess_data[i_thread]);\n\t\t\tmxFree(yr_seg[i_thread]);\n\t\t\tmxFree(yi_seg[i_thread]);\n\t\t}\n\t}\n\tif (n_threads > 1){\n\t\tpthread_barrier_destroy(&barrier_after_sweep_before_halo_average);\n\t\tmxFree(thread_args_average);\n\t\tmxFree(thread_data);\n\t\tmxFree(copy_init_guess_data);\n\t\tmxFree(yr_seg);\n\t\tmxFree(yi_seg);\n\t}\n\tmxFree(idx);\n\tmxFree(thread_args_sweep);\n\tpthread_attr_destroy(&attr);\n\n\t/* Don't think I need pthread_exit() here, because pthread_join is called above */\n\treturn;\n}\n", "meta": {"hexsha": "e7bdd923d7afc90df0b346237f79d53af925c0ec", "size": 22885, "ext": "c", "lang": "C", "max_stars_repo_path": "tools/deprecated/solvers/Krylov/sweepR_mex.c", "max_stars_repo_name": "liaman/SLIM-release-apps-public", "max_stars_repo_head_hexsha": "4db4043a38c5a4b7ccfee87be3e43992a38e8054", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-26T02:42:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T13:36:49.000Z", "max_issues_repo_path": "tools/deprecated/solvers/Krylov/sweepR_mex.c", "max_issues_repo_name": "yuanyuxin0077/SLIM-release-apps-public", "max_issues_repo_head_hexsha": "3fb78e7338b9f1702dfcc0a94748ce5e86562739", "max_issues_repo_licenses": ["MIT"], "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/deprecated/solvers/Krylov/sweepR_mex.c", "max_forks_repo_name": "yuanyuxin0077/SLIM-release-apps-public", "max_forks_repo_head_hexsha": "3fb78e7338b9f1702dfcc0a94748ce5e86562739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-15T02:34:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T08:46:39.000Z", "avg_line_length": 39.2538593482, "max_line_length": 182, "alphanum_fraction": 0.7098536159, "num_tokens": 6637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3792038089785084}}
{"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk_4_3.c\n * \\brief Source file to optimize Runge-Kutta 4 steps 3rd order methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include <string.h>\n#include <math.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include <libintl.h>\n#include <gsl/gsl_rng.h>\n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_4_3.h\"\n\n#define DEBUG_RK_4_3 0          ///< macro to debug.\n\n/**\n * Function to obtain the coefficients of a 4 steps 3rd order Runge-Kutta \n * method.\n */\nint\nrk_tb_4_3 (Optimize * optimize) ///< Optimize struct.\n{\n  long double *tb, *r;\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_tb_4_3: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t4 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  b21 (tb) = r[2];\n  t3 (tb) = r[3];\n  b32 (tb) = r[4];\n  b43 (tb) = r[5];\n  b42 (tb) = ((1.L / 3.L - b43 (tb) * sqr (t3 (tb)))\n              - t1 (tb) * (0.5L - b43 (tb) * t3 (tb)))\n    / (t2 (tb) * (t2 (tb) - t1 (tb)));\n  if (isnan (b42 (tb)))\n    return 0;\n  b41 (tb) = (0.5L - b42 (tb) * t2 (tb) - b43 (tb) * t3 (tb)) / t1 (tb);\n  if (isnan (b41 (tb)))\n    return 0;\n  b31 (tb) = ((1.L / 6.L - b42 (tb) * b21 (tb) * t1 (tb)) / b43 (tb)\n              - b32 (tb) * t2 (tb)) / t1 (tb);\n  if (isnan (b31 (tb)))\n    return 0;\n  rk_b_4 (tb);\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_tb_4_3: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 4 steps 3rd order, 4th order in\n * equations depending only in time, Runge-Kutta method.\n */\nint\nrk_tb_4_3t (Optimize * optimize)        ///< Optimize struct.\n{\n  long double *tb, *r;\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_tb_4_3t: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t4 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  b21 (tb) = r[2];\n  t3 (tb) = r[3];\n  b32 (tb) = r[4];\n  b43 (tb) = (0.25L - 1.L / 3.L * t1 (tb)\n              - (1.L / 3.L - 0.5L * t1 (tb)) * t2 (tb))\n    / (t3 (tb) * (t3 (tb) - t2 (tb)) * (t3 (tb) - t1 (tb)));\n  b42 (tb) = ((1.L / 3.L - b43 (tb) * sqr (t3 (tb)))\n              - t1 (tb) * (0.5L - b43 (tb) * t3 (tb)))\n    / (t2 (tb) * (t2 (tb) - t1 (tb)));\n  b41 (tb) = (0.5L - b42 (tb) * t2 (tb) - b43 (tb) * t3 (tb)) / t1 (tb);\n  b31 (tb) = ((1.L / 6.L - b42 (tb) * b21 (tb) * t1 (tb)) / b43 (tb)\n              - b32 (tb) * t2 (tb)) / t1 (tb);\n  rk_b_4 (tb);\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_tb_4_3t: end\\n\");\n#endif\n  if (isnan (b31 (tb)) || isnan (b41 (tb)) || isnan (b42 (tb))\n      || isnan (b43 (tb)))\n    return 0;\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 4 steps 2nd-3rd order Runge-Kutta \n * pair.\n */\nint\nrk_tb_4_3p (Optimize * optimize)        ///< Optimize struct.\n{\n  long double *tb;\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_tb_4_3p: start\\n\");\n#endif\n  if (!rk_tb_4_3 (optimize))\n    return 0;\n  tb = optimize->coefficient;\n  e41 (tb) = 0.5L / t1 (tb);\n  e42 (tb) = 0.L;\n  rk_e_4 (tb);\n#if DEBUG_RK_4_3\n  rk_print_e (optimize, \"rk_tb_4_3p\", stderr);\n  fprintf (stderr, \"rk_tb_4_3p: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 4 steps 2nd-3rd order, 3rd-4th order\n * in equations depending only in time, Runge-Kutta pair.\n */\nint\nrk_tb_4_3tp (Optimize * optimize)       ///< Optimize struct.\n{\n  long double *tb;\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_tb_4_3tp: start\\n\");\n#endif\n  if (!rk_tb_4_3t (optimize))\n    return 0;\n  tb = optimize->coefficient;\n  e42 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb)));\n  e41 (tb) = (0.5L - e42 (tb) * t2 (tb)) / t1 (tb);\n  rk_e_4 (tb);\n#if DEBUG_RK_4_3\n  rk_print_e (optimize, \"rk_tb_4_3tp\", stderr);\n  fprintf (stderr, \"rk_tb_4_3tp: end\\n\");\n#endif\n  if (isnan (e42 (tb)) || isnan (e41 (tb)))\n    return 0;\n  return 1;\n}\n\n/**\n * Function to calculate the objective function of a 4 steps 3rd order \n * Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_4_3 (RK * rk)   ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_objective_tb_4_3: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b31 (tb) < 0.L)\n    o += b31 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b41 (tb) < 0.L)\n    o += b41 (tb);\n  if (b42 (tb) < 0.L)\n    o += b42 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_objective_tb_4_3: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_4_3: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 4 steps 3rd order, 4th\n * oder in equations depending only in time, Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_4_3t (RK * rk)  ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_objective_tb_4_3t: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b31 (tb) < 0.L)\n    o += b31 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b41 (tb) < 0.L)\n    o += b41 (tb);\n  if (b42 (tb) < 0.L)\n    o += b42 (tb);\n  if (b43 (tb) < 0.L)\n    o += b43 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_objective_tb_4_3t: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_4_3t: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 4 steps 2nd-3rd order \n * Runge-Kutta pair.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_4_3p (RK * rk)  ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_objective_tb_4_3p: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b31 (tb) < 0.L)\n    o += b31 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b41 (tb) < 0.L)\n    o += b41 (tb);\n  if (b42 (tb) < 0.L)\n    o += b42 (tb);\n  if (e40 (tb) < 0.L)\n    o += e40 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_objective_tb_4_3p: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_4_3p: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 4 steps 2nd-3rd order, \n * 3rd-4th oder in equations depending only in time, Runge-Kutta pair.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_4_3tp (RK * rk) ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_objective_tb_4_3tp: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b31 (tb) < 0.L)\n    o += b31 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b41 (tb) < 0.L)\n    o += b41 (tb);\n  if (b42 (tb) < 0.L)\n    o += b42 (tb);\n  if (b43 (tb) < 0.L)\n    o += b43 (tb);\n  if (e40 (tb) < 0.L)\n    o += e40 (tb);\n  if (e41 (tb) < 0.L)\n    o += e41 (tb);\n  if (e42 (tb) < 0.L)\n    o += e42 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), t3 (tb))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_4_3\n  fprintf (stderr, \"rk_objective_tb_4_3tp: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_4_3tp: end\\n\");\n#endif\n  return o;\n}\n", "meta": {"hexsha": "34f65a4bd481a8ff05fa18b4d79593e5e70d9fce", "size": 9374, "ext": "c", "lang": "C", "max_stars_repo_path": "rk_4_3.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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": "rk_4_3.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk_4_3.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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.5422343324, "max_line_length": 80, "alphanum_fraction": 0.5890761681, "num_tokens": 3574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786991753931, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3792038017272067}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C code headers for the implementation of the Fourier domain response for LIGO-VIRGO detectors\n *\n *\n */\n\n#ifndef _LLVFDRESPONSE_H\n#define _LLVFDRESPONSE_H\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n#include \"LLVgeometry.h\"\n#include \"struct.h\"\n#include \"waveform.h\"\n#include \"timeconversion.h\"\n\n\n/**************************************************/\n/**************** Prototypes **********************/\n\n/* Function to convert string input network string to Networktag */\nNetworktag ParseNetworktag(char* string);\n\n/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LLV response (for a given detector), for given values of the inclination, position in the sky and polarization angle */\nint LLVSimFDResponse(\n  struct tagListmodesCAmpPhaseFrequencySeries **listhlm,  /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */\n  struct tagListmodesCAmpPhaseFrequencySeries **lists,    /* Output: list of contribution of each mode in the detector signal, in Frequency-domain amplitude and phase form, for the given detector and sky position */\n  const double gpstime,                                   /* GPS time (s) when the signal at coalescence reaches geocenter */\n  const double ra,                                        /* Position in the sky: J2000.0 right ascension (rad) */\n  const double dec,                                       /* Position in the sky: J2000.0 declination (rad) */\n  const double inclination,                               /* Inclination of the source (rad) */\n  const double psi,                                       /* Polarization angle (rad) */\n  const Detectortag tag);                                 /* Tag identifying the detector */\n\n  /* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LLV response, for given values of the inclination, position in the sky and polarization angle */\n  int LLVSimFDResponse3Det(\n    struct tagListmodesCAmpPhaseFrequencySeries **listDet1,  /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the detector 1 */\n    struct tagListmodesCAmpPhaseFrequencySeries **listDet2,  /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the detector 2 */\n    struct tagListmodesCAmpPhaseFrequencySeries **listDet3,  /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the detector 3 */\n    struct tagListmodesCAmpPhaseFrequencySeries **list,      /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */\n    const double gpstime,                                    /* GPS time (s) when the signal at coalescence reaches geocenter */\n    const double ra,                                            /* First angle for the position in the sky */\n    const double dec,                                           /* Second angle for the position in the sky */\n    const double inclination,                                   /* Inclination of the source */\n    const double psi,                                           /* Polarization angle */\n    const Networktag tag);                               /* Selector for the detector network */\n\n/* Function setting the response matrix of a given detector, in cartesian coordinates */\nvoid SetMatrixD(\n  gsl_matrix* D,                       /* Output: matrix of the detector response Dij */\n  const Detectortag tag);              /* Tag identifying the detector */\n/* Function setting the position of a detector, in cartesian coordinates */\nvoid SetVectorXd(\n  gsl_vector* Xd,                      /* Output: position vector of the detector */\n  const Detectortag tag);              /* Tag identifying the detector */\n\n/* Function setting the cartesian coordinates of the wave frame vectors (X,Y,Z), given the position in the sky and polarization */\nvoid SetVectorsXYZ(\n  gsl_vector* X,                       /* Output: cartesian vector of the wave frame unit vector X */\n  gsl_vector* Y,                       /* Output: cartesian vector of the wave frame unit vector Y */\n  gsl_vector* Z,                       /* Output: cartesian vector of the wave frame unit vector Z */\n  const double theta,                  /* First angle for the position in the sky (Earth-based spherical angle) */\n  const double phi,                    /* Second angle for the position in the sky (Earth-based spherical angle) */\n  const double psi);                   /* Polarization angle */\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _LLVFDRESPONSE_H */\n", "meta": {"hexsha": "19219f44074ce48b49cca1649f35bc3ce93fcf3a", "size": 5200, "ext": "h", "lang": "C", "max_stars_repo_path": "LLVsim/LLVFDresponse.h", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "LLVsim/LLVFDresponse.h", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LLVsim/LLVFDresponse.h", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 52.5252525253, "max_line_length": 216, "alphanum_fraction": 0.6423076923, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.795658104908603, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.37919446200332774}}
{"text": "/* Dickman's rho function (to compute probability of success of ecm).\n\nCopyright 2004, 2005, 2006, 2008, 2009, 2010, 2011, 2012, 2013\nAlexander Kruppa, Paul Zimmermann.\n\nThis file is part of the ECM Library.\n\nThe ECM Library is free software; you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or (at your\noption) any later version.\n\nThe ECM Library is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\nor FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public\nLicense for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with the ECM Library; see the file COPYING.LIB.  If not, see\nhttp://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,\n51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */\n\n/* define TESTDRIVE to compile rho as a stand-alone program, in which case\n   you need to have libgsl installed */\n\n#include \"config.h\"\n#if defined(TESTDRIVE)\n#define _ISOC99_SOURCE 1\n#endif\n#if defined(DEBUG_NUMINTEGRATE) || defined(TESTDRIVE)\n# include <stdio.h>\n#endif\n#include <stdlib.h>\n#include <math.h>\n#if defined(TESTDRIVE)\n#include <string.h>\n#include \"primegen.h\"\n#endif\n#if defined(TESTDRIVE)\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_sf_expint.h>\n#include <gsl/gsl_integration.h>\n#endif\n#include \"ecm-impl.h\"\n\n/* For Suyama's curves, we have a known torsion factor of 12 = 2^2*3^1, and\n   an average extra exponent of 1/2 for 2, and 1/3 for 3 due to the probability\n   that the group order divided by 12 is divisible by 2 or 3, thus on average\n   we should have 2^2.5*3^1.333 ~ 24.5, however experimentally we have\n   2^3.323*3^1.687 ~ 63.9 (see Alexander Kruppa's thesis, Table 5.1 page 96,\n   row sigma=2, http://tel.archives-ouvertes.fr/tel-00477005/en/).\n   The exp(ECM_EXTRA_SMOOTHNESS) value takes into account the extra\n   smoothness with respect to a random number. */\n#ifndef ECM_EXTRA_SMOOTHNESS\n#define ECM_EXTRA_SMOOTHNESS 3.134\n#endif\n\n#define M_PI_SQR   9.869604401089358619 /* Pi^2 */\n#define M_PI_SQR_6 1.644934066848226436 /* Pi^2/6 */\n/* gsl_math.h defines M_EULER */\n#ifndef M_EULER\n#define M_EULER    0.577215664901532861\n#endif\n#define M_EULER_1   0.422784335098467139 /* 1 - Euler */\n\n#ifndef MAX\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n#endif\n#ifndef MIN\n#define MIN(x,y) ((x) < (y) ? (x) : (y))\n#endif\n\nvoid rhoinit (int, int); /* used in stage2.c */\n\nstatic double *rhotable = NULL;\nstatic int invh = 0;\nstatic double h = 0.;\nstatic int tablemax = 0;\n#if defined(TESTDRIVE)\n#define PRIME_PI_MAX 10000\n#define PRIME_PI_MAP(x) (((x)+1)/2)\n/* The number of primes up to i. Use prime_pi[PRIME_PI_MAP(i)].\n   Only correct for i >= 2. */\nstatic unsigned int prime_pi[PRIME_PI_MAP(PRIME_PI_MAX)+1];\n#endif\n\n/* Fixme: need prime generating funcion without static state variables */\nconst unsigned char primemap[667] = {\n  254, 223, 239, 126, 182, 219, 61, 249, 213, 79, 30, 243, 234, 166, 237, 158, \n  230, 12, 211, 211, 59, 221, 89, 165, 106, 103, 146, 189, 120, 30, 166, 86, \n  86, 227, 173, 45, 222, 42, 76, 85, 217, 163, 240, 159, 3, 84, 161, 248, 46, \n  253, 68, 233, 102, 246, 19, 58, 184, 76, 43, 58, 69, 17, 191, 84, 140, 193, \n  122, 179, 200, 188, 140, 79, 33, 88, 113, 113, 155, 193, 23, 239, 84, 150, \n  26, 8, 229, 131, 140, 70, 114, 251, 174, 101, 146, 143, 88, 135, 210, 146, \n  216, 129, 101, 38, 227, 160, 17, 56, 199, 38, 60, 129, 235, 153, 141, 81, \n  136, 62, 36, 243, 51, 77, 90, 139, 28, 167, 42, 180, 88, 76, 78, 38, 246, \n  25, 130, 220, 131, 195, 44, 241, 56, 2, 181, 205, 205, 2, 178, 74, 148, 12, \n  87, 76, 122, 48, 67, 11, 241, 203, 68, 108, 36, 248, 25, 1, 149, 168, 92, \n  115, 234, 141, 36, 150, 43, 80, 166, 34, 30, 196, 209, 72, 6, 212, 58, 47, \n  116, 156, 7, 106, 5, 136, 191, 104, 21, 46, 96, 85, 227, 183, 81, 152, 8, \n  20, 134, 90, 170, 69, 77, 73, 112, 39, 210, 147, 213, 202, 171, 2, 131, 97, \n  5, 36, 206, 135, 34, 194, 169, 173, 24, 140, 77, 120, 209, 137, 22, 176, 87, \n  199, 98, 162, 192, 52, 36, 82, 174, 90, 64, 50, 141, 33, 8, 67, 52, 182, \n  210, 182, 217, 25, 225, 96, 103, 26, 57, 96, 208, 68, 122, 148, 154, 9, 136, \n  131, 168, 116, 85, 16, 39, 161, 93, 104, 30, 35, 200, 50, 224, 25, 3, 68, \n  115, 72, 177, 56, 195, 230, 42, 87, 97, 152, 181, 28, 10, 104, 197, 129, \n  143, 172, 2, 41, 26, 71, 227, 148, 17, 78, 100, 46, 20, 203, 61, 220, 20, \n  197, 6, 16, 233, 41, 177, 130, 233, 48, 71, 227, 52, 25, 195, 37, 10, 48, \n  48, 180, 108, 193, 229, 70, 68, 216, 142, 76, 93, 34, 36, 112, 120, 146, \n  137, 129, 130, 86, 38, 27, 134, 233, 8, 165, 0, 211, 195, 41, 176, 194, 74, \n  16, 178, 89, 56, 161, 29, 66, 96, 199, 34, 39, 140, 200, 68, 26, 198, 139, \n  130, 129, 26, 70, 16, 166, 49, 9, 240, 84, 47, 24, 210, 216, 169, 21, 6, 46, \n  12, 246, 192, 14, 80, 145, 205, 38, 193, 24, 56, 101, 25, 195, 86, 147, 139, \n  42, 45, 214, 132, 74, 97, 10, 165, 44, 9, 224, 118, 196, 106, 60, 216, 8, \n  232, 20, 102, 27, 176, 164, 2, 99, 54, 16, 49, 7, 213, 146, 72, 66, 18, 195, \n  138, 160, 159, 45, 116, 164, 130, 133, 120, 92, 13, 24, 176, 97, 20, 29, 2, \n  232, 24, 18, 193, 1, 73, 28, 131, 48, 103, 51, 161, 136, 216, 15, 12, 244, \n  152, 136, 88, 215, 102, 66, 71, 177, 22, 168, 150, 8, 24, 65, 89, 21, 181, \n  68, 42, 82, 225, 179, 170, 161, 89, 69, 98, 85, 24, 17, 165, 12, 163, 60, \n  103, 0, 190, 84, 214, 10, 32, 54, 107, 130, 12, 21, 8, 126, 86, 145, 1, 120, \n  208, 97, 10, 132, 168, 44, 1, 87, 14, 86, 160, 80, 11, 152, 140, 71, 108, \n  32, 99, 16, 196, 9, 228, 12, 87, 136, 11, 117, 11, 194, 82, 130, 194, 57, \n  36, 2, 44, 86, 37, 122, 49, 41, 214, 163, 32, 225, 177, 24, 176, 12, 138, \n  50, 193, 17, 50, 9, 197, 173, 48, 55, 8, 188, 145, 130, 207, 32, 37, 107, \n  156, 48, 143, 68, 38, 70, 106, 7, 73, 142, 9, 88, 16, 2, 37, 197, 196, 66, \n  90, 128, 160, 128, 60, 144, 40, 100, 20, 225, 3, 132, 81, 12, 46, 163, 138, \n  164, 8, 192, 71, 126, 211, 43, 3, 205, 84, 42, 0, 4, 179, 146, 108, 66, 41, \n  76, 131, 193, 146, 204, 28};\n\n#ifdef TESTDRIVE\nunsigned long\ngcd (unsigned long a, unsigned long b)\n{\n  unsigned long t;\n\n  while (b != 0)\n    {\n      t = a % b;\n      a = b;\n      b = t;\n    }\n\n  return a;\n}\n\nunsigned long\neulerphi (unsigned long n)\n{\n  unsigned long phi = 1, p;\n\n  for (p = 2; p * p <= n; p += 2)\n    {\n      if (n % p == 0)\n        {\n          phi *= p - 1;\n          n /= p;\n          while (n % p == 0)\n            {\n              phi *= p;\n              n /= p;\n            }\n        }\n\n      if (p == 2)\n        p--;\n    }\n\n  /* now n is prime */\n\n  return (n == 1) ? phi : phi * (n - 1);\n}\n\n\n/* The number of positive integers up to x that have no prime factor up to y,\n   for x >= y >= 2. Uses Buchstab's identity */\nunsigned long\nBuchstab_Phi(unsigned long x, unsigned long y) \n{\n  unsigned long p, s;\n  primegen pg[1];\n\n  if (x < 1)\n    return 0;\n  if (x <= y)\n    return 1;\n#if 0\n  if (x < y^2)\n    return(1 + primepi(x) - primepi (y)));\n#endif\n\n  s = 1;\n  primegen_init (pg);\n  primegen_skipto (pg, y + 1);\n  for (p = primegen_next(pg); p <= x; p = primegen_next(pg))\n    s += Buchstab_Phi(x / p, p - 1);\n  return (s);\n}\n\n\n/* The number of positive integers up to x that have no prime factor\n   greter than y, for x >= y >= 2. Uses Buchstab's identity */\nunsigned long \nBuchstab_Psi(const unsigned long x, const unsigned long y) \n{\n  unsigned long r, p;\n  primegen pg[1];\n\n  if (x <= y)\n    return (x);\n\n  if (y == 1UL)\n    return (1);\n\n  /* If y^2 > x, then\n     Psi(x,y) = x - \\sum_{y < p < x, p prime} floor(x/p)\n\n     We separate the sum into ranges where floor(x/p) = k,\n     which is x/(k+1) < p <= x/k.\n     We also need to satisfy y < p, so we need k < x/y - 1,\n     or k_max = ceil (x/y) - 2.\n     The primes y < p <= x/(k_max + 1) are summed separately. */\n  if (x <= PRIME_PI_MAX && x < y * y)\n    {\n      unsigned long kmax = x / y - 1;\n      unsigned long s1, s2, k;\n      \n        s1 = (kmax + 1) * (prime_pi [PRIME_PI_MAP(x / (kmax + 1))] - \n                           prime_pi [PRIME_PI_MAP(y)]);\n        s2 = 0;\n        for (k = 1; k <= kmax; k++)\n          s2 += prime_pi[PRIME_PI_MAP(x / k)];\n        s2 -= kmax * prime_pi [PRIME_PI_MAP(x / (kmax+1))];\n        return (x - s1 - s2);\n    }\n\n  r = 1;\n  primegen_init (pg);\n  for (p = primegen_next(pg); p <= y; p = primegen_next(pg))\n    r += Buchstab_Psi (x / p, p);\n  return (r);\n}\n\n#endif /* TESTDRIVE */\n\n\n#if defined(TESTDRIVE)\nstatic double\nLi (const double x)\n{\n  return (- gsl_sf_expint_E1 (- log(x)));\n}\n#endif\n\n/*\n  Evaluate dilogarithm via the sum \n  \\Li_{2}(z)=\\sum_{k=1}^{\\infty} \\frac{z^k}{k^2}, \n  see http://mathworld.wolfram.com/Dilogarithm.html\n  Assumes |z| <= 0.5, for which the sum converges quickly.\n */\n\nstatic double\ndilog_series (const double z)\n{\n  double r = 0.0, zk; /* zk = z^k */\n  int k, k2; /* k2 = k^2 */\n  /* Doubles have 53 bits in significand, with |z| <= 0.5 the k+1-st term\n     is <= 1/(2^k k^2) of the result, so 44 terms should do */\n  for (k = 1, k2 = 1, zk = z; k <= 44; k2 += 2 * k + 1, k++, zk *= z)\n    r += zk / (double) k2;\n\n  return r;\n}\n\nstatic double\ndilog (double x)\n{\n  ASSERT(x <= -1.0); /* dilog(1-x) is called from rhoexact for 2 < x <= 3 */\n\n  if (x <= -2.0)\n    return -dilog_series (1./x) - M_PI_SQR_6 - 0.5 * log(-1./x) * log(-1./x);\n  else /* x <= -1.0 */\n    {\n      /* L2(z) = -L2(1 - z) + 1/6 * Pi^2 - ln(1 - z)*ln(z) \n         L2(z) = -L2(1/z) - 1/6 * Pi^2 - 0.5*ln^2(-1/z)\n         ->\n         L2(z) = -(-L2(1/(1-z)) - 1/6 * Pi^2 - 0.5*ln^2(-1/(1-z))) + 1/6 * Pi^2 - ln(1 - z)*ln(z)\n               = L2(1/(1-z)) - 1/6 * Pi^2 + 0.5*ln(1 - z)^2 - ln(1 - z)*ln(-z)\n         z in [-1, -2) -> 1/(1-z) in [1/2, 1/3)\n      */\n      double log1x = log (1. - x);\n      return dilog_series (1. / (1. - x)) \n             - M_PI_SQR_6 + log1x * (0.5 * log1x - log (-x));\n    }\n}\n\n#if 0\nstatic double \nL2 (double x)\n{\n  return log (x) * (1 - log (x-1)) + M_PI_SQR_6 - dilog (1 - x);\n}\n#endif\n\nstatic double\nrhoexact (double x)\n{\n  ASSERT(x <= 3.);\n  if (x <= 0.)\n    return 0.;\n  else if (x <= 1.)\n    return 1.;\n  else if (x <= 2.)\n    return 1. - log (x);\n  else /* 2 < x <= 3 thus -2 <= 1-x < -1 */\n    return 1. - log (x) * (1. - log (x - 1.)) + dilog (1. - x) + 0.5 * M_PI_SQR_6;\n}\n\n\n#if defined(TESTDRIVE)\n\n/* The Buchstab omega(x) function, exact for x <= 4 where it can be \n   evaluated without numerical integration, and approximated by \n   exp(gamma) for larger x. */\n\nstatic double\nBuchstab_omega (const double x)\n{\n  /* magic = dilog(-1) + 1  = Pi^2/12 + 1 */\n  const double magic = 1.82246703342411321824; \n\n  if (x < 1.) return (0.);\n  if (x <= 2.) return (1. / x);\n  if (x <= 3.) return ((log (x - 1.) + 1.) / x);\n  if (x <= 4.)\n    return ((dilog(2. - x) + (1. + log(x - 2.)) * log(x - 1.) + magic) / x);\n\n  /* If argument is out of range, return the limiting value for \n     $x->\\infty$: e^-gamma. \n     For x only a little larger than 4., this has relative error 2.2e-6,\n     for larger x the error rapidly drops further */\n\n  return 0.56145948356688516982;\n}\n\n#endif\n\nvoid \nrhoinit (int parm_invh, int parm_tablemax)\n{\n  int i;\n\n  if (parm_invh == invh && parm_tablemax == tablemax)\n    return;\n\n  if (rhotable != NULL)\n    {\n      free (rhotable);\n      rhotable = NULL;\n      invh = 0;\n      h = 0.;\n      tablemax = 0;\n    }\n  \n  /* The integration below expects 3 * invh > 4 */\n  if (parm_tablemax == 0 || parm_invh < 2)\n    return;\n    \n  invh = parm_invh;\n  h = 1. / (double) invh;\n  tablemax = parm_tablemax;\n  \n  rhotable = (double *) malloc (parm_invh * parm_tablemax * sizeof (double));\n  ASSERT_ALWAYS(rhotable != NULL);\n  \n  for (i = 0; i < (3 < parm_tablemax ? 3 : parm_tablemax) * invh; i++)\n    rhotable[i] = rhoexact (i * h);\n  \n  for (i = 3 * invh; i < parm_tablemax * invh; i++)\n    {\n      /* rho(i*h) = 1 - \\int_{1}^{i*h} rho(x-1)/x dx\n                  = rho((i-4)*h) - \\int_{(i-4)*h}^{i*h} rho(x-1)/x dx */\n      \n      rhotable[i] = rhotable[i - 4] - 2. / 45. * (\n          7. * rhotable[i - invh - 4] / (double)(i - 4)\n        + 32. * rhotable[i - invh - 3] / (double)(i - 3)\n        + 12. * rhotable[i - invh - 2] / (double)(i - 2)\n        + 32. * rhotable[i - invh - 1] / (double)(i - 1)\n        + 7. * rhotable[i - invh]  / (double)i );\n      if (rhotable[i] < 0.)\n        {\n#ifndef DEBUG_NUMINTEGRATE\n          rhotable[i] = 0.;\n#else\n          printf (stderr, \"rhoinit: rhotable[%d] = %.16f\\n\", i, \n                   rhotable[i]);\n          exit (EXIT_FAILURE);\n#endif\n        }\n    }\n}\n\n/* assumes alpha < tablemax */\nstatic double\ndickmanrho (double alpha)\n{\n  ASSERT(alpha < tablemax);\n\n  if (alpha <= 3.)\n     return rhoexact (alpha);\n  {\n    int a = floor (alpha * invh);\n    double rho1 = rhotable[a];\n    double rho2 = (a + 1) < tablemax * invh ? rhotable[a + 1] : 0;\n    return rho1 + (rho2 - rho1) * (alpha * invh - (double) a);\n  }\n}\n\n#if 0\nstatic double \ndickmanrhosigma (double alpha, double x)\n{\n  if (alpha <= 0.)\n    return 0.;\n  if (alpha <= 1.)\n    return 1.;\n  if (alpha < tablemax)\n    return dickmanrho (alpha) + M_EULER_1 * dickmanrho (alpha - 1.) / log (x);\n  \n  return 0.;\n}\n\nstatic double\ndickmanrhosigma_i (int ai, double x)\n{\n  if (ai <= 0)\n    return 0.;\n  if (ai <= invh)\n    return 1.;\n  if (ai < tablemax * invh)\n    return rhotable[ai] - M_EULER * rhotable[ai - invh] / log(x);\n  \n  return 0.;\n}\n#endif\n\nstatic double\ndickmanlocal (double alpha, double x)\n{\n  if (alpha <= 1.)\n    return rhoexact (alpha);\n  if (alpha < tablemax)\n    return dickmanrho (alpha) - M_EULER * dickmanrho (alpha - 1.) / log (x);\n  return 0.;\n}\n\nstatic double\ndickmanlocal_i (int ai, double x)\n{\n  if (ai <= 0)\n    return 0.;\n  if (ai <= invh)\n    return 1.;\n  if (ai <= 2 * invh && ai < tablemax * invh)\n    return rhotable[ai] - M_EULER / log (x);\n  if (ai < tablemax * invh)\n    {\n      double logx = log (x);\n      return rhotable[ai] - (M_EULER * rhotable[ai - invh]\n             + M_EULER_1 * rhotable[ai - 2 * invh] / logx) / logx;\n    }\n\n  return 0.;\n}\n\nstatic int \nisprime(unsigned long n)\n{\n  unsigned int r;\n\n  if (n % 2 == 0)\n    return (n == 2);\n  if (n % 3 == 0)\n    return (n == 3);\n  if (n % 5 == 0)\n    return (n == 5);\n\n  if (n / 30 >= sizeof (primemap))\n    abort();\n  \n  r = n % 30; /* 8 possible values: 1,7,11,13,17,19,23,29 */\n  r = (r * 16 + r) / 64; /* maps the 8 values onto 0, ..., 7 */\n\n  return ((primemap[n / 30] & (1 << r)) != 0);\n}\n\nstatic double\ndickmanmu_sum (const unsigned long B1, const unsigned long B2, \n\t       const double x)\n{\n  double s = 0.;\n  const double logB1 = 1. / log(B1);\n  const double logx = log(x); \n  unsigned long p;\n\n  for (p = B1 + 1; p <= B2; p++)\n    if (isprime(p))\n      s += dickmanlocal ((logx - log(p)) * logB1, x / p) / p;\n\n  return (s);\n}\n\nstatic double\ndickmanmu (double alpha, double beta, double x)\n{\n  double a, b, sum;\n  int ai, bi, i;\n  ai = ceil ((alpha - beta) * invh);\n  if (ai > tablemax * invh)\n    ai = tablemax * invh;\n  a = (double) ai * h;\n  bi = floor ((alpha - 1.) * invh);\n  if (bi > tablemax * invh)\n    bi = tablemax * invh;\n  b = (double) bi * h;\n  sum = 0.;\n  for (i = ai + 1; i < bi; i++)\n    sum += dickmanlocal_i (i, x) / (alpha - i * h);\n  sum += 0.5 * dickmanlocal_i (ai, x) / (alpha - a);\n  sum += 0.5 * dickmanlocal_i (bi, x) / (alpha - b);\n  sum *= h;\n  sum += (a - alpha + beta) * 0.5 * (dickmanlocal_i (ai, x) / (alpha - a) + dickmanlocal (alpha - beta, x) / beta);\n  sum += (alpha - 1. - b) * 0.5 * (dickmanlocal (alpha - 1., x) + dickmanlocal_i (bi, x) / (alpha - b));\n\n  return sum;\n}\n\nstatic double\nbrentsuyama (double B1, double B2, double N, double nr)\n{\n  double a, alpha, beta, sum;\n  int ai, i;\n  alpha = log (N) / log (B1);\n  beta = log (B2) / log (B1);\n  ai = floor ((alpha - beta) * invh);\n  if (ai > tablemax * invh)\n    ai = tablemax * invh;\n  a = (double) ai * h;\n   sum = 0.;\n  for (i = 1; i < ai; i++)\n    sum += dickmanlocal_i (i, N) / (alpha - i * h) * (1 - exp (-nr * pow (B1, (-alpha + i * h))));\n  sum += 0.5 * (1 - exp(-nr / pow (B1, alpha)));\n  sum += 0.5 * dickmanlocal_i (ai, N) / (alpha - a) * (1 - exp(-nr * pow (B1, (-alpha + a))));\n  sum *= h;\n  sum += 0.5 * (alpha - beta - a) * (dickmanlocal_i (ai, N) / (alpha - a) + dickmanlocal (alpha - beta, N) / beta);\n\n  return sum;\n}\n\nstatic double \nbrsudickson (double B1, double B2, double N, double nr, int S)\n{\n  int i, f;\n  double sum;\n  sum = 0;\n  f = eulerphi (S) / 2;\n  for (i = 1; i <= S / 2; i++)\n      if (gcd (i, S) == 1)\n        sum += brentsuyama (B1, B2, N, nr * (gcd (i - 1, S) + gcd (i + 1, S) - 4) / 2);\n  \n  return sum / (double)f;\n}\n\nstatic double\nbrsupower (double B1, double B2, double N, double nr, int S)\n{\n  int i, f;\n  double sum;\n  sum = 0;\n  f = eulerphi (S);\n  for (i = 1; i < S; i++)\n      if (gcd (i, S) == 1)\n        sum += brentsuyama (B1, B2, N, nr * (gcd (i - 1, S) - 2));\n  \n  return sum / (double)f;\n}\n\n/* Assume N is as likely smooth as a number around N/exp(delta) */\n\nstatic double\nprob (double B1, double B2, double N, double nr, int S, double delta)\n{\n  const double sumthresh = 20000.;\n  double alpha, beta, stage1, stage2, brsu;\n  const double effN = N / exp (delta);\n\n  ASSERT(rhotable != NULL);\n  \n  /* What to do if rhotable is not initialised and asserting is not enabled?\n     For now, bail out with 0. result. Not really pretty, either */\n  if (rhotable == NULL)\n    return 0.;\n\n  if (B1 < 2. || N <= 1.)\n    return 0.;\n  \n  if (effN <= B1)\n    return 1.;\n\n#ifdef TESTDRIVE\n  printf (\"B1 = %f, B2 = %f, N = %.0f, nr = %f, S = %d\\n\", B1, B2, N, nr, S);\n#endif\n  \n  alpha = log (effN) / log (B1);\n  stage1 = dickmanlocal (alpha, effN);\n  stage2 = 0.;\n  if (B2 > B1)\n    {\n      if (B1 < sumthresh)\n\t{\n\t  stage2 += dickmanmu_sum (B1, MIN(B2, sumthresh), effN);\n\t  beta = log (B2) / log (MIN(B2, sumthresh));\n\t}\n      else\n\tbeta = log (B2) / log (B1);\n\n      if (beta > 1.)\n\tstage2 += dickmanmu (alpha, beta, effN);\n    }\n  brsu = 0.;\n  if (S < -1)\n    brsu = brsudickson (B1, B2, effN, nr, -S * 2);\n  if (S > 1)\n    brsu = brsupower (B1, B2, effN, nr, S * 2);\n\n#ifdef TESTDRIVE\n  printf (\"stage 1 : %f, stage 2 : %f, Brent-Suyama : %f\\n\", stage1, stage2, brsu);\n#endif\n\n  return (stage1 + stage2 + brsu) > 0. ? (stage1 + stage2 + brsu) : 0.;\n}\n\ndouble\necmprob (double B1, double B2, double N, double nr, int S)\n{\n  return prob (B1, B2, N, nr, S, ECM_EXTRA_SMOOTHNESS);\n}\n\ndouble\npm1prob (double B1, double B2, double N, double nr, int S, const mpz_t go)\n{\n  mpz_t cof;\n  /* A prime power q^k divides p-1, p prime, with probability 1/(q^k-q^(k-1))\n     not with probability 1/q^k as for random numbers. This is taken into \n     account by the \"smoothness\" value here; a prime p-1 is about as likely\n     smooth as a random number around (p-1)/exp(smoothness).\n     smoothness = \\sum_{q in Primes} log(q)/(q-1)^2 */\n  double smoothness = 1.2269688;\n  unsigned long i;\n  \n  if (go != NULL && mpz_cmp_ui (go, 1UL) > 0)\n    {\n      mpz_init (cof);\n      mpz_set (cof, go);\n      for (i = 2; i < 100; i++)\n        if (mpz_divisible_ui_p (cof, i))\n          {\n            /* If we know that q divides p-1 with probability 1, we need to\n               adjust the smoothness parameter */\n            smoothness -= log ((double) i) / (double) ((i-1)*(i-1));\n            /* printf (\"pm1prob: Dividing out %lu\\n\", i); */\n            while (mpz_divisible_ui_p (cof, i))\n              mpz_tdiv_q_ui (cof, cof, i);\n          }\n      /* printf (\"pm1prob: smoothness after dividing out go primes < 100: %f\\n\", \n               smoothness); */\n      return prob (B1, B2, N, nr, S, smoothness + log(mpz_get_d (cof)));\n      mpz_clear (cof);\n    }\n\n  return prob (B1, B2, N, nr, S, smoothness);\n}\n\n#if defined(TESTDRIVE)\n\n/* Compute probability for primes p == r (mod m) */\n\nstatic double\npm1prob_rm (double B1, double B2, double N, double nr, int S, unsigned long r,\n            unsigned long m)\n{\n  unsigned long cof;\n  double smoothness = 1.2269688;\n  unsigned long p;\n  \n  cof = m;\n  \n  for (p = 2UL; p < 100UL; p++)\n    if (cof % p == 0UL) /* For each prime in m */\n      {\n        unsigned long cof_r, k, i;\n        /* Divisibility by i is determined by r and m. We need to\n           adjust the smoothness parameter. In P-1, we had estimated the \n           expected value for the exponent of p as p/(p-1)^2. Undo that. */\n        smoothness -= (double)p / ((p-1)*(p-1)) * log ((double) p);\n        /* The expected value for the exponent of this prime is k s.t.\n           p^k || r, plus 1/(p-1) if p^k || m as well */\n        cof_r = gcd (r - 1UL, m);\n        for (k = 0UL; cof_r % p == 0UL; k++)\n          cof_r /= p;\n        smoothness += k * log ((double) p);\n\n        cof_r = m;\n        for (i = 0UL; cof_r % p == 0UL; i++)\n          cof_r /= p;\n\n        if (i == k)\n          smoothness += (1./(p - 1.) * log ((double) p));\n        \n        while (cof % p == 0UL)\n          cof /= p;\n        printf (\"pm1prob_rm: p = %lu, k = %lu, i = %lu, new smoothness = %f\\n\", \n                p, i, k, smoothness); \n      }\n\n  return prob (B1, B2, N, nr, S, smoothness);\n}\n\n\n/* The \\Phi(x,y) function gives the number of natural numbers <= x \n   that have no prime factor <= y, see Tenenbaum, \n   \"Introduction the analytical and probabilistic number theory\", III.6.\n   This function estimates the \\Phi(x,y) function via eq. (48) of the 1st\n   edition resp. equation (6.49) of the 3rd edition of Tenenbaum's book. */\n\nstatic double \nintegrand1 (double x, double *y)\n{\n  return pow (*y, x) / x * log(x-1.);\n}\n\n\nstatic double \nintegrand2 (double v, double *y)\n{\n  return Buchstab_omega (v) * pow (*y, v);\n}\n\n\n/* Return approximate number of integers n with x1 < n <= x2\n   that have no prime factor <= y */\n\ndouble \nno_small_prime (double x1, double x2, double y)\n{\n  double u1, u2;\n  ASSERT (x1 >= 2.);\n  ASSERT (x2 >= x1);\n  ASSERT (y >= 2.);\n  if (x1 == x2 || x2 <= y)\n    return 0.;\n  if (x1 < y)\n    x1 = y;\n  \n  u1 = log(x1)/log(y);\n  u2 = log(x2)/log(y);\n\n   /* If no prime factors <= sqrt(x2), numbers must be a primes > y */\n  if (x2 <= y*y)\n    return (Li(x2) - Li(x1));\n  \n  if (u2 <= 3)\n    {\n      double r, abserr;\n      size_t neval;\n      gsl_function f;\n\n      f.function = (double (*) (double, void *)) &integrand1;\n      f.params = &y;\n\n      /* intnum(v=1,u,buchstab(v)*y^v) */\n\n      /* First part: intnum(v=u1, u, y^v/v*log(v-1.)) */\n      gsl_integration_qng (&f, MAX(u1, 2.) , u2, 0., 0.001, &r, &abserr, &neval);\n\n      /* Second part: intnum(v=u1, u2, y^v/v) = Li(x2) - Li(x1) */\n      r += Li (x2) - Li (x1);\n      \n      return r;\n    }\n    \n  {\n    double r, abserr;\n    size_t neval;\n    gsl_function f;\n  \n    f.function = (double (*) (double, void *)) &integrand2;\n    f.params = &y;\n    \n    gsl_integration_qng (&f, u1, u2, 0., 0.001, &r, &abserr, &neval);\n    return r;\n  }\n}\n\n\nstatic double \nintegrand3 (double p, double *param)\n{\n  const double x1 = param[0];\n  const double x2 = param[1];\n  const double y = param[2];\n  \n  return no_small_prime (x1 / p, x2 / p, y) / log(p);\n}\n\n\ndouble \nno_small_prime_factor (const double x1, const double x2, const double y, \n                       const double z1, const double z2)\n{\n  double r, abserr, param[3];\n  size_t neval;\n  gsl_function f;\n\n  param[0] = x1;\n  param[1] = x2;\n  param[2] = y;\n  f.function = (double (*) (double, void *)) &integrand3;\n  f.params = &param;\n  \n  gsl_integration_qng (&f, z1, z2, 0., 0.01, &r, &abserr, &neval);\n  \n  return r;\n}\n\n#endif\n\n\n#ifdef TESTDRIVE\nint\nmain (int argc, char **argv)\n{\n  double B1, B2, N, nr, r, m;\n  int S;\n  unsigned long p, i, pi;\n  primegen pg[1];\n\n  primegen_init (pg);\n  i = pi = 0;\n  for (p = primegen_next (pg); p <= PRIME_PI_MAX; p = primegen_next (pg))\n    {\n      for ( ; i < p; i++)\n        prime_pi[PRIME_PI_MAP(i)] = pi;\n      pi++;\n    }\n  for ( ; i < p; i++)\n    prime_pi[PRIME_PI_MAP(i)] = pi;\n  \n\n  if (argc < 2)\n    {\n      printf (\"Usage: rho <B1> <B2> <N> <nr> <S> [<r> <m>]\\n\");\n      return 1;\n    }\n  \n  if (strcmp (argv[1], \"-Buchstab_Phi\") == 0)\n    {\n      unsigned long x, y, r;\n      if (argc < 4)\n        {\n          printf (\"-Buchstab_Phi needs x and y paramters\\n\");\n          exit (EXIT_FAILURE);\n        }\n      x = strtoul (argv[2], NULL, 10);\n      y = strtoul (argv[3], NULL, 10);\n      r = Buchstab_Phi (x, y);\n      printf (\"Buchstab_Phi (%lu, %lu) = %lu\\n\", x, y, r);\n      exit (EXIT_SUCCESS);\n    }\n  else if (strcmp (argv[1], \"-Buchstab_Psi\") == 0)\n    {\n      unsigned long x, y, r;\n      if (argc < 4)\n        {\n          printf (\"-Buchstab_Psi needs x and y paramters\\n\");\n          exit (EXIT_FAILURE);\n        }\n      x = strtoul (argv[2], NULL, 10);\n      y = strtoul (argv[3], NULL, 10);\n      r = Buchstab_Psi (x, y);\n      printf (\"Buchstab_Psi (%lu, %lu) = %lu\\n\", x, y, r);\n      exit (EXIT_SUCCESS);\n    }\n  else if (strcmp (argv[1], \"-nsp\") == 0)\n    {\n      double x1, x2, y, r;\n      \n      if (argc < 5)\n        {\n          printf (\"-nsp needs x1, x2, and y paramters\\n\");\n          exit (EXIT_FAILURE);\n        }\n      x1 = atof (argv[2]);\n      x2 = atof (argv[3]);\n      y = atof (argv[4]);\n      r = no_small_prime (x1, x2, y);\n      printf (\"no_small_prime(%f, %f, %f) = %f\\n\", x1, x2, y, r);\n      exit (EXIT_SUCCESS);\n    }\n  else if (strcmp (argv[1], \"-nspf\") == 0)\n    {\n      double x1, x2, y, z1, z2, r;\n      \n      if (argc < 7)\n        {\n          printf (\"-nspf needs x1, x2, y, z1, and z2 paramters\\n\");\n          exit (EXIT_FAILURE);\n        }\n      x1 = atof (argv[2]);\n      x2 = atof (argv[3]);\n      y = atof (argv[4]);\n      z1 = atof (argv[5]);\n      z2 = atof (argv[6]);\n      r = no_small_prime_factor (x1, x2, y, z1, z2);\n      printf (\"no_small_prime(%f, %f, %f, %f, %f) = %f\\n\", x1, x2, y, z1, z2, r);\n      exit (EXIT_SUCCESS);\n    }\n\n\n  if (argc < 6)\n    {\n      printf (\"Need 5 or 7 arguments: B1 B2 N nr S [r m]\\n\");\n      exit (EXIT_FAILURE);\n    }\n  \n  B1 = atof (argv[1]);\n  B2 = atof (argv[2]);\n  N = atof (argv[3]);\n  nr = atof (argv[4]);\n  S = atoi (argv[5]);\n  r = 0; m = 1;\n  if (argc > 7)\n    {\n      r = atoi (argv[6]);\n      m = atoi (argv[7]);\n    }\n\n  rhoinit (256, 10);\n  if (N < 50.)\n    {\n      double sum;\n      sum = ecmprob(B1, B2, exp2 (N), nr, S);\n      sum += 4. * ecmprob(B1, B2, 3./2. * exp2 (N), nr, S);\n      sum += ecmprob(B1, B2, 2. * exp2 (N), nr, S);\n      sum *= 1./6.;\n      printf (\"ECM: %.16f\\n\", sum);\n\n      sum = pm1prob_rm (B1, B2, exp2 (N), nr, S, r, m);\n      sum += 4. * pm1prob_rm (B1, B2, 3./2. * exp2 (N), nr, S, r, m);\n      sum += pm1prob_rm (B1, B2, 2. * exp2 (N), nr, S, r, m);\n      sum *= 1./6.;\n      printf (\"P-1: %.16f\\n\", sum);\n    }\n  else\n    {\n      printf (\"ECM: %.16f\\n\", ecmprob(B1, B2, N, nr, S));\n      printf (\"P-1: %.16f\\n\", pm1prob_rm (B1, B2, N, nr, S, r, m));\n    }\n  rhoinit (0, 0);\n  return 0;\n}\n#endif\n", "meta": {"hexsha": "e32ee2bef9658da79835b389d14fd1deb28f348b", "size": 26782, "ext": "c", "lang": "C", "max_stars_repo_path": "picoctf/EasyRsa/gmp-ecm/rho.c", "max_stars_repo_name": "beninato8/ctfs", "max_stars_repo_head_hexsha": "b28c7b1e5f15a74fd62774da2b93aac225e38f57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "picoctf/EasyRsa/gmp-ecm/rho.c", "max_issues_repo_name": "beninato8/ctfs", "max_issues_repo_head_hexsha": "b28c7b1e5f15a74fd62774da2b93aac225e38f57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "picoctf/EasyRsa/gmp-ecm/rho.c", "max_forks_repo_name": "beninato8/ctfs", "max_forks_repo_head_hexsha": "b28c7b1e5f15a74fd62774da2b93aac225e38f57", "max_forks_repo_licenses": ["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.5534979424, "max_line_length": 115, "alphanum_fraction": 0.5436487193, "num_tokens": 10628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.3790429809215912}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <gsl/gsl_sf_legendre.h>\n#include <gsl/gsl_sf_bessel.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n/************************************************************************************************************************************************************************/\n/************************************************************************************************************************************************************************/\n\n                        //VARIABLE GLOBALE\nint size = 100;\nint limit = 100;   \ngsl_interp_accel *acc[25];\ngsl_spline *spline[25];\ndouble\tfg,\t\t\t\t\t\t\t\t\t\t// growth factor\n\t\t\t \tb,\t\t\t\t\t\t\t\t\t\t\t//Bias factor\n\t\t\t \tsmin, \t\t\t\t\t\t\t\t\t// Minimum of s range\n\t\t\t \tsmax, \t\t\t\t\t\t\t\t\t// Maximum of s range\n\t\t\t \tsigv, \t\t\t\t\t\t\t\t\t// Value of Sigma_v (define in sigma_v function)\n\t\t\t \tsig8, \t\t\t\t\t\t\t\t\t// Value of sigma 8 (define in main function)\n\t\t\t\tkmin,   \t\t\t\t\t\t\t\t// minimum k in the power spectrum file (define in main function)\n\t\t\t \tkmax, \t\t\t\t\t\t\t\t\t// minimum k in the power spectrum file (define in main function)\n\t\t\t \tlk, \t\t\t\t\t\t\t\t\t    // lk = kmax-kmin lenth for the integral calculation (define in main function)\n\t\t\t \tf1,\t\t\t\t\t\t\t\t\t\t//Bias factor CLPT\n\t\t\t \tf2,\t\t\t\t\t\t\t\t\t\t//Bias factor CLPT\n\t\t\t\tsig_shift;\t\t\t\t\t\t\t\n\tconst int val=160;\t\t\t\t\t\t\t\t\t// Nb of lines in the files Xi_r_CLPT, Sigma_CLPT and V12_CLPT\nstruct my_f_params { double a; double b; };\n\n/*********************************************************************************************************************************************************************/\n/*******************\\\\ Gauss-Legendre integral quadrature\\\\***********************************************************************************************************/\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\nstatic const double x[] = {\n    1.56289844215430828714e-02,    4.68716824215916316162e-02,\n    7.80685828134366366918e-02,    1.09189203580061115002e-01,\n    1.40203137236113973212e-01,    1.71080080538603274883e-01,\n    2.01789864095735997236e-01,    2.32302481844973969643e-01,\n    2.62588120371503479163e-01,    2.92617188038471964730e-01,\n    3.22360343900529151720e-01,    3.51788526372421720979e-01,\n    3.80872981624629956772e-01,    4.09585291678301542532e-01,\n    4.37897402172031513100e-01,    4.65781649773358042251e-01,\n    4.93210789208190933576e-01,    5.20158019881763056670e-01,\n    5.46597012065094167460e-01,    5.72501932621381191292e-01,\n    5.97847470247178721259e-01,    6.22608860203707771585e-01,\n    6.46761908514129279840e-01,    6.70283015603141015784e-01,\n    6.93149199355801965946e-01,    7.15338117573056446485e-01,\n    7.36828089802020705530e-01,    7.57598118519707176062e-01,\n    7.77627909649495475605e-01,    7.96897892390314476375e-01,\n    8.15389238339176254384e-01,    8.33083879888400823522e-01,\n    8.49964527879591284320e-01,    8.66014688497164623416e-01,\n    8.81218679385018415547e-01,    8.95561644970726986709e-01,\n    9.09029570982529690453e-01,    9.21609298145333952679e-01,\n    9.33288535043079545942e-01,    9.44055870136255977955e-01,\n    9.53900782925491742847e-01,    9.62813654255815527284e-01,\n    9.70785775763706331929e-01,    9.77809358486918288561e-01,\n    9.83877540706057015509e-01,    9.88984395242991747997e-01,\n    9.93124937037443459632e-01,    9.96295134733125149166e-01,\n    9.98491950639595818382e-01,    9.99713726773441233703e-01\n};\n\nstatic const double A[] = {\n    3.12554234538633569472e-02,    3.12248842548493577326e-02,\n    3.11638356962099067834e-02,    3.10723374275665165874e-02,\n    3.09504788504909882337e-02,    3.07983790311525904274e-02,\n    3.06161865839804484966e-02,    3.04040795264548200160e-02,\n    3.01622651051691449196e-02,    2.98909795933328309169e-02,\n    2.95904880599126425122e-02,    2.92610841106382766198e-02,\n    2.89030896011252031353e-02,    2.85168543223950979908e-02,\n    2.81027556591011733175e-02,    2.76611982207923882944e-02,\n    2.71926134465768801373e-02,    2.66974591835709626611e-02,\n    2.61762192395456763420e-02,    2.56294029102081160751e-02,\n    2.50575444815795897034e-02,    2.44612027079570527207e-02,\n    2.38409602659682059633e-02,    2.31974231852541216230e-02,\n    2.25312202563362727021e-02,    2.18430024162473863146e-02,\n    2.11334421125276415432e-02,    2.04032326462094327666e-02,\n    1.96530874944353058650e-02,    1.88837396133749045537e-02,\n    1.80959407221281166640e-02,    1.72904605683235824399e-02,\n    1.64680861761452126430e-02,    1.56296210775460027242e-02,\n    1.47758845274413017686e-02,    1.39077107037187726882e-02,\n    1.30259478929715422855e-02,    1.21314576629794974079e-02,\n    1.12251140231859771176e-02,    1.03078025748689695861e-02,\n    9.38041965369445795116e-03,    8.44387146966897140266e-03,\n    7.49907325546471157895e-03,    6.54694845084532276405e-03,\n    5.58842800386551515727e-03,    4.62445006342211935096e-03,\n    3.65596120132637518238e-03,    2.68392537155348241939e-03,\n    1.70939265351810523958e-03,    7.34634490505671730396e-04\n};\n\n#define NUM_OF_POSITIVE_ZEROS  sizeof(x) / sizeof(double)\n#define NUM_OF_ZEROS           NUM_OF_POSITIVE_ZEROS+NUM_OF_POSITIVE_ZEROS\n\ndouble \n  Gauss_Legendre_Integration2_100pts(double a, double b, double (*f)(double, void *), void *prms)\n{\n   double integral = 0.0; \n   double c = 0.5 * (b - a);\n   double d = 0.5 * (b + a);\n   double dum;\n   const double *px = &x[NUM_OF_POSITIVE_ZEROS - 1];\n   const double *pA = &A[NUM_OF_POSITIVE_ZEROS - 1];\n\n   for (; px >= x; pA--, px--) {\n      dum = c * *px;\n      integral += *pA * ( (*f)(d - dum,prms) + (*f)(d + dum,prms) );\n   }\n\n   return c * integral;\n}\n\nvoid Gauss_Legendre_Zeros_100pts( double zeros[] ) {\n   \n   const double *px = &x[NUM_OF_POSITIVE_ZEROS - 1];\n   double *pz = &zeros[NUM_OF_ZEROS - 1];\n\n   for (; px >= x; px--)  {\n      *(zeros++) = - *px;\n      *(pz--) = *px;\n   }   \n}\n\nvoid Gauss_Legendre_Coefs_100pts( double coefs[] ) {\n\n   const double *pA = &A[NUM_OF_POSITIVE_ZEROS - 1];\n   double *pc = &coefs[NUM_OF_ZEROS - 1];\n\n   for (; pA >= A; pA--)  {\n      *(coefs++) =  *pA;\n      *(pc--) = *pA;\n   }   \n}\n\n/***********************************************************************************************************************************************************************/\n/********************************\\\\ Interpolation Function \\\\***********************************************************************************************************/\n\ndouble Pm(double k)\n{\n    if (k>=kmin && k<=kmax)  return gsl_spline_eval (spline[1], k, acc[1]);\n    else return 0;\n}\n\ndouble Xim_interp(double s)\n{\n\tif (s>=smin && s<=smax-1)\treturn gsl_spline_eval (spline[2], s, acc[2]);\n    else\treturn 0;\n}\n\ndouble V12_interp(double s)\n{\t \n\tif (s>=smin && s<=smax-1)\treturn gsl_spline_eval (spline[3], s, acc[3]);\n    else return 0;\n}\n\ndouble Psiper_interp(double s)\n{\n\tif (s>=smin && s<=smax-1) \treturn gsl_spline_eval (spline[4], s, acc[4]);\n    else return 0;\n\n}\n\ndouble Psipar_interp(double s)\n{\n\tif (s>=smin && s<=smax-1)\treturn gsl_spline_eval (spline[5], s, acc[5]);\n    else    return 0;\n}\n\ndouble Xi_R_CLPT(double s)\n{\n\tif (s>=smin && s<=smax)\treturn\t gsl_spline_eval (spline[6], s, acc[6])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f1*gsl_spline_eval (spline[7], s, acc[7])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f2*gsl_spline_eval (spline[8], s, acc[8])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f1*f1*gsl_spline_eval (spline[9], s, acc[9])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f1*f2*gsl_spline_eval (spline[10], s, acc[10])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f2*f2*gsl_spline_eval (spline[11], s, acc[11]);\n    else\treturn 0;\n}\n\ndouble V12_CLPT(double s)\n{\n\tif (s>=smin && s<=smax)\treturn \tgsl_spline_eval (spline[12], s, acc[12])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f1*gsl_spline_eval (spline[13], s, acc[13])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f2*gsl_spline_eval (spline[14], s, acc[14])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f1*f1*gsl_spline_eval (spline[15], s, acc[15])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f1*f2*gsl_spline_eval (spline[16], s, acc[16]);\n    else return 0;\n}\n\ndouble Sig_par_CLPT(double s)\n{\n\tif (s>=smin && s<= smax) \treturn \tgsl_spline_eval (spline[17], s, acc[17])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f1*gsl_spline_eval (spline[18], s, acc[18])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f2*gsl_spline_eval (spline[19], s, acc[19])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f1*f1*gsl_spline_eval (spline[20], s, acc[20]);\n    else return 0;\n}\n\ndouble Sig_per_CLPT(double s)\n{\n\tif (s>=smin && s<=smax)\treturn \tgsl_spline_eval (spline[21], s, acc[21])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f1*gsl_spline_eval (spline[22], s, acc[22])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f2*gsl_spline_eval (spline[23], s, acc[23])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ f1*f1*gsl_spline_eval (spline[24], s, acc[24]);\n    else    return 0;\n}\n\n/**********************************************************************************************************************************************************************/\n/*************\\\\ Gaussian Function\\\\***********************************************************************************************************************************/\n     \ndouble gaus (double x, double moy, double var2)\n{\n    return 1./(sqrt(2.*M_PI*var2))*exp(-pow((x-moy),2)/(2.*var2));\n}\n\n/**********************************************************************************************************************************************************************/\n/*************\\\\Decomposition of s and r\\\\*****************************************************************************************************************************/\n                                                                                                                              \ndouble spar (double s, double mu_s)\n{\n    return s*mu_s;\n}\n\ndouble rperp (double s, double spar) // rp = sp (perp)\n{\n    return sqrt(s*s-spar*spar);\n}\n\ndouble r_real(double rp, double rpar)\n{\n    return sqrt(rp*rp+rpar*rpar);   \n}\n\ndouble mu_r(double rpar, double r)\n{\n    return rpar/r;\n}\n\n/***********************************************************************************************************************************************************************/\n/***************\\\\ Sigma_8\\\\********************************************************************************************************************************************/\n\ndouble fS8 (double k, void * params) \n{\n  double x = k*8;                   \n  return Pm(k)*k*k*(sin(x)-x*cos(x))*(sin(x)-x*cos(x))/pow(x,6);\n}\n\ndouble S8 (void)   \n{\n    double result, error;   \n                   \n    gsl_function F;\n    F.function = &fS8; \n    \n    gsl_integration_cquad_workspace *w = gsl_integration_cquad_workspace_alloc(size);\n    gsl_integration_cquad(&F, smin, smax, 0, 1e-12, w, &result, &error, NULL);\n    gsl_integration_cquad_workspace_free(w);\n    \n    return 9./(2.*M_PI*M_PI)*result;\n}\n\n/*********************************************************************************************************************************************************************/\n/****************\\\\Normalisation of P_m\\\\*****************************************************************************************************************************/\n\ndouble Pm_norm (double s)\n{\n\treturn Pm(s)/sig8;\n}\n\n/***********************************************************************************************************************************************************************/\n/*****************\\\\ V_12(r) Function\\\\*********************************************************************************************************************************/\n\n //Decomposition of bessel function j1\ndouble vsin (double k, void * params) \n{\n  double alpha = *(double *) params;               \n  return Pm_norm(k)*alpha/k; \n}\n\ndouble vcos (double k, void * params) \n{\n  double alpha = *(double *) params;\n  return Pm_norm(k)*alpha;\n}\n \ndouble V12(double r) \n{\n\tif(r>=.1){\n\t\tdouble result1, error1, result2, error2, alpha, alpha1, err;\n\t\tif(r<1) err = 0.1;\n\t\t\telse err= 0.1;\n\t\t\t\n\t\t// Vsin calculation \n\t\talpha = 1./(r*r);\n\t\tgsl_function F1;\n\t\tF1.function = &vsin;\n\t\tF1.params = &alpha;   \n\t\t\n\t\tgsl_integration_workspace *w1 = gsl_integration_workspace_alloc(size);\n\t\tgsl_integration_workspace *w2 = gsl_integration_workspace_alloc(size);    \n\t\tgsl_integration_qawo_table *t1 = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_SINE, size);\n\t\tgsl_integration_qawf(&F1, kmin, err, limit, w1, w2, t1, &result1, &error1);\n\t\t\n\t\t// Vcos calculation    \n\t\talpha1 = 1./r;\n\t\tgsl_function F2;\n\t\tF2.function = &vcos;\n\t\tF2.params = &alpha1;   \n\t\t \n\t\tgsl_integration_workspace *w3 = gsl_integration_workspace_alloc(size);\n\t\tgsl_integration_workspace *w4 = gsl_integration_workspace_alloc(size);    \n\t\tgsl_integration_qawo_table *t2 = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_COSINE, size);\n\t\tgsl_integration_qawf(&F2, kmin, err, limit, w3, w4, t2, &result2, &error2);\n\t\t\n\t\tgsl_integration_workspace_free(w1);\n\t\tgsl_integration_workspace_free(w2);    \n\t\tgsl_integration_qawo_table_free(t1);  \n\t\tgsl_integration_workspace_free(w3);\n\t\tgsl_integration_workspace_free(w4);    \n\t\tgsl_integration_qawo_table_free(t2);    \n\t\treturn result2-result1;\n\t}\n\telse return 0;\n}\n\n/************************************************************************************************************************************************************************/\n/*************\\\\Sigma_12(mu,r) functions\\\\*******************************************************************************************************************************/\n\n// Sigma_v\ndouble fsigmav(double k, void * params)\n{\n    double alpha = *(double *) params;\n    return alpha*Pm_norm(k);\n}\n\ndouble Sigmav(void)\n{\n    double result,error;\n    double alpha = 1./3.;   \n    \n    gsl_function F;\n    F.function = &fsigmav;\n    F.params = &alpha;  \n    \n    gsl_integration_workspace *w =  gsl_integration_workspace_alloc(size);\n    gsl_integration_qag(&F, kmin, kmax, 0, 1e-5, limit, 6, w, &result, &error); \n    gsl_integration_workspace_free(w);\n    \n    return result;\n}\n\n//\tPsiper(r)  \n\n //Decomposition of bessel function j1\ndouble Psipersin(double k, void * params)\n{\n    double alpha = *(double *) params;\n    return alpha*Pm_norm(k)/(pow(k,3));\n}\n\ndouble Psipercos(double k, void * params)\n{\n    double alpha = *(double *) params;\n    return alpha*Pm_norm(k)/(k*k);\n}\n\ndouble Psiper(double r)\t\t\t// We adapt the error at lower scale to compute the integral\n{\n\tif (r>=0.8){\n\t\tdouble err; \n//\t\tfor sin part\n\t\tdouble result1,error1; \n\t\tdouble alpha = 1./pow(r,3);\n//\t\tfor cos part\n\t\tdouble result2,error2; \n\t\tdouble alpha1 = 1./(r*r);\n\t\t\n\t\tif(r<10) {\t\t\t\t\t\t\t\t\t\n\t\t\tif (r<2.1) err = 10;\n\t\t\telse err= 1;}   \n\t\telse err=0.5;  \n\t\t\t\n// \tPsipersin calculation    \n\t\tgsl_function F1;\n\t\tF1.function = &Psipersin;\n\t\tF1.params = &alpha;    \n\t\t\t\n\t\tgsl_integration_workspace *w1 = gsl_integration_workspace_alloc(size);\n\t\tgsl_integration_workspace *w2 = gsl_integration_workspace_alloc(size);    \n\t\tgsl_integration_qawo_table *t1 = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_SINE, size);\n\t\tgsl_integration_qawf(&F1, kmin, err, limit, w1, w2, t1, &result1, &error1);    \n\t\t\n\t\t// Psipercos calculation \n\t\tgsl_function F2;\n\t\tF2.function = &Psipercos;\n\t\tF2.params = &alpha1;         \n\t\t\t   \n\t\tgsl_integration_workspace *w3 = gsl_integration_workspace_alloc(size);\n\t\tgsl_integration_workspace *w4 = gsl_integration_workspace_alloc(size);    \n\t\tgsl_integration_qawo_table *t2 = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_COSINE, size);\n\t\tgsl_integration_qawf(&F2, kmin, err, limit, w3, w4, t2, &result2, &error2);    \n\t\t\n\t\tgsl_integration_workspace_free(w1);\n\t\tgsl_integration_workspace_free(w2);    \n\t\tgsl_integration_qawo_table_free(t1);  \n\t\tgsl_integration_workspace_free(w3);\n\t\tgsl_integration_workspace_free(w4);    \n\t\tgsl_integration_qawo_table_free(t2);\n\t\t\n\t\treturn (result1-result2);}\n    else return 0;\n}\n\n//\t Psipar(r)\ndouble psiparf(double k, void * params)\n{\n    double alpha = *(double *) params; \n    return alpha*Pm_norm(k)/k;\n}\n\ndouble Psipar(double r)\n{\n    double result,error;\n    double alpha = 1./r;\n    \n    gsl_function F;\n    F.function = &psiparf;\n    F.params = &alpha;\n    \n    gsl_integration_workspace *w1 = gsl_integration_workspace_alloc(size);\n    gsl_integration_workspace *w2 = gsl_integration_workspace_alloc(size);    \n    gsl_integration_qawo_table *t1 = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_SINE, size);\n    gsl_integration_qawf(&F, kmin, 1e-1, limit, w1, w2, t1, &result, &error);\n    \n    gsl_integration_workspace_free(w1);\n    gsl_integration_workspace_free(w2);\n    gsl_integration_qawo_table_free(t1);\n    \n    return (result-2.*Psiper(r));\n}\n\n/********Sigma_12(mu,r)***************************************************************************************************************************************************/\n\ndouble Sigma12 (double mu, double r, double sigv) \t\t\t\t// from linear (Gaussian streaming) model\n{\n    return 2.*(sigv-mu*mu*Psipar_interp(r)-(1.-(mu*mu))*Psiper_interp(r));\n}\n\ndouble Sigma12_CLPT (double mu, double r)\t\t\t\t\t\t\t// from CLPT prediction\n{\n    return (mu*mu*Sig_par_CLPT(r)+(1.-mu*mu)*Sig_per_CLPT(r))/(1.+Xi_R_CLPT(r))-27.;\n}\n/***********************************************************************************************************************************************************************/\n/************\\\\Correlation function in real space\\\\*********************************************************************************************************************/\n              \ndouble fXim(double k, void * params)\n{\n    double alpha = *(double *) params;\n    double f = alpha*Pm_norm(k)*k;\n    return f;\n}\n\ndouble Xim (double r)\n{\n    double result, error;\n    double alpha = 1./(2.*M_PI*M_PI*r);\n    \n    gsl_function F;\n    F.function = &fXim;\n    F.params = &alpha;       \n     \n    gsl_integration_workspace *w1 = gsl_integration_workspace_alloc(200);\n    gsl_integration_workspace *w2 = gsl_integration_workspace_alloc(200);    \n    gsl_integration_qawo_table *t = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_SINE, size);\n    gsl_integration_qawf(&F, kmin, 1e-3, 200, w1, w2, t, &result, &error);\n    \n    gsl_integration_workspace_free(w1);\n    gsl_integration_workspace_free(w2);\n    gsl_integration_qawo_table_free(t);\n    return result;    \n}\n\n/***********************************************************************************************************************************************************************/\n/*************\\\\Correlation function in z-space\\\\***********************************************************************************************************************/\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ndouble fXis (double y, void *p)\n{\n    struct my_f_params * params = (struct my_f_params *)p;\n    double spp = (params->a);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// parallel component of s\n    double rp = (params->b);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// perpendicular componant of s\n    double r = r_real(rp, y);                        \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// norm of r\n\tdouble v = fg*b/(M_PI*M_PI)*V12_interp(r); \t\t\t\t\t\t\t\t\t\t\t// V_12(r)\n\tdouble mu_r = y/r;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\tdouble x = spp-y;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\tdouble moy = mu_r*v;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// average of the gaussian distribution\t\t\n\tdouble var = pow(fg,2)/(2.*M_PI*M_PI)*Sigma12(mu_r,r,sigv); \t\t\t// Variance Sigma_12\n\tif (var>0)\treturn (1.+Xim_interp(r))*gaus(x, moy, var); \t\t\t\t\t\n\telse\t\t\t\treturn 0;\n}\n\ndouble Xis (double sp, double spi)   //Compute in sperp, spar\n{\n\tstruct my_f_params params = {spi, sp};  \n    double result = Gauss_Legendre_Integration2_100pts(-200, 200, &fXis, &params);\n    return result -1.;\n}\n\n/*********************************************************************************************************************************************************************/\n/****************\\\\Correlation function in z-space for CLPT prediction\\\\**********************************************************************************************/\n\ndouble fXis_CLPT (double y, void *p)\n{\n    struct my_f_params * params = (struct my_f_params *)p;\n    double spp = (params->a);\n    double rp = (params->b);\n    double r = r_real(rp, y);                        \t\t\t\t\t\n\tdouble v = fg*V12_CLPT(r)/(1.+Xi_R_CLPT(r));\n\tdouble mu_r = y/r;\n\tdouble x = spp-y;\n\tdouble moy = mu_r*v;\n\tdouble var = pow(fg,2)*Sigma12_CLPT(mu_r,r);\n\tif (var>0)\treturn (1.+Xi_R_CLPT(r))*gaus(x, moy, var); \n\telse\t\t\t\treturn 0;\n}\n\ndouble Xis_CLPT (double sp, double spi)   \n{\n\tstruct my_f_params params = {spi, sp};  \n    double result = Gauss_Legendre_Integration2_100pts(-200, 200, &fXis_CLPT, &params);\n    return result -1.;\t\n}\n\n/**********************************************************************************************************************************************************************/\n/*********\\\\Legendre Multipole\\\\***************************************************************************************************************************************/\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ndouble fmultipole(double mu, void * p) \n{\n    struct my_f_params * params = (struct my_f_params *)p;\n    double s = (params->a);\n    double l = (params->b);\n    double rp = s*sqrt(1-mu*mu);\t\t\t// Decomposition of S in spar (=spi) and sp=rp\n    double spi = s*mu;\n    double Xi_s= Xis(rp,spi);\n\treturn Xi_s*gsl_sf_legendre_Pl(l,mu);\n}\n\ndouble multipole(double s, double l)   \n{\n    double result;\n    struct my_f_params params = {s, l}; \n\tresult = Gauss_Legendre_Integration2_100pts(-1, 1, &fmultipole, &params);\n\treturn (2.*l+1.)/2.*result;\n}\n\n/********************************************************************************************************************************************************************/\n/****************\\\\Legendre Multipole with CLPT prediction\\\\*********************************************************************************************************/\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ndouble fmultipole_CLPT(double mu, void * p) \n{\n    struct my_f_params * params = (struct my_f_params *)p;\n    double s = (params->a);\n    double l = (params->b);\n    double rp = s*sqrt(1.-mu*mu);\n    double spi = s*mu;\t\t\t\t\t\t\t\t\t\t\t\t// Decomposition of S in spar (=spi) and sp=rp\n    double Xi_s= Xis_CLPT(rp,spi);\n\treturn Xi_s*gsl_sf_legendre_Pl(l,mu);\n}\n\ndouble multipole_CLPT(double s, double l)   \n{\n    double result;\n    struct my_f_params params = {s, l}; \n\tresult = Gauss_Legendre_Integration2_100pts(-1, 1, &fmultipole_CLPT, &params);\n\treturn (2.*l+1.)/2.*result;\n}\n/************************************************************************************************************************************************************************/\n/***********\\\\ Interpolation \\\\*****************************************************************************************************************************/\n\nvoid interpole(int n, char ficher[100],int vmax)\n{\n\tdouble T_x[vmax];\n\tdouble T_y[vmax];\n\tFILE* f;\n\tint i = 0;\n\tf =fopen(ficher, \"r\");\n\tfor(i=0; i < vmax; i++) fscanf(f, \"%lf %lf\\n\", &T_x[i], &T_y[i]);\n\tacc[n] = gsl_interp_accel_alloc ();\n    spline[n] = gsl_spline_alloc(gsl_interp_cspline, vmax);\n    gsl_spline_init (spline[n], T_x, T_y, vmax);\n    fclose(f);\n}\n\nvoid interpole_Xi()\n{\n\tFILE *fxi;\n\tint i;\n\tdouble Xi_x[val], Xi_f0[val], Xi_f1[val], Xi_f2[val], Xi_f1_2[val], Xi_f1_f2[val], Xi_f2_2[val];\n\t\n\tfxi = fopen(\"data/Xi_r_CLPT.dat\", \"r\");\n\tfor(i=0; i < val; i++) fscanf(fxi, \"%lf %lf %lf %lf %lf %lf %lf\\n\",&Xi_x[i], &Xi_f0[i], &Xi_f1[i], &Xi_f2[i], &Xi_f1_2[i], &Xi_f1_f2[i], &Xi_f2_2[i]); \n    acc[6] = gsl_interp_accel_alloc ();\n    spline[6] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[6], Xi_x, Xi_f0, val);\n   \tacc[7] = gsl_interp_accel_alloc ();\n    spline[7] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[7], Xi_x, Xi_f1, val);\n    acc[8] = gsl_interp_accel_alloc ();\n    spline[8] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[8], Xi_x, Xi_f2, val);\n    acc[9] = gsl_interp_accel_alloc ();\n    spline[9] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[9], Xi_x, Xi_f1_2, val);\n    acc[10] = gsl_interp_accel_alloc ();\n    spline[10] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[10], Xi_x, Xi_f1_f2, val);\n    acc[11] = gsl_interp_accel_alloc ();\n    spline[11] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[11], Xi_x, Xi_f2_2, val);\n    fclose(fxi);\n}\n\nvoid interpole_V12()\n{\n\tFILE *fv12;\n\tint i;\n\tdouble V12_x[val], V12_f0[val], V12_f1[val], V12_f2[val], V12_f1_2[val], V12_f1_f2[val];\n\t\n\tfv12 = fopen(\"data/V_12_CLPT.dat\", \"r\");\n\tfor(i=0; i < val; i++) fscanf(fv12, \"%lf %lf %lf %lf %lf %lf\\n\",&V12_x[i], &V12_f0[i], &V12_f1[i], &V12_f2[i], &V12_f1_2[i], &V12_f1_f2[i]);\n    acc[12] = gsl_interp_accel_alloc ();\n    spline[12] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[12], V12_x, V12_f0, val);\n   \tacc[13] = gsl_interp_accel_alloc ();\n    spline[13] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[13], V12_x, V12_f1, val);\n    acc[14] = gsl_interp_accel_alloc ();\n    spline[14] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[14], V12_x, V12_f2, val);\n    acc[15] = gsl_interp_accel_alloc ();\n    spline[15] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[15], V12_x, V12_f1_2, val);\n    acc[16] = gsl_interp_accel_alloc ();\n    spline[16] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[16], V12_x, V12_f1_f2, val);\n    fclose(fv12);\n}\n/*\nvoid interpole_sigma()\n{\t\n\tint i, val =150;\n\tdouble S_x[val], S_par[val], S_per[val];\n\tFILE* fx;\n   \tfx = fopen(\"../../CLPT/Sigma.dat\", \"r\");\n\tfor(i=0; i < val; i++) fscanf(fx, \"%lf %lf %lf\\n\", &S_x[i], &S_par[i], &S_per[i]);\n\tacc[8] = gsl_interp_accel_alloc ();\n    spline[8] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[8], S_x, S_par, val);\n    acc[9] = gsl_interp_accel_alloc ();\n    spline[9] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[9], S_x, S_per, val);\n    fclose(fx);\n}*/\n\nvoid interpole_sigma()\n{\t\n\tint i;\n\tdouble S_x[val], S_par_f0[val], S_par_f1[val], S_par_f2[val], S_par_f1_2[val], S_per_f0[val], S_per_f1[val], S_per_f2[val], S_per_f1_2[val];\n\tFILE* fsig;\n\t\n   \tfsig = fopen(\"data/Sigma_12_CLPT.dat\", \"r\");\n\tfor(i=0; i<val; i++) fscanf(fsig, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf\\n\", &S_x[i], &S_par_f0[i], &S_par_f1[i], &S_par_f2[i], &S_par_f1_2[i], &S_per_f0[i], &S_per_f1[i], &S_per_f2[i], &S_per_f1_2[i]);\n   acc[17] = gsl_interp_accel_alloc ();\n    spline[17] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[17], S_x, S_par_f0, val);\n   \tacc[18] = gsl_interp_accel_alloc ();\n    spline[18] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[18], S_x, S_par_f1, val);\n    acc[19] = gsl_interp_accel_alloc ();\n    spline[19] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[19], S_x, S_par_f2, val);\n    acc[20] = gsl_interp_accel_alloc ();\n    spline[20] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[20], S_x, S_par_f1_2, val);\n       acc[21] = gsl_interp_accel_alloc ();\n    spline[21] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[21], S_x, S_per_f0, val);\n   \tacc[22] = gsl_interp_accel_alloc ();\n    spline[22] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[22], S_x, S_per_f1, val);\n    acc[23] = gsl_interp_accel_alloc ();\n    spline[23] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[23], S_x, S_per_f2, val);\n    acc[24] = gsl_interp_accel_alloc ();\n    spline[24] = gsl_spline_alloc(gsl_interp_cspline, val);\n    gsl_spline_init (spline[24], S_x, S_per_f1_2, val);\n    fclose(fsig);\n}\n\n/***********************************************************************************************************************************************************************/\n/************\\\\Count the number of ligne in a file\\\\********************************************************************************************************************/\n\nint compte(FILE *fichier)\n{\n\tint c;\n\tint nLignes = 0;\n\tint c2 = '\\0';\n\twhile((c=fgetc(fichier)) != EOF){\tif(c=='\\n')\tnLignes++;\tc2 = c;}\n\tif(c2 != '\\n') nLignes++;  \n\treturn nLignes;\n}\n\n/************************************************************************************************************************************************************************/\n/******\\\\Write in a file\\\\***********************************************************************************************************************************************/\n\nvoid write(char f[], double func(double))\n{    \n\tdouble spi;\n\tFILE* fi;\n    fi = fopen(f,\"w+\"); \t\t\t  \n    for(spi=smin; spi<smax; spi+=0.5)\tfprintf(fi,\"%le %le\\n\", spi, func(spi));\n    fclose(fi);\n}\n\n/******************************************************************************************************************************************************************/\n/***************\\\\MAIN FUNCTION\\\\**********************************************************************************************************************************/\nint main (int argc, char *argv[])\n{\t\n\tdouble spi,sp,li;\n    int i, nLignes;\n\tFILE *fi, *par, *ps, *f;\n\tchar file[BUFSIZ];\n/*\t\n\tsig_shift = 0;\n\tb = 1;\n\tfg = 0.820165;\n\tf1 = atof(argv[1]);\n\tf2 = atof(argv[2]);\n\tsmin=2.5;\n\tsmax=158;\n\tval=160;\n//\tprintf(\"f1=%lf f2=%lf\\n\",f1,f2);\n//\tchar* file = \"power_spec_EBOSS.txt\";*/\n\tpar = fopen(argv[1],\"r\");  \n\t\n// Check parameter file\n\tif (argc ==2 && par!=0) EXIT_SUCCESS;\t\t\t\t\t\t\t\t\t\t\t\n\telse {\n\t\tprintf(\"Wrong parameter file\\n\"); \n\t\treturn EXIT_FAILURE;\n\t}\n\t\t\t\n// Read parameter file\n\tfscanf(par,\"%*s %lf\\n\", &smin);\n\tfscanf(par,\"%*s %lf\\n\", &smax);\n\tfscanf(par,\"%*s %lf\\n\", &b);\n\tfscanf(par,\"%*s %lf\\n\", &fg);\n\tfscanf(par,\"%*s %lf\\n\", &f1);\n\tfscanf(par,\"%*s %lf\\n\", &f2);\n\tfscanf(par,\"%*s %lf\\n\", &sig_shift);\n\tfscanf(par,\"%*s %s\\n\",file);\n\t\n//Check smin and smax\n\tli = (smax-smin)/0.5;\n\tif (li<0){ \n\t\tprintf(\"wrong parameters smin/smax\");\n\t\treturn EXIT_FAILURE;\n\t\t}\n\t\t\n// Count number of lines\n\tps = fopen(file, \"r\"); \n\tif (ps!=0){\n\t\tnLignes = compte(ps);\n\t\t} \n\telse {\n\t\tprintf(\"Error openning power spectrum file.\\n\");\n\t\treturn 1;\n\t}\n\n// Read kmin and kmax\t\n\trewind(ps);\n\tkmin=1e30;\n\tkmax=0;\t\t\n\tfor(i=0; i < nLignes; i++) {\n\t\tdouble va;\n\t\tfscanf(ps, \"%lf %*f\\n\", &va);\n\t\tif (va<kmin) kmin=va;\n\t\tif (va>kmax) kmax=va;\n\t}\n\tfclose(ps);\n\tlk = kmax-kmin;\t\n// Interpolation of power spectrum file\n\tinterpole(1,file, nLignes);    \n\n\tsig8=1.;\n\tsigv = Sigmav();\n//\tprintf(\"s8=%lf\\n\",sig8);\n\n// Compute and save functions in text files\t\n\twrite(\"data/Xim.dat\",Xim);\n    write(\"data/V12.dat\",V12);\n    write(\"data/Psiper.dat\",Psiper);\n    write(\"data/Psipar.dat\",Psipar);\n\n    interpole(2,\"data/Xim.dat\", li); \n    interpole(3,\"data/V12.dat\", li); \t\t\n    interpole(4,\"data/Psiper.dat\", li); \n    interpole(5,\"data/Psipar.dat\", li); \n\n\tinterpole_Xi();\n\tinterpole_V12();\n\tinterpole_sigma();\n\t\n\n\n//\tMultipoles calculation \n\tfi = fopen(\"data/multipole.dat\",\"w+\"); \t;     \n\tprintf(\"Calcul des multipoles\\n\");\n\tfor(spi=smin; spi<smax; spi+=1){     \t\t                \n\t\tdouble xi0=sig8*multipole(spi,0); \n\t\tdouble xi2=sig8*multipole(spi,2);\n\t\tdouble xi4=sig8*multipole(spi,4);          \n\t\tfprintf(fi,\"%le %le %le %le\\n\", spi, xi0, xi2, xi4);\n\t}\n\tfclose(fi);\t\t\n\n\tfi = fopen(\"data/multipole_CLPT.dat\",\"w+\");     \n\tprintf(\"Calcul des  multipoles CLPT\\n\");\n\tfor(spi=smin; spi<smax; spi+=1){     \t\t                \n\t\tdouble xi0=multipole_CLPT(spi,0); \n\t\tdouble xi2=multipole_CLPT(spi,2);\n\t\tdouble xi4=multipole_CLPT(spi,4);          \n\t\t//printf(\"%lf %lf %lf \", spi, xi0, xi2);\n\t\tfprintf(fi,\"%lf %lf %lf %lf\\n\", spi, xi0, xi2,xi4);\n\t}\n\tfclose(fi);\n\n\t//Correlation function Xi_s(spar,sper)\n\tf = fopen(\"data/Xi_s.dat\",\"w+\");       \n    printf(\"Calcul de Xis\\n\");\t  \n    for(spi=smin; spi<smax; spi+=0.1){   \n   \t\tfor(sp=smin; sp<smax; sp+=0.1){                         \n\t\t \tdouble V=Xis(sp,spi);           \n\t\t \tfprintf(f,\"%le %le %le\\n\",sp, spi, V);\n     \t}\n     }\n    fclose(f);\n\n\tf = fopen(\"data/Xi_s_CLPT.dat\",\"w+\");       \n    printf(\"Calcul de Xis_CLPT\\n\");       \t\t\t  \n    for(spi=smin; spi<smax; spi+=0.1){   \n   \t\tfor(sp=smin; sp<smax; sp+=0.1){                         \n\t\t \tdouble V=Xis_CLPT(sp,spi);           \n\t\t \tfprintf(f,\"%le %le %le\\n\",sp, spi, V);\n     \t}\n     }\n    fclose(f);\n\n    for (i=0; i<25; i++){\n    \tgsl_spline_free (spline[i]);\n   \t\tgsl_interp_accel_free (acc[i]);\n   \t}\n   \t\t\n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "b1378da78315290cc1aa23d2b77ca0698c3fbb52", "size": 32273, "ext": "c", "lang": "C", "max_stars_repo_path": "Code_RSD_GS.c", "max_stars_repo_name": "antoine-rocher/Master-2-internship", "max_stars_repo_head_hexsha": "39f2422f922b007351ba94ba69d05b87cc6ec9a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T14:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T10:33:28.000Z", "max_issues_repo_path": "Code_RSD_GS.c", "max_issues_repo_name": "antoine-rocher/Master-2-internship", "max_issues_repo_head_hexsha": "39f2422f922b007351ba94ba69d05b87cc6ec9a0", "max_issues_repo_licenses": ["MIT"], "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_RSD_GS.c", "max_forks_repo_name": "antoine-rocher/Master-2-internship", "max_forks_repo_head_hexsha": "39f2422f922b007351ba94ba69d05b87cc6ec9a0", "max_forks_repo_licenses": ["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.180875576, "max_line_length": 201, "alphanum_fraction": 0.524865987, "num_tokens": 9379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.37881543535175627}}
{"text": "/* ode-initval/gear2.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Gear 2 */\n\n/* Author:  G. Jungman\n */\n#include <config.h>\n#include <stdlib.h>\n#include <string.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include \"odeiv_util.h\"\n#include \"gsl_odeiv.h\"\n\n\n/* gear2 state object */\ntypedef struct {\n  int primed;                /* flag indicating that yim1 is ready */\n  double t_primed;           /* system was primed for this value of t */\n  double last_h;             /* last step size */\n  gsl_odeiv_step * primer;   /* stepper to use for priming */\n  double * yim1;             /* y_{i-1}    */\n  double * k;                /* work space */\n  double * y0;               /* work space */\n  int stutter;\n}\ngear2_state_t;\n\nstatic void *\ngear2_alloc (size_t dim)\n{\n  gear2_state_t *state = (gear2_state_t *) malloc (sizeof (gear2_state_t));\n\n  if (state == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for gear2_state\", GSL_ENOMEM);\n    }\n\n  state->yim1 = (double *) malloc (dim * sizeof (double));\n\n  if (state->yim1 == 0)\n    {\n      free (state);\n      GSL_ERROR_NULL (\"failed to allocate space for yim1\", GSL_ENOMEM);\n    }\n\n  state->k = (double *) malloc (dim * sizeof (double));\n\n  if (state->k == 0)\n    {\n      free (state->yim1);\n      free (state);\n      GSL_ERROR_NULL (\"failed to allocate space for k\", GSL_ENOMEM);\n    }\n\n  state->y0 = (double *) malloc (dim * sizeof (double));\n\n  if (state->y0 == 0)\n    {\n      free (state->k);\n      free (state->yim1);\n      free (state);\n      GSL_ERROR_NULL (\"failed to allocate space for y0\", GSL_ENOMEM);\n    }\n\n  state->primed = 0;\n  state->primer = gsl_odeiv_step_alloc (gsl_odeiv_step_rk4imp, dim);\n  state->last_h = 0.0;\n\n  return state;\n}\n\nstatic int\ngear2_apply(void * vstate,\n            size_t dim,\n            double t,\n            double h,\n            double y[],\n            double yerr[],\n            const double dydt_in[],\n            double dydt_out[],\n            const gsl_odeiv_system * sys)\n{\n  gear2_state_t *state = (gear2_state_t *) vstate;\n\n  state->stutter = 0;\n\n  if(state->primed == 0 || t == state->t_primed || h != state->last_h) {\n\n    /* Execute a single-step method to prime the process.  Note that\n     * we do this if the step size changes, so frequent step size\n     * changes will cause the method to stutter. \n     * \n     * Note that we reuse this method if the time has not changed,\n     * which can occur when the adaptive driver is attempting to find\n     * an appropriate step-size on its first iteration */\n\n    int status;\n    DBL_MEMCPY(state->yim1, y, dim);\n    \n    status = gsl_odeiv_step_apply(state->primer, t, h, y, yerr, dydt_in, dydt_out, sys);\n\n    /* Make note of step size and indicate readiness for a Gear step. */\n\n    state->primed = 1;\n    state->t_primed = t;\n    state->last_h = h;\n    state->stutter = 1;\n\n    return status;\n  } else {\n    /* We have a previous y value in the buffer, and the step\n     * sizes match, so we go ahead with the Gear step.\n     */\n\n    double * const k  = state->k;\n    double * const y0 = state->y0;\n    double * const yim1 = state->yim1;\n\n    const int iter_steps = 3;\n    int status = 0;\n    int nu;\n    size_t i;\n\n    DBL_MEMCPY(y0, y, dim);\n\n    /* iterative solution */\n\n    if(dydt_out != NULL) {\n      DBL_MEMCPY(k, dydt_out, dim);\n    }\n\n    for(nu=0; nu<iter_steps; nu++) {\n      int s = GSL_ODEIV_FN_EVAL(sys, t + h, y, k);\n      GSL_STATUS_UPDATE(&status, s);\n      for(i=0; i<dim; i++) {\n        y[i] = ((4.0 * y0[i] - yim1[i]) + 2.0 * h * k[i]) / 3.0;\n      }\n    }\n\n    /* Estimate error and update the state buffer. */\n    for(i=0; i<dim; i++) {\n      yerr[i] = h * h * (y[i] - y0[i]); /* error is third order */\n      yim1[i] = y0[i];\n    }\n\n    /* Make note of step size. */\n    state->last_h = h;\n\n    return status;\n  }\n}\n\nstatic int\ngear2_reset(void * vstate, size_t dim)\n{\n  gear2_state_t *state = (gear2_state_t *) vstate;\n\n  DBL_ZERO_MEMSET (state->yim1, dim);\n  DBL_ZERO_MEMSET (state->k, dim);\n  DBL_ZERO_MEMSET (state->y0, dim);\n\n  state->primed = 0;\n  state->last_h = 0.0;\n  return GSL_SUCCESS;\n}\n\nstatic unsigned int\ngear2_order (void *vstate)\n{\n  gear2_state_t *state = (gear2_state_t *) vstate;\n  state = 0; /* prevent warnings about unused parameters */\n  return 3;\n}\n\nstatic void\ngear2_free(void *vstate)\n{\n  gear2_state_t *state = (gear2_state_t *) vstate;\n\n  free(state->yim1);\n  free(state->k);\n  free(state->y0);\n  gsl_odeiv_step_free(state->primer);\n\n  free(state);\n}\n\nstatic const gsl_odeiv_step_type gear2_type = { \"gear2\",\t/* name */\n  1,\t\t\t\t/* can use dydt_in */\n  0,\t\t\t\t/* gives exact dydt_out */\n  &gear2_alloc,\n  &gear2_apply,\n  &gear2_reset,\n  &gear2_order,\n  &gear2_free\n};\n\nconst gsl_odeiv_step_type *gsl_odeiv_step_gear2 = &gear2_type;\n", "meta": {"hexsha": "3c49d286cd19c66d13e0cef2b731aff3e263704a", "size": 5488, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/ode-initval/gear2.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/ode-initval/gear2.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/ode-initval/gear2.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.2903225806, "max_line_length": 88, "alphanum_fraction": 0.6155247813, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3786345880682296}}
{"text": "#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_poly.h>\n\nvoid mgsl_poly_complex_eval(const double c[], const int len, const gsl_complex *z, gsl_complex *ret)\n{\n  *ret = gsl_poly_complex_eval(c, len, *z);\n}\n\nvoid mgsl_complex_poly_complex_eval(gsl_complex **c, const int len, const gsl_complex *z, gsl_complex *ret)\n{\n  gsl_complex *zc = calloc(len, sizeof(gsl_complex));\n  int i;\n  for(i=0; i<len; i++) zc[i] = *c[i];\n  *ret = gsl_complex_poly_complex_eval(zc, len, *z);\n}\n", "meta": {"hexsha": "4f2bb4e56539be07dd19e4db2c8050169352b65c", "size": 506, "ext": "c", "lang": "C", "max_stars_repo_path": "src/polynomial.c", "max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Polynomial", "max_stars_repo_head_hexsha": "0695d9d36be997c6805bc68afd64e178cbd96f8f", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomial.c", "max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Polynomial", "max_issues_repo_head_hexsha": "0695d9d36be997c6805bc68afd64e178cbd96f8f", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomial.c", "max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Polynomial", "max_forks_repo_head_hexsha": "0695d9d36be997c6805bc68afd64e178cbd96f8f", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7647058824, "max_line_length": 107, "alphanum_fraction": 0.7134387352, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3785266545896734}}
{"text": "/* linalg/test_common.c\n *\n * Copyright (C) 2017, 2018, 2019, 2020 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_rng.h>\n\nstatic int create_random_vector(gsl_vector * v, gsl_rng * r);\nstatic int create_random_matrix(gsl_matrix * m, gsl_rng * r);\nstatic int create_posdef_matrix(gsl_matrix * m, gsl_rng * r);\nstatic int create_hilbert_matrix2(gsl_matrix * m);\n\nstatic int\ncreate_random_vector(gsl_vector * v, gsl_rng * r)\n{\n  const size_t N = v->size;\n  size_t i;\n\n  for (i = 0; i < N; ++i)\n    {\n      double vi = gsl_rng_uniform(r);\n      gsl_vector_set(v, i, vi);\n    }\n\n  return GSL_SUCCESS;\n}\n\nstatic int\ncreate_random_complex_vector(gsl_vector_complex * v, gsl_rng * r)\n{\n  const size_t N = v->size;\n  size_t i;\n\n  for (i = 0; i < N; ++i)\n    {\n      gsl_complex vi;\n      GSL_REAL(vi) = gsl_rng_uniform(r);\n      GSL_IMAG(vi) = gsl_rng_uniform(r);\n      gsl_vector_complex_set(v, i, vi);\n    }\n\n  return GSL_SUCCESS;\n}\n\nstatic int\ncreate_random_matrix(gsl_matrix * m, gsl_rng * r)\n{\n  const size_t M = m->size1;\n  const size_t N = m->size2;\n  size_t i, j;\n\n  for (i = 0; i < M; ++i)\n    {\n      for (j = 0; j < N; ++j)\n        {\n          double mij = gsl_rng_uniform(r);\n          gsl_matrix_set(m, i, j, mij);\n        }\n    }\n\n  return GSL_SUCCESS;\n}\n\nstatic int\ncreate_random_complex_matrix(gsl_matrix_complex * m, gsl_rng * r)\n{\n  const size_t M = m->size1;\n  const size_t N = m->size2;\n  size_t i, j;\n\n  for (i = 0; i < M; ++i)\n    {\n      for (j = 0; j < N; ++j)\n        {\n          gsl_complex mij;\n\n          GSL_REAL(mij) = gsl_rng_uniform(r);\n          GSL_IMAG(mij) = gsl_rng_uniform(r);\n\n          gsl_matrix_complex_set(m, i, j, mij);\n        }\n    }\n\n  return GSL_SUCCESS;\n}\n\nstatic int\ncreate_symm_matrix(gsl_matrix * m, gsl_rng * r)\n{\n  const size_t N = m->size1;\n  size_t i, j;\n\n  for (i = 0; i < N; ++i)\n    {\n      for (j = 0; j <= i; ++j)\n        {\n          double mij = gsl_rng_uniform(r);\n          gsl_matrix_set(m, i, j, mij);\n        }\n    }\n\n  /* copy lower triangle to upper */\n  gsl_matrix_transpose_tricpy(CblasLower, CblasUnit, m, m);\n\n  return GSL_SUCCESS;\n}\n\nstatic int\ncreate_herm_matrix(gsl_matrix_complex * m, gsl_rng * r)\n{\n  const size_t N = m->size1;\n  size_t i, j;\n\n  for (i = 0; i < N; ++i)\n    {\n      for (j = 0; j <= i; ++j)\n        {\n          double re = gsl_rng_uniform(r);\n          double im = (i != j) ? gsl_rng_uniform(r) : 0.0;\n          gsl_complex z = gsl_complex_rect(re, im);\n\n          gsl_matrix_complex_set(m, i, j, z);\n\n          if (i != j)\n            gsl_matrix_complex_set(m, j, i, gsl_complex_conjugate(z));\n        }\n    }\n\n  return GSL_SUCCESS;\n}\n\n/* create symmetric banded matrix with p sub/super-diagonals */\nstatic int\ncreate_symm_band_matrix(const size_t p, gsl_matrix * m, gsl_rng * r)\n{\n  size_t i;\n\n  gsl_matrix_set_zero(m);\n\n  for (i = 0; i < p + 1; ++i)\n    {\n      gsl_vector_view subdiag = gsl_matrix_subdiagonal(m, i);\n      create_random_vector(&subdiag.vector, r);\n\n      if (i > 0)\n        {\n          gsl_vector_view superdiag = gsl_matrix_superdiagonal(m, i);\n          gsl_vector_memcpy(&superdiag.vector, &subdiag.vector);\n        }\n    }\n\n  return GSL_SUCCESS;\n}\n\n/* create (p,q) banded matrix */\nstatic int\ncreate_band_matrix(const size_t p, const size_t q, gsl_matrix * m, gsl_rng * r)\n{\n  size_t i;\n\n  gsl_matrix_set_zero(m);\n\n  for (i = 0; i <= p; ++i)\n    {\n      gsl_vector_view v = gsl_matrix_subdiagonal(m, i);\n      create_random_vector(&v.vector, r);\n    }\n\n  for (i = 1; i <= q; ++i)\n    {\n      gsl_vector_view v = gsl_matrix_superdiagonal(m, i);\n      create_random_vector(&v.vector, r);\n    }\n\n  return GSL_SUCCESS;\n}\n\nstatic int\ncreate_posdef_matrix(gsl_matrix * m, gsl_rng * r)\n{\n  const size_t N = m->size1;\n  const double alpha = 10.0 * N;\n  size_t i;\n\n  /* The idea is to make a symmetric diagonally dominant\n   * matrix. Make a symmetric matrix and add alpha*I to\n   * its diagonal */\n\n  create_symm_matrix(m, r);\n\n  for (i = 0; i < N; ++i)\n    {\n      double mii = gsl_matrix_get(m, i, i);\n      gsl_matrix_set(m, i, i, mii + alpha);\n    }\n\n  return GSL_SUCCESS;\n}\n\nstatic int\ncreate_posdef_complex_matrix(gsl_matrix_complex *m, gsl_rng *r)\n{\n  const size_t N = m->size1;\n  const double alpha = 10.0 * N;\n  size_t i;\n\n  create_herm_matrix(m, r);\n\n  for (i = 0; i < N; ++i)\n    {\n      gsl_complex * mii = gsl_matrix_complex_ptr(m, i, i);\n      GSL_REAL(*mii) += alpha;\n    }\n\n  return GSL_SUCCESS;\n}\n\nstatic int\ncreate_hilbert_matrix2(gsl_matrix * m)\n{\n  const size_t N = m->size1;\n  size_t i, j;\n\n  for (i = 0; i < N; i++)\n    {\n      for (j = 0; j < N; j++)\n        {\n          gsl_matrix_set(m, i, j, 1.0/(i+j+1.0));\n        }\n    }\n\n  return GSL_SUCCESS;\n}\n\nstatic int\ncreate_posdef_band_matrix(const size_t p, gsl_matrix * m, gsl_rng * r)\n{\n  const size_t N = m->size1;\n  const double alpha = 10.0 * N;\n  size_t i;\n\n  /* The idea is to make a symmetric diagonally dominant\n   * matrix. Make a symmetric matrix and add alpha*I to\n   * its diagonal */\n\n  create_symm_band_matrix(p, m, r);\n\n  for (i = 0; i < N; ++i)\n    {\n      double *mii = gsl_matrix_ptr(m, i, i);\n      *mii += alpha;\n    }\n\n  return GSL_SUCCESS;\n}\n\n/* transform dense symmetric banded matrix to compact form, with bandwidth p */\nstatic int\nsymm2band_matrix(const size_t p, const gsl_matrix * m, gsl_matrix * bm)\n{\n  const size_t N = m->size1;\n\n  if (bm->size1 != N)\n    {\n      GSL_ERROR(\"banded matrix requires N rows\", GSL_EBADLEN);\n    }\n  else if (bm->size2 != p + 1)\n    {\n      GSL_ERROR(\"banded matrix requires p + 1 columns\", GSL_EBADLEN);\n    }\n  else\n    {\n      size_t i;\n\n      gsl_matrix_set_zero(bm);\n\n      for (i = 0; i < p + 1; ++i)\n        {\n          gsl_vector_const_view diag = gsl_matrix_const_subdiagonal(m, i);\n          gsl_vector_view v = gsl_matrix_subcolumn(bm, i, 0, N - i);\n\n          gsl_vector_memcpy(&v.vector, &diag.vector);\n        }\n\n      return GSL_SUCCESS;\n    }\n}\n\n/* transform general dense (p,q) banded matrix to compact banded form */\nstatic int\ngen2band_matrix(const size_t p, const size_t q, const gsl_matrix * A, gsl_matrix * AB)\n{\n  const size_t N = A->size2;\n\n  if (AB->size1 != N)\n    {\n      GSL_ERROR(\"banded matrix requires N rows\", GSL_EBADLEN);\n    }\n  else if (AB->size2 != 2*p + q + 1)\n    {\n      GSL_ERROR(\"banded matrix requires 2*p + q + 1 columns\", GSL_EBADLEN);\n    }\n  else\n    {\n      size_t i;\n\n      gsl_matrix_set_zero(AB);\n\n      /* copy diagonal and subdiagonals */\n      for (i = 0; i <= p; ++i)\n        {\n          gsl_vector_const_view v = gsl_matrix_const_subdiagonal(A, i);\n          gsl_vector_view w = gsl_matrix_subcolumn(AB, p + q + i, 0, v.vector.size);\n          gsl_vector_memcpy(&w.vector, &v.vector);\n        }\n\n      /* copy superdiagonals */\n      for (i = 1; i <= q; ++i)\n        {\n          gsl_vector_const_view v = gsl_matrix_const_superdiagonal(A, i);\n          gsl_vector_view w = gsl_matrix_subcolumn(AB, p + q - i, i, v.vector.size);\n          gsl_vector_memcpy(&w.vector, &v.vector);\n        }\n\n      return GSL_SUCCESS;\n    }\n}\n", "meta": {"hexsha": "aece28edc02caa3cdaac17497425680fc6e161a9", "size": 7874, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_common.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_common.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_common.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 22.6264367816, "max_line_length": 86, "alphanum_fraction": 0.6098552197, "num_tokens": 2360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.37831120261812573}}
{"text": "/*\n  @copyright Russell Standish 2000-2013\n  @author Russell Standish\n  This file is part of EcoLab\n\n  Open source licensed under the MIT license. See LICENSE for details.\n*/\n\n/**\\file\n\\brief random generator based on GNUSL implementation\n*/\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\nnamespace ecolab\n{\n\n  class urand: public random_gen\n  {\n    void operator=(urand&);\n    CLASSDESC_ACCESS(urand);\n  public:\n    gsl_rng *gen;\n    urand(const gsl_rng_type *descr=gsl_rng_mt19937) {gen=gsl_rng_alloc(descr);}\n    ~urand() {gsl_rng_free(gen);}\n    void Seed(int s) {gsl_rng_set(gen,s);}\n    void seed(TCL_args args) {Seed(args);}\n    double rand();\n    /* select a different uniform random generator according the GSL's rng\n       string interface */\n    void set_gen(TCL_args args); \n    void Set_gen(const string& descr)\n    {\n      static const gsl_rng_type ** rngTypes=gsl_rng_types_setup();\n      const gsl_rng_type **g=rngTypes;\n      for (; *g; ++g)\n        if (descr==(*g)->name)\n          {\n            gsl_rng_free(gen);\n            gen=gsl_rng_alloc(*g);\n            break;\n          }\n      if (!*g) throw error(\"Cannot create generator %s\",descr.c_str());\n    }\n  };\n\n  class gaussrand: public random_gen\n  {\n    void operator=(gaussrand&);\n    CLASSDESC_ACCESS(gaussrand);\n  public:\n    urand uni;\n    double rand();\n  };\n}\n\n /* don't attempt to send these objects over the wire ! */\n#ifdef CLASSDESC\n#pragma omit pack  ecolab::urand \n#pragma omit unpack  ecolab::urand \n#endif\nnamespace classdesc_access\n{\n  template <>\n  struct access_pack<ecolab::urand>: \n    public classdesc::NullDescriptor<classdesc::pack_t> {};\n  template <>\n  struct access_unpack<ecolab::urand>: \n    public classdesc::NullDescriptor<classdesc::unpack_t> {};\n  template <>\n  struct access_pack<ecolab::urand*>: \n    public classdesc::NullDescriptor<classdesc::pack_t> {};\n  template <>\n  struct access_unpack<ecolab::urand*>: \n    public classdesc::NullDescriptor<classdesc::unpack_t> {};\n}\n", "meta": {"hexsha": "da5da2713880841112bb32f237539b4b250e828f", "size": 1991, "ext": "h", "lang": "C", "max_stars_repo_path": "include/random_gsl.h", "max_stars_repo_name": "digiperfect/ecolab", "max_stars_repo_head_hexsha": "52751dfa805b67b775ea50e37c5d02c2735ed0d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-04-19T15:02:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T05:03:56.000Z", "max_issues_repo_path": "include/random_gsl.h", "max_issues_repo_name": "digiperfect/ecolab", "max_issues_repo_head_hexsha": "52751dfa805b67b775ea50e37c5d02c2735ed0d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-01-17T21:14:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-28T13:18:28.000Z", "max_forks_repo_path": "include/random_gsl.h", "max_forks_repo_name": "digiperfect/ecolab", "max_forks_repo_head_hexsha": "52751dfa805b67b775ea50e37c5d02c2735ed0d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T20:32:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-29T19:11:21.000Z", "avg_line_length": 25.8571428571, "max_line_length": 80, "alphanum_fraction": 0.6654947263, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.3783111940219658}}
{"text": "#include <math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n#include <galpy_potentials.h>\n// MovingObjectPotential\n// 3 arguments: amp, t0, tf\nvoid constrain_range(double * d) {\n  // Constrains index to be within interpolation range\n  if (*d < 0) *d = 0.0;\n  if (*d > 1) *d = 1.0;\n}\ndouble MovingObjectPotentialRforce(double R,double z, double phi,\n\t\t\t\t   double t,\n\t\t\t\t   struct potentialArg * potentialArgs){\n  double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z, Rdist,RF;\n  double * args= potentialArgs->args;\n  //Get args\n  amp= *args;\n  t0= *(args+1);\n  tf= *(args+2);\n  d_ind= (t-t0)/(tf-t0);\n  x= R*cos(phi);\n  y= R*sin(phi);\n  constrain_range(&d_ind);\n  // Interpolate x, y, z\n  obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);\n  obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,\n\t\t\t *(potentialArgs->acc1d+1));\n  obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,\n\t\t\t *(potentialArgs->acc1d+2));\n  Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);\n  // Calculate R force\n  RF= calcRforce(Rdist,(obj_z-z),phi,t,potentialArgs->nwrapped,\n\t\t potentialArgs->wrappedPotentialArg);\n  return -amp*RF*(cos(phi)*(obj_x-x)+sin(phi)*(obj_y-y))/Rdist;\n}\n\ndouble MovingObjectPotentialzforce(double R,double z,double phi,\n\t\t\t\t      double t,\n\t\t\t\t      struct potentialArg * potentialArgs){\n  double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z, Rdist;\n  double * args= potentialArgs->args;\n  //Get args\n  amp= *args;\n  t0= *(args+1);\n  tf= *(args+2);\n  d_ind= (t-t0)/(tf-t0);\n  x= R*cos(phi);\n  y= R*sin(phi);\n  constrain_range(&d_ind);\n  // Interpolate x, y, z\n  obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);\n  obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,\n\t\t\t *(potentialArgs->acc1d+1));\n  obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,\n\t\t\t *(potentialArgs->acc1d+2));\n  Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);\n  // Calculate z force\n  return -amp * calczforce(Rdist,(obj_z-z),phi,t,potentialArgs->nwrapped,\n\t\t\t   potentialArgs->wrappedPotentialArg);\n}\n\ndouble MovingObjectPotentialphiforce(double R,double z,double phi,\n\t\t\t\t\tdouble t,\n\t\t\t\t\tstruct potentialArg * potentialArgs){\n  double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z, Rdist,RF;\n  double * args= potentialArgs->args;\n  //Get args\n  amp= *args;\n  t0= *(args+1);\n  tf= *(args+2);\n  d_ind= (t-t0)/(tf-t0);\n  x= R*cos(phi);\n  y= R*sin(phi);\n  constrain_range(&d_ind);\n  // Interpolate x, y, z\n  obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);\n  obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,\n\t\t\t *(potentialArgs->acc1d+1));\n  obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,\n\t\t\t *(potentialArgs->acc1d+2));\n  Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);\n  // Calculate phiforce\n  RF= calcRforce(Rdist,(obj_z-z),phi,t,potentialArgs->nwrapped,\n\t\t potentialArgs->wrappedPotentialArg);\n  return -amp*RF*R*(cos(phi)*(obj_y-y)-sin(phi)*(obj_x-x))/Rdist;\n}\n\ndouble MovingObjectPotentialPlanarRforce(double R, double phi,\n\t\t\t\t      double t,\n\t\t\t\t      struct potentialArg * potentialArgs){\n  double amp,t0,tf,d_ind,x,y,obj_x,obj_y,Rdist,RF;\n  double * args= potentialArgs->args;\n  //Get args\n  amp= *args;\n  t0= *(args+1);\n  tf= *(args+2);\n  d_ind= (t-t0)/(tf-t0);\n  x= R*cos(phi);\n  y= R*sin(phi);\n  constrain_range(&d_ind);\n  // Interpolate x, y\n  obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);\n  obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,\n\t\t\t *(potentialArgs->acc1d+1));\n  Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);\n  // Calculate R force\n  RF= calcPlanarRforce(Rdist, phi, t, potentialArgs->nwrapped,\n\t\t       potentialArgs->wrappedPotentialArg);\n  return -amp*RF*(cos(phi)*(obj_x-x)+sin(phi)*(obj_y-y))/Rdist;\n}\n\ndouble MovingObjectPotentialPlanarphiforce(double R, double phi,\n\t\t\t\t\tdouble t,\n\t\t\t\t\tstruct potentialArg * potentialArgs){\n  double amp,t0,tf,d_ind,x,y,obj_x,obj_y,Rdist,RF;\n  double * args= potentialArgs->args;\n  // Get args\n  amp= *args;\n  t0= *(args+1);\n  tf= *(args+2);\n  d_ind= (t-t0)/(tf-t0);\n  x= R*cos(phi);\n  y= R*sin(phi);\n  constrain_range(&d_ind);\n  // Interpolate x, y\n  obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);\n  obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,\n\t\t\t *(potentialArgs->acc1d+1));\n  Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);\n  // Calculate phiforce\n  RF= calcPlanarRforce(Rdist, phi, t, potentialArgs->nwrapped,\n\t\t       potentialArgs->wrappedPotentialArg);\n  return -amp*RF*R*(cos(phi)*(obj_y-y)-sin(phi)*(obj_x-x))/Rdist;\n}\n", "meta": {"hexsha": "dee65196a6f1f4469b290f71e3742415325b17ab", "size": 4592, "ext": "c", "lang": "C", "max_stars_repo_path": "galpy/potential/potential_c_ext/MovingObjectPotential.c", "max_stars_repo_name": "gusbeane/galpy", "max_stars_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 147.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:06:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T14:47:41.000Z", "max_issues_repo_path": "galpy/potential/potential_c_ext/MovingObjectPotential.c", "max_issues_repo_name": "gusbeane/galpy", "max_issues_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 269.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T15:58:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T18:42:08.000Z", "max_forks_repo_path": "galpy/potential/potential_c_ext/MovingObjectPotential.c", "max_forks_repo_name": "gusbeane/galpy", "max_forks_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 110.0, "max_forks_repo_forks_event_min_datetime": "2015-02-08T10:57:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T07:56:49.000Z", "avg_line_length": 33.7647058824, "max_line_length": 79, "alphanum_fraction": 0.6744337979, "num_tokens": 1566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.37821620984145304}}
{"text": "/* \n** Various utilities for LISA algorithm\n**\n** G.Lohmann, Jan 2017\n*/\n#include <viaio/VImage.h>\n#include <viaio/Vlib.h>\n#include <viaio/mu.h>\n#include <viaio/option.h>\n\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <stdlib.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_histogram.h>\n\n\n#define SQR(x) ((x)*(x))\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\nextern float kth_smallest(float *a, size_t n, size_t k);\n#define Median(a,n) kth_smallest(a,n,(((n)&1)?((n)/2):(((n)/2)-1)))\n\n\n\n/* update histogram */\nvoid HistoUpdate(VImage src1,gsl_histogram *hist)\n{\n  float u,tiny = 1.0e-6;\n  size_t i;\n  float xmin = gsl_histogram_min (hist);\n  float xmax = gsl_histogram_max (hist);\n\n  float *pp1 = VImageData(src1);\n  for (i=0; i<VImageNPixels(src1); i++) {\n    u = *pp1++;\n    if (ABS(u) < tiny) continue;\n    if (u > xmax) u = xmax-tiny;\n    if (u < xmin) u = xmin+tiny;\n    gsl_histogram_increment (hist,u);\n  }\n}\n\n\n\n/* In moderately skewed or asymmetrical distribution (Pearson) */\nfloat VGetMode(VImage src)\n{\n  size_t i,n=0;\n  float u,tiny=1.0e-8;\n  VFloat *pp = VImageData(src);\n  for (i=0; i<VImageNPixels(src); i++) {\n    u = (*pp++);\n    if (fabs(u) > tiny) n++;\n  }\n  float *data = (float *) VCalloc(n,sizeof(float));\n  \n  double sum=0,nx=0;\n  n=0;\n  pp = VImageData(src);\n  for (i=0; i<VImageNPixels(src); i++) {\n    u = (*pp++);\n    if (fabs(u) > tiny) { \n      data[n] = u;\n      sum += u;\n      n++;\n    }\n  }\n  nx = (double)n;\n  float median = Median(data,n);\n  float mean = (float)(sum/nx);\n  float mode = 3.0*median - 2.0*mean;\n  /* fprintf(stderr,\" mean: %f,  median: %f,  mode: %f\\n\",mean,median,mode); */\n  VFree(data);\n  return mode;\n}\n\n\n\n/* scale z-values */\nvoid VZScale(VImage src,float mode,float stddev)\n{\n  size_t i=0;\n  float u=0,tiny=1.0e-8;\n  VFloat *pp=VImageData(src);\n  for (i=0; i<VImageNPixels(src); i++) {\n    u = (*pp);\n    if (fabs(u) > tiny) (*pp) = (u-mode)/stddev;\n    pp++;\n  }  \n}\n\n/* get max z-value */\nfloat VZMax(VImage src)\n{\n  size_t i=0;\n  float u=0,umax=0;\n  VFloat *pp=VImageData(src);\n  for (i=0; i<VImageNPixels(src); i++) {\n    u = (*pp++);\n    if (u > umax) umax = u;\n  }\n  return umax;\n}\n\n\n\n/* get image variance */\ndouble VImageVar(VImage src)\n{\n  size_t i=0;\n  double u=0,s1=0,s2=0,nx=0,tiny=1.0e-8;\n  VFloat *pp=VImageData(src);\n  for (i=0; i<VImageNPixels(src); i++) {\n    u = (double)(*pp++);\n    if (ABS(u) < tiny) continue;\n    s1 += u;\n    s2 += u*u;\n    nx++;\n  }\n  if (nx < 3.0) VError(\" number of nonzero voxels: %g\\n\",nx);\n  double mean = s1/nx;\n  double var = (s2 - nx * mean * mean) / (nx - 1.0);\n  return var;\n}\n\n\n/* count nonzero voxels */\nvoid VImageCount(VImage src)\n{\n  float u=0;\n  size_t i=0,npos=0;\n  VFloat *pp=VImageData(src);\n  for (i=0; i<VImageNPixels(src); i++) {\n    u = (float)(*pp++);\n    if (u > 0) npos++;\n  }\n}\n\n\n/* check histogram range, image is normalized so [-10,10] should be okay */\nvoid VGetHistRange(VImage src,double *hmin,double *hmax)\n{\n  size_t i=0;\n  double u=0,x=0,y=0;\n  double zmin = -10.0;\n  double zmax = 10.0;\n\n  VFloat *pp=VImageData(src);\n  size_t npix=0,npos=0,nneg=0;\n  for (i=0; i<VImageNPixels(src); i++) {\n    u = (*pp++);\n    if (u < zmin) nneg++;\n    if (u > zmax) npos++;\n    if (fabs(u) > 0) npix++;\n  }\n  if (npix < 1) VError(\" image has no non-zero pixels\");\n\n  if (npos > 0 || nneg > 0) {\n    x = (double)npos/(double)npix;\n    y = (double)nneg/(double)npix;\n    if (x > 0.01 || y > 0.01) {\n      zmin = -20.0;\n      zmax = 20.0;\n    }\n  }\n \n  /* output */\n  *hmin = zmin;\n  *hmax = zmax;\n}\n\n\n\n\n\n/* remove isolated voxels */\nvoid VIsolatedVoxels(VImage src,float threshold)\n{\n  int b,r,c,bb,rr,cc;\n  float u=0;\n  size_t i;\n\n  VImage tmp = VCreateImage(VImageNBands(src),VImageNRows(src),VImageNColumns(src),VBitRepn);\n  VFillImage(tmp,VAllBands,0);\n\n  VFloat *pp=VImageData(src);\n  VBit *pa=VImageData(tmp);\n  for (i=0; i<VImageNPixels(src); i++) {\n    u = (*pp++);\n    if (u > threshold) *pa = 1;\n    pa++;\n  }\n\n  for (b=1; b<VImageNBands(src)-1; b++) {\n    for (r=1; r<VImageNRows(src)-1; r++) {\n      for (c=1; c<VImageNColumns(src)-1; c++) {\n\n\tint n=0;\n\tfor (bb=b-1; bb<=b+1; bb++) {\n\t  for (rr=r-1; rr<=r+1; rr++) {\n\t    for (cc=c-1; cc<=c+1; cc++) {\n\t      if (VPixel(tmp,bb,rr,cc,VBit) > 0) n++;\n\t      if (n >= 2) goto skip;\n\t    }\n\t  }\n\t}\n\tif (n < 2) VPixel(src,b,r,c,VFloat) = 0;\n      skip: ;\n      }\n    }\n  }\n  VDestroyImage(tmp);\n}\n", "meta": {"hexsha": "eeaa7beeecf34feed9386aaaf7a00d81287c1c9d", "size": 4383, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/utils/Hotspot.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/utils/Hotspot.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/utils/Hotspot.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 20.198156682, "max_line_length": 93, "alphanum_fraction": 0.5610312571, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3778102212788976}}
{"text": "////\n//\n// Copyright (c) 2010- \n//      NAKASATO, Naohito\n//      All 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#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <malloc.h>\n#include <string.h>\n#include <sys/time.h>\n#include <sys/resource.h>\n#include <cblas.h>\n#include \"accllib.h\"\n\n#include \"kernel_TN.h\"\n#include \"kernel_NN.h\"\n#include \"kernel_NT.h\"\n#include \"kernel_TT.h\"\n\nint dev = 0;\n\ndouble e_time(void)\n{\n  static struct timeval now;\n  gettimeofday(&now, NULL);\n  return (double)(now.tv_sec  + now.tv_usec/1000000.0);\n}\n\ndouble *tmp_A, *tmp_B, *tmp_C, *tmp_D, *tmp_E;\n\nvoid get_matrix(int dev, double *src, int isrc, double *dma, int idma, int s)\n{\n  ACCLmemcpy(dev, isrc, idma);\n  memcpy(src, dma, s);\n}\n\nvoid set_matrix(int dev, double *src, int isrc, double *dma, int idma, int s)\n{\n  memcpy(dma, src, s);\n  ACCLmemcpy(dev, idma, isrc);\n}\n\nvoid my_dgemm(int dev, int mod, int n)\n{\n  set_matrix(dev, tmp_A, 0, tmp_E, 6, sizeof(double)*n*n);\n  set_matrix(dev, tmp_B, 1, tmp_E, 6, sizeof(double)*n*n);\n  set_matrix(dev, tmp_C, 2, tmp_E, 6, sizeof(double)*n*n);\n\n  ACCLrun_on_domain(dev, mod, n/4, n/4);\n\n  get_matrix(dev, tmp_C, 2, tmp_E, 6, sizeof(double)*n*n);\n}\n\nvoid check(double *p1, double *p2, int n)\n{\n  double norm = 0.0;\n  for(int i = 0; i < n*n; i++) {\n    double dx = fabs(p1[i] - p2[i]);\n    if (dx > norm) {\n      norm = dx;\n    }\n  }\n  printf(\"N = %5i : norm %e\\t\", n, norm);\n}\n\nvoid out(int n, double t_noio, double t_io, int niter)\n{\n  fprintf(stdout, \"%g %g %g %g\\n\",\n\t  t_noio/niter, niter*(double)n*(double)n*(double)n*2.0/t_noio/1.0e9, \n\t  t_io/niter,   niter*(double)n*(double)n*(double)n*2.0/t_io/1.0e9\n\t  );\n}\n\nint main(int narg, char **argv)\n{\n  int n;\n  int ss;\n  int flag = 0;\n  int test_mode = 0;\n  int mod;\n  double alpha, beta;\n\n  ACCLopen();\n  ACCLallocate(dev);\n\n  if ( ACCLloadkernel(dev, 0, d_TN, 2) < 0) exit(-1);\n  if ( ACCLloadkernel(dev, 1, d_NN, 2) < 0) exit(-1);\n  if ( ACCLloadkernel(dev, 2, d_NT, 2) < 0) exit(-1);\n  if ( ACCLloadkernel(dev, 3, d_TT, 2) < 0) exit(-1);\n\n  if (narg == 1) {\n    n = 512;\n  } else {\n    n = atoi(argv[1]);\n  }\n  if (n % 64 != 0) {\n    printf(\"N is not multiple of 64! Error!\\n\");\n    exit(-1);\n  }\n  if (narg >= 3) {\n    test_mode = atoi(argv[2]);\n    switch(test_mode) {\n    case 0:\n      break;\n    case 1:\n      break;\n    case 2:\n      break;\n    case 3:\n      break;\n    default:\n      printf(\"Error!!!!\\n\");\n      exit(-1);\n    }\n  }\n  if (narg == 4) flag = 1;\n\n  alpha = 1.0;\n  beta = 1.0;\n\n  ss = n*n;\n\n  mod = test_mode;\n  ACCLallocatememory(dev, mod, 0, ACCL_DOUBLE_2_2DIM_GPU, n/2, n);\n  ACCLallocatememory(dev, mod, 1, ACCL_DOUBLE_2_2DIM_GPU, n/2, n);\n  ACCLallocatememory(dev, mod, 2, ACCL_DOUBLE_2_2DIM_GPU | ACCL_GLOBAL_BUFFER, n/2, n);\n  ACCLallocateresource0(dev, 3, ACCL_FLOAT_4_1DIM_WRITE, 1, 1);\n  ACCLrebindmemory(dev, mod, 3, \"cb0\");\n  ACCLallocateresource0(dev, 4, ACCL_INT_4_1DIM_WRITE, 1, 1);\n  ACCLrebindmemory(dev, mod, 4, \"cb1\");\n  ACCLallocateresource0(dev, 5, ACCL_DOUBLE_2_1DIM_WRITE, 1, 1);\n  ACCLrebindmemory(dev, mod, 5, \"cb2\");\n\n  srand(time(NULL));\n  tmp_A = (double *)memalign(256, ss*sizeof(double));\n  tmp_B = (double *)memalign(256, ss*sizeof(double));\n  tmp_C = (double *)memalign(256, ss*sizeof(double));\n  tmp_D = (double *)memalign(256, ss*sizeof(double));\n  tmp_E = (double *)memalign(256, ss*sizeof(double));\n  ACCLallocateresource_pinned(dev, 6, ACCL_DOUBLE_2_2DIM_CPU, n/2, n, tmp_E, ss*sizeof(double));\n\n  for(int i = 0; i < ss; i++) {\n    tmp_A[i] = (double)rand()/(RAND_MAX);\n    tmp_B[i] = (double)rand()/(RAND_MAX);\n    tmp_C[i] = (double)rand()/(RAND_MAX);\n  }\n\n  if (flag == 1) {\n    memcpy(tmp_D, tmp_C, ss*sizeof(double));\n\n    switch(test_mode) {\n    case 0:\n      cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, n, n, alpha, tmp_A, n, tmp_B, n, beta, tmp_D, n);\n      break;\n    case 1:\n      cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n, n, alpha, tmp_A, n, tmp_B, n, beta, tmp_D, n);\n      break;\n    case 2:\n      cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n, n, n, alpha, tmp_A, n, tmp_B, n, beta, tmp_D, n);\n      break;\n    case 3:\n      cblas_dgemm(CblasRowMajor, CblasTrans, CblasTrans, n, n, n, alpha, tmp_A, n, tmp_B, n, beta, tmp_D, n);\n      break;\n    }\n  }\n\n  float cb[4] = {(float)(n/2), (float)n, 0.0, 0.0};\n  ACCLwritememory_float(dev, 3, 4, cb);\n  int cb1[4] = {0, n/2, n, 3*n/2};\n  ACCLwritememory_int(dev, 4, 4, cb1);\n  double cb2[2] = {beta, alpha};\n  ACCLwritememory_double(dev, 5, 2, cb2);\n\n  my_dgemm(dev, mod, n);\n\n  if (flag == 1) {\n    check(tmp_D, tmp_C, n);\n  } \n\n  {\n    const int ccc = 5;\n    double dum = e_time();\n    for(int i = 0; i < ccc; i++) {\n      ACCLrun_on_domain(dev, mod, n/4, n/4);\n    }\n    dum = e_time() - dum;\n\n    double dum2 = e_time();\n    for(int i = 0; i < ccc; i++) my_dgemm(dev, mod, n);\n    dum2 = e_time() - dum2;\n\n    out(n, dum, dum2, ccc);\n  }\n\n  ACCLcleanup(dev);\n\n  return 0;\n}\n", "meta": {"hexsha": "c7bef86108064ede6f5bfc54f1d137c80f0e4ea7", "size": 6210, "ext": "c", "lang": "C", "max_stars_repo_path": "main.c", "max_stars_repo_name": "dadeba/dgemm_cypress", "max_stars_repo_head_hexsha": "dbe13de39a0bccc236a433222c883deae20a01dc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-08-03T04:37:18.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-08T06:51:06.000Z", "max_issues_repo_path": "main.c", "max_issues_repo_name": "dadeba/dgemm_cypress", "max_issues_repo_head_hexsha": "dbe13de39a0bccc236a433222c883deae20a01dc", "max_issues_repo_licenses": ["BSD-2-Clause"], "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.c", "max_forks_repo_name": "dadeba/dgemm_cypress", "max_forks_repo_head_hexsha": "dbe13de39a0bccc236a433222c883deae20a01dc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8475336323, "max_line_length": 113, "alphanum_fraction": 0.6373590982, "num_tokens": 2139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.37771990316108817}}
{"text": "/*\n * Evaluation of the scheduling algorithms HET, RTA, RTA2 and RTA3.\n * v1.0 -- 12/01/2017 -- initial version.\n * v2.0 -- 16/05/2017 -- second version.\n */\n#include <libxml/xmlreader.h>\n#include <libxml/parser.h>\n#include <libxml/xpath.h>\n#include <math.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <time.h>\n#include <getopt.h>\n#include <gsl/gsl_statistics.h>\n\n/*\n * Ceil and floor operations without using the library math, when period\n * and wcet values are integers.\n */\n#define U_CEIL( x, y )    ( ( x / y ) + ( x % y != 0 ) )\n#define U_FLOOR( x, y )   ( x / y )\n\n/*\n * Elementos en el archivo XML.\n */\n#define ELEMENT             1                               // Tag end\n#define END_ELEMENT         15                              // Tag start\n#define SET_TAG             (const xmlChar*) \"Set\"          // <Set> tag -- set\n#define S_TAG               (const xmlChar*) \"S\"            // <S> tag -- rts\n#define I_TAG               (const xmlChar*) \"i\"            // <i> tag -- task\n#define SET_SIZE_ATTR       (const xmlChar*) \"size\"         // \"size\" attribute in <Set> tag\n#define SET_RTS_SIZE_ATTR   (const xmlChar*) \"n\"            // \"n\" attribute in <Set> tag\n#define SET_UF_ATTR         (const xmlChar*) \"u\"            // \"u\" attribute in <Set> tag\n#define RTS_ID_ATTR         (const xmlChar*) \"count\"        // \"count\" attribute in <S> tag\n#define RTS_UF_ATTR         (const xmlChar*) \"U\"            // \"U\" attribute in <S> tag\n#define ID_ATTR             (const xmlChar*) \"nro\"          // \"nro\" attribute in <i> tag\n#define WCET_ATTR           (const xmlChar*) \"C\"            // \"C\" attribute in <i> tag\n#define T_ATTR              (const xmlChar*) \"T\"            // \"T\" attribute in <i> tag\n#define D_ATTR              (const xmlChar*) \"D\"            // \"D\" attribute in <i> tag\n\n/*\n * Number of schedulability methods to test.\n */\n#define NUM_SCHED_METHODS 4\n\n/*\n * Name of the schedulability methods to evaluate.\n */\n#define HET    \"het\"\n#define RTA    \"rta\"\n#define RTA2   \"rta2\"\n#define RTA3   \"rta3\"\n\n/*\n * Position of the method in the schedulable array.\n */\n#define HET_ID    0\n#define RTA_ID    1\n#define RTA2_ID   2\n#define RTA3_ID   3\n\n/*\n * Return value for the schedulability methods.\n */\n#define SCHED     1\n#define NON_SCHED 0\n\n/*\n * Global variables.\n */\nint rts_founded = 0;        // Number of RTS in the XML file evaluated.\nint verbose = 0;            // Print addtional info to stderr\nFILE* out_file;             // Result file\n\n// Tarea\nstruct task_t {\n    int id;                         // task id\n    int c;                          // wcet\n    int t;                          // period\n    int d;                          // deadline\n    int tmc;                        // t - c\n    int wcrt[NUM_SCHED_METHODS];    // wcrt\n    int cc[NUM_SCHED_METHODS];      // cc\n    int loops_w[NUM_SCHED_METHODS]; // number of while loops\n    int loops_f[NUM_SCHED_METHODS]; // number of for loops\n    int a_rta2;\n    int b_rta2;    \n    int a_rta3;\n    int b_rta3;\n    int last_psi;           // het\n    int last_workload;      // het    \n};\n\n// rts\nstruct rts_t {\n    int rts_id;\n    int rts_uf;\n    int rts_ntask;\n    int *schedulable;\n    struct task_t **tasks;    \n};\n\n// set of rts\nstruct set_t {\n    int set_size;\n    int set_uf;   \n    int set_rts_ntask;\n    struct rts_t **rts_list;\n};\n\n// prototipe for scheduling analysis methods\ntypedef int (*sched_test_method) (struct rts_t*);\n\n// test method result\nstruct result_t {\n    double *cc;\n    double *loops;\n    double cc_mean;\n    double cc_std;\n    double loops_mean;\n    double loops_std;\n};\n\nstruct method_t {\n    char* method_name;\n    int method_id;\n    sched_test_method method;\n    struct result_t *result;\n};\n\n/*\n * Prototipes\n */\nint rta_wcrt(struct rts_t*);\nint rta2_wcrt(struct rts_t*);\nint rta3_wcrt(struct rts_t*);\nint het_workload(int i, int b, int n, struct task_t**);\nint het_wcrt(struct rts_t*);\n\nint het_workload(int i, int b, int n, struct task_t **tasks)\n{\n    tasks[n]->loops_w[HET_ID] += 1;\n\n    double tmp = (double) b / (double) tasks[i]->t;\n    int f = (int) floor(tmp);\n    int c = (int) ceil(tmp);\n\n    tasks[n]->cc[HET_ID] += 2;\n\n    int branch0 = b - f * (tasks[i]->t - tasks[i]->c);\n    int branch1 = c * tasks[i]->c;\n\n    if (i > 0) {\n        int l_w = tasks[i - 1]->last_workload;\n        int tmp = f * tasks[i]->t;\n        if (tmp > tasks[i - 1]->last_psi) {\n            l_w = het_workload(i - 1, tmp, n, tasks);\n        }\n\n        branch0 += l_w;\n        branch1 += het_workload(i - 1, b, n, tasks);\n    }\n\n    tasks[i]->last_psi = b;\n\n    if (branch0 <= branch1) {\n        tasks[i]->last_workload = branch0;\n    } else {\n        tasks[i]->last_workload = branch1;\n    }\n\n    return tasks[i]->last_workload;\n}\n\n/*\n * HET\n * \"Schedulability Analysis of Periodic Fixed Priority Systems\"\n * http://ieeexplore.ieee.org/document/1336766/\n * --\n * See also:\n * \"Efficient Exact Schedulability Tests for Fixed Priority Real-Time Systems\"\n * http://ieeexplore.ieee.org/document/4487061/\n */\nint het_wcrt(struct rts_t *rts)\n{\n    struct task_t **tasks = rts->tasks;\n    \n    int i;\n    for (i = 1; i < rts->rts_ntask; i++) {\n        tasks[i]->loops_f[HET_ID] += 1;\n\n        int w = het_workload(i - 1, tasks[i]->d, i, tasks);\n\n        if ((w + tasks[i]->c) > tasks[i]->d) {\n            rts->schedulable[HET_ID] = NON_SCHED;\n            return NON_SCHED;\n        }\n        \n        tasks[i]->wcrt[HET_ID] = w + tasks[i]->c;\n    } \n    \n    rts->schedulable[HET_ID] = SCHED;\n    return SCHED;\n}\n\n/*\n * RTA\n * \"Improved Response-Time Analysis Calculations\"\n * http://doi.ieeecomputersociety.org/10.1109/REAL.1998.739773\n */\nint rta_wcrt(struct rts_t *rts)\n{\n    struct task_t **tasks = rts->tasks;\n    \n    int w = 0;\n    int tr = 0;\n    int t = tasks[0]->c;\n    tasks[0]->wcrt[RTA_ID] = tasks[0]->c;\n\n    int i, j;\n    for (i = 1; i < rts->rts_ntask; i++) {\n        tr = t + tasks[i]->c;\n        tasks[i]->loops_f[RTA_ID] += 1;\n\n        do {\n            tasks[i]->loops_w[RTA_ID] += 1;\n            t = tr;\n            w = tasks[i]->c;\n\n            for (j = 0; j < i; j++) {\n                tasks[i]->loops_f[RTA_ID] += 1;\n                \n                int c_j = tasks[j]->c;\n                int t_j = tasks[j]->t;\n                int a = (int) ceil( ((double) tr) / ((double) t_j) );\n                tasks[i]->cc[RTA_ID] += 1;\n                \n                w = w + (a * c_j);\n                \n                if (w > tasks[i]->d) {\n                    rts->schedulable[RTA_ID] = NON_SCHED;\n                    return NON_SCHED;\n                }\n            }\n            \n            tr = w;\n        \n        } while (t != tr);\n\n        tasks[i]->wcrt[RTA_ID] = t;\n    }\n    \n    rts->schedulable[RTA_ID] = SCHED;\n    return SCHED;\n}\n\n/*\n * RTA2\n * \"Reduced computational cost in the calculation of worst case response time for real time systems\"\n * http://sedici.unlp.edu.ar/handle/10915/9654\n */\nint rta2_wcrt(struct rts_t *rts)\n{\n    struct task_t **tasks = rts->tasks;\n\n    int tr = 0;\n    int t = tasks[0]->c;\n    tasks[0]->wcrt[RTA2_ID] = tasks[0]->c;\n\n    int i, j;\n    for (i = 1; i < rts->rts_ntask; i++) {\n        tr = t + tasks[i]->c;\n        tasks[i]->loops_f[RTA2_ID] += 1;\n\n        do {\n            tasks[i]->loops_w[RTA2_ID] += 1;\n            t = tr;\n\n            for (j = 0; j < i; j++) {\n                tasks[i]->loops_f[RTA2_ID] += 1;\n                \n                int a = (int) ceil( ((double) tr) / ((double) tasks[j]->t) );\n                tasks[i]->cc[RTA2_ID] += 1;\n                a = a * tasks[j]->c;\n                \n                if (a > tasks[j]->a_rta2) {\n                    tr = tr + a - tasks[j]->a_rta2;\n                    tasks[j]->a_rta2 = a;\n                    \n                    if (tr > tasks[i]->d) {\n                        rts->schedulable[RTA2_ID] = NON_SCHED;\n                        return NON_SCHED;\n                    }\n                }\n            }\n        } while (t != tr);\n     \n        tasks[i]->wcrt[RTA2_ID] = t;\n    }\n    \n    rts->schedulable[RTA2_ID] = SCHED;\n    return SCHED;\n}\n\n/*\n * RTA3\n * \"Computational Cost Reduction for Real-Time Schedulability Tests Algorithms\"\n * http://ieeexplore.ieee.org/document/7404899/\n */\nint rta3_wcrt(struct rts_t *rts)\n{\n    struct task_t **tasks = rts->tasks;\n\n    int tr = 0;\n    int t = tasks[0]->c;\n    tasks[0]->wcrt[RTA3_ID] = tasks[0]->c;\n\n    int i, j;\n    for (i = 1; i < rts->rts_ntask; i++) {\n        tr = t + tasks[i]->c;\n        tasks[i]->loops_f[RTA3_ID] += 1;\n\n        do {\n            tasks[i]->loops_w[RTA3_ID] += 1;\n            t = tr;\n            \n            for (j = i - 1; j >= 0; j--) {\n                tasks[i]->loops_f[RTA3_ID] += 1;\n            \n                if (tr > tasks[j]->b_rta3) {\n                    int a_t = (int) ceil( ((double)tr) / ((double)tasks[j]->t) );\n                    tasks[i]->cc[RTA3_ID] += 1;\n\n                    int a = a_t * tasks[j]->c;\n                    tr = tr + a - tasks[j]->a_rta3;\n\n                    tasks[j]->a_rta3 = a;\n                    tasks[j]->b_rta3 = a_t * tasks[j]->t;\n                    \n                    // verifica vencimiento\n                    if (tr > tasks[i]->d) {\n                        rts->schedulable[RTA3_ID] = NON_SCHED;\n                        return NON_SCHED;\n                    }\n                }\n            }            \n        } while (t != tr);\n\n        tasks[i]->wcrt[RTA3_ID] = t;\n    }\n    \n    rts->schedulable[RTA3_ID] = SCHED;\n    return SCHED;\n}\n\nvoid reset_rts(struct rts_t *rts)\n{\n    int i, j;\n    for (i = 0; i < rts->rts_ntask; i++) {\n        struct task_t *task = rts->tasks[i];\n\n        task->a_rta2 = task->c;\n        task->b_rta2 = task->t;\n        task->a_rta3 = task->c;\n        task->b_rta3 = task->t;\n        task->last_psi = 0;\n        task->last_workload = 0;\n                       \n        for (j = 0; j < NUM_SCHED_METHODS; j++) {\n            task->cc[j] = 0;\n            task->loops_w[j] = 0;\n            task->loops_f[j] = 0;\n            task->wcrt[j] = 0;\n        }\n    }\n}\n\n/*\n * Parse the XML file. If a new RTS is found, it is evalutad with the methods in method array.\n */\nvoid processXmlFile(xmlTextReaderPtr reader, struct set_t *rts_set, struct method_t *methods)\n{\n    xmlChar *name = xmlTextReaderLocalName(reader);\n\n    // Tag <Set> -- initial tag\n    if (xmlStrcasecmp(name, SET_TAG) == 0) {\n        if (xmlTextReaderNodeType(reader) == ELEMENT) {            \n            xmlChar *c_set_rts_uf = xmlTextReaderGetAttribute(reader, SET_UF_ATTR);\n            xmlChar *c_set_rts_size = xmlTextReaderGetAttribute(reader, SET_SIZE_ATTR);\n            xmlChar *c_set_rts_ntask = xmlTextReaderGetAttribute(reader, SET_RTS_SIZE_ATTR);\n\n            rts_set->set_uf = atoi((char*) c_set_rts_uf);\n            rts_set->set_size = atoi((char*) c_set_rts_size);\n            rts_set->set_rts_ntask = atoi((char*) c_set_rts_ntask);\n\n            xmlFree(c_set_rts_uf);\n            xmlFree(c_set_rts_size);\n            xmlFree(c_set_rts_ntask);\n        }\n    }\n\n    // Tag <S> -- RTS\n    if (xmlStrcasecmp(name, S_TAG) == 0) {\n        if (xmlTextReaderNodeType(reader) == ELEMENT) {\n            xmlChar *c_rts_id = xmlTextReaderGetAttribute(reader, RTS_ID_ATTR);\n            xmlChar *c_rts_uf = xmlTextReaderGetAttribute(reader, RTS_UF_ATTR);\n\n            // reserve memory for the rts and add it to rts_list\n            struct rts_t *new_rts = malloc(sizeof(struct rts_t));            \n\n            // reserve memory for the methods results\n            new_rts->schedulable = malloc(sizeof(int) * NUM_SCHED_METHODS);\n            // reserve memory for the rts tasks\n            new_rts->tasks = malloc(sizeof(struct task_t*) * rts_set->set_rts_ntask);\n\n            // complete data about this rts\n            new_rts->rts_id = atoi((char*) c_rts_id);\n            new_rts->rts_uf = atoi((char*) c_rts_uf);\n            new_rts->rts_ntask = rts_set->set_rts_ntask;\n\n            // add rts to set\n            rts_set->rts_list[rts_founded] = new_rts;\n\n            // free memory\n            xmlFree(c_rts_id);\n            xmlFree(c_rts_uf);\n        }\n\n        if (xmlTextReaderNodeType(reader) == END_ELEMENT) {            \n            struct rts_t *rts = rts_set->rts_list[rts_founded];\n            reset_rts(rts);\n            \n            // evaluate the methods\n            int i, j;\n            for (i = 0; i < NUM_SCHED_METHODS; i++) {\n                int method_id = methods[i].method_id;\n                rts->schedulable[method_id] = (*methods[i].method)(rts);\n\n                // store totals\n                for (j = 0; j < rts->rts_ntask; j++) {\n                    struct task_t *task = rts->tasks[j];\n                    methods[i].result->cc[rts_founded] += task->cc[method_id];\n                    methods[i].result->loops[rts_founded] += task->loops_w[method_id] + task->loops_f[method_id];\n                }\n            }\n\n            rts_founded = rts_founded + 1;\n        }\n    }\n\n    // Tag <i> -- a real-time task\n    if (xmlStrcasecmp(name, I_TAG) == 0) {\n        xmlChar *c_id = xmlTextReaderGetAttribute(reader, ID_ATTR);\n        xmlChar *wcet = xmlTextReaderGetAttribute(reader, WCET_ATTR);\n        xmlChar *t = xmlTextReaderGetAttribute(reader, T_ATTR);\n        xmlChar *d = xmlTextReaderGetAttribute(reader, D_ATTR);\n\n        int id = atoi((char*) c_id) - 1;\n\n        struct rts_t *rts = rts_set->rts_list[rts_founded];\n        \n        // reserve memory for the task\n        struct task_t *task = malloc(sizeof(struct task_t));\n\n        // complete the basic task data\n        task->id = id + 1;\n        task->c = atoi((char*) wcet);\n        task->t = atoi((char*) t);\n        task->d = atoi((char*) d);\n        task->tmc = task->t - task->c;\n\n        // add the task to rts\n        rts->tasks[id] = task;\n\n        xmlFree(c_id);\n        xmlFree(wcet);\n        xmlFree(t);\n        xmlFree(d);       \n    }\n\n    xmlFree(name);\n}\n\nvoid testRtsInXml(char *file, struct set_t* rts_set, struct method_t *methods, int limit)\n{    \n    // get read pointer\n    xmlTextReaderPtr reader = xmlNewTextReaderFilename(file);\n    if (reader == NULL) {\n        fprintf(stderr, \"Unable to open %s\\n\", file);\n        exit(EXIT_FAILURE);\n    }\n\n    // parse xml file and evaluate schedulability methods\n    int ret = xmlTextReaderRead(reader);\n    while (ret == 1) {\n        if (limit > 0 && rts_founded == limit) {\n            break;\n        }\n        processXmlFile(reader, rts_set, methods);\n        ret = xmlTextReaderRead(reader);\n    }\n\n    if (rts_set->set_size < limit) {\n        fprintf(stderr, \"Warning: %d str in file according to XML info, but %d to be tested.\\n\", rts_set->set_size, limit);\n    }\n\n    xmlFreeTextReader(reader);\n}\n\n/*\n * Print method results to out_file.\n */\nvoid save_result(char* method, struct result_t* result, int use_csv, char *csv_sep)\n{\n    if (use_csv == 0) {\n        fprintf(out_file, \"%10s%15f%15f%15f%15f\\n\", method, result->cc_mean, result->cc_std, \n                                                    result->loops_mean, result->loops_std);\n    } else {\n        fprintf(out_file, \"%2$s%1$s%3$f%1$s%4$f%1$s%5$f%1$s%6$f\\n\", csv_sep, method, result->cc_mean, result->cc_std, \n                                                                                     result->loops_mean, result->loops_std);\n    }    \n}\n\n/*\n * Print help and usage information.\n */\nvoid printUsage(char* progName, int exitCode)\n{\n    fprintf(stderr, \"Usage: %s [options] file\\n\", progName);\n    fprintf(stderr,\n            \"\\t-v  --verbose\\tDisplay additional information about the clock used.\\n\"\n            \"\\t-h  --help\\tDisplay this information.\\n\"\n            \"\\t-l  --limit\\tTest first n RTS in file.\\n\"\n            \"\\t-c  --csv\\tCSV output with specified line separator.\\n\");\n    exit(exitCode);\n}\n\nint main(int argc, char **argv)\n{\n    int i, j, k;\n\n    if (argc <= 1) {\n        printUsage(argv[0], EXIT_FAILURE);\n    }\n\n    // options -- short format\n    const char *shortOpts = \"hvl:c:\";\n    // options -- long format\n    const struct option longOpts[] = {\n        {\"help\",    no_argument,        NULL, 'h'},\n        {\"verbose\", no_argument,        NULL, 'v'},\n        {\"limit\",   required_argument,  NULL, 'l'},\n        {\"csv\",     required_argument,  NULL, 'c'},\n        {0, 0, 0, 0}\n    };\n\n    verbose = 0;\n    rts_founded = 0;\n    int limit = 0;\n    \n    int use_csv = 0;\n    char* csv_sep;\n\n    int nextOption;\n\n    do {\n        nextOption = getopt_long(argc, argv, shortOpts, longOpts, NULL);\n        switch (nextOption) {\n            case 'h': // -h or --help\n                printUsage(argv[0], EXIT_SUCCESS);\n            case 'v': // -v or --verbose\n                verbose = 1;\n                break;\n            case 'l': // -l or --limit\n                limit = atoi(optarg);\n                break;            \n            case 'c': // -c or --csv\n                use_csv = 1;\n                csv_sep = optarg;\n                break;\n            case '?': // invalid option\n                printUsage(argv[0], EXIT_FAILURE);\n            case -1: // no more options\n                break;\n            default:\n                abort();\n        }\n    } while (nextOption != -1);\n    \n    // print info to stderr if requested\n    if (verbose == 1) {\n        fprintf(stderr, \"Testing %s...\\n\", argv[optind]);\n    }\n\n    // stdout as default output file\n    out_file = stdout;\n\n    // reserve memory for the set\n    struct set_t *rts_set = malloc(sizeof(struct set_t));\n    rts_set->set_uf = 0;\n    rts_set->set_size = 0;\n    rts_set->set_rts_ntask = 0;\n    // reserve memory to store the rts to test\n    rts_set->rts_list = malloc(sizeof(struct rts_t*) * limit);\n\n    // reserve memory for test results\n    struct result_t* het_results = malloc(sizeof(struct result_t));\n    struct result_t* rta_results = malloc(sizeof(struct result_t));\n    struct result_t* rta2_results = malloc(sizeof(struct result_t));\n    struct result_t* rta3_results = malloc(sizeof(struct result_t));\n\n    // methods to test\n    struct method_t methods[] = {[RTA_ID]  {RTA,  RTA_ID,  rta_wcrt,  rta_results},\n                                 [RTA2_ID] {RTA2, RTA2_ID, rta2_wcrt, rta2_results},\n                                 [RTA3_ID] {RTA3, RTA3_ID, rta3_wcrt, rta3_results},\n                                 [HET_ID]  {HET,  HET_ID,  het_wcrt,  het_results}\n                                 };\n\n    for (i = 0; i < NUM_SCHED_METHODS; i++) {\n        methods[i].result->cc = calloc(limit, sizeof(double));\n        methods[i].result->loops = calloc(limit, sizeof(double));\n    }\n\n    if (verbose == 1) {\n        fprintf(stderr, \"Testing %d rts.\\n\", limit);\n    }\n\n    // read rts from xml file into rts_set\n    char *filename = argv[optind];\n    testRtsInXml(filename, rts_set, methods, limit);\n\n    // compute means and stdev\n    for (i = 0; i < NUM_SCHED_METHODS; i++) {\n        methods[i].result->cc_mean = gsl_stats_mean(methods[i].result->cc, 1, rts_founded);\n        methods[i].result->cc_std = gsl_stats_sd_m(methods[i].result->cc, 1, rts_founded, methods[i].result->cc_mean);\n        methods[i].result->loops_mean = gsl_stats_mean(methods[i].result->loops, 1, rts_founded);\n        methods[i].result->loops_std = gsl_stats_sd_m(methods[i].result->loops, 1, rts_founded, methods[i].result->loops_mean);\n    }\n        \n    int rts_sched_cnt = 0; \n    int rts_nonsched_cnt = 0;\n\n    // verify that all methods give the same result\n    for (i = 0; i < rts_founded; i++) {\n        struct rts_t *rts = rts_set->rts_list[i];        \n\n        int sum = 0;\n        for (j = 0; j < NUM_SCHED_METHODS; j++) {\n            sum += rts->schedulable[j];\n        }\n\n        if (sum > 0 && sum < NUM_SCHED_METHODS) {\n            fprintf(stderr, \"Error! Method results are not the same. RTS %d\\n\", i);\n            for (j = 0; j < NUM_SCHED_METHODS; j++) {\n                fprintf(stderr, \"%s: %d\\n\", methods[j].method_name, rts->schedulable[j]);\n            }\n            break;\n        }\n\n        if (rts->schedulable[RTA_ID] == SCHED) {\n            rts_sched_cnt += 1;\n        } else {\n            rts_nonsched_cnt += 1; \n        }\n    }\n    \n    // verify that all wcrt are the same (only RTA methods)\n    for (j = 0; j < rts_founded; j++) {\n        struct rts_t *rts = rts_set->rts_list[j];\n        for (k = 0; k < rts->rts_ntask; k++) {\n            struct task_t *task = rts->tasks[k];\n            int ref_wcrt = task->wcrt[RTA_ID];\n            if (ref_wcrt != task->wcrt[RTA2_ID] || ref_wcrt != task->wcrt[RTA3_ID]) \n            {\n                fprintf(stderr, \"Error! WCRT are not the same. RTS %d, task %d\\n\", j, k);                \n                \n                int i = 0;                \n                fprintf(stderr, \"%13s%10s%10s%10s%10s\\n\", \"RTA\", \"RTA2\", \"RTA3\", \"C_i\", \"D_i\"); \n                for (i = 0; i < rts->rts_ntask; i++) {\n                    fprintf(stderr, \"%3d%10d%10d%10d%10d%10d\\n\", i, rts->tasks[i]->wcrt[RTA_ID], rts->tasks[i]->wcrt[RTA2_ID], \n                                                                    rts->tasks[i]->wcrt[RTA3_ID], rts->tasks[i]->c, rts->tasks[i]->d );\n                }\n            \n                return(EXIT_FAILURE);\n            }\n        }\n    }                \n    \n    // get timestamp for the test\n    char test_date[50];\n    time_t current_time = time(NULL);            \n    strftime(test_date, 50, \"%R %d/%m/%Y\", localtime(&current_time));\n    \n    // print header\n    fprintf(out_file, \"%s\\n\", filename);\n    fprintf(out_file, \"%s\\n\", test_date);\n    fprintf(out_file, \"Total: %d\\n\", rts_founded);\n    fprintf(out_file, \"Sched: %d\\n\", rts_sched_cnt);\n    fprintf(out_file, \"Non sched: %d\\n\", rts_nonsched_cnt);\n\n    // print column names\n    if (use_csv == 0) {\n        fprintf(out_file, \"%10s%15s%15s%15s%15s\\n\", \"method\", \"cc_mean\", \"cc_mean_std\", \"loops_mean\", \"loops_mean_std\");\n    } else {\n        fprintf(out_file, \"method%1$scc_mean%1$scc_mean_std%1$sloops_mean%1$sloops_mean_std\\n\", csv_sep);\n    }    \n                      \n    // print the results\n    for (i = 0; i < NUM_SCHED_METHODS; i++) {\n        save_result(methods[i].method_name, methods[i].result, use_csv, csv_sep);\n    }\n    \n    return(EXIT_SUCCESS);\n}\n\n", "meta": {"hexsha": "76096717d4882cd838287ffa8659d80fdfd8a81f", "size": 22173, "ext": "c", "lang": "C", "max_stars_repo_path": "wcrt-test-sim.c", "max_stars_repo_name": "unpsjb-rtsg/wcrt", "max_stars_repo_head_hexsha": "31b4a1148020dbeb4269d087cf65f4485bfa6c44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wcrt-test-sim.c", "max_issues_repo_name": "unpsjb-rtsg/wcrt", "max_issues_repo_head_hexsha": "31b4a1148020dbeb4269d087cf65f4485bfa6c44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wcrt-test-sim.c", "max_forks_repo_name": "unpsjb-rtsg/wcrt", "max_forks_repo_head_hexsha": "31b4a1148020dbeb4269d087cf65f4485bfa6c44", "max_forks_repo_licenses": ["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.967877095, "max_line_length": 135, "alphanum_fraction": 0.5207234023, "num_tokens": 6327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3776888293823031}}
{"text": "#pragma once\n#include \"GradUtil.h\"\n#include \"DistanceGrad.h\"\n\n#ifndef _NOGSL\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#else\n#include \"CustomSolver.h\"\n#endif\n\n#include <limits>\n#include <math.h>\n#include <vector>\n#include \"BasicError.h\"\n\nusing namespace std;\n\nclass IntervalGrad {\n\tdouble low;\n\tdouble high;\n\tgsl_vector* lgrad;\n\tgsl_vector* hgrad;\n\t\n\t//static constexpr double DELTA = 0.7;\n\npublic:\n\tbool singleton;\n\tIntervalGrad(double _low, double _high, gsl_vector* _lgrad, gsl_vector* _hgrad): low(_low), high(_high), lgrad(_lgrad), hgrad(_hgrad) {\n\t\tsingleton = false;\n\t}\n\t~IntervalGrad(void) {\n\t\tgsl_vector_free(lgrad);\n\t\tgsl_vector_free(hgrad);\n\t}\n\tdouble getLow() const { return low; }\n\tdouble getHigh() const { return high; }\n\tgsl_vector* getLGrad() const { return lgrad; }\n\tgsl_vector* getHGrad() const { return hgrad; }\n\tvoid update(double _low, double _high) {\n\t\tlow = _low;\n\t\thigh = _high;\n\t}\n\tstatic void ig_plus(IntervalGrad* m, IntervalGrad* f, IntervalGrad* o); // o = m + f\n\tstatic void ig_times(IntervalGrad* m, IntervalGrad* f, IntervalGrad* o); // o = m * f\n\tstatic void ig_div(IntervalGrad* m, IntervalGrad* f, IntervalGrad* o); // o = m / f\n\tstatic void ig_neg(IntervalGrad* m, IntervalGrad* o); // o = -m\n\tstatic void ig_union(const vector<IntervalGrad*>& m, IntervalGrad* o); // o = m_1 V m_2 V ...\n\tstatic void ig_equal(IntervalGrad* m, IntervalGrad* f, DistanceGrad* o); // o = m == f\n\tstatic void ig_lt(IntervalGrad* m, IntervalGrad* f, DistanceGrad* o); // o = m < f\n\tstatic void ig_square(IntervalGrad* m, IntervalGrad* o); // o = m * m\n\tstatic void ig_arctan(IntervalGrad* m, IntervalGrad* o); // o = arctan(m)\n\tstatic void ig_sin(IntervalGrad* m, IntervalGrad* o); // o = sin(m)\n\tstatic void ig_cos(IntervalGrad* m, IntervalGrad* o); // o = cos(m)\n\tstatic void ig_tan(IntervalGrad* m, IntervalGrad* o); // o = tan(m)\n\tstatic void ig_sqrt(IntervalGrad* m, IntervalGrad* o); // o = sqrt(m)\n\tstatic void ig_exp(IntervalGrad* m, IntervalGrad* o);\n\tstatic void ig_copy(IntervalGrad* i1, IntervalGrad* i2); // copy i1 into i2\n\tstatic void ig_cast_int_float(IntervalGrad* m, IntervalGrad* o);\n\t\n\tstatic void ig_conditionalUnion(IntervalGrad* m, IntervalGrad* f, DistanceGrad* d, IntervalGrad* o);\n\tstatic void ig_intersect(const vector<IntervalGrad*>& m, IntervalGrad* o);\n\t\n\tstring print() {\n\t\tstringstream str;\n\t\tstr << \"Range: \" << low << \" \" << high;\n\t\treturn str.str();\n\t}\n\t\n\tstring printFull() {\n\t\tstringstream str;\n\t\tstr << \"Range: \" << low << \" \" << high << endl;\n\t\tstr << \"LGrads: \";\n\t\tfor (int i = 0; i < lgrad->size; i++) {\n\t\t str << gsl_vector_get(lgrad, i) << \", \";\n\t\t}\n\t\tstr << endl;\n\t\tstr << \"HGrads: \" ;\n\t\tfor (int i = 0; i < hgrad->size; i++) {\n\t\t str << gsl_vector_get(hgrad, i) << \", \";\n\t\t}\n\t\treturn str.str();\n\t}\n\t\nprivate:\n\tvoid bound() {\n\t\tdouble oldLow = low;\n\t\tlow = GradUtil::bound(low);\n\t\tif (oldLow != low) {\n\t\t\tGradUtil::default_grad(lgrad);\n\t\t}\n\t\tdouble oldHigh = high;\n\t\thigh = GradUtil::bound(high);\n\t\tif (oldHigh != high) {\n\t\t\tGradUtil::default_grad(hgrad);\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < lgrad->size; i++) {\n\t\t\tgsl_vector_set(lgrad, i, GradUtil::bound(gsl_vector_get(lgrad, i)));\n\t\t\tgsl_vector_set(hgrad, i, GradUtil::bound(gsl_vector_get(hgrad, i)));\n\t\t}\n\t}\n};\n", "meta": {"hexsha": "1e5fca6b6681367fa7b202750eba5971f5fa1ebf", "size": 3230, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/IntervalGrad.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/IntervalGrad.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/IntervalGrad.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "avg_line_length": 31.0576923077, "max_line_length": 136, "alphanum_fraction": 0.6656346749, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3776644593437741}}
{"text": "#include <string.h>\n#include <math.h>\n#include <mpi.h>\n\n#include <gsl/gsl_rng.h>\n\n#include <fastpm/libfastpm.h>\n#include <fastpm/logging.h>\n#include \"pmpfft.h\"\n\n/* The following functions fill the gaussian field*/\nstatic void\npmic_fill_gaussian_gadget(PM * pm, FastPMFloat * delta_k, int seed);\nstatic void\npmic_fill_gaussian_fast(PM * pm, FastPMFloat * delta_k, int seed);\nstatic void\npmic_fill_gaussian_slow(PM * pm, FastPMFloat * delta_k, int seed);\n\nvoid\nfastpm_ic_fill_gaussiank(PM * pm, FastPMFloat * delta_k, int seed, enum FastPMFillDeltaKScheme scheme)\n{\n\n    /* clear the memory to avoid any modes that we forget to set. */\n    memset(delta_k, 0, pm_allocsize(pm) * sizeof(delta_k[0]));\n\n    switch(scheme) {\n        case FASTPM_DELTAK_GADGET:\n            pmic_fill_gaussian_gadget(pm, delta_k, seed);\n            break;\n        case FASTPM_DELTAK_FAST:\n            pmic_fill_gaussian_fast(pm, delta_k, seed);\n            break;\n        case FASTPM_DELTAK_SLOW:\n            pmic_fill_gaussian_slow(pm, delta_k, seed);\n            break;\n        default:\n            pmic_fill_gaussian_gadget(pm, delta_k, seed);\n            break;\n    }\n}\n\nstruct PofK {\n    fastpm_fkfunc func;\n    void * data;\n    double Volume;\n} ;\n\nstatic double _powerspec_to_transfer(double k, struct PofK * pk)\n{\n    double f = sqrt(pk->func(k, pk->data));\n    f *= sqrt(1.0 / pk->Volume);\n    return f;\n}\n\nvoid\nfastpm_ic_induce_correlation(PM * pm, FastPMFloat * delta_k, fastpm_fkfunc pkfunc, void * data)\n{\n    struct PofK pk;\n    pk.func = pkfunc;\n    pk.data = data;\n    pk.Volume = pm->Volume;\n\n    fastpm_apply_any_transfer(pm, delta_k, delta_k, (fastpm_fkfunc) _powerspec_to_transfer, &pk);\n}\n\nvoid\nfastpm_ic_remove_variance(PM * pm, FastPMFloat * delta_k)\n{\n#pragma omp parallel\n    {\n        PMKIter kiter;\n\n        for(pm_kiter_init(pm, &kiter);\n            !pm_kiter_stop(&kiter);\n            pm_kiter_next(&kiter)) {\n            double k2 = 0;\n            int d;\n            for(d = 0; d < 3; d++) {\n                k2 += kiter.kk[d][kiter.iabs[d]];\n            }\n\n            /* https://en.wikipedia.org/wiki/Atan2 */\n            double a = delta_k[kiter.ind];\n            double b = delta_k[kiter.ind + 1];\n\n            if(a == 0 && b == 0)   {\n                delta_k[kiter.ind + 0] = 0;\n                delta_k[kiter.ind + 1] = 0;\n            } else {\n                double phase = atan2(b, a);\n                delta_k[kiter.ind + 0] = cos(phase);\n                delta_k[kiter.ind + 1] = sin(phase);\n            }\n\n        }\n\n    }\n}\n\n\nstatic inline void \nSETSEED(PM * pm, unsigned int * table[2][2], int i, int j, gsl_rng * rng) \n{ \n    unsigned int seed = 0x7fffffff * gsl_rng_uniform(rng); \n\n    int ii[2] = {i, (pm->Nmesh[0] - i) % pm->Nmesh[0]};\n    int jj[2] = {j, (pm->Nmesh[1] - j) % pm->Nmesh[1]};\n    int d1, d2;\n    for(d1 = 0; d1 < 2; d1++) {\n        ii[d1] -= pm->ORegion.start[0];\n        jj[d1] -= pm->ORegion.start[1];\n    }\n    for(d1 = 0; d1 < 2; d1++)\n    for(d2 = 0; d2 < 2; d2++) {\n        if( ii[d1] >= 0 && \n            ii[d1] < pm->ORegion.size[0] &&\n            jj[d2] >= 0 &&\n            jj[d2] < pm->ORegion.size[1]\n        ) {\n            table[d1][d2][ii[d1] * pm->ORegion.size[1] + jj[d2]] = seed;\n        }\n    }\n}\nstatic inline unsigned int \nGETSEED(PM * pm, unsigned int * table[2][2], int i, int j, int d1, int d2) \n{\n    i -= pm->ORegion.start[0];\n    j -= pm->ORegion.start[1];\n    if(i < 0) abort();\n    if(j < 0) abort();\n    if(i >= pm->ORegion.size[0]) abort();\n    if(j >= pm->ORegion.size[1]) abort();\n    return table[d1][d2][i * pm->ORegion.size[1] + j];\n}\n\nstatic void \nSAMPLE(gsl_rng * rng, double * ampl, double * phase)\n{\n    *phase = gsl_rng_uniform(rng) * 2 * M_PI;\n    *ampl = 0;\n    do *ampl = gsl_rng_uniform(rng); while(*ampl == 0);\n}\n\nstatic void\npmic_fill_gaussian_gadget(PM * pm, FastPMFloat * delta_k, int seed)\n{\n    /* Fill delta_k with gadget scheme */\n    int d;\n    int i, j, k;\n\n    memset(delta_k, 0, sizeof(delta_k[0]) * pm->allocsize);\n\n    gsl_rng * rng = gsl_rng_alloc(gsl_rng_ranlxd1);\n    gsl_rng_set(rng, seed);\n\n    unsigned int * seedtable[2][2];\n    for(i = 0; i < 2; i ++)\n    for(j = 0; j < 2; j ++) {\n            seedtable[i][j] = calloc(pm->ORegion.size[0] * pm->ORegion.size[1], sizeof(int));\n    }\n\n    for(i = 0; i < pm->Nmesh[0] / 2; i++) {\n        for(j = 0; j < i; j++) SETSEED(pm, seedtable, i, j, rng);\n        for(j = 0; j < i + 1; j++) SETSEED(pm, seedtable, j, i, rng);\n        for(j = 0; j < i; j++) SETSEED(pm, seedtable, pm->Nmesh[0] - 1 - i, j, rng);\n        for(j = 0; j < i + 1; j++) SETSEED(pm, seedtable, pm->Nmesh[1] - 1 - j, i, rng);\n        for(j = 0; j < i; j++) SETSEED(pm, seedtable, i, pm->Nmesh[1] - 1 - j, rng);\n        for(j = 0; j < i + 1; j++) SETSEED(pm, seedtable, j, pm->Nmesh[0] - 1 - i, rng);\n        for(j = 0; j < i; j++) SETSEED(pm, seedtable, pm->Nmesh[0] - 1 - i, pm->Nmesh[1] - 1 - j, rng);\n        for(j = 0; j < i + 1; j++) SETSEED(pm, seedtable, pm->Nmesh[1] - 1 - j, pm->Nmesh[0] - 1 - i, rng);\n    }\n    gsl_rng_free(rng);\n\n    ptrdiff_t irel[3];\n    for(i = pm->ORegion.start[0]; \n        i < pm->ORegion.start[0] + pm->ORegion.size[0]; \n        i ++) {\n\n        gsl_rng * lower_rng = gsl_rng_alloc(gsl_rng_ranlxd1);\n        gsl_rng * this_rng = gsl_rng_alloc(gsl_rng_ranlxd1);\n\n        int ci = pm->Nmesh[0] - i;\n        if(ci >= pm->Nmesh[0]) ci -= pm->Nmesh[0];\n\n        for(j = pm->ORegion.start[1]; \n            j < pm->ORegion.start[1] + pm->ORegion.size[1]; \n            j ++) {\n            /* always pull the gaussian from the lower quadrant plane for k = 0\n             * plane*/\n            /* always pull the whitenoise from the lower quadrant plane for k = 0\n             * plane and k == Nmesh / 2 plane*/\n            int d1 = 0, d2 = 0;\n            int cj = pm->Nmesh[1] - j;\n            if(cj >= pm->Nmesh[1]) cj -= pm->Nmesh[1];\n\n            /* d1, d2 points to the conjugate quandrant */\n            if( (ci == i && cj < j)\n             || (ci < i && cj != j)\n             || (ci < i && cj == j)) {\n                d1 = 1;\n                d2 = 1;\n            }\n\n            unsigned int seed_conj, seed_this;\n            /* the lower quadrant generator */\n            seed_conj = GETSEED(pm, seedtable, i, j, d1, d2);\n            gsl_rng_set(lower_rng, seed_conj);\n\n            seed_this = GETSEED(pm, seedtable, i, j, 0, 0);\n            gsl_rng_set(this_rng, seed_this);\n\n            for(k = 0; k <= pm->Nmesh[2] / 2; k ++) {\n                int use_conj = (d1 != 0 || d2 != 0) && (k == 0 || k == pm->Nmesh[2] / 2);\n\n                double ampl, phase;\n                if(use_conj) {\n                    /* on k = 0 and Nmesh/2 plane, we use the lower quadrant generator, \n                     * then hermit transform the result if it is nessessary */\n                    SAMPLE(this_rng, &ampl, &phase);\n                    SAMPLE(lower_rng, &ampl, &phase);\n                } else {\n                    SAMPLE(lower_rng, &ampl, &phase);\n                    SAMPLE(this_rng, &ampl, &phase);\n                }\n\n                ptrdiff_t iabs[3] = {i, j, k};\n                ptrdiff_t ip = 0;\n                for(d = 0; d < 3; d ++) {\n                    irel[d] = iabs[d] - pm->ORegion.start[d];\n                    ip += pm->ORegion.strides[d] * irel[d];\n                }\n\n                if(irel[2] < 0) continue;\n                if(irel[2] >= pm->ORegion.size[2]) continue;\n\n                /* we want two numbers that are of std ~ 1/sqrt(2) */\n                ampl = sqrt(- log(ampl));\n\n                (delta_k + 2 * ip)[0] = ampl * cos(phase);\n                (delta_k + 2 * ip)[1] = ampl * sin(phase);\n\n                if(use_conj) {\n                    (delta_k + 2 * ip)[1] *= -1;\n                }\n\n                if((pm->Nmesh[0] - iabs[0]) % pm->Nmesh[0] == iabs[0] &&\n                   (pm->Nmesh[1] - iabs[1]) % pm->Nmesh[1] == iabs[1] &&\n                   (pm->Nmesh[2] - iabs[2]) % pm->Nmesh[2] == iabs[2]) {\n                    /* The mode is self conjuguate, thus imaginary mode must be zero */\n                    (delta_k + 2 * ip)[1] = 0;\n                    (delta_k + 2 * ip)[0] = ampl * cos(phase);\n                }\n\n                if(iabs[0] == 0 && iabs[1] == 0 && iabs[2] == 0) {\n                    /* the mean is zero */\n                    (delta_k + 2 * ip)[0] = 0;\n                    (delta_k + 2 * ip)[1] = 0;\n                }\n            }\n        }\n        gsl_rng_free(lower_rng);\n        gsl_rng_free(this_rng);\n    }\n    for(i = 0; i < 2; i ++)\n    for(j = 0; j < 2; j ++) {\n        free(seedtable[i][j]);\n    }\n/*\n    char * fn[1000];\n    sprintf(fn, \"canvas.dump.f4.%d\", pm->ThisTask);\n    fwrite(pm->canvas, sizeof(pm->canvas[0]), pm->ORegion.total * 2, fopen(fn, \"w\"));\n*/\n}\n\nstatic void\npmic_fill_gaussian_fast(PM * pm, FastPMFloat * delta_k, int seed)\n{\n    ptrdiff_t ind;\n    int d;\n\n    gsl_rng* random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);\n\n    /* set uncorrelated seeds */\n    gsl_rng_set(random_generator, seed);\n    for(d = 0; d < pm->ThisTask * 8; d++) {\n        seed = 0x7fffffff * gsl_rng_uniform(random_generator);\n    }\n\n    gsl_rng_set(random_generator, seed);\n\n    FastPMFloat * g_x = pm_alloc(pm);\n\n    for(ind = 0; ind < pm->IRegion.total; ind += 2) {\n        double phase = gsl_rng_uniform(random_generator) * 2 * M_PI;\n        double ampl;\n        do\n            ampl = gsl_rng_uniform(random_generator);\n        while(ampl == 0.0);\n\n        /* we need two gaussians of std=1.0 in real space (see footnote 1) */\n        ampl = sqrt(-2.0 * log(ampl));\n        /* r2c will reduce the variance, so we compensate here. */\n        ampl *= sqrt(pm_norm(pm));\n\n        g_x[ind] = ampl * sin(phase);\n        g_x[ind + 1] = ampl * cos(phase);\n    }\n    pm_r2c(pm, g_x, delta_k);\n    pm_free(pm, g_x);\n}\n\nstatic void \npmic_fill_gaussian_slow(PM * pm, FastPMFloat * delta_k, int seed)\n{\n    ptrdiff_t i[3] = {0};\n    int d;\n    gsl_rng* random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);\n\n    gsl_rng_set(random_generator, seed);\n\n    FastPMFloat * g_x = pm_alloc(pm);\n\n    for(i[0] = 0; i[0] < pm->Nmesh[0]; i[0]++)\n    for(i[1] = 0; i[1] < pm->Nmesh[1]; i[1]++)\n    for(i[2] = 0; i[2] < pm->Nmesh[2]; i[2]++) {\n        double phase = gsl_rng_uniform(random_generator) * 2 * M_PI;\n        double ampl;\n        do\n            ampl = gsl_rng_uniform(random_generator);\n        while(ampl == 0.0);\n        ptrdiff_t ii[3];\n        ptrdiff_t ind = 0;\n        for(d = 0; d < 3; d ++) {\n            if(i[d] < pm->IRegion.start[d]) goto next;\n            if(i[d] >= pm->IRegion.start[d] + pm->IRegion.size[d]) goto next;\n            ii[d] = i[d] - pm->IRegion.start[d];\n            ind += ii[d] * pm->IRegion.strides[d];\n        }\n        /* we need two gaussians of std=1.0 in real space */\n        ampl = sqrt(-2.0 * log(ampl));\n\n        /* r2c will reduce the variance, so we compensate here. */\n        ampl *= sqrt(pm_norm(pm));\n\n        g_x[ind] = ampl * sin(phase);\n        next:\n        continue;\n    }\n    pm_r2c(pm, g_x, delta_k);\n    pm_free(pm, g_x);\n    gsl_rng_free(random_generator);\n}\n\n\n/* Footnotes */ \n\n/* 1): \n * We want delta(k) = delta_real + I delta_imag, where delta_real and\n * delta_imag are Gaussian random variables with variance given by\n * power spectrum, \\sigma^2=P(k). We can obtain this equivalently as\n *\n *   delta(k) = A exp(i phase),\n *\n * where the phase is random (i.e. sampled from a uniform distribution)\n * and the amplitude A follows a Rayleigh distribution (see \n * https://en.wikipedia.org/wiki/Rayleigh_distribution). To sample from \n * Rayleigh distribution, use inverse transform sampling\n * (see https://en.wikipedia.org/wiki/Inverse_transform_sampling), i.e.\n * start from uniform random variable in [0,1] and then apply inverse of CDF\n * of Rayleigh distribution. From F(A)=CDF(A)=1-e^{-A^2/(2\\sigma^2)} we get\n * A = \\sigma \\sqrt{-2 ln(1-CDF)}. So if x is uniform random number in [0,1], then \n * A = \\sigma \\sqrt(-2 ln(x)) follows Rayleigh distribution as desired. \n * Here we used x instead of 1-x because this does not make a difference for a \n * uniform random number in [0,1]. In the code below, we start with \\sigma=1 and \n * multiply by sqrt(P(k)) later.\n */\n", "meta": {"hexsha": "f6ad5f73defe060cc32bd1d3183f8dd78246dbcc", "size": 12221, "ext": "c", "lang": "C", "max_stars_repo_path": "fastpm/libfastpm/initialcondition.c", "max_stars_repo_name": "sbird/FastPMRunner", "max_stars_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fastpm/libfastpm/initialcondition.c", "max_issues_repo_name": "sbird/FastPMRunner", "max_issues_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-04-19T23:01:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:51:04.000Z", "max_forks_repo_path": "fastpm/libfastpm/initialcondition.c", "max_forks_repo_name": "sbird/FastPMRunner", "max_forks_repo_head_hexsha": "f38f6e69c603fb699436b645fe7b4eb418ee82c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T23:24:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T23:24:19.000Z", "avg_line_length": 32.4164456233, "max_line_length": 107, "alphanum_fraction": 0.523115948, "num_tokens": 3818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3774574879198376}}
{"text": "/* -*- linux-c -*- */\n/* fewbody_nonks.c\n\n   Copyright (C) 2002-2004 John M. Fregeau\n   \n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n   \n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n   \n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n*/\n\n#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_odeiv.h>\n#include \"fewbody.h\"\n\n/* the derivatives function for the GSL ODE integrator */\n#define FB_FM(i, j, k) fm[nstar*3*i + 3*j + k]\nint fb_nonks_func(double t, const double *y, double *f, void *params)\n{\n\tint i, j, k, nstar;\n\tdouble r[3], *m, *fm, val;\n\n\tnstar = (*(fb_nonks_params_t *) params).nstar;\n\tm = (*(fb_nonks_params_t *) params).m;\n\n\tfm = fb_malloc_vector(nstar * nstar * 3);\n\n\t/* calculate the matrix */\n\tfor (i=0; i<nstar; i++) {\n\t\tfor (j=0; j<i; j++) {\n\t\t\tfor (k=0; k<3; k++) {\n\t\t\t\tFB_FM(i, j, k) = -FB_FM(j, i, k);\n\t\t\t}\n\t\t}\n\n\t\tfor (j=i+1; j<nstar; j++) {\n\t\t\tfor (k=0; k<3; k++) {\n\t\t\t\tr[k] = y[j*6+k] - y[i*6+k];\t\n\t\t\t}\n\t\t\t\n\t\t\tval = 1.0 / fb_cub(fb_mod(r));\n\n\t\t\tfor (k=0; k<3; k++) {\n\t\t\t\tFB_FM(i, j, k) = val * r[k];\n\t\t\t}\n\t\t}\n\t}\n\n\t/* calculate derivatives */\n\tfor (i=0; i<nstar; i++) {\n\t\tfor (k=0; k<3; k++) {\n\t\t\tf[i*6+k] = y[i*6+k+3];\n\t\t\tf[i*6+k+3] = 0.0;\n\t\t}\n\t\t\n\t\tfor (j=0; j<i; j++) {\n\t\t\tfor (k=0; k<3; k++) {\n\t\t\t\tf[i*6+k+3] += m[j] * FB_FM(i, j, k);\n\t\t\t}\n\t\t}\n\n\t\tfor (j=i+1; j<nstar; j++) {\n\t\t\tfor (k=0; k<3; k++) {\n\t\t\t\tf[i*6+k+3] += m[j] * FB_FM(i, j, k);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfb_free_vector(fm);\n\n\treturn(GSL_SUCCESS);\n}\n#undef FB_FM\n\n/* the Jacobian for the GSL ODE integrator */\nint fb_nonks_jac(double t, const double *y, double *dfdy, double *dfdt, void *params)\n{\n\tunsigned int i, j, k, a, b, kk;\n\tint nstar;\n\tdouble r[3], *m, val;\n\tgsl_matrix_view dfdy_mat;\n\tgsl_matrix *matrix;\n\n\tnstar = (*(fb_nonks_params_t *) params).nstar;\n\tm = (*(fb_nonks_params_t *) params).m;\n\n\t/* allocate matrices */\n\tdfdy_mat = gsl_matrix_view_array(dfdy, nstar*6, nstar*6);\n\tmatrix = &dfdy_mat.matrix;\n\t\n\t/* set dfdt to zero */\n\tfor (j=0; j< (unsigned int) nstar*6; j++) {\n\t\tdfdt[j] = 0.0;\n\t}\n\n\t/* set the matrix to zero to begin with */\n\tgsl_matrix_set_zero(matrix);\n\n\t/* then set the actual values */\n\tfor (i=0; i< (unsigned int) nstar; i++) {\n\t\tfor (a=0; a<3; a++) {\n\t\t\tgsl_matrix_set(matrix, i+a, i+a+3, 1.0);\n\n\t\t\tfor (k=0; k< (unsigned int) nstar; k++) {\n\t\t\t\tfor (b=0; b<3; b++) {\n\t\t\t\t\tval = 0.0;\n\t\t\t\t\tfor (j=0; j< (unsigned int) nstar; j++) {\n\t\t\t\t\t\tif (j != i) {\n\t\t\t\t\t\t\tfor (kk=0; kk<3; kk++) {\n\t\t\t\t\t\t\t\tr[kk] = y[i*6+kk] - y[j*6+kk];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tval -= m[j] * ((double) (FB_DELTA(i, k) - FB_DELTA(j, k))) / fb_cub(fb_mod(r)) * \\\n\t\t\t\t\t\t\t\t(((double) FB_DELTA(a, b)) - 3.0 * (y[i*6+a] - y[j*6+a])*(y[i*6+b] - y[j*6+b])/fb_dot(r, r));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tgsl_matrix_set(matrix, i+a+3, k+b, val);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn(GSL_SUCCESS);\n}\n\nvoid fb_euclidean_to_nonks(fb_obj_t **star, double *y, int nstar)\n{\n\tint i, j;\n\t\n\tfor (i=0; i<nstar; i++) {\n\t\tfor (j=0; j<3; j++) {\n\t\t\ty[i*6+j] = star[i]->x[j];\n\t\t\ty[i*6+j+3] = star[i]->v[j];\n\t\t}\n\t}\n}\n\nvoid fb_nonks_to_euclidean(double *y, fb_obj_t **star, int nstar)\n{\n\tint i, j;\n\n\tfor (i=0; i<nstar; i++) {\n\t\tfor (j=0; j<3; j++) {\n\t\t\tstar[i]->x[j] = y[i*6+j];\n\t\t\tstar[i]->v[j] = y[i*6+j+3];\n\t\t}\n\t}\t\n}\n", "meta": {"hexsha": "1cf3a33fa4c7bc0c572e88cbe730ff74f8ff6b6b", "size": 3808, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody_nonks.c", "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": ["PSF-2.0"], "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/fewbod/fewbody-0.26/fewbody_nonks.c", "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_licenses": ["PSF-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/fewbody_nonks.c", "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": ["PSF-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5061728395, "max_line_length": 101, "alphanum_fraction": 0.5667016807, "num_tokens": 1433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.37729761127357875}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#include \"tz_error.h\"\n#if HAVE_LIBGSL == 1\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_statistics_double.h>\n#endif\n#include \"tz_constant.h\"\n#include \"tz_iarray.h\"\n#include \"tz_darray.h\"\n#include \"tz_voxel_linked_list.h\"\n#include \"tz_stack_sampling.h\"\n#include \"tz_voxel_graphics.h\"\n#include \"tz_neurotrace.h\"\n#include \"tz_stack_math.h\"\n#include \"tz_stack_utils.h\"\n#include \"tz_objdetect.h\"\n#include \"tz_voxeltrans.h\"\n#include \"tz_stack_stat.h\"\n#include \"tz_stack_draw.h\"\n#include \"tz_geo3d_vector.h\"\n#include \"tz_stack_bwmorph.h\"\n#include \"tz_vrml_io.h\"\n#include \"tz_locseg_chain.h\"\n#include \"tz_trace_utils.h\"\n#include \"tz_fmatrix.h\"\n#include \"tz_fimage_lib.h\"\n#include \"tz_arraytrans.h\"\n#include \"tz_neuron_structure.h\"\n#include \"tz_utilities.h\"\n#include \"tz_workspace.h\"\n#include \"tz_stack_graph.h\"\n#include \"tz_stack_attribute.h\"\n#include \"tz_math.h\"\n#include \"tz_stack_threshold.h\"\n\nINIT_EXCEPTION_MAIN(e)\n\nint main(int argc, char* argv[])\n{\n#if 0\n  Stack *stack = Read_Stack(\"/tmp/binimg.tif\");\n \n  Stack *dist = Stack_Bwdist(stack);\n\n  Stack *seeds = Stack_Local_Max(dist, NULL, STACK_LOCMAX_ALTER1);\n  \n  Write_Stack(\"/tmp/seedimg.tif\", seeds);\n#endif\n\n#if 0\n  Stack *stack = Read_Stack(\"/tmp/seedimg.tif\");\n\n  Voxel_List *list = Stack_To_Voxel_List(stack);\n\n  Print_Voxel_List(list);\n\n  Kill_Stack(stack);\n  \n  \n  stack = Read_Stack(\"/tmp/binimg.tif\");\n  Stack *dist = Stack_Bwdist(stack);\n\n  Pixel_Array *pa = Voxel_List_Sampling(dist, list);\n  \n  Print_Pixel_Array(pa);\n\n  Pixel_Array_Write(\"/tmp/seeds.pa\", pa);\n#endif\n\n#if 0\n  Stack *stack = Read_Stack(\"/tmp/seedimg.tif\");\n\n  Voxel_List *list = Stack_To_Voxel_List(stack);\n\n  //Print_Voxel_List(list);\n\n  Pixel_Array *pa = Pixel_Array_Read(\"/tmp/seeds.pa\");\n  //Print_Pixel_Array(pa);\n\n  Voxel *seed;\n\n  int i;\n  double *pa_array = (double *) pa->array;\n\n  gsl_vector_view gv = gsl_vector_view_array(pa_array, pa->size);\n  printf(\"mean: %g, std: %g\\n\", gsl_stats_mean(pa_array, 1, pa->size), \n\t sqrt(gsl_stats_variance(pa_array, 1, pa->size)));\n  \n  double threshold = gsl_stats_mean(pa_array, 1, pa->size) + \n    3.0 * sqrt(gsl_stats_variance(pa_array, 1, pa->size));\n  \n\n  \n  dim_type dim[3];\n  dim[0] = stack->width;\n  dim[1] = stack->height;\n  dim[2] = stack->depth;\n  \n  IMatrix *chord = Make_IMatrix(dim, 3);\n  \n  Stack *code = Make_Stack(GREY16, stack->width, stack->height, stack->depth);\n\n  Kill_Stack(stack);\n  stack = Read_Stack(\"/tmp/binimg.tif\");\n\n  Stack_Not(stack, stack);\n\n  Rgb_Color color;\n  Set_Color(&color, 255, 0, 0);\n\n  Stack *signal = Read_Stack(\"../data/testneurotrace.tif\");\n\n  Stack *canvas = Translate_Stack(signal, COLOR, 0);\n\n\n  /************** soma detection *************/\n#if 0\n  Struct_Element *se = Make_Ball_Se(((int) threshold));\n  Stack *stack1 = Stack_Erode_Fast(stack, NULL, se);\n  Stack *soma = Stack_Dilate(stack1, NULL, se);\n  Kill_Stack(stack1);  \n\n  Stack_And(stack, soma, soma);\n\n  Stack_Label_Bwc(canvas, soma, color);\n\n  Kill_Stack(soma);\n\n  Write_Stack(\"../data/test.tif\", canvas);\n  return 0;\n#endif\n  /*******************************************/\n  \n\n  Object_3d *obj = NULL;\n  int seed_offset = -1;\n\n  Neurochain *chain = NULL;\n  double z_scale = 0.8;\n \n  Stack *traced = \n    Make_Stack(GREY, signal->width, signal->height, signal->depth);\n  One_Stack(traced);\n\n  for (i = 0; i < pa->size; i++) {\n    seed = Voxel_Queue_De(&list);\n    printf(\"%d, color: %u, %u, %u\\n\", \n\t   i,\n\t   *STACK_PIXEL_8(canvas, seed->x, seed->y, seed->z, 0), \n\t   *STACK_PIXEL_8(canvas, seed->x, seed->y, seed->z, 1),\n\t   *STACK_PIXEL_8(canvas, seed->x, seed->y, seed->z, 2));\n    if (*STACK_PIXEL_8(canvas, seed->x, seed->y, seed->z, 2) == 0) {\n      continue;\n    }\n\n    double width = pa_array[i];\n\n    if (width > threshold) {\n      continue;\n    }\n\n    chain = New_Neurochain();\n\n    Print_Voxel(seed);\n    printf(\"%g\\n\", width);\n\n    \n    int max_level = (int) (width + 0.5);\n    if (max_level < 6) {\n      max_level = 6;\n    }\n\n    seed_offset = Stack_Util_Offset(seed->x, seed->y, seed->z, \n\t\t\t\t    stack->width, stack->height, stack->depth);\n    Stack_Level_Code_Constraint(stack, code, chord->array, &seed_offset, 1, \n\t\t\t\tmax_level + 1);\n\n    Voxel_t v;\n    Voxel_To_Tvoxel(seed, v);\n\n    Print_Tvoxel(v);\n\n    Stack *tmp_stack = Copy_Stack(stack);\n    obj = Stack_Grow_Object_Constraint(tmp_stack, 1, v, chord, code, \n\t\t\t\t       max_level);\n    Free_Stack(tmp_stack);\n\n    Print_Object_3d_Info(obj);\n\n    double vec[3];\n    Object_3d_Orientation_Zscale(obj, vec, MAJOR_AXIS, z_scale);\n\n    double theta, psi;\n    Geo3d_Vector obj_vec;\n    Set_Geo3d_Vector(&obj_vec, vec[0], vec[1], vec[2]);\n\n    darray_print2(vec, 3, 1);\n\n    Geo3d_Vector_Orientation(&obj_vec, &theta, &psi);\n    \n    Set_Neuroseg(&(chain->locseg.seg), width, width, 10.0, \n\t\t theta, psi);\n\n    double cpos[3];\n    cpos[0] = seed->x;\n    cpos[1] = seed->y;\n    cpos[2] = seed->z;\n    cpos[2] *= 0.8;\n\n    Set_Neuroseg_Position(&(chain->locseg), cpos, NEUROSEG_CENTER);\n\n    if (Initialize_Tracing(signal, chain, NULL, z_scale) >= MIN_SCORE) {\n      chain = Trace_Neuron(signal, chain, BOTH, traced, z_scale);\n\n      Print_Neurochain(chain);\n\n      //Stack_Draw_Object_Bwc(canvas, obj, color);\n\n      Neurochain_Erase(traced, Neurochain_Head(chain), z_scale);\n      Neurochain_Label(canvas, Neurochain_Head(chain), z_scale);\n    }\n\n    Free_Neurochain(chain);\n\n    free(seed);\n\n    Kill_Object_3d(obj);\n  }\n\n  Write_Stack(\"../data/test2.tif\", traced);\n  Write_Stack(\"../data/test.tif\", canvas);\n  \n#endif\n\n#if 0\n  Stack *stack = Read_Stack(\"/tmp/seedimg.tif\");\n  Voxel_List *list = Stack_To_Voxel_List(stack);\n  \n  Kill_Stack(stack);\n  stack = Read_Stack(\"../data/testneurotrace.tif\");\n  Pixel_Array *pa = Voxel_List_Sampling(stack, list);\n  \n  Print_Pixel_Array(pa);\n\n  Pixel_Array_Write(\"/tmp/test.pa\", pa);\n  Pixel_Array *pa2 = Pixel_Array_Read(\"/tmp/test.pa\");\n  Print_Pixel_Array(pa2);\n#endif\n\n#if 0\n  Stack *stack = Read_Stack(\"../data/fly_neuron.tif\");\n  double z_scale = 1.0;\n  Neurochain *chain = New_Neurochain();\n\n#if 0\n  Set_Neuroseg(&(chain->locseg.seg), 2.78302, 3.60932, 12.0, 3.58051, 4.6416);\n  Set_Neuropos(chain->locseg.pos, 308.154, 49.7471, 134.73);\n#endif\n\n#if 0\n  Set_Neuroseg(&(chain->locseg.seg), 2.7830153868018668, 3.6093167912750355, 12.0, 3.5805148810681988, 4.641602279067599);\n  Set_Neuropos(chain->locseg.pos, 308.15367011522028, 49.747085927056794, 134.73010125059292);\n#endif\n  \n#if 0\n  Set_Neuroseg(&(chain->locseg.seg), 2.7165, 3.49483, 12.0, 3.39146, 4.70638);\n  Set_Neuropos(chain->locseg.pos, 306.119, 49.8914, 139.075);\n#endif\n\n#if 0\n  Set_Neuroseg(&(chain->locseg.seg), 3.17991, 4.56142, 12.0, 2.10521, 2.34306,\n\t       0);\n  Set_Neuropos(chain->locseg.pos, 344.281, 258.937, 138.332);\n#endif\n  \n  Set_Neuroseg(&(chain->locseg.seg), 2.12805, 3.37411, 12.0, 2.94503, 2.25645,\n\t       0);\n  Set_Neuropos(chain->locseg.pos, 343.556, 258.344, 143.04);\n\n  //refit_local_neuroseg(&(chain->locseg), stack, z_scale, NULL);\n  \n  Neuroseg_Fit_Score fs;\n  fs.n = 1;\n  fs.options[0] = 1;\n  printf(\"%g\\n\", Local_Neuroseg_Score(&(chain->locseg), stack, z_scale, &fs));\n  //Trace_Neuron2(stack, chain, BACKWARD, NULL, z_scale, 10);\n  \n  //Print_Neurochain(chain);\n\n  stack = Translate_Stack(stack, COLOR, 1);\n  Neurochain_Label(stack, Neurochain_Head(chain), z_scale);\n  Write_Stack(\"../data/test.tif\", stack);\n\n#endif\n\n#if 0\n  Stack *stack = Read_Stack(\"../data/testneurotrace.tif\");\n\n  double z_scale = 0.488/0.585;\n\n  Neurochain *chain = New_Neurochain();\n  Set_Neuroseg(&(chain->locseg.seg), 2.0, 2.0, 12.0, -TZ_PI_2, 0.0);\n  //Set_Neuropos(chain->locseg.pos, 95, 96, 162*0.8);\n  //Set_Neuropos(chain->locseg.pos, 39, 192, 283 * z_scale);\n  Set_Neuropos(chain->locseg.pos, 129, 170, 239 * z_scale);\n\n  //Trace_Neuron(stack, chain, BOTH, NULL, z_scale, 100);\n\n  //Set_Neuropos(chain->locseg.pos, 143, 99, 107*0.8);\n  //Set_Position(chain->position, 127, 68, 34*0.8);\n  //Set_Position(chain->position, 60, 136, 91*0.8);\n  //Set_Position(chain->position, 176, 221, 184*0.8);\n\n  //Fit_Local_Neuroseg(stack, &(chain->seg), chain->position, TRUE); \n\n  /*  \n  Set_Neuroseg(&(chain->locseg.seg), 1.8295717513170491, 1.2647574210394514, \n\t       12, -1.2864278377709504, 0.51799979287881037);\n  Set_Neuropos(chain->locseg.pos, 91.370009398825573, 98.614687377839488, \n\t       131.9121806489851);\n  */\n\n  /*\n  Set_Neuroseg(&(chain->locseg.seg), 5, 5, \n\t       11.1336, -TZ_PI_2, 0.0);\n  Set_Neuropos(chain->locseg.pos, 90.1456, 99.1741, 132.564);\n  */\n\n  int i;\n  for (i = 0; i < 1; i++) {\n    Initialize_Tracing(stack, chain, NULL, z_scale);\n  }\n  \n  /*\n  int var_index[LOCAL_NEUROSEG_NPARAM];\n  int nvar = Local_Neuroseg_Var_Mask_To_Index(NEUROSEG_VAR_MASK_ORIENTATION, \n\t\t\t\t\t      NEUROPOS_VAR_MASK_NONE, \n\t\t\t\t\t      var_index);\n\n  Fit_Local_Neuroseg(&(chain->locseg), stack, var_index, nvar, z_scale,\n\t\t      NULL);\n\n  nvar = Local_Neuroseg_Var_Mask_To_Index(NEUROSEG_VAR_MASK_R, \n\t\t\t\t\t  NEUROPOS_VAR_MASK_NONE, \n\t\t\t\t\t  var_index);\n\n  Fit_Local_Neuroseg(&(chain->locseg), stack, var_index, nvar, z_scale,\n\t\t      NULL);\n\n  printf(\"score: %g\\n\", \n\t Local_Neuroseg_Score(&(chain->locseg), stack, z_scale, NULL));\n  */\n\n  Trace_Neuron2(stack, chain, BOTH, NULL, z_scale, 10);\n\n  \n\n  //Print_Neurochain(chain);\n\n  stack = Translate_Stack(stack, COLOR, 1);\n  Neurochain_Label(stack, Neurochain_Head(chain), z_scale);\n  //Flip_Local_Neuroseg(&(chain->locseg));\n  //Local_Neuroseg_Label(&(chain->locseg), stack, 1, z_scale);\n\n  Write_Stack(\"../data/test.tif\", stack);\n\n  Kill_Stack(stack);\n#endif\n  \n#if 0 /* fly neuron tracing */\n  //Stack *stack = Read_Stack(\"../data/fly_neuron.tif\");\n  //Stack *stack = Read_Stack(\"../data/resimg.tif\");\n  Stack *stack = Read_Stack(\"../data/fly_neuron2.tif\");\n\n  double z_scale = 1.0;\n  \n  Neurochain *chain = New_Neurochain();\n\n  //Set_Neuroseg(&(chain->locseg.seg), 2.19832, 2.18053, 12, -3.54093, 0.779524);\n  Set_Neuropos(chain->locseg.pos, 166, 325, 43); /* fly_neuron2 */\n  \n\n  Set_Neuroseg(&(chain->locseg.seg), 2.0, 2.0, 12.0, -TZ_PI_2, 0.0);\n  //Set_Neuroseg(&(chain->locseg.seg), 2.0, 2.0, 12.0, TZ_PI_2, TZ_PI_2);\n  //Set_Neuroseg(&(chain->locseg.seg), 1.70074, 1.09443, 12, 2.12734, 1.77422);\n  //Set_Neuroseg(&(chain->locseg.seg), 4.51936, 4.19414, 12, 3.56059, 3.13054);\n  \n  //Set_Neuropos(chain->locseg.pos, 294, 178, 172);\n\n  //Set_Neuropos(chain->locseg.pos, 280.328, 60.8357, 198.226);\n  //Set_Neuropos(chain->locseg.pos, 281, 64, 202);\n  //Set_Neuropos(chain->locseg.pos, 207, 227, 168);\n  //Set_Neuropos(chain->locseg.pos, 166, 238, 141);\n  //Set_Neuropos(chain->locseg.pos, 294, 178, 175);\n  //Set_Neuropos(chain->locseg.pos, 296, 217, 160);\n  //Set_Neuropos(chain->locseg.pos, 296, 217, 160);\n  //Set_Neuropos(chain->locseg.pos, 282, 64, 204);\n  //Set_Neuropos(chain->locseg.pos, 294, 255, 158);\n  //Set_Neuropos(chain->locseg.pos, 220, 342, 68);\n  //Set_Neuropos(chain->locseg.pos, 227, 283, 139);\n  //Set_Neuropos(chain->locseg.pos, 231, 327, 67);\n  //Set_Neuropos(chain->locseg.pos, 179, 266, 142);\n  //Set_Neuropos(chain->locseg.pos, 246.546, 296.202, 106.407);\n  //Set_Neuropos(chain->locseg.pos, 307.867, 62.5301, 274.218);\n  \n  //Trace_Neuron(stack, chain, BOTH, NULL, z_scale, 100);\n\n  //Set_Neuropos(chain->locseg.pos, 143, 99, 107*0.8);\n  //Set_Position(chain->position, 127, 68, 34*0.8);\n  //Set_Position(chain->position, 60, 136, 91*0.8);\n  //Set_Position(chain->position, 176, 221, 184*0.8);\n\n  //Fit_Local_Neuroseg(stack, &(chain->seg), chain->position, TRUE); \n\n  /*\n  Set_Neuroseg(&(chain->locseg.seg), 1.8295717513170491, 1.2647574210394514, \n\t       12, -1.2864278377709504, 0.51799979287881037);\n  Set_Neuropos(chain->locseg.pos, 91.370009398825573, 98.614687377839488, \n\t       131.9121806489851);\n  */  \n\n  /*\n  Set_Neuroseg(&(chain->locseg.seg), 5, 5, \n\t       11.1336, -TZ_PI_2, 0.0);\n  Set_Neuropos(chain->locseg.pos, 90.1456, 99.1741, 132.564);\n  */  \n\n\n  int i;\n  for (i = 0; i < 1; i++) {\n    Initialize_Tracing(stack, chain, NULL, z_scale);\n  }\n\n#if 0  \n  /*\n  int var_index[LOCAL_NEUROSEG_NPARAM];\n  int nvar = Local_Neuroseg_Var_Mask_To_Index(NEUROSEG_VAR_MASK_ORIENTATION, \n\t\t\t\t\t      NEUROPOS_VAR_MASK_NONE, \n\t\t\t\t\t      var_index);\n\n  Fit_Local_Neuroseg(&(chain->locseg), stack, var_index, nvar, z_scale,\n\t\t      NULL);\n\n  nvar = Local_Neuroseg_Var_Mask_To_Index(NEUROSEG_VAR_MASK_R, \n\t\t\t\t\t  NEUROPOS_VAR_MASK_NONE, \n\t\t\t\t\t  var_index);\n\n  Fit_Local_Neuroseg(&(chain->locseg), stack, var_index, nvar, z_scale,\n\t\t      NULL);\n\n  printf(\"score: %g\\n\", \n\t Local_Neuroseg_Score(&(chain->locseg), stack, z_scale, NULL));\n  */\n\n  Trace_Neuron2(stack, chain, FORWARD, NULL, z_scale, 30);  \n#endif\n\n  Print_Neurochain(chain);\n\n  printf(\"%g\\n\", Local_Neuroseg_Score(&(chain->locseg), stack, z_scale, NULL));\n  \n  stack = Translate_Stack(stack, COLOR, 1);\n  Neurochain_Label(stack, Neurochain_Head(chain), z_scale);\n  //Flip_Local_Neuroseg(&(chain->locseg));\n  //Local_Neuroseg_Label(&(chain->locseg), stack, 1, z_scale);\n\n  Write_Stack(\"../data/test.tif\", stack);\n\n  Kill_Stack(stack);\n#endif\n\n#if 0 /* check segments */\n  Neurochain *chain = New_Neurochain();\n  FILE *fp = fopen(\"../data/fly_neuron/chain103.bn\", \"r\");\n  Neurochain_Fread(chain, fp);\n  fclose(fp);\n  int length = Neurochain_Length(chain, FORWARD);\n  printf(\"%d\\n\", length);\n  //Print_Neurochain(chain);\n\n  Stack *stack = Read_Stack(\"../data/fly_neuron.tif\");\n  double z_scale = 1.0;\n  Neuroseg_Fit_Score fs;\n  fs.n = 1;\n  fs.options[0] = 1;\n  double score = Neurochain_Score(chain, stack, z_scale, &fs);\n  printf(\"%g\\n\", score / length);\n#endif\n\n#if 0 /* check chain features */\n  char cmd[100];\n  sprintf(cmd, \"ls ../data/%s/*.wrl > ../data/%s/wrllist.txt\")\n  system(cmd);\n#endif\n\n#if 0\n  /* read stack */\n  Stack *stack = Read_Stack(\"../data/run_w1_t1.tif\");\n  double z_scale = 1.0;\n\n  /* Initialize neurochain */\n  Neurochain *chain = New_Neurochain();\n  Set_Neuroseg(&(chain->locseg.seg), 3.0, 3.0, 12.0, 0.0, 0.0, 0.0);\n  Set_Neuropos(chain->locseg.pos, 72, 35, 0);\n\n  //Initialize_Tracing(stack, chain, NULL, z_scale);\n  Trace_Neuron2(stack, chain, FORWARD, NULL, z_scale, 30);\n\n  Translate_Stack(stack, COLOR, 1);\n  Neurochain_Label(stack, Neurochain_Head(chain), z_scale);\n  \n  Write_Stack(\"../data/test.tif\", stack);\n#endif\n\n#if 0\n  double pos[] = {268, 265, 56};\n  double r = 3.0;\n  Local_Neuroseg_Ellipse *locne = New_Local_Neuroseg_Ellipse();\n  Set_Local_Neuroseg_Ellipse(locne, r, r, TZ_PI_2, 0, 0, 0,\n\t\t\t     pos[0], pos[1], pos[2]);\n  char *imgfile = \"../data/mouse_neuron.tif\";\n  Stack *stack = Read_Stack(imgfile);\n\n  Locne_Chain *chain = Trace_Soma(stack, 1.0, locne, NULL);\n  \n  double point[] = {277.5, 255.5, 56.5};\n  BOOL hit = Locne_Chain_Hittest(chain, point);\n\n  if (hit == TRUE) {\n    printf(\"The point hits the object\\n\");\n  } else {\n    printf(\"The point misses the object\\n\");\n  }\n#endif\n\n#if 0\n  Geo3d_Scalar_Field *seed = \n    Read_Geo3d_Scalar_Field(\"../data/mouse_neuron_org/seeds\");\n\n  int *indices = iarray_malloc(seed->size);\n  double *values = darray_malloc(seed->size);\n\n  int i;\n  for (i = 0; i < seed->size; i++) {\n    indices[i] = i;\n  }\n\n  darraycpy(values, seed->values, 0, seed->size);\n\n  darray_qsort(values, indices, seed->size);\n  \n  int index = indices[seed->size-1];\n\n  printf(\"%d\\n\", seed->size);\n\n  printf(\"%g\\n\", seed->values[index]);\n  printf(\"%g, %g, %g\\n\", seed->points[index][0], \n\t seed->points[index][1], seed->points[index][2]);\n  \n  double r = seed->values[index];\n\n\n  Local_Neuroseg_Ellipse *segs[10];\n\n  segs[0] = New_Local_Neuroseg_Ellipse();\n  Set_Local_Neuroseg_Ellipse(segs[0], r, r, TZ_PI_2, 0, 0, 0, 0,\n\t\t\t     seed->points[index][0],\n\t\t\t     seed->points[index][1],\n\t\t\t     seed->points[index][2]);\n  char *imgfile = \"../data/mouse_neuron_org.tif\";\n  Stack *stack = Read_Stack(imgfile);\n\n  Locne_Chain *somas[10];\n  int nsoma = 0;\n\n  Soma_Trace_Workspace *stw = New_Soma_Trace_Workspace();\n  stw->tw.dyvar[0] = r * 3.0;\n  stw->tw.dyvar[1] = 5.0;\n  stw->tw.test_func = Locne_Chain_Trace_Test;\n\n  somas[nsoma++] = Trace_Soma(stack, 1.0, segs[0], stw);\n\n\n  int j;\n\n  for (i = seed->size - 1; i >= 0; i--) {\n    BOOL traced = FALSE;\n    for (j = 0; j < nsoma; j++) {\n      if (Locne_Chain_Hittest(somas[j], seed->points[indices[i]]) == TRUE) {\n\ttraced = TRUE;\n\tPrint_Coordinate_3d(seed->points[indices[i]]);\n\tbreak;\n      }\n    }\n    \n    if (traced == FALSE) {\n      index = indices[i];\n\n      r = seed->values[index];\n      segs[nsoma] = New_Local_Neuroseg_Ellipse();\n      Set_Local_Neuroseg_Ellipse(segs[nsoma], r, r, TZ_PI_2, 0, 0, 0, 0,\n\t\t\t\t seed->points[index][0],\n\t\t\t\t seed->points[index][1],\n\t\t\t\t seed->points[index][2]);\n      somas[nsoma] = Trace_Soma(stack, 1.0, segs[nsoma], stw);\n      nsoma++;\n    }\n    \n    if (nsoma >= 10) {\n      break;\n    }\n  }\n\n  for (i = 0; i < nsoma; i++) {\n    Print_Local_Neuroseg_Ellipse(segs[i]);\n    printf(\"soma score: %g\\n\", Soma_Score(somas[i]));\n    if (Soma_Score(somas[i]) > 1.0) {\n      char file_path[100];\n      sprintf(file_path, \"../data/mouse_neuron/soma%d.bn\", i); \n      Write_Locne_Chain(file_path, somas[i]);\n      //Soma_Stack_Mask(somas[i], stack, 1.0, 0.0);\n    }\n  }\n\n  darray_write(\"../data/test.bn\", values, seed->size);\n\n  //Write_Stack(\"../data/test.tif\", stack);\n\n#  if 1\n  Stack *label = Make_Stack(FLOAT32, stack->width, stack->height, stack->depth);\n  Zero_Stack(label);\n  double coef[] = {0.1, 255.0};\n  double range[] = {0.0, 10000.0};\n\n  FILE *fp = fopen(\"../data/test.wrl\", \"w\");\n  \n  Vrml_Head_Fprint(fp, \"V2.0\", \"utf8\");\n\n  Geo3d_Scalar_Field* field = NULL;\n  Local_Neuroseg_Ellipse *locne;\n  for (i = 0; i < nsoma; i++) {\n    if ((Soma_Score(somas[i]) > 1.0) && Locne_Chain_Length(somas[i]) >= 10) {\n      Locne_Chain *chain = somas[i];\n      Locne_Chain_Vrml_Fprint(fp, chain, 0);\n      Locne_Chain_Iterator_Start(chain);\n      int offset = 0;\n      while ((locne = Locne_Chain_Next(chain)) != NULL) {\n\tfield = Local_Neuroseg_Ellipse_Field(locne, 0.5, NULL);\n\tGeo3d_Scalar_Field_Draw_Stack(field, label, coef, range);\n\tKill_Geo3d_Scalar_Field(field);\n\toffset++;\n      }\n\n      //printf(\"%d\\n\", Locne_Chain_Length(chain));\n    }\n  }\n\n  fclose(fp);\n\n  /* Turn the stack to GREY type */\n  label = Scale_Float_Stack((float *) label->array, label->width, label->height,\n\t\t\t    label->depth, GREY);\n\n  /* Make canvas */\n  Translate_Stack(stack, COLOR, 1);\n  \n  /* Label the canvas */\n  Stack_Label_Color(stack, label, 5.0, 1.0, label);\n\n  /* Save the stack */\n  Write_Stack(\"../data/test.tif\", stack);\n#  endif\n\n#endif\n\n#if 0\n  Trace_Workspace *tw = New_Trace_Workspace();\n  tw->trace_direction = DL_FORWARD;\n\n  Stack *stack = Read_Stack(\"../data/fly_neuron2.tif\");\n\n  double z_scale = 1.0;\n  \n  Local_Neuroseg *locseg = New_Local_Neuroseg();\n  Set_Neuropos(locseg->pos, 166, 325, 43); /* fly_neuron2 */\n  Set_Neuroseg(&(locseg->seg), 2.0, 2.0, 12.0, -TZ_PI_2, 0.0, 0.0);\n\n  tw->test_func = Locseg_Chain_Trace_Test;\n  tw->dyvar[0] = 10.0;\n  \n  Stack_Fit_Score fs;\n  fs.n = 2;\n  fs.options[0] = 0;\n  fs.options[1] = tw->tscore_option;\n  Locseg_Chain* chain = Locseg_Chain_Trace_Init(stack, z_scale, locseg, &fs);\n  \n  Trace_Locseg(stack, z_scale, chain, tw);\n\n  Print_Locseg_Chain(chain);\n\n  Translate_Stack(stack, COLOR, 1);\n  Locseg_Chain_Label(chain, stack, z_scale);\n\n  Write_Stack(\"../data/test.tif\", stack);\n#endif\n\n#if 0\n  Trace_Workspace *tw = New_Trace_Workspace();\n  tw->trace_direction = DL_BOTHDIR;\n\n  Stack *stack = Read_Stack(\"../data/fly_neuron2.tif\");\n\n  double z_scale = 1.0;\n  \n  Local_Neuroseg *locseg = New_Local_Neuroseg();\n  Set_Neuropos(locseg->pos, 164, 322, 43);\n  Set_Neuroseg(&(locseg->seg), 2.0, 0.0, 12.0, -TZ_PI_2, 0.0, 0.0, 0.0, 1.0);\n  //Local_Neuroseg_Height_Search_P(locseg, stack, 1.0);\n  Print_Local_Neuroseg(locseg);\n\n\n  tw->test_func = Locseg_Chain_Trace_Test;\n  tw->dyvar[0] = 10.0;\n  \n  Locseg_Fit_Workspace *fw = New_Locseg_Fit_Workspace();\n  \n  Locseg_Chain* chain = Locseg_Chain_Trace_Init(stack, z_scale, locseg, fw);\n\n\n  // Local_Neuroseg_Height_Search_P(locseg, stack, 1.0);\n  Print_Locseg_Chain(chain);\n\n  Trace_Locseg(stack, z_scale, chain, tw);\n  //Locseg_Chain_Remove_Overlap_Ends(chain);\n  //Locseg_Chain_Remove_Turn_Ends(chain, 1.0);\n\n  /*\n  Local_Neuroseg_Plane *locnp = Local_Neuroseg_To_Plane(locseg, 12.0, NULL);\n  Locnp_Chain *locnp_chain = Locnp_Chain_Trace_Init(stack, z_scale, locnp);\n  \n  tw->length = locseg->seg.h * 10;\n  tw->fit_first = FALSE;\n  tw->tscore_option = 1;\n  tw->min_score = 0.5;\n  tw->trace_direction = DL_FORWARD;\n  tw->trace_mask = NULL;\n  tw->dyvar[0] = 100.0;\n  tw->test_func = Locnp_Chain_Trace_Test;\n  Trace_Locnp(stack, 1.0, locnp_chain, tw);\n  \n  Locseg_Chain_Append_Locnp(chain, locnp_chain);\n\n  Kill_Locnp_Chain(locnp_chain);\n  */\n  Translate_Stack(stack, COLOR, 1);\n  Locseg_Chain_Label(chain, stack, z_scale);\n\n  Write_Stack(\"../data/test.tif\", stack);\n\n  Kill_Stack(stack);\n  Kill_Locseg_Chain(chain);\n#endif\n\n#if 0\n  Neurochain *chain = Read_Neurochain(\"../data/mouse_neuron3_org/chain9810.bn\");\n\n  Stack *stack = Read_Stack(\"../data/mouse_neuron3_org.tif\");\n  double z_scale = 1.0;\n\n  Locseg_Chain *locseg_chain = Neurochain_To_Locseg_Chain(chain);\n\n  Locseg_Chain_Remove_End(locseg_chain, DL_HEAD);\n  Locseg_Chain_Remove_End(locseg_chain, DL_TAIL);\n\n  Print_Locseg_Chain(locseg_chain);\n\n\n  Trace_Workspace tw;\n  tw.length = 100;\n  tw.fit_first = FALSE;\n  tw.tscore_option = 1;\n  tw.min_score = 0.3;\n  tw.trace_direction = DL_FORWARD;\n  tw.trace_mask = NULL;//Read_Stack(\"../data/mouse_neuron3_org/trace_mask.tif\");\n  tw.dyvar[0] = 10.0;\n  tw.test_func = Locnp_Chain_Trace_Test;\n  Locseg_Chain_Trace_Np(stack, z_scale, locseg_chain, &tw);\n\n  Stretch_Stack_Value_Q(stack, 0.999);\n  Stack *canvas = Translate_Stack(stack, COLOR, 1);\n  Locseg_Chain_Label(locseg_chain, canvas, 1.0);\n  Write_Stack(\"../data/test.tif\", canvas);\n#endif\n\n#if 0\n  Stack *stack1 = Read_Stack(\"../data/fly_neuron/trace_mask.tif\");\n  Stack *stack2 = Read_Stack(\"../data/fly_neuron/mask.tif\");\n  Stack_And(stack1, stack2, stack2);\n  Write_Stack(\"../data/test.tif\", stack2);\n#endif\n\n#if 0\n  static char *Spec[] = { \"-p <int> <int> <int>\",\n\t\t\t  NULL};\n\n  Process_Arguments(argc, argv, Spec, 1);\n  \n  double pos[3];\n  pos[0] = Get_Int_Arg(\"-p\", 1);\n  pos[1] = Get_Int_Arg(\"-p\", 2);\n  pos[2] = Get_Int_Arg(\"-p\", 3);\n  \n  Geo3d_Scalar_Field *seed = \n    Read_Geo3d_Scalar_Field(\"../data/mouse_neuron3_org/seeds\");\n\n  int i;\n  for (i = 0; i < seed->size; i++) {\n    if ((fabs(pos[0] - seed->points[i][0]) < 1.0) &&\n\t(fabs(pos[1] - seed->points[i][1]) < 1.0) &&\n\t(fabs(pos[2] - seed->points[i][2]) < 1.0)) {\n      printf(\"%d, %g\\n\", i, seed->values[i]);\n      break;\n    }\n  }\n  \n  char chain_file_path[100];\n  sprintf(chain_file_path, \"../data/mouse_neuron3_org/chain%d.bn\", i);\n  Neurochain *chain = Read_Neurochain(chain_file_path);\n  Print_Neurochain(chain);\n#endif\n\n#if 0\n  Trace_Record *tr = NULL;\n  fp = fopen(\"../data/test\", \"w\");\n  Trace_Record_Fwrite(tr, fp);\n  fclose(fp);\n\n \n#endif\n\n\n#if 0\n  Geo3d_Scalar_Field *seed = \n    Read_Geo3d_Scalar_Field(\"../data/adult_fly_neuron/seeds\");\n\n  Stack *stack = Read_Stack(\"../data/adult_fly_neuron.tif\");\n\n  double z_scale = 1.0;\n  int index = 1213;\n  double r0 = seed->values[index];\n  if (r0 < 3.0) {\n    r0 = 3.0;\n  }\n\n  printf(\"(%g %g %g) %g\\n\", seed->points[index][0], seed->points[index][1],\n\t seed->points[index][2], seed->values[index]);\n\n  Local_Neuroseg *locseg = New_Local_Neuroseg();\n  Set_Neuroseg_Position(locseg, seed->points[index], NEUROSEG_CENTER);\n  Set_Neuroseg(&(locseg->seg), r0, r0, 12.0, 0.0, 0.0, 0.0);\n  Stack_Fit_Score ortfs;\n  ortfs.n = 1;\n  ortfs.options[0] = STACK_FIT_CORRCOEF;\n  Local_Neuroseg_Orientation_Search_C(locseg, stack, z_scale, &ortfs); \n  \n\n  Trace_Workspace *tw = New_Trace_Workspace();\n  tw->length = 200;\n  tw->fit_first = FALSE;\n  tw->tscore_option = STACK_FIT_CORRCOEF;\n  tw->min_score = 0.3;\n  tw->trace_direction = DL_BOTHDIR;\n  tw->trace_status[0] = TRACE_NORMAL;\n  tw->trace_status[1] = TRACE_NORMAL;\n  tw->trace_range[0] = 0;\n  tw->trace_range[1] = 0;\n  tw->trace_range[2] = 0;\n  tw->trace_range[3] = stack->width - 1;\n  tw->trace_range[4] = stack->height - 1;\n  tw->trace_range[5] = stack->depth - 1;\n  tw->trace_mask = NULL;\n  tw->dyvar[0] = 10.0;\n  tw->test_func = Locseg_Chain_Trace_Test;\n\n  Stack_Fit_Score fs;\n  fs.n = 1;\n  fs.options[0] = tw->tscore_option;\n  Locseg_Chain *chain = Locseg_Chain_Trace_Init(stack, z_scale, locseg, &fs);\n\n  tic();\n  if (fs.scores[0] >= tw->min_score) {\n    Trace_Locseg(stack, z_scale, chain, tw);\n  }\n  printf(\"time passed: %lld\\n\", toc());\n  \n  Print_Locseg_Chain(chain);\n\n  Translate_Stack(stack, GREY, 1);\n  Stretch_Stack_Value_Q(stack, 0.999);   \n  Stack *canvas = Translate_Stack(stack, COLOR, 0);\n  Neurochain *chain_head = Neurochain_From_Locseg_Chain(chain);\n  Neurochain_Label(canvas, chain_head, z_scale);\n  Write_Stack(\"../data/test.tif\", canvas);\n  Kill_Stack(canvas);\n  Kill_Stack(stack);\n  \n#endif\n\n#if 0\n  Locseg_Chain *chain1 = Read_Locseg_Chain(\"../data/fly_neuron/chain26.bn\");\n  Locseg_Chain *chain2 = Read_Locseg_Chain(\"../data/fly_neuron/chain90.bn\");\n  \n  Stack *stack = Read_Stack(\"../data/fly_neuron.tif\");\n\n  neurocomp_conn_t conn;\n  conn[0] = NEUROCOMP_CONN_HL;\n  Locseg_Chain_Connection_Test(chain1, chain2, stack, 1.0, conn, NULL);\n\n  Print_Neurocomp_Conn(conn);\n\n  /*\n  Int_Arraylist *path = Locseg_Chain_Path2(chain1, chain2, stack, 1.0);\n  //Print_Int_Arraylist(path, \"%d\");\n  \n  Pixel_Array *pa = Stack_Index_Sampling(stack, path->array, path->length);\n  Print_Pixel_Array(pa);\n  Pixel_Array_Export(\"../data/test.bn\", pa);\n  */\n  \n  /*\n  Image_Array ima;\n  Translate_Stack(stack, COLOR, 1);\n  ima.array = stack->array;\n\n  int i;\n  for (i = 0; i < path->length; i++) {\n    ima.arrayc[path->array[i]][0] = 255;\n    ima.arrayc[path->array[i]][1] = 0;\n    ima.arrayc[path->array[i]][1] = 0;\n  }\n\n  Locseg_Chain_Label(chain1, stack, 1.0);\n  //Locseg_Chain_Label(chain2, stack, 1.0);\n  Write_Stack(\"../data/test.tif\",stack);\n  */\n#endif\n\n#if 0\n  \n  Stack *stack = Read_Stack(\"../data/mouse_single_org.tif\");\n  Stack *mask = Read_Stack(\"../data/mouse_single_org/mask2.tif\");\n  \n  /*\n  Stack *stack = Read_Stack(\"../data/rn003/cross_45_0.tif\");\n  Stack *mask = Read_Stack(\"../data/rn003/cross_45_0/mask2.tif\");\n  */\n\n  Stack_Seed_Workspace *ssw = New_Stack_Seed_Workspace();\n  Geo3d_Scalar_Field *seed = Stack_Seed(mask, ssw);\n\n  Trace_Evaluate_Seed_Workspace *ws = New_Trace_Evaluate_Seed_Workspace();\n  Trace_Evaluate_Seed(seed, stack, 1.0, ws);\n  \n  Trace_Workspace *tw = New_Trace_Workspace();\n  Locseg_Chain_Default_Trace_Workspace(tw, stack);\n  \n  \n  double sigma[3] = {1.0, 1.0, 0.5};\n  FMatrix *filter = Gaussian_3D_Filter_F(sigma, NULL);\n  FMatrix *result = Filter_Stack_Fast_F(stack, filter, NULL, 0);\n  \n  Array_Link *a = FMatrix_To_Stack(result); \n\n  tw->sup_stack = Get_Stack_At(a);\n\n\n  int nchain1;\n  \n  Locseg_Chain **chain = \n    Trace_Locseg_S(stack, 1.0, ws->locseg, ws->score, ws->nseed, tw, &nchain1);\n\n  Stack_Binarize(tw->trace_mask);\n  Stack *trace_mask = Translate_Stack(tw->trace_mask, GREY, 0);\n\n  Stack_Or(trace_mask, ws->base_mask, trace_mask);\n  Struct_Element *se = Make_Zline_Se(5);\n  Stack *submask = Stack_Dilate(trace_mask, NULL, se);\n\n  Stack_Bsub(mask, submask, mask);\n  // Stack_Brighten_Bw(mask);\n\n  Stack *mask2 = Stack_Remove_Small_Object(mask, NULL, 27, 26);\n  /*\n  Stack_Brighten_Bw(mask2);\n\n  Write_Stack(\"../data/test.tif\", mask2);\n\n  return 1;\n  */\n\n  Geo3d_Scalar_Field *seed2 = Stack_Seed(mask2, ssw);\n  Trace_Evaluate_Seed(seed2, stack, 1.0, ws);\n\n  tw->min_chain_length = NEUROSEG_DEFAULT_H * 1.5;\n\n  int nchain2;\n  Locseg_Chain **chain2 = \n    Trace_Locseg_S(stack, 1.0, ws->locseg, ws->score, ws->nseed, tw, &nchain2); \n  \n  Print_Geo3d_Scalar_Field(seed2);\n\n  Write_Stack(\"../data/test.tif\", tw->canvas);\n\n\n  Kill_FMatrix(result);\n\n  int nchain = nchain1 + nchain2;\n\n  Locseg_Chain **allchain = (Locseg_Chain**) \n    Guarded_Malloc(sizeof(Locseg_Chain*) * nchain, \"main\");\n  memcpy(allchain, chain, sizeof(Locseg_Chain*) * nchain1);\n  memcpy(allchain + nchain1, chain2, sizeof(Locseg_Chain*) * nchain2);\n\n#  if 1\n  /* Array to store corrected chains */\n  Neuron_Component *chain_array = Make_Neuron_Component_Array(nchain);\n  int chain_number = 0;\n\n  int i;\n\n  /* build chain map */\n  for (i = 0; i < nchain; i++) {\n    if (allchain[i] != NULL) {\n      if (Locseg_Chain_Geolen(allchain[i]) >= tw->min_chain_length) {\n\tSet_Neuron_Component(chain_array + chain_number, \n\t\t\t     NEUROCOMP_TYPE_LOCSEG_CHAIN, allchain[i]);\n\tchain_number++;\n      }\n    }\n  }\n\n  Neuron_Structure *ns = Locseg_Chain_Comp_Neurostruct(chain_array, \n\t\t\t\t\t\t       chain_number,\n\t\t\t\t\t\t       stack, 1.0, NULL);\n  Process_Neuron_Structure(ns);\n  Neuron_Structure* ns2=\n    Neuron_Structure_Locseg_Chain_To_Circle(ns);\n  \n  Neuron_Structure_Main_Graph(ns2);\n  Neuron_Structure_To_Tree(ns2);\n  \n  Neuron_Structure_To_Swc_File_Circle(ns2, \n\t\t\t\t      fullpath(\"../data\", \"test.swc\", NULL));\n#  endif\n\n#endif\n\n#if 0\n  Stack *signal = Read_Stack(\"../data/diadem_e1.tif\");\n  Locseg_Chain *chain1 = Read_Locseg_Chain(\"../data/diadem_e1/chain0.tb\");\n  Local_Neuroseg locseg[2];\n  Local_Neuroseg_Copy(locseg, Locseg_Chain_Head_Seg(chain1));\n  Local_Neuroseg_Copy(locseg + 1, Locseg_Chain_Tail_Seg(chain1));\n  while (1) {\n    Trace_Workspace *tw = New_Trace_Workspace();\n    Locseg_Chain_Default_Trace_Workspace(tw, signal);\n    tw->break_refit = TRUE;\n    strcpy(tw->save_path, \"../data/test/chain\");\n\n    int nchain;\n    Locseg_Chain **chain = Trace_Locseg_S(signal, 1.0, locseg, NULL, 2, tw,\n\t\t\t\t\t  &nchain);\n\n    printf(\"%d\\n\", nchain);\n\n    Kill_Trace_Workspace(tw);\n    int i;\n    for (i = 0; i < nchain; i++) {\n      Kill_Locseg_Chain(chain[i]);\n    }\n    free(chain);\n  }\n#endif\n\n#if 0\n  Stack *signal = Read_Stack(\"../data/fly_neuron_n1.tif\");\n  Stack *mask = Read_Stack(\"../data/fly_neuron_n1/trace_mask.tif\");\n  \n  Locseg_Chain *chain = Read_Locseg_Chain(\"../data/fly_neuron_n1/chain0.tb\");\n  Local_Neuroseg *locseg = Locseg_Chain_Head_Seg(chain);\n  Local_Neuroseg_Push(locseg, signal, 1.0, mask, STACK_FIT_VALID_SIGNAL_RATIO,\n\t\t      NULL, NULL);\n#endif\n\n#if 0\n  Trace_Workspace *tw = New_Trace_Workspace();\n  Locseg_Chain_Default_Trace_Workspace(tw, NULL);\n  Print_Trace_Workspace(tw);\n  Print_Locseg_Fit_Workspace((Locseg_Fit_Workspace*) tw->fit_workspace);\n#endif\n\n#if 0\n  Trace_Record *tr = New_Trace_Record();\n  tr->mask = ALL_ON_BIT_MASK;\n  \n  tr->fs.n = 1;\n  tr->fs.options[0] = 1;\n  tr->fs.scores[0] = 0.3;\n  tr->hit_region = 1;\n  tr->index = 2;\n  tr->refit = 1;\n\n  Print_Trace_Record(tr);\n\n  /*\n  FILE *fp = fopen(\"../data/test.bn\", \"w\");\n  Trace_Record_Fwrite(tr, fp);\n  fclose(fp);\n  */\n\n  Trace_Record *tr2 = New_Trace_Record();\n\n  FILE *fp2 = fopen(\"../data/test.bn\", \"r\");\n  Trace_Record_Fread(tr2, fp2);\n  fclose(fp2);\n  \n  Print_Trace_Record(tr2);\n\n  char *ct1 = (char*) tr;\n  char *ct2 = (char*) tr2;\n  \n  int i;\n  for (i = 0; i < sizeof(Trace_Record); i++) {\n    if (ct1[i] != ct2[i]) {\n      printf(\"Possible bug.\\n\");\n      break;\n    }\n  }\n\n#endif\n\n#if 0\n  Trace_Record *tr = New_Trace_Record();\n  tr->mask = ALL_ON_BIT_MASK;\n  \n  tr->fs.n = 1;\n  tr->fs.options[0] = 1;\n  tr->fs.scores[0] = 0.3;\n  tr->hit_region = 1;\n  tr->index = 2;\n  tr->refit = 1;\n\n  Local_Neuroseg *locseg = \n    Local_Neuroseg_Import_Xml(\"../data/locseg.xml\", NULL);\n\n  Locseg_Node *node = Make_Locseg_Node(locseg, tr);\n  Print_Locseg_Node(node);\n\n  \n  FILE *fp = fopen(\"../data/test.bn\", \"w\");\n  Locseg_Node_Fwrite(node, fp);\n  fclose(fp);\n  \n\n  Locseg_Node *node2 = New_Locseg_Node();\n\n  FILE *fp2 = fopen(\"../data/test.bn\", \"r\");\n  Locseg_Node_Fread(node2, fp2);\n  fclose(fp2);\n\n  Print_Locseg_Node(node2);\n#endif\n\n#if 0 /* Test what's going on during end tuning */\n  Locseg_Chain *chain = Read_Locseg_Chain(\"../data/diadem_e3/chain7.tb\");\n  Stack *signal = Read_Stack(\"../data/diadem_e3.tif\");\n  double z_scale = 1.0;\n\n  Trace_Workspace *tw = New_Trace_Workspace();\n  Locseg_Chain_Default_Trace_Workspace(tw, signal);\n  tw->refit = FALSE;\n  tw->tune_end = TRUE;\n\n  tw->fit_workspace = New_Locseg_Fit_Workspace();  \n\n  tw->trace_step = 0.1;\n  //fw->sws->field_func = Neurofield_S1;\n\n  Locseg_Label_Workspace *ws = New_Locseg_Label_Workspace();\n  ws->signal = signal;\n  ws->sratio = 1.0;\n  ws->sdiff = 0.0;\n  ws->option = 6;\n  //ws->flag = 0;\n\n  tw->trace_mask = Make_Stack(GREY, signal->width, signal->height, \n\t\t\t      signal->depth);\n  Zero_Stack(tw->trace_mask);\n\n  tw->chain_id = 28;\n\n  int i;\n  char file_path[100];\n  for (i = 0; i < tw->chain_id; i++) {\n    sprintf(file_path, \"../data/diadem_e3/chain%d.tb\", i);\n    if (fexist(file_path)) {\n      printf(\"id: %d\\n\", i);\n      Locseg_Chain *chain = Read_Locseg_Chain(file_path);\n      //ws->value = i + 1;\n      Locseg_Chain_Label_W(chain, tw->trace_mask, 1.0, \n\t\t\t   0, Locseg_Chain_Length(chain) - 1, \n\t\t\t   ws); \n    }\n  }\n  \n  ws->option = 7;\n  Locseg_Chain_Label_W(chain, tw->trace_mask, 1.0, \n\t\t       0, Locseg_Chain_Length(chain) - 1, \n\t\t       ws); \n      \n#  if 1\n  tw->trace_status[0] = TRACE_NORMAL;\n  tw->trace_status[1] = TRACE_NORMAL;\n  Trace_Locseg(signal, 1.0, chain, tw);\n#  endif\n\n  Locseg_Chain_Down_Sample(chain);\n      \n  Locseg_Chain_Tune_End(chain, signal, z_scale, tw->trace_mask, DL_HEAD);\n  Locseg_Chain_Tune_End(chain, signal, z_scale, tw->trace_mask, DL_TAIL);\n  \n  if (Locseg_Chain_Length(chain) > 0) {\n    Write_Locseg_Chain(\"../data/test.tb\", chain);\n  }\n#endif\n\n#if 0\n  Stack *stack = \n    Read_Stack(\"../data/benchmark/stack_graph/neuroseg/cross_60_8.tif\");\n\n  Locseg_Chain *chain = \n    Read_Locseg_Chain(\"../data/benchmark/stack_graph/neuroseg/seg0.tb\");\n  Print_Locseg_Chain(chain);\n\n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  sgw->conn = 26;\n  sgw->wf = Stack_Voxel_Weight_R;\n  sgw->group_mask = Make_Stack(GREY, stack->width, stack->height, stack->depth);\n  Zero_Stack(sgw->group_mask);\n  \n  Locseg_Chain_Label_G(chain, sgw->group_mask, 1.0, 0, -1, 1.0, 0.0, 0, 1);\n\n  //sgw->group_mask = NULL;\n\n  int start[3] = {66, 21, 58};\n  int end[3] = {49, 48, 49};\n  //int end[3] = {13, 49, 50};\n\n  //int start[3] = {66, 21, 58};\n  //int end[3] = {63, 26, 58};\n\n  Stack_Graph_Workspace_Set_Range(sgw, start[0], end[0], \n\t\t\t\t  start[1], end[1], \n\t\t\t\t  start[2], end[2]);\n\n  sgw->sp_option = 1;\n  Int_Arraylist *offset_path = \n    Stack_Route(stack, start, end, sgw);\n\n  Stack *canvas = Translate_Stack(stack, COLOR, 0);\n\n  if (sgw->group_mask != NULL) {\n    Stack_Blend_Mc(canvas, sgw->group_mask, 4.0);\n  }\n\n  Image_Array ima;\n  ima.array = canvas->array;\n\n  int i;\n  int nvoxel = Stack_Voxel_Number(stack);\n\n  for (i = 0; i < offset_path->length; i++) {\n    int index = offset_path->array[i];\n    if ((index < nvoxel) && (index >= 0)) {\n      ima.arrayc[index][0] = 255;\n      ima.arrayc[index][1] = 0;\n      ima.arrayc[index][2] = 0;\n    }\n  }\n    \n  Kill_Stack_Graph_Workspace(sgw);\n  Kill_Int_Arraylist(offset_path);\n\n  //Write_Stack(\"../data/presentation9/cross_path.tif\", canvas); \n  Write_Stack(\"../data/test.tif\", canvas); \n#endif\n\n#if 1\n  Locseg_Chain *source = \n    Read_Locseg_Chain(\"../data/benchmark/stack_graph/fork/chain1.tb\");\n\n  Locseg_Chain *target = \n    Read_Locseg_Chain(\"../data/benchmark/stack_graph/fork/chain0.tb\");\n\n  double pos[3];\n  Locseg_Chain_End_Pos(source, DL_TAIL, pos);\n\n  int seg_index;\n  double dist = Locseg_Chain_Point_Dist(target, pos, &seg_index, NULL);\n  \n  printf(\"dist: %g\\n\", dist);\n\n  Locseg_Label_Workspace *ws = New_Locseg_Label_Workspace();\n  Stack *stack = Read_Stack(\"../data/benchmark/stack_graph/fork/fork.tif\");\n  \n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  sgw->conn = 26;\n  sgw->wf = Stack_Voxel_Weight_R;\n  sgw->group_mask = Make_Stack(GREY, stack->width, stack->height, stack->depth);\n  Zero_Stack(sgw->group_mask);\n\n  int start, end;\n  start = seg_index - 1;\n  end = seg_index + 2;\n  \n  if (start < 0) {\n    start = 0;\n  }\n  int length = Locseg_Chain_Length(target);\n  if (end >= length) {\n    end = length - 1;\n  }\n\n  printf(\"seg index: %d--%d\\n\", start, end);\n  \n  ws->flag = 0;\n  ws->value = 1;\n  Locseg_Chain_Label_W(target, sgw->group_mask, 1.0, start, end, ws);\n\n  Stack_Graph_Workspace_Set_Range(sgw, (int) pos[0], ws->range[0], \n\t\t\t\t  (int) pos[1], ws->range[1], \n\t\t\t\t  (int) pos[2], ws->range[2]);\n  Stack_Graph_Workspace_Update_Range(sgw, ws->range[3], ws->range[4], \n\t\t\t\t     ws->range[5]); \n  \n  int start_pos[3];\n  int end_pos[3];\n  \n  start_pos[0] = (int) pos[0];\n  start_pos[1] = (int) pos[1];\n  start_pos[2] = (int) pos[2];\n\n  Local_Neuroseg *locseg = Locseg_Chain_Peek_Seg_At(target, seg_index);\n  Print_Local_Neuroseg(locseg);\n  Local_Neuroseg_Center(locseg, pos);\n\n  end_pos[0] = iround(pos[0]);\n  end_pos[1] = iround(pos[1]);\n  end_pos[2] = iround(pos[2]);\n\n  sgw->sp_option = 1;\n  Int_Arraylist *offset_path = \n    Stack_Route(stack, start_pos, end_pos, sgw);\n  \n  Stack *canvas = Translate_Stack(stack, COLOR, 0);\n\n  if (sgw->group_mask != NULL) {\n    Stack_Blend_Mc(canvas, sgw->group_mask, 4.0);\n  }\n\n  Image_Array ima;\n  ima.array = canvas->array;\n\n  int i;\n  int nvoxel = Stack_Voxel_Number(stack);\n\n  for (i = 0; i < offset_path->length; i++) {\n    int index = offset_path->array[i];\n    if ((index < nvoxel) && (index >= 0)) {\n      ima.arrayc[index][0] = 255;\n      ima.arrayc[index][1] = 0;\n      ima.arrayc[index][2] = 0;\n    }\n  }\n    \n  Kill_Stack_Graph_Workspace(sgw);\n  Kill_Int_Arraylist(offset_path);\n\n  //Write_Stack(\"../data/presentation9/fork_path.tif\", canvas);\n  Write_Stack(\"../data/test.tif\", canvas);\n\n#endif\n\n#if 0\n  Locseg_Chain *source = \n    Read_Locseg_Chain(\"../data/diadem_e1/chain7.tb\");\n\n  Locseg_Chain *target = \n    Read_Locseg_Chain(\"../data/diadem_e1/chain0.tb\");\n\n  double pos[3];\n  Locseg_Chain_End_Pos(source, DL_TAIL, pos);\n\n  int seg_index;\n  double dist = Locseg_Chain_Point_Dist(target, pos, &seg_index);\n  \n  printf(\"dist: %g\\n\", dist);\n\n  Locseg_Label_Workspace *ws = New_Locseg_Label_Workspace();\n  Stack *stack = Read_Stack(\"../data/diadem_e1.tif\");\n  \n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  sgw->conn = 26;\n  sgw->wf = Stack_Voxel_Weight_S;\n  sgw->group_mask = Make_Stack(GREY, stack->width, stack->height, stack->depth);\n  Zero_Stack(sgw->group_mask);\n\n  int start, end;\n  start = seg_index - 2;\n  end = seg_index + 2;\n  \n  if (start < 0) {\n    start = 0;\n  }\n  int length = Locseg_Chain_Length(target);\n  if (end >= length) {\n    end = length - 1;\n  }\n\n  printf(\"seg index: %d--%d\\n\", start, end);\n  \n  ws->flag = 0;\n  ws->value = 1;\n  Locseg_Chain_Label_W(target, sgw->group_mask, 1.0, start, end, ws);\n\n  Stack_Graph_Workspace_Set_Range(sgw, (int) pos[0], ws->range[0], \n\t\t\t\t  (int) pos[1], ws->range[1], \n\t\t\t\t  (int) pos[2], ws->range[2]);\n  Stack_Graph_Workspace_Update_Range(sgw, ws->range[3], ws->range[4], \n\t\t\t\t     ws->range[5]); \n  \n  int start_pos[3];\n  int end_pos[3];\n  \n  start_pos[0] = (int) pos[0];\n  start_pos[1] = (int) pos[1];\n  start_pos[2] = (int) pos[2];\n\n  Local_Neuroseg *locseg = Locseg_Chain_Peek_Seg_At(target, seg_index);\n  Print_Local_Neuroseg(locseg);\n  Local_Neuroseg_Center(locseg, pos);\n\n  end_pos[0] = iround(pos[0]);\n  end_pos[1] = iround(pos[1]);\n  end_pos[2] = iround(pos[2]);\n\n  Int_Arraylist *offset_path = \n    Stack_Route(stack, start_pos, end_pos, sgw);\n  \n  printf(\"dist: %g\\n\", sgw->value);\n\n  Stack *canvas = Translate_Stack(stack, COLOR, 0);\n\n  if (sgw->group_mask != NULL) {\n    Stack_Blend_Mc(canvas, sgw->group_mask, 4.0);\n  }\n\n  Image_Array ima;\n  ima.array = canvas->array;\n\n  int i;\n  int nvoxel = Stack_Voxel_Number(stack);\n\n  Int_Arraylist *path_value = Make_Int_Arraylist(0, 1);\n\n  for (i = 0; i < offset_path->length; i++) {\n    int index = offset_path->array[i];\n    if ((index < nvoxel) && (index >= 0)) {\n      printf(\"%d-(%d)->\", index, stack->array[index]);\n      Int_Arraylist_Add(path_value, stack->array[index]);\n      ima.arrayc[index][0] = 255;\n      ima.arrayc[index][1] = 0;\n      ima.arrayc[index][2] = 0;\n    }\n  }\n  printf(\"\\n\");\n    \n  iarray_write(\"../data/presentation9/diadem_e1/path_value_ws.bn\", \n\t       path_value->array, path_value->length - 1);\n\t       \n\n  Kill_Stack_Graph_Workspace(sgw);\n  Kill_Int_Arraylist(offset_path);\n\n  Write_Stack(\"../data/presentation9/diadem_e1_path_ws.tif\", canvas);\n\n#endif\n\n#if 0\n  Locseg_Chain *source = \n    Read_Locseg_Chain(\"../data/diadem_e1/chain22.tb\");\n\n  Locseg_Chain *target = \n    Read_Locseg_Chain(\"../data/diadem_e1/chain0.tb\");\n\n  //double pos[3] = {378, 183, 38};\n  //Locseg_Chain_End_Pos(source, DL_TAIL, pos);\n\n  Stack *stack = Read_Stack(\"../data/diadem_e1.tif\");\n\n  double pos[3];\n  Locseg_Chain_Bright_End(source, DL_HEAD, stack, 1.0, pos);\n\n  int seg_index;\n  double dist = Locseg_Chain_Point_Dist(target, pos, &seg_index);\n  \n  printf(\"dist: %g\\n\", dist);\n\n  Locseg_Label_Workspace *ws = New_Locseg_Label_Workspace();\n  \n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  sgw->conn = 26;\n  sgw->wf = Stack_Voxel_Weight_S;\n  sgw->group_mask = Make_Stack(GREY, stack->width, stack->height, stack->depth);\n  Zero_Stack(sgw->group_mask);\n\n  int start, end;\n  start = seg_index - 1;\n  end = seg_index + 2;\n  \n  if (start < 0) {\n    start = 0;\n  }\n  int length = Locseg_Chain_Length(target);\n  if (end >= length) {\n    end = length - 1;\n  }\n\n  printf(\"seg index: %d--%d\\n\", start, end);\n  \n  ws->flag = 0;\n  ws->value = 1;\n  Locseg_Chain_Label_W(target, sgw->group_mask, 1.0, start, end, ws);\n\n  Stack_Graph_Workspace_Set_Range(sgw, (int) pos[0], ws->range[0], \n\t\t\t\t  (int) pos[1], ws->range[1], \n\t\t\t\t  (int) pos[2], ws->range[2]);\n  Stack_Graph_Workspace_Update_Range(sgw, ws->range[3], ws->range[4], \n\t\t\t\t     ws->range[5]); \n  \n  int start_pos[3];\n  int end_pos[3];\n  \n  start_pos[0] = (int) pos[0];\n  start_pos[1] = (int) pos[1];\n  start_pos[2] = (int) pos[2];\n\n  Local_Neuroseg *locseg = Locseg_Chain_Peek_Seg_At(target, seg_index);\n  Print_Local_Neuroseg(locseg);\n  Local_Neuroseg_Center(locseg, pos);\n\n  end_pos[0] = iround(pos[0]);\n  end_pos[1] = iround(pos[1]);\n  end_pos[2] = iround(pos[2]);\n\n  Int_Arraylist *offset_path = \n    Stack_Route(stack, start_pos, end_pos, sgw);\n  \n  printf(\"dist: %g\\n\", sgw->value);\n\n  Stack *canvas = Translate_Stack(stack, COLOR, 0);\n\n  if (sgw->group_mask != NULL) {\n    Stack_Blend_Mc(canvas, sgw->group_mask, 4.0);\n  }\n\n  Image_Array ima;\n  ima.array = canvas->array;\n\n  int i;\n  int nvoxel = Stack_Voxel_Number(stack);\n\n  Int_Arraylist *path_value = Make_Int_Arraylist(0, 1);\n\n  for (i = 0; i < offset_path->length; i++) {\n    int index = offset_path->array[i];\n    if ((index < nvoxel) && (index >= 0)) {\n      printf(\"%d-(%d)->\", index, stack->array[index]);\n      Int_Arraylist_Add(path_value, stack->array[index]);\n      ima.arrayc[index][0] = 255;\n      ima.arrayc[index][1] = 0;\n      ima.arrayc[index][2] = 0;\n    }\n  }\n  printf(\"\\n\");\n    \n  iarray_write(\"../data/presentation9/diadem_e1/path_value_gap_ws.bn\", \n\t       path_value->array, path_value->length - 1);\n\t       \n\n  Kill_Stack_Graph_Workspace(sgw);\n  Kill_Int_Arraylist(offset_path);\n\n  Write_Stack(\"../data/presentation9/diadem_e1_path_gap_ws.tif\", canvas);\n\n#endif\n\n#if 0\n  Locseg_Chain *source = \n    Read_Locseg_Chain(\"../data/diadem_e1/chain22.tb\");\n\n  Locseg_Chain *target = \n    Read_Locseg_Chain(\"../data/diadem_e1/chain0.tb\");\n\n  Stack *stack = Read_Stack(\"../data/diadem_e1.tif\");\n\n  double pos[3];\n  Locseg_Chain_Bright_End(source, DL_HEAD, stack, 1.0, pos);\n\n  int seg_index;\n  double dist = Locseg_Chain_Point_Dist(target, pos, &seg_index);\n  \n  printf(\"dist: %g\\n\", dist);\n\n  Locseg_Label_Workspace *ws = New_Locseg_Label_Workspace();  \n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  sgw->conn = 26;\n  sgw->wf = Stack_Voxel_Weight_S;\n  sgw->group_mask = Make_Stack(GREY, stack->width, stack->height, stack->depth);\n  Zero_Stack(sgw->group_mask);\n\n  int start, end;\n  start = seg_index - 2;\n  end = seg_index + 2;\n  \n  if (start < 0) {\n    start = 0;\n  }\n  int length = Locseg_Chain_Length(target);\n  if (end >= length) {\n    end = length - 1;\n  }\n\n  printf(\"seg index: %d--%d\\n\", start, end);\n  \n  ws->flag = 0;\n  ws->value = 1;\n  Locseg_Chain_Label_W(target, sgw->group_mask, 1.0, start, end, ws);\n\n  Stack_Graph_Workspace_Set_Range(sgw, (int) pos[0], ws->range[0], \n\t\t\t\t  (int) pos[1], ws->range[1], \n\t\t\t\t  (int) pos[2], ws->range[2]);\n  Stack_Graph_Workspace_Update_Range(sgw, ws->range[3], ws->range[4], \n\t\t\t\t     ws->range[5]); \n  \n  int start_pos[3];\n  int end_pos[3];\n  \n  start_pos[0] = (int) pos[0];\n  start_pos[1] = (int) pos[1];\n  start_pos[2] = (int) pos[2];\n\n  Local_Neuroseg *locseg = Locseg_Chain_Peek_Seg_At(target, seg_index);\n  Print_Local_Neuroseg(locseg);\n  Local_Neuroseg_Center(locseg, pos);\n\n  end_pos[0] = iround(pos[0]);\n  end_pos[1] = iround(pos[1]);\n  end_pos[2] = iround(pos[2]);\n\n  Int_Arraylist *offset_path = \n    Stack_Route(stack, start_pos, end_pos, sgw);\n  \n  printf(\"dist: %g\\n\", sgw->value);\n\n  Stack *canvas = Translate_Stack(stack, COLOR, 0);\n\n  if (sgw->group_mask != NULL) {\n    Stack_Blend_Mc(canvas, sgw->group_mask, 4.0);\n  }\n\n  Image_Array ima;\n  ima.array = canvas->array;\n\n  int i;\n  int nvoxel = Stack_Voxel_Number(stack);\n\n  Int_Arraylist *path_value = Make_Int_Arraylist(0, 1);\n\n  for (i = 0; i < offset_path->length; i++) {\n    int index = offset_path->array[i];\n    if ((index < nvoxel) && (index >= 0)) {\n      printf(\"%d-(%d)->\", index, stack->array[index]);\n      Int_Arraylist_Add(path_value, stack->array[index]);\n      ima.arrayc[index][0] = 255;\n      ima.arrayc[index][1] = 0;\n      ima.arrayc[index][2] = 0;\n    }\n  }\n  printf(\"\\n\");\n  \n  /*  \n  iarray_write(\"../data/presentation9/diadem_e1/path_value_ws.bn\", \n\t       path_value->array, path_value->length - 1);\n  */\t       \n\n  Kill_Stack_Graph_Workspace(sgw);\n  Kill_Int_Arraylist(offset_path);\n\n  Write_Stack(\"../data/test.tif\", canvas);\n\n#endif\n\n#if 0\n  Locseg_Chain *source = \n    Read_Locseg_Chain(\"../data/diadem_e3/chain14.tb\");\n\n  Locseg_Chain *target = \n    Read_Locseg_Chain(\"../data/diadem_e3/chain0.tb\");\n\n  Stack *stack = Read_Stack(\"../data/diadem_e3.tif\");\n\n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  sgw->conn = 26;\n  sgw->wf = Stack_Voxel_Weight_S;\n  sgw->resolution[2] = 3.03;\n  sgw->signal_mask = \n    Make_Stack(GREY, stack->width, stack->height, stack->depth);\n  One_Stack(sgw->signal_mask);\n\n  Locseg_Chain_Erase(source, sgw->signal_mask, 1.0);\n  Locseg_Chain_Erase(target, sgw->signal_mask, 1.0);\n  \n  Local_Neuroseg *source_seg = Locseg_Chain_Tail_Seg(source);\n  Locseg_Chain_Update_Stack_Graph_Workspace(source_seg, target, stack,\n\t\t\t\t\t   1.0, sgw);\n\n  /*  \n  Stack *substack = Crop_Stack(new_stack, sgw->range[0], sgw->range[2], \n\t\t\t       sgw->range[4], \n\t\t\t       sgw->range[1] - sgw->range[0] + 1, \n\t\t\t       sgw->range[3] - sgw->range[2] + 1,\n\t\t\t       sgw->range[5] - sgw->range[4] + 1, NULL);\n  Kill_Stack(new_stack);\n\n  double c1, c2;\n  int thre = Stack_Threshold_RC_R(substack, 0, 255, &c1, &c2);\n\n  sgw->argv[3] = thre;\n  sgw->argv[4] = c2 - c1;\n  if (sgw->argv[4] < 1.0) {\n    sgw->argv[4] = 1.0;\n  }\n  sgw->argv[4] /= 9.2;\n  */\n  Int_Arraylist *path = Locseg_Chain_Shortest_Path(source, target, stack, 1.0,\n\t\t\t\t\t\t   sgw);\n\n  Stack *canvas = Translate_Stack(stack, COLOR, 0);\n\n  if (sgw->group_mask != NULL) {\n    Stack_Blend_Mc(canvas, sgw->group_mask, 4.0);\n  }\n\n  Kill_Stack_Graph_Workspace(sgw);\n  \n  Image_Array ima;\n  ima.array = canvas->array;\n\n  int i;\n  for (i = 0; i < path->length; i++) {\n    int index = path->array[i];\n    ima.arrayc[index][0] = stack->array[i];\n    ima.arrayc[index][1] = 128;\n    ima.arrayc[index][2] = 128;\n  }\n\n  Write_Stack(\"../data/test.tif\", canvas);\n#endif\n\n#if 0\n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  Kill_Stack_Graph_Workspace(sgw);\n#endif\n\n#if 0\n  Locseg_Chain *source = \n    Read_Locseg_Chain(\"../data/diadem_e3/chain13.tb\");\n\n  Locseg_Chain *target = \n    Read_Locseg_Chain(\"../data/diadem_e3/chain8.tb\");\n\n  Stack *stack = Read_Stack(\"../data/diadem_e3.tif\");\n\n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  sgw->conn = 26;\n  sgw->wf = Stack_Voxel_Weight_S;\n  sgw->resolution[0] = 0.33;\n  sgw->resolution[1] = 0.33;\n  sgw->resolution[2] = 1.00;\n\n  /*\n  Int_Arraylist *path = Locseg_Chain_Shortest_Path(source, target, stack, 1.0,\n\t\t\t\t\t\t   sgw);\n  */\n\n  Connection_Test_Workspace *ctw = New_Connection_Test_Workspace();\n  ctw->dist_thre = NEUROSEG_DEFAULT_H * 1.5;\n  ctw->mask = Make_Stack(GREY, stack->width, stack->height, stack->depth);\n  One_Stack(ctw->mask);\n  Locseg_Chain_Erase(source, ctw->mask, 1.0);\n  Locseg_Chain_Erase(target, ctw->mask, 1.0);\n\n  Neurocomp_Conn conn;\n  conn.mode = NEUROCOMP_CONN_HL;\n  Locseg_Chain_Connection_Test(source, target, stack, 1.0, &conn, ctw);\n  Print_Neurocomp_Conn(&conn);\n\n  Kill_Locseg_Chain(source);\n  Kill_Locseg_Chain(target);\n  Kill_Stack(stack);\n  Kill_Connection_Test_Workspace(ctw);\n  \n  Kill_Stack_Graph_Workspace(sgw);\n  \n#endif\n\n#if 0\n  Locseg_Chain *source = \n    Read_Locseg_Chain(\"../data/diadem_e1/chain7.tb\");\n\n  Locseg_Chain *target = \n    Read_Locseg_Chain(\"../data/diadem_e1/chain0.tb\");\n\n  Stack *stack = Read_Stack(\"../data/diadem_e1.tif\");\n\n  Local_Neuroseg *source_seg = Locseg_Chain_Tail_Seg(source);\n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  Locseg_Chain_Update_Stack_Graph_Workspace(source_seg, target, stack,\n\t\t\t\t\t   1.0, sgw);\n  Int_Arraylist *path = Locseg_Chain_Shortest_Path(source, target, stack, 1.0,\n\t\t\t\t\t\t   sgw);\n  Locseg_Chain *chain2 = Locseg_Chain_Bridge_Sp(source_seg, target,\n                                                stack, 1.0, sgw, NULL);\n\n  Print_Locseg_Chain(chain2);\n#endif\n\n#if 0\n  Locseg_Chain *source = \n    Read_Locseg_Chain(\"../data/diadem_e3/chain1.tb\");\n\n  Locseg_Chain *target = \n    Read_Locseg_Chain(\"../data/diadem_e3/chain0.tb\");\n\n  Stack *stack = Read_Stack(\"../data/diadem_e3.tif\");\n\n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  sgw->conn = 26;\n  sgw->wf = Stack_Voxel_Weight_S;\n  sgw->resolution[2] = 3.03;\n  sgw->signal_mask = \n    Make_Stack(GREY, stack->width, stack->height, stack->depth);\n  One_Stack(sgw->signal_mask);\n\n  Locseg_Chain_Erase(source, sgw->signal_mask, 1.0);\n  Locseg_Chain_Erase(target, sgw->signal_mask, 1.0);\n  \n  Local_Neuroseg *source_seg = Locseg_Chain_Tail_Seg(source);\n  Locseg_Chain_Update_Stack_Graph_Workspace(source_seg, target, stack,\n\t\t\t\t\t   1.0, sgw);\n\n  printf(\"%g, %g\\n\", sgw->argv[3], sgw->argv[4]);\n\n  Int_Arraylist *path = Locseg_Chain_Shortest_Path(source, target, stack, \n\t\t\t\t\t\t\t1.0, sgw);\n\n  Stack *canvas = Translate_Stack(stack, COLOR, 0);\n\n  if (sgw->group_mask != NULL) {\n    Stack_Blend_Mc(canvas, sgw->group_mask, 4.0);\n  }\n\n  Kill_Stack_Graph_Workspace(sgw);\n  \n  Image_Array ima;\n  ima.array = canvas->array;\n\n  int i;\n  for (i = 0; i < path->length; i++) {\n    int index = path->array[i];\n    ima.arrayc[index][0] = stack->array[index];\n    ima.arrayc[index][1] = 128;\n    ima.arrayc[index][2] = 128;\n  }\n\n  Write_Stack(\"../data/test.tif\", canvas);\n#endif\n\n#if 0\n    Locseg_Chain *source = \n    Read_Locseg_Chain(\"../data/diadem_e3/chain3.tb\");\n\n  Locseg_Chain *target = \n    Read_Locseg_Chain(\"../data/diadem_e3/chain1.tb\");\n\n  Stack *stack = Read_Stack(\"../data/diadem_e3.tif\");\n\n  Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace();\n  sgw->conn = 26;\n  sgw->wf = Stack_Voxel_Weight_S;\n  sgw->resolution[2] = 3.03;\n  sgw->signal_mask = \n    Make_Stack(GREY, stack->width, stack->height, stack->depth);\n  One_Stack(sgw->signal_mask);\n\n  Locseg_Chain_Erase(source, sgw->signal_mask, 1.0);\n  Locseg_Chain_Erase(target, sgw->signal_mask, 1.0);\n  \n  Local_Neuroseg *source_seg = Locseg_Chain_Tail_Seg(source);\n  Locseg_Chain_Update_Stack_Graph_Workspace(source_seg, target, stack,\n\t\t\t\t\t   1.0, sgw);\n\n  printf(\"%g, %g\\n\", sgw->argv[3], sgw->argv[4]);\n\n  Int_Arraylist *path = Locseg_Chain_Shortest_Path(source, target, stack, \n\t\t\t\t\t\t\t1.0, sgw);\n\n  Stack *canvas = Translate_Stack(stack, COLOR, 0);\n\n  if (sgw->group_mask != NULL) {\n    Stack_Blend_Mc(canvas, sgw->group_mask, 3.0);\n  }\n\n  Kill_Stack_Graph_Workspace(sgw);\n  \n  Image_Array ima;\n  ima.array = canvas->array;\n\n  int i;\n  for (i = 0; i < path->length; i++) {\n    int index = path->array[i];\n    ima.arrayc[index][0] = stack->array[index];\n    ima.arrayc[index][1] = 255;\n    ima.arrayc[index][2] = 128;\n  }\n\n  Write_Stack(\"../data/test.tif\", canvas);\n#endif\n\n#if 0\n  Stack *stack = Read_Stack(\"../data/benchmark/fork2/fork2.tif\");\n  int z = 34;\n  stack_adjust_zpos(stack, 50, 44, &z);\n  printf(\"%d\\n\", z);\n#endif\n\n  return 0;\n}\n", "meta": {"hexsha": "0584319a5c6b13207606124e6e2dc28188f8c7e2", "size": 52408, "ext": "c", "lang": "C", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/testneurotrace.c", "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/testneurotrace.c", "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/testneurotrace.c", "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": ["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.6843177189, "max_line_length": 122, "alphanum_fraction": 0.6563120134, "num_tokens": 18082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.37728970109442483}}
{"text": "/*\n * Copyright 2014 Marc Normandin\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n *     Unless required by applicable law or agreed to in writing, software\n *     distributed under the License is distributed on an \"AS IS\" BASIS,\n *     WITHOUT WARRANTIES OR CONDITIONS OF 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 * rng.h\n *\n *  Created on: Jul 3, 2013\n *      Author: marc\n */\n\n#ifndef RNG_H_\n#define RNG_H_\n\n#include <climits> // ULONG_MAX\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <iostream>\n\n// Seeds for GNU GSL random number generators\ntypedef unsigned long int gslseed_t;\n\nclass RandomNumberGenerator\n{\npublic:\n    /*\n    RandomNumberGenerator()\n    : mRngType( gsl_rng_default ), mSeed( time(0) ) {\n    \tinitializeRNG();\n    }*/\n\n    RandomNumberGenerator(const gslseed_t& seed)\n        : mRngType( gsl_rng_default ), mSeed( seed )\n    {\n        initializeRNG();\n    }\n\n    RandomNumberGenerator(const RandomNumberGenerator& rhs)\n    {\n        mRngType = rhs.mRngType;\n        mRng = gsl_rng_clone( rhs.mRng );\n        mSeed = rhs.randomSeed();\n        gsl_rng_set (mRng, mSeed);\n    }\n\n    ~RandomNumberGenerator()\n    {\n        gsl_rng_free( mRng );\n    }\n\n    // Random uniform number between 0 and 1.\n    double uniform() const\n    {\n        return gsl_rng_uniform( mRng );\n    }\n\n    // Random uniform number between min and max\n    double uniform(const double min, const double max) const\n    {\n        const double u = uniform();\n        return ( min + u * (max - min) );\n    }\n    \n    double gaussian(const double sigma) const\n    {\n        return ( gsl_ran_gaussian (mRng, sigma) );\n    }\n\n    // Beta distribution. Random x between 0 and 1.\n    double beta(const double alpha, const double beta) const\n    {\n        return ( gsl_ran_beta(mRng, alpha, beta) );\n    }\n\n    gslseed_t randomSeed() const\n    {\n    \t// I wrote the following after looking into the GSL code itself.\n        const unsigned long int offset = mRng->type->min;\n        const unsigned long int range = mRng->type->max - offset;\n        gslseed_t rseed = 1 + gsl_rng_uniform_int(mRng, range-2);\n        //std::cerr << \"generated random seed = \" << rseed << std::endl;\n        return rseed;\n    }\n\nprotected:\n    void initializeRNG()\n    {\n        mRng = gsl_rng_alloc (mRngType);\n        gsl_rng_set (mRng, mSeed);\n    }\n\nprivate:\n    // Prevent copying and assignment\n    //RandomNumberGenerator(const RandomNumberGenerator&);\n    void operator=(const RandomNumberGenerator&);\n\n    const gsl_rng_type* mRngType;\n    gslseed_t\t\t\tmSeed;\n    gsl_rng* \t\t\tmRng;\n};\n\n\n#endif /* RNG_H_ */\n", "meta": {"hexsha": "e667f20c0a1836ff194644368798c7a42ddbe81b", "size": 2903, "ext": "h", "lang": "C", "max_stars_repo_path": "rng.h", "max_stars_repo_name": "marcnormandin/ParticleSwarmOptimization", "max_stars_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-05-28T05:27:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-09T21:25:19.000Z", "max_issues_repo_path": "rng.h", "max_issues_repo_name": "marcnormandin/ParticleSwarmOptimization", "max_issues_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T05:48:44.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-11T20:48:15.000Z", "max_forks_repo_path": "rng.h", "max_forks_repo_name": "marcnormandin/ParticleSwarmOptimization", "max_forks_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5", "max_forks_repo_licenses": ["Apache-2.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.025862069, "max_line_length": 79, "alphanum_fraction": 0.6400275577, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.3771985155057126}}
{"text": "/* Copyright (c) 2011-2012, J\u00e9r\u00e9my Fix. All rights reserved. */\n\n/* Redistribution and use in source and binary forms, with or without */\n/* modification, are permitted provided that the following conditions are met: */\n\n/* * Redistributions of source code must retain the above copyright notice, */\n/* this list of conditions and the following disclaimer. */\n/* * Redistributions in binary form must reproduce the above copyright notice, */\n/* this list of conditions and the following disclaimer in the documentation */\n/* and/or other materials provided with the distribution. */\n/* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */\n\n/* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND */\n/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */\n/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */\n/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */\n/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */\n/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */\n/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */\n/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */\n/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */\n/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */\n\n#ifndef EKF_H\n#define EKF_H\n\n#include \"ekf_types.h\"\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n\nnamespace ekf\n{\n\n  void ekf_init(ekf_param &p, ekf_state &s)\n  {\n\n    // Matrices for the state\n    s.xk = gsl_vector_alloc(p.n);\n    gsl_vector_set_zero(s.xk);\n\n    s.xkm = gsl_vector_alloc(p.n);\n    gsl_vector_set_zero(s.xkm);\n\n    s.Pxk = gsl_matrix_alloc(p.n, p.n);\n    gsl_matrix_set_zero(s.Pxk);\n\n    s.Fxk = gsl_matrix_alloc(p.n, p.n);\n    gsl_matrix_set_zero(s.Fxk);\n\n    s.Rv = gsl_matrix_alloc(p.n, p.n);\n    gsl_matrix_set_zero(s.Rv);\n\n    // Matrices for the observations\n    s.yk = gsl_vector_alloc(p.no);\n    gsl_vector_set_zero(s.yk);\n\n    s.ino_yk = gsl_vector_alloc(p.no);\n    gsl_vector_set_zero(s.ino_yk);\n\n    s.Hyk = gsl_matrix_alloc(p.no, p.n);\n    gsl_matrix_set_zero(s.Hyk);\n\n    s.Rn = gsl_matrix_alloc(p.no, p.no);\n    gsl_matrix_set_zero(s.Rn);\n\n    // Matrices for the kalman gain and the updates\n    s.Kk = gsl_matrix_alloc(p.n, p.no);\n    gsl_matrix_set_zero(s.Kk);\n\n    // Temporary matrices\n    s.temp_n_n = gsl_matrix_alloc(p.n, p.n);\n    gsl_matrix_set_zero(s.temp_n_n);\n\n    s.temp_n_1 = gsl_matrix_alloc(p.n, 1);\n    gsl_matrix_set_zero(s.temp_n_1);\n\n    s.temp_no_no = gsl_matrix_alloc(p.no, p.no);\n    gsl_matrix_set_zero(s.temp_no_no);\n\n    s.temp_n_no = gsl_matrix_alloc(p.n, p.no);\n    gsl_matrix_set_zero(s.temp_n_no);\n\n    s.temp_2_n_n = gsl_matrix_alloc(p.n, p.n);\n    gsl_matrix_set_zero(s.temp_2_n_n);\n\n    s.temp_no = gsl_vector_alloc(p.no);\n    gsl_vector_set_zero(s.temp_no);\n\n    // Initialize the noises\n    //gsl_matrix_set_identity(s.Rv);\n    //gsl_matrix_scale(s.Rv, p.evolution_noise);\n    p.evolution_noise->init(p, s);\n    //printf(\"Evolution noise : max = %e , min = %e \\n\", gsl_matrix_max(s.Rv), gsl_matrix_min(s.Rv));\n\n    gsl_matrix_set_identity(s.Rn);\n    gsl_matrix_scale(s.Rn, p.observation_noise);\n\n    // Initialize the covariance of the parameters\n    gsl_matrix_set_identity(s.Pxk);\n    gsl_matrix_scale(s.Pxk, p.prior_pk);\n\n  }\n\n  void ekf_free(ekf_param &p, ekf_state &s)\n  {\n    gsl_vector_free(s.xk);\n    gsl_vector_free(s.xkm);\n    gsl_matrix_free(s.Pxk);\n    gsl_matrix_free(s.Fxk);\n    gsl_matrix_free(s.Rv);\n\n    gsl_vector_free(s.yk);\n    gsl_vector_free(s.ino_yk);\n    gsl_matrix_free(s.Hyk);\n    gsl_matrix_free(s.Rn);\n\n    gsl_matrix_free(s.Kk);\n\n    gsl_matrix_free(s.temp_n_n);\n    gsl_matrix_free(s.temp_n_1);\n    gsl_matrix_free(s.temp_no_no);\n    gsl_matrix_free(s.temp_n_no);\n    gsl_matrix_free(s.temp_2_n_n);\n    gsl_vector_free(s.temp_no);\n  }\n  template<typename FFunc,\n    typename DFFunc,\n    typename HFunc,\n    typename DHFunc>\n    void ekf_iterate(ekf_param &p, ekf_state &s, \n\t\t     FFunc f, DFFunc df,\n\t\t     HFunc h, DHFunc dh,\n\t\t     gsl_vector* yk)\n  {\n    /****************************/\n    /***** Prediction step  *****/\n    /****************************/\n\n    // Compute the Jacobian of the evolution\n    // Eq. 2.34\n    df(s.params, s.xk, s.Fxk);\n\n    // Compute the predicted state mean and covariance\n    // Eq. 2.36\n    // s.xk will now hold the predicted state !\n    f(s.params, s.xk, s.xkm);\n\n    // Eq. 2.37\n    // s.Pxk will now hold Pxk^-\n    gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, s.Pxk, s.Fxk, 0.0, s.temp_n_n);\n    gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Fxk, s.temp_n_n, 0.0, s.Pxk);\n    gsl_matrix_add(s.Pxk, s.Rv);\n\n    /****************************/\n    /***** Correction step  *****/\n    /****************************/\n\n    // Compute the Jacobian of the observation model\n    // Eq. 2.38\n    dh(s.params, s.xkm, s.Hyk);\n\n    if(!p.observation_gradient_is_diagonal)\n      {\n\t// Update the estimates\n\t// Eq 2.40\n\t// 1 - Compute H.P^-.H^T + Rn\n\tgsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, s.Pxk, s.Hyk, 0.0, s.temp_n_no);\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Hyk, s.temp_n_no, 0.0, s.temp_no_no);\n\tgsl_matrix_add(s.temp_no_no, s.Rn);\n\t// 2 - Compute its inverse\n\tgsl_linalg_cholesky_decomp(s.temp_no_no);\n\tgsl_linalg_cholesky_invert(s.temp_no_no);\n\n\t// 3 - Compute P^-.H ^T.( H P H^T + R)^-1\n\tgsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, s.Hyk, s.temp_no_no, 0.0, s.temp_n_no);\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Pxk, s.temp_n_no, 0.0, s.Kk);\n      }\n    else\n      {\n\t// We can make some simplifications when computing H P H^T = H P H\n\t// and also when computing P . H . (H P H^T + R) ^-1\n\n\t// Update the estimates\n\t// Eq 2.40\n\t// 1 - Compute H.P^-.H^T + Rn\n\tfor(int i = 0 ; i < p.no ; ++i)\n\t  {\n\t    for(int j = 0 ; j < p.no ; ++j)\n\t      {\n\t\tgsl_matrix_set(s.temp_no_no, i, j, gsl_matrix_get(s.Hyk, i, i) * gsl_matrix_get(s.Hyk, j, j) * gsl_matrix_get(s.Pxk, i, j) + gsl_matrix_get(s.Rn, i, j));\n\t      }\n\t  }\n\t// Compute its inverse : U = (H P H^T + R) ^-1\n\tgsl_linalg_cholesky_decomp(s.temp_no_no);\n\tgsl_linalg_cholesky_invert(s.temp_no_no);\n\n\t// 3 - Compute P^- H^T . U\n\n\t// Compute H^T . U\n\tfor(int i = 0 ; i < p.no; ++i)\n\t  for(int j = 0 ; j < p.no ; ++j)\n\t    gsl_matrix_set(s.temp_n_no, i, j, gsl_matrix_get(s.Hyk, i,i) * gsl_matrix_get(s.temp_no_no, i, j));\n\tfor(int i = p.no ; i < p.n; ++i)\n\t  for(int j = 0 ; j < p.no ; ++j)\n\t    gsl_matrix_set(s.temp_n_no, i, j, 0.0);\n\t// Compute P^- . (H^T . U)\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Pxk, s.temp_n_no, 0.0, s.Kk);\n\n      }\n    // Update the current estimate\n    // Eq 2.41\n    // 1 - We need the observations\n    h(s.params, s.xkm, s.yk);\n    gsl_vector_memcpy(s.ino_yk, yk);\n    gsl_vector_sub(s.ino_yk, s.yk);\n    gsl_vector_memcpy(s.xk, s.xkm);\n    gsl_blas_dgemv(CblasNoTrans, 1.0, s.Kk, s.ino_yk, 1.0,s.xk);\n\n    // Update the variance/covariance matrix\n    // Compute  -Kk * Hk\n    if(!p.observation_gradient_is_diagonal)\n      {\n\tgsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, s.Kk, s.Hyk, 0.0, s.temp_n_n);\n\n\t// Add identity : I - Kk * Hk\n\tfor(int i = 0 ; i < p.n ; ++i)\n\t  gsl_matrix_set(s.temp_n_n, i, i,gsl_matrix_get(s.temp_n_n,i,i) + 1.0);\n      }\n    else\n      {\n\t// We can make some simplifications when H is diagonal\n\tfor(int i = 0 ; i < p.n ; ++i)\n\t  {\n\t    for(int j = 0 ; j < p.no ; ++j)\n\t      {\n\t\tgsl_matrix_set(s.temp_n_n, i, j, (i==j?1.0:0.0) - gsl_matrix_get(s.Kk, i,j) * gsl_matrix_get(s.Hyk, j,j) );\n\t      }\n\t    for(int j = p.no ; j < p.n ; ++j)\n\t      {\n\t\tgsl_matrix_set(s.temp_n_n, i, j, (i == j ? 1.0 : 0.0));\n\t      }\n\t  }\n      }\n\n    gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.temp_n_n, s.Pxk, 0.0, s.temp_2_n_n);\n    gsl_matrix_memcpy(s.Pxk, s.temp_2_n_n);\n\n    /***********************************/\n    /***** Evolution noise update  *****/\n    /***********************************/\n\n    p.evolution_noise->updateEvolutionNoise(p, s);\n  }\n}\n\n#endif // EKF_H\n", "meta": {"hexsha": "dbe2e5b2bba39c7b5aed4e3c1306a0086e685fc6", "size": 8234, "ext": "h", "lang": "C", "max_stars_repo_path": "src/ekf.h", "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_issues_repo_path": "src/ekf.h", "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_forks_repo_path": "src/ekf.h", "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 52.0, "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "avg_line_length": 31.9147286822, "max_line_length": 158, "alphanum_fraction": 0.6379645373, "num_tokens": 2622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.37719850583480313}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_errno.h>\n\n#include \"ccl.h\"\n\nccl_f2d_t *ccl_f2d_t_copy(ccl_f2d_t *f2d_o, int *status)\n{\n  int s2dstatus=0;\n  ccl_f2d_t *f2d = malloc(sizeof(ccl_f2d_t));\n  if (f2d == NULL)\n    *status = CCL_ERROR_MEMORY;\n\n  if(*status==0) {\n    f2d->lkmin = f2d_o->lkmin;\n    f2d->lkmax = f2d_o->lkmax;\n    f2d->amin = f2d_o->amin;\n    f2d->amax = f2d_o->amax;\n    f2d->is_factorizable = f2d_o->is_factorizable;\n    f2d->is_k_constant = f2d_o->is_k_constant;\n    f2d->is_a_constant = f2d_o->is_a_constant;\n    f2d->extrap_linear_growth = f2d_o->extrap_linear_growth;\n    f2d->extrap_order_lok = f2d_o->extrap_order_lok;\n    f2d->extrap_order_hik = f2d_o->extrap_order_hik;\n    f2d->is_log = f2d_o->is_log;\n    f2d->growth = f2d_o->growth;\n    f2d->growth_factor_0 = f2d_o->growth_factor_0;\n    f2d->growth_exponent = f2d_o->growth_exponent;\n\n    if(f2d_o->fk != NULL) {\n      f2d->fk = gsl_spline_alloc(gsl_interp_cspline,\n                                 f2d_o->fk->size);\n      if(f2d->fk == NULL)\n        *status = CCL_ERROR_MEMORY;\n\n      if(*status==0) {\n        s2dstatus |= gsl_spline_init(f2d->fk, f2d_o->fk->x,\n                                     f2d_o->fk->y, f2d_o->fk->size);\n        if(s2dstatus)\n          *status = CCL_ERROR_SPLINE;\n      }\n    }\n    else\n      f2d->fk = NULL;\n  }\n\n  if(*status==0) {\n    if(f2d_o->fa != NULL) {\n      f2d->fa = gsl_spline_alloc(gsl_interp_cspline,\n                                 f2d_o->fa->size);\n      if(f2d->fa == NULL)\n        *status = CCL_ERROR_MEMORY;\n\n      if(*status==0) {\n        s2dstatus |= gsl_spline_init(f2d->fa, f2d_o->fa->x,\n                                     f2d_o->fa->y, f2d_o->fa->size);\n        if(s2dstatus)\n          *status = CCL_ERROR_SPLINE;\n      }\n    }\n    else\n      f2d->fa = NULL;\n  }\n\n  if(*status==0) {\n    if(f2d_o->fka != NULL) {\n      f2d->fka = gsl_spline2d_alloc(gsl_interp2d_bicubic,\n                                    f2d_o->fka->interp_object.xsize,\n                                    f2d_o->fka->interp_object.ysize);\n      if(f2d->fka == NULL)\n        *status = CCL_ERROR_MEMORY;\n\n      if(*status==0) {\n        s2dstatus |= gsl_spline2d_init(f2d->fka, f2d_o->fka->xarr,\n                                       f2d_o->fka->yarr, f2d_o->fka->zarr,\n                                       f2d_o->fka->interp_object.xsize,\n                                       f2d_o->fka->interp_object.ysize);\n        if(s2dstatus)\n          *status = CCL_ERROR_SPLINE;\n      }\n    }\n    else\n      f2d->fka = NULL;\n  }\n\n  return f2d;\n}\n  \nccl_f2d_t *ccl_f2d_t_new(int na,double *a_arr,\n                         int nk,double *lk_arr,\n                         double *fka_arr,\n                         double *fk_arr,\n                         double *fa_arr,\n                         int is_factorizable,\n                         int extrap_order_lok,\n                         int extrap_order_hik,\n                         ccl_f2d_extrap_growth_t extrap_linear_growth,\n                         int is_fka_log,\n                         double (*growth)(double),\n                         double growth_factor_0,\n                         int growth_exponent,\n                         ccl_f2d_interp_t interp_type,\n                         int *status) {\n  int s2dstatus=0;\n  ccl_f2d_t *f2d = malloc(sizeof(ccl_f2d_t));\n  if (f2d == NULL)\n    *status = CCL_ERROR_MEMORY;\n\n  if (*status == 0) {\n    is_factorizable = is_factorizable || (a_arr == NULL) || (lk_arr == NULL) || (fka_arr == NULL);\n    f2d->is_factorizable = is_factorizable;\n    f2d->is_k_constant = ((lk_arr == NULL) || ((fka_arr == NULL) && (fk_arr == NULL)));\n    f2d->is_a_constant = ((a_arr == NULL) || ((fka_arr == NULL) && (fa_arr == NULL)));\n    f2d->extrap_order_lok = extrap_order_lok;\n    f2d->extrap_order_hik = extrap_order_hik;\n    f2d->extrap_linear_growth = extrap_linear_growth;\n    f2d->is_log = is_fka_log;\n    f2d->growth = growth;\n    f2d->growth_factor_0 = growth_factor_0;\n    f2d->growth_exponent = growth_exponent;\n    f2d->fka = NULL;\n    f2d->fk = NULL;\n    f2d->fa = NULL;\n\n    if (!(f2d->is_k_constant)) { //If it's not constant\n      f2d->lkmin = lk_arr[0];\n      f2d->lkmax = lk_arr[nk-1];\n    }\n    if (!(f2d->is_a_constant)) {\n      f2d->amin = a_arr[0];\n      f2d->amax = a_arr[na-1];\n    }\n  }\n\n  if ((extrap_order_lok > 2) || (extrap_order_lok < 0) || (extrap_order_hik > 2) || (extrap_order_hik < 0))\n    *status = CCL_ERROR_INCONSISTENT;\n\n  if ((extrap_linear_growth != ccl_f2d_cclgrowth) &&\n      (extrap_linear_growth != ccl_f2d_customgrowth) &&\n      (extrap_linear_growth != ccl_f2d_constantgrowth) &&\n      (extrap_linear_growth != ccl_f2d_no_extrapol))\n    *status = CCL_ERROR_INCONSISTENT;\n\n  if(*status == 0) {\n    switch(interp_type) {\n    case(ccl_f2d_3):\n      if (f2d->is_factorizable) {\n        // Do not allocate spline if constant\n        if(f2d->is_k_constant)\n          f2d->fk = NULL;\n        else { //Otherwise allocate and check\n          f2d->fk = gsl_spline_alloc(gsl_interp_cspline, nk);\n          if(f2d->fk == NULL)\n            *status = CCL_ERROR_MEMORY;\n        }\n\n        // Do not allocate spline if constant\n        if (f2d->is_a_constant)\n          f2d->fa = NULL;\n        else { //Otherwise allocate and check\n          f2d->fa = gsl_spline_alloc(gsl_interp_cspline, na);\n          if (f2d->fa == NULL)\n            *status = CCL_ERROR_MEMORY;\n        }\n      }\n      else {\n        // Do not allocate spline if constant\n        if ((f2d->is_k_constant) || (f2d->is_a_constant))\n          f2d->fka = NULL;\n        else { //Otherwise allocate and check\n          f2d->fka = gsl_spline2d_alloc(gsl_interp2d_bicubic, nk, na);\n          if (f2d->fka == NULL)\n            *status = CCL_ERROR_MEMORY;\n        }\n      }\n      break;\n\n    default:\n      f2d->fk = NULL;\n      f2d->fa = NULL;\n      f2d->fka = NULL;\n    }\n  }\n\n  if (*status == 0) {\n    if (f2d->is_factorizable) {\n      if (f2d->fk != NULL)\n        s2dstatus |= gsl_spline_init(f2d->fk, lk_arr, fk_arr, nk);\n      if (f2d->fa != NULL)\n        s2dstatus |= gsl_spline_init(f2d->fa, a_arr, fa_arr, na);\n    }\n    else {\n      if (f2d->fka != NULL)\n        s2dstatus=gsl_spline2d_init(f2d->fka, lk_arr, a_arr, fka_arr, nk, na);\n    }\n    if (s2dstatus)\n      *status = CCL_ERROR_SPLINE;\n  }\n\n  return f2d;\n}\n\ndouble ccl_f2d_t_eval(ccl_f2d_t *f2d,double lk,double a,void *cosmo, int *status) {\n  int is_hiz, is_loz;\n  double a_ev = a;\n  if (f2d->is_a_constant) {\n    is_hiz = 0;\n    is_loz = 0;\n  }\n  else {\n    is_hiz = a < f2d->amin;\n    is_loz = a > f2d->amax;\n    if (is_loz) { // Are we above the interpolation range in a?\n      if (f2d->extrap_linear_growth == ccl_f2d_no_extrapol) {\n        *status=CCL_ERROR_SPLINE_EV;\n        return NAN;\n      }\n      a_ev = f2d->amax;\n    }\n    else if (is_hiz) { // Are we below the interpolation range in a?\n      if (f2d->extrap_linear_growth == ccl_f2d_no_extrapol) {\n        *status=CCL_ERROR_SPLINE_EV;\n        return NAN;\n      }\n      a_ev = f2d->amin;\n    }\n  }\n\n  int is_hik, is_lok;\n  double fka_pre, fka_post;\n  double lk_ev = lk;\n  if (f2d->is_k_constant) {\n    is_hik = 0;\n    is_lok = 0;\n  }\n  else {\n    is_hik = lk > f2d->lkmax;\n    is_lok = lk < f2d->lkmin;\n    if (is_hik) // Are we above the interpolation range in k?\n      lk_ev = f2d->lkmax;\n    else if (is_lok) // Are we below the interpolation range in k?\n      lk_ev = f2d->lkmin;\n  }\n\n  // Evaluate spline\n  int spstatus=0;\n  if (f2d->is_factorizable) {\n    double fk, fa;\n    if (f2d->fk == NULL) {\n      if (f2d->is_log)\n        fk = 0;\n      else\n        fk = 1;\n    }\n    else\n      spstatus |= gsl_spline_eval_e(f2d->fk, lk_ev, NULL, &fk);\n\n    if (f2d->fa == NULL) {\n      if (f2d->is_log)\n        fa = 0;\n      else\n        fa = 1;\n    }\n    else\n      spstatus |= gsl_spline_eval_e(f2d->fa, a_ev, NULL, &fa);\n      if (f2d->is_log)\n        fka_pre = fk+fa;\n      else\n        fka_pre = fk*fa;\n  }\n  else {\n    if (f2d->fka == NULL) {\n      if (f2d->is_log)\n        fka_pre = 0;\n      else\n        fka_pre = 1;\n    }\n    else\n      spstatus = gsl_spline2d_eval_e(f2d->fka, lk_ev, a_ev, NULL, NULL, &fka_pre);\n  }\n\n  if (spstatus) {\n    *status = CCL_ERROR_SPLINE_EV;\n    return NAN;\n  }\n\n  // Now extrapolate in k if needed\n  if (is_hik) {\n    fka_post = fka_pre;\n    if (f2d->extrap_order_hik > 0) {\n      double pd;\n      double dlk = lk-lk_ev;\n      if (f2d->is_factorizable)\n        spstatus = gsl_spline_eval_deriv_e(f2d->fk, lk_ev, NULL, &pd);\n      else\n        spstatus = gsl_spline2d_eval_deriv_x_e(f2d->fka, lk_ev, a_ev, NULL, NULL, &pd);\n      if (spstatus) {\n        *status = CCL_ERROR_SPLINE_EV;\n        return NAN;\n      }\n      fka_post += pd*dlk;\n      if (f2d->extrap_order_hik > 1) {\n        if (f2d->is_factorizable)\n          spstatus = gsl_spline_eval_deriv2_e(f2d->fk, lk_ev, NULL, &pd);\n        else\n          spstatus = gsl_spline2d_eval_deriv_xx_e(f2d->fka, lk_ev, a_ev, NULL, NULL, &pd);\n        if (spstatus) {\n          *status=CCL_ERROR_SPLINE_EV;\n          return NAN;\n        }\n        fka_post += pd*dlk*dlk*0.5;\n      }\n    }\n  }\n  else if (is_lok) {\n    fka_post = fka_pre;\n    if (f2d->extrap_order_lok > 0) {\n      double pd;\n      double dlk = lk-lk_ev;\n      if (f2d->is_factorizable)\n        spstatus = gsl_spline_eval_deriv_e(f2d->fk, lk_ev, NULL, &pd);\n      else\n        spstatus = gsl_spline2d_eval_deriv_x_e(f2d->fka, lk_ev, a_ev, NULL, NULL, &pd);\n      if (spstatus) {\n        *status = CCL_ERROR_SPLINE_EV;\n        return NAN;\n      }\n      fka_post += pd*dlk;\n\n      if (f2d->extrap_order_lok > 1) {\n        if (f2d->is_factorizable)\n          spstatus = gsl_spline_eval_deriv2_e(f2d->fk, lk_ev, NULL, &pd);\n        else\n          spstatus = gsl_spline2d_eval_deriv_xx_e(f2d->fka, lk_ev, a_ev, NULL, NULL, &pd);\n        if (spstatus) {\n          *status = CCL_ERROR_SPLINE_EV;\n          return NAN;\n        }\n        fka_post += pd*dlk*dlk*0.5;\n      }\n    }\n  }\n  else\n    fka_post = fka_pre;\n\n  // Exponentiate if needed\n  if (f2d->is_log)\n    fka_post = exp(fka_post);\n\n  // Extrapolate in a if needed\n  if (is_hiz) {\n    double gz;\n    if (f2d->extrap_linear_growth == ccl_f2d_cclgrowth) { // Use CCL's growth function\n      ccl_cosmology *csm = (ccl_cosmology *)cosmo;\n      if (!csm->computed_growth) {\n        *status = CCL_ERROR_GROWTH_INIT;\n        ccl_cosmology_set_status_message(\n          csm,\n          \"ccl_f2d.c: ccl_f2d_t_eval(): growth factor splines have not been precomputed!\");\n        return NAN;\n      }\n      gz = (\n        ccl_growth_factor(csm, a, status) /\n        ccl_growth_factor(csm, a_ev, status));\n    }\n    else if (f2d->extrap_linear_growth == ccl_f2d_customgrowth) // Use internal growth function\n      gz = f2d->growth(a) / f2d->growth(a_ev);\n    else // Use constant growth factor\n      gz = f2d->growth_factor_0;\n\n    fka_post *= pow(gz, f2d->growth_exponent);\n  }\n\n  return fka_post;\n}\n\nvoid ccl_f2d_t_free(ccl_f2d_t *f2d)\n{\n  if(f2d != NULL) {\n    if(f2d->fka != NULL)\n      gsl_spline2d_free(f2d->fka);\n    if(f2d->fk != NULL)\n      gsl_spline_free(f2d->fk);\n    if(f2d->fa != NULL)\n      gsl_spline_free(f2d->fa);\n    free(f2d);\n  }\n}\n", "meta": {"hexsha": "3ea62479b740014c44a5a84ef6c8c17a5d9aac0a", "size": 11235, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_f2d.c", "max_stars_repo_name": "borisbolliet/CCL", "max_stars_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_f2d.c", "max_issues_repo_name": "borisbolliet/CCL", "max_issues_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_f2d.c", "max_forks_repo_name": "borisbolliet/CCL", "max_forks_repo_head_hexsha": "6ddd35e49f9d2968cef3d3bc1bac8b55dbb4cf91", "max_forks_repo_licenses": ["BSD-3-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.5877862595, "max_line_length": 107, "alphanum_fraction": 0.5573653761, "num_tokens": 3762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.37663760976798283}}
{"text": "/* normal.c\n * \n * Copyright (C) 2015, 2016 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_multilarge.h>\n\ntypedef struct\n{\n  size_t p;              /* number of columns of LS matrix */\n  gsl_matrix *ATA;       /* A^T A, p-by-p */\n  gsl_vector *ATb;       /* A^T b, p-by-1 */\n  double normb;          /* || b || */\n  gsl_matrix *work_ATA;  /* workspace for chol(ATA), p-by-p */\n  gsl_vector *workp;     /* workspace size p */\n  gsl_vector *work3p;    /* workspace size 3*p */\n  gsl_vector *D;         /* scale factors for ATA, size p */\n  gsl_vector *c;         /* solution vector for L-curve */\n  int eigen;             /* 1 if eigenvalues computed */\n  double eval_min;       /* minimum eigenvalue */\n  double eval_max;       /* maximum eigenvalue */\n  gsl_eigen_symm_workspace *eigen_p;\n} normal_state_t;\n\nstatic void *normal_alloc(const size_t p);\nstatic void normal_free(void *vstate);\nstatic int normal_reset(void *vstate);\nstatic int normal_accumulate(gsl_matrix * A, gsl_vector * b,\n                             void * vstate);\nstatic int normal_solve(const double lambda, gsl_vector * x,\n                        double * rnorm, double * snorm,\n                        void * vstate);\nstatic int normal_rcond(double * rcond, void * vstate);\nstatic int normal_lcurve(gsl_vector * reg_param, gsl_vector * rho,\n                         gsl_vector * eta, void * vstate);\nstatic const gsl_matrix * normal_ATA(const void * vstate);\nstatic const gsl_vector * normal_ATb(const void * vstate);\nstatic int normal_solve_system(const double lambda, gsl_vector * x,\n                               normal_state_t *state);\nstatic int normal_solve_cholesky(gsl_matrix * ATA, const gsl_vector * ATb,\n                                 gsl_vector * x, normal_state_t *state);\nstatic int normal_calc_norms(const gsl_vector *x, double *rnorm,\n                             double *snorm, normal_state_t *state);\nstatic int normal_eigen(normal_state_t *state);\n\n/*\nnormal_alloc()\n  Allocate workspace for solving large linear least squares\nproblems using the normal equations approach\n\nInputs: p    - number of columns of LS matrix\n\nReturn: pointer to workspace\n*/\n\nstatic void *\nnormal_alloc(const size_t p)\n{\n  normal_state_t *state;\n\n  if (p == 0)\n    {\n      GSL_ERROR_NULL(\"p must be a positive integer\",\n                     GSL_EINVAL);\n    }\n\n  state = calloc(1, sizeof(normal_state_t));\n  if (!state)\n    {\n      GSL_ERROR_NULL(\"failed to allocate normal state\", GSL_ENOMEM);\n    }\n\n  state->p = p;\n\n  state->ATA = gsl_matrix_alloc(p, p);\n  if (state->ATA == NULL)\n    {\n      normal_free(state);\n      GSL_ERROR_NULL(\"failed to allocate ATA matrix\", GSL_ENOMEM);\n    }\n\n  state->work_ATA = gsl_matrix_alloc(p, p);\n  if (state->work_ATA == NULL)\n    {\n      normal_free(state);\n      GSL_ERROR_NULL(\"failed to allocate temporary ATA matrix\", GSL_ENOMEM);\n    }\n\n  state->ATb = gsl_vector_alloc(p);\n  if (state->ATb == NULL)\n    {\n      normal_free(state);\n      GSL_ERROR_NULL(\"failed to allocate ATb vector\", GSL_ENOMEM);\n    }\n\n  state->D = gsl_vector_alloc(p);\n  if (state->D == NULL)\n    {\n      normal_free(state);\n      GSL_ERROR_NULL(\"failed to allocate D vector\", GSL_ENOMEM);\n    }\n\n  state->workp = gsl_vector_alloc(p);\n  if (state->workp == NULL)\n    {\n      normal_free(state);\n      GSL_ERROR_NULL(\"failed to allocate temporary ATb vector\", GSL_ENOMEM);\n    }\n\n  state->work3p = gsl_vector_alloc(3 * p);\n  if (state->work3p == NULL)\n    {\n      normal_free(state);\n      GSL_ERROR_NULL(\"failed to allocate work3p\", GSL_ENOMEM);\n    }\n\n  state->c = gsl_vector_alloc(p);\n  if (state->c == NULL)\n    {\n      normal_free(state);\n      GSL_ERROR_NULL(\"failed to allocate c vector\", GSL_ENOMEM);\n    }\n\n  state->eigen_p = gsl_eigen_symm_alloc(p);\n  if (state->eigen_p == NULL)\n    {\n      normal_free(state);\n      GSL_ERROR_NULL(\"failed to allocate eigen workspace\", GSL_ENOMEM);\n    }\n\n  normal_reset(state);\n\n  return state;\n}\n\nstatic void\nnormal_free(void *vstate)\n{\n  normal_state_t *state = (normal_state_t *) vstate;\n\n  if (state->ATA)\n    gsl_matrix_free(state->ATA);\n\n  if (state->work_ATA)\n    gsl_matrix_free(state->work_ATA);\n\n  if (state->ATb)\n    gsl_vector_free(state->ATb);\n\n  if (state->D)\n    gsl_vector_free(state->D);\n\n  if (state->workp)\n    gsl_vector_free(state->workp);\n\n  if (state->work3p)\n    gsl_vector_free(state->work3p);\n\n  if (state->c)\n    gsl_vector_free(state->c);\n\n  if (state->eigen_p)\n    gsl_eigen_symm_free(state->eigen_p);\n\n  free(state);\n}\n\nstatic int\nnormal_reset(void *vstate)\n{\n  normal_state_t *state = (normal_state_t *) vstate;\n\n  gsl_matrix_set_zero(state->ATA);\n  gsl_vector_set_zero(state->ATb);\n  state->normb = 0.0;\n  state->eigen = 0;\n  state->eval_min = 0.0;\n  state->eval_max = 0.0;\n\n  return GSL_SUCCESS;\n}\n\n/*\nnormal_accumulate()\n  Add a new block of rows to the normal equations system\n\nInputs: A      - new block of rows, n-by-p\n        b      - new rhs vector n-by-1\n        vstate - workspace\n\nReturn: success/error\n*/\n\nstatic int\nnormal_accumulate(gsl_matrix * A, gsl_vector * b, void * vstate)\n{\n  normal_state_t *state = (normal_state_t *) vstate;\n  const size_t n = A->size1;\n\n  if (A->size2 != state->p)\n    {\n      GSL_ERROR(\"columns of A do not match workspace\", GSL_EBADLEN);\n    }\n  else if (n != b->size)\n    {\n      GSL_ERROR(\"A and b have different numbers of rows\", GSL_EBADLEN);\n    }\n  else\n    {\n      int s;\n\n      /* ATA += A^T A, using only the lower half of the matrix */\n      s = gsl_blas_dsyrk(CblasLower, CblasTrans, 1.0, A, 1.0, state->ATA);\n      if (s)\n        return s;\n\n      /* ATb += A^T b */\n      s = gsl_blas_dgemv(CblasTrans, 1.0, A, b, 1.0, state->ATb);\n      if (s)\n        return s;\n\n      /* update || b || */\n      state->normb = gsl_hypot(state->normb, gsl_blas_dnrm2(b));\n\n      return GSL_SUCCESS;\n    }\n}\n\n/*\nnormal_solve()\n  Solve normal equations system:\n\n(A^T A + \\lambda^2 I) x = A^T b\n\nusing Cholesky decomposition\n\nInputs: lambda - regularization parameter\n        x      - (output) solution vector p-by-1\n        rnorm  - (output) residual norm ||b - A x||\n        snorm  - (output) solution norm ||x||\n        vstate - workspace\n\nReturn: success/error\n*/\n\nstatic int\nnormal_solve(const double lambda, gsl_vector * x,\n             double * rnorm, double * snorm,\n             void * vstate)\n{\n  normal_state_t *state = (normal_state_t *) vstate;\n\n  if (x->size != state->p)\n    {\n      GSL_ERROR(\"solution vector does not match workspace\", GSL_EBADLEN);\n    }\n  else\n    {\n      int status;\n\n      /* solve system (A^T A) x = A^T b */\n      status = normal_solve_system(lambda, x, state);\n      if (status)\n        {\n          GSL_ERROR(\"failed to solve normal equations\", status);\n        }\n\n      /* compute residual norm ||y - X c|| and solution norm ||x|| */\n      normal_calc_norms(x, rnorm, snorm, state);\n\n      return GSL_SUCCESS;\n    }\n}\n\nstatic int\nnormal_rcond(double * rcond, void * vstate)\n{\n  normal_state_t *state = (normal_state_t *) vstate;\n  int status = GSL_SUCCESS;\n  double rcond_ATA;\n\n  status = gsl_linalg_cholesky_rcond(state->work_ATA, &rcond_ATA, state->work3p);\n  if (status == GSL_SUCCESS)\n    *rcond = sqrt(rcond_ATA);\n\n  return status;\n}\n\n/*\nnormal_lcurve()\n  Compute L-curve of least squares system\n\nInputs: reg_param - (output) vector of regularization parameters\n        rho       - (output) vector of residual norms\n        eta       - (output) vector of solution norms\n        vstate    - workspace\n\nReturn: success/error\n*/\n\nstatic int\nnormal_lcurve(gsl_vector * reg_param, gsl_vector * rho,\n              gsl_vector * eta, void * vstate)\n{\n  normal_state_t *state = (normal_state_t *) vstate;\n  int status;\n  double smin, smax; /* minimum/maximum singular values */\n  size_t i;\n\n  if (state->eigen == 0)\n    {\n      status = normal_eigen(state);\n      if (status)\n        return status;\n    }\n\n  if (state->eval_max < 0.0)\n    {\n      GSL_ERROR(\"matrix is not positive definite\", GSL_EDOM);\n    }\n\n  /* compute singular values which are sqrts of eigenvalues */\n  smax = sqrt(state->eval_max);\n  if (state->eval_min > 0.0)\n    smin = sqrt(state->eval_min);\n  else\n    smin = 0.0;\n\n  /* compute vector of regularization parameters */\n  gsl_multifit_linear_lreg(smin, smax, reg_param);\n\n  /* solve normal equations for each regularization parameter */\n  for (i = 0; i < reg_param->size; ++i)\n    {\n      double lambda = gsl_vector_get(reg_param, i);\n      double rnorm, snorm;\n\n      status = normal_solve_system(lambda, state->c, state);\n      if (status)\n        return status;\n\n      /* compute ||y - X c|| and ||c|| */\n      normal_calc_norms(state->c, &rnorm, &snorm, state);\n\n      gsl_vector_set(rho, i, rnorm);\n      gsl_vector_set(eta, i, snorm);\n    }\n\n  return GSL_SUCCESS;\n}\n\nstatic const gsl_matrix *\nnormal_ATA(const void * vstate)\n{\n  const normal_state_t *state = (const normal_state_t *) vstate;\n  return state->ATA;\n}\n\nstatic const gsl_vector *\nnormal_ATb(const void * vstate)\n{\n  const normal_state_t *state = (const normal_state_t *) vstate;\n  return state->ATb;\n}\n\n/*\nnormal_solve_system()\n  Compute solution to normal equations:\n\n(A^T A + lambda^2*I) x = A^T b\n\nusing LDL decomposition.\n\nInputs: x     - (output) solution vector\n        state - workspace\n\nReturn: success/error\n*/\n\nstatic int\nnormal_solve_system(const double lambda, gsl_vector * x, normal_state_t *state)\n{\n  int status;\n  const double lambda_sq = lambda * lambda;\n  gsl_vector_view d = gsl_matrix_diagonal(state->work_ATA);\n\n  /* copy ATA matrix to temporary workspace and regularize */\n  gsl_matrix_tricpy(CblasLower, CblasNonUnit, state->work_ATA, state->ATA);\n  gsl_vector_add_constant(&d.vector, lambda_sq);\n\n  /* solve with Cholesky decomposition */\n  status = normal_solve_cholesky(state->work_ATA, state->ATb, x, state);\n  if (status)\n    return status;\n\n  return status;\n}\n\nstatic int\nnormal_solve_cholesky(gsl_matrix * ATA, const gsl_vector * ATb,\n                      gsl_vector * x, normal_state_t *state)\n{\n  int status;\n\n  status = gsl_linalg_cholesky_decomp2(ATA, state->D);\n  if (status)\n    return status;\n\n  status = gsl_linalg_cholesky_solve2(ATA, state->D, ATb, x);\n  if (status)\n    return status;\n\n  return GSL_SUCCESS;\n}\n\n/*\nnormal_calc_norms()\n  Compute residual norm ||y - X c|| and solution\nnorm ||c||\n\nInputs: x     - solution vector\n        rnorm - (output) residual norm ||y - X c||\n        snorm - (output) solution norm ||c||\n        state - workspace\n*/\n\nstatic int\nnormal_calc_norms(const gsl_vector *x, double *rnorm,\n                  double *snorm, normal_state_t *state)\n{\n  double r2;\n\n  /* compute solution norm ||x|| */\n  *snorm = gsl_blas_dnrm2(x);\n\n  /* compute residual norm ||b - Ax|| */\n\n  /* compute: A^T A x - 2 A^T b */\n  gsl_vector_memcpy(state->workp, state->ATb);\n  gsl_blas_dsymv(CblasLower, 1.0, state->ATA, x, -2.0, state->workp);\n\n  /* compute: x^T A^T A x - 2 x^T A^T b */\n  gsl_blas_ddot(x, state->workp, &r2);\n\n  /* add b^T b */\n  r2 += state->normb * state->normb;\n\n  *rnorm = sqrt(r2);\n\n  return GSL_SUCCESS;\n}\n\n/*\nnormal_eigen()\n  Compute eigenvalues of A^T A matrix, which\nare stored in state->workp on output. Also,\nstate->eval_min and state->eval_max are set\nto the minimum/maximum eigenvalues\n*/\n\nstatic int\nnormal_eigen(normal_state_t *state)\n{\n  int status;\n\n  /* copy lower triangle of ATA to temporary workspace */\n  gsl_matrix_tricpy(CblasLower, CblasNonUnit, state->work_ATA, state->ATA);\n\n  /* compute eigenvalues of ATA */\n  status = gsl_eigen_symm(state->work_ATA, state->workp, state->eigen_p);\n  if (status)\n    return status;\n\n  gsl_vector_minmax(state->workp, &state->eval_min, &state->eval_max);\n\n  state->eigen = 1;\n\n  return GSL_SUCCESS;\n}\n\nstatic const gsl_multilarge_linear_type normal_type =\n{\n  \"normal\",\n  normal_alloc,\n  normal_reset,\n  normal_accumulate,\n  normal_solve,\n  normal_rcond,\n  normal_lcurve,\n  normal_ATA,\n  normal_ATb,\n  normal_free\n};\n\nconst gsl_multilarge_linear_type * gsl_multilarge_linear_normal =\n  &normal_type;\n", "meta": {"hexsha": "64cd3bce2725bef8231df885b16a7af75408e82a", "size": 12911, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/multilarge/normal.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/multilarge/normal.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/multilarge/normal.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.8288461538, "max_line_length": 81, "alphanum_fraction": 0.6507629153, "num_tokens": 3546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.37658452912299833}}
{"text": "/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/*\n Contains collection of low-level routines for handling lists, \n one-hot matrices, evaluation metrics (f1-scores), and other.\n\n Dimitris Berberidis \n University of Minnesota 2017-2018\n*/\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <inttypes.h>\n#include <cblas.h>\n#include <sys/stat.h>\n#include <stdbool.h>\n\n#include \"my_utils.h\"\n#include \"my_defs.h\"\n\n\n\nvoid assert_all_nodes_present(csr_graph graph, const sz_long* seed_indices, sz_med num_seeds){\n\t\n\tfor(sz_med i=0;i<num_seeds;i++){\n\t\tif(seed_indices[i]>graph.num_nodes){\n\t\t\tprintf(\"ERROR: Seed node index does not appear in edgelist (probably an isolated node)\\n\");\n\t\t        exit(EXIT_FAILURE); \t\t\n\t\t}\t\t\t\n\t}\n\t\n}\n\n\nsz_long rand_lim(sz_long limit) {\n\t/* return a random number between 0 and limit inclusive.\n\t */\n\tint divisor = RAND_MAX/((int)limit+1);\n\tint retval;\n\tdo { \n\t\tretval = rand() / divisor;\n\t} while (retval > limit);\n\treturn retval;\n}\n\n\n//Draw random samples with replacement from 0 to N-1\nvoid random_sample( sz_long* seeds, abstract_labels labels, abstract_labels all_labels, sz_med num_seeds, sz_long N){\n\n\tsz_long temp;\n\tsz_short flag;\n\t\n\t//Draw seed indexes\n\tseeds[0]=rand_lim(N-1);\n\tfor(sz_med i=1;i<num_seeds;i++){\n\t\tdo{\n\t\t\ttemp=rand_lim(N-1);\n\t\t\tflag=0;\n\t\t\tfor(sz_med j=0;j<i;j++){\n\t\t\t\tif(temp==seeds[j])\n\t\t\t\t\tflag=1;\n\t\t\t}\n\t\t}while(flag==1);\n\t\tseeds[i]=temp;\n\t}\n\n\t//Draw corresponding labels\n\tif(all_labels.is_multilabel){\n\t\tfor(sz_med i=0;i<num_seeds;i++){\n\t\t\tfor(sz_short j=0; j<all_labels.mlabel.num_class;j++) \n\t\t\t\tlabels.mlabel.bin[j][i] = all_labels.mlabel.bin[j][seeds[i]];\n\t\t}\t\t\n\t}else{\n\t\t\n\t\tfor(sz_med i=0;i<num_seeds;i++){ \n\t\t\tlabels.mclass[i]=all_labels.mclass[seeds[i]];\n\t\t\t//printf(\"%d\\n\",seeds[i]);\n\t\t}\n\t}\n\n\t// +1 seed indexes !\n\tfor(sz_med i=0;i<num_seeds;i++){seeds[i]+=1;}\t\n\n}\n\n\n\n//My comparator for two collumn array. Sorts second col according to first\nint compare ( const void *pa, const void *pb ) \n{\n\tconst sz_long *a = *(const sz_long **)pa;\n\tconst sz_long *b = *(const sz_long **)pb;\n\tif(a[0] == b[0])\n\t\treturn a[1] - b[1];\n\telse\n\t\treturn a[0] - b[0];\n}  \n\n//My comparator for a struct with double and index\nint compare2 ( const void *pa, const void *pb ) \n{\n  val_and_ind *a1 = (val_and_ind*)pa;\n  val_and_ind *a2 = (val_and_ind*)pb;\n  if((*a1).val>(*a2).val)return -1;\n  else if((*a1).val<(*a2).val)return 1;\n  else return 0;\n}  \n\n//frobenious norm of double-valued square matrix\ndouble frob_norm(double* A, sz_med dim){\n\tdouble norm=0.0f;\n\n\tfor(sz_med i=0;i<dim*dim;i++){\n\t\tnorm+=pow(A[i],2.0f);\n\t}\n\t\t\n\treturn sqrt(norm);\t\n}\n\n//mean of double array\ndouble mean(double* a, int len){\n\tdouble sum=0;\n\tfor(int i=0;i<len;i++) sum+=a[i];\t\t\n\treturn sum/(double)len;\t\n}\n\n//Simple linear system solver using the LU decomposition\n/* INPUT: A,P filled in LUPDecompose; b - rhs vector; N - dimension\n * OUTPUT: x - solution vector of A*x=b\n */\nvoid LUPSolve(double **A, int *P, double *b, int N, double *x){\n\n    for (int i = 0; i < N; i++) {\n        x[i] = b[P[i]];\n\n        for (int k = 0; k < i; k++)\n            x[i] -= A[i][k] * x[k];\n    }\n\n    for (int i = N - 1; i >= 0; i--) {\n        for (int k = i + 1; k < N; k++)\n            x[i] -= A[i][k] * x[k];\n\n        x[i] = x[i] / A[i][i];\n    }\n}\n\n\n\n//Simple LU decomposition routine\n/* INPUT: A - array of pointers to rows of a square matrix having dimension N\n *        Tol - small tolerance number to detect failure when the matrix is near degenerate\n * OUTPUT: Matrix A is changed, it contains both matrices L-E and U as A=(L-E)+U such that P*A=L*U.\n *        The permutation matrix is not stored as a matrix, but in an integer vector P of size N+1 \n *        containing column indexes where the permutation matrix has \"1\". The last element P[N]=S+N, \n *        where S is the number of row exchanges needed for determinant computation, det(P)=(-1)^S    \n */\nint LUPDecompose(double **A, int N, double Tol, int *P) {\n\n    int i, j, k, imax; \n    double maxA, *ptr, absA;\n\n    for (i = 0; i <= N; i++)\n        P[i] = i; //Unit permutation matrix, P[N] initialized with N\n\n    for (i = 0; i < N; i++) {\n        maxA = 0.0;\n        imax = i;\n\n        for (k = i; k < N; k++)\n            if ((absA = fabs(A[k][i])) > maxA) { \n                maxA = absA;\n                imax = k;\n            }\n\n        if (maxA < Tol) return 0; //failure, matrix is degenerate\n\n        if (imax != i) {\n            //pivoting P\n            j = P[i];\n            P[i] = P[imax];\n            P[imax] = j;\n\n            //pivoting rows of A\n            ptr = A[i];\n            A[i] = A[imax];\n            A[imax] = ptr;\n\n            //counting pivots starting from N (for determinant)\n            P[N]++;\n        }\n\n        for (j = i + 1; j < N; j++) {\n            A[j][i] /= A[i][i];\n\n            for (k = i + 1; k < N; k++)\n                A[j][k] -= A[j][i] * A[i][k];\n        }\n    }\n\n    return 1;  //decomposition done \n}\n\n\n\n//Interface for CBLAS matrix vector product\nvoid matvec(double*y, double* A, double* x, sz_med M, sz_med N ){\n\t \t\n\tfor(int i=0;i<M;i++){y[i]=0.0f;}\n\n\tcblas_dgemv( CblasRowMajor , CblasNoTrans , (int)M , (int)N, 1.0f, A, (int)M, x, 1, 0.0f, y, 1);\n\n\n}\n\n\n\n\n//Interface for CBLAS matrix vector product\nvoid matvec_trans(double*y, double* A, double* x, sz_med M, sz_med N ){\n\t \n\tfor(sz_med i=0;i<M;i++){y[i]=0.0f;}\n\n\tcblas_dgemv( CblasRowMajor , CblasTrans , (int)M , (int)N, 1.0f, A, (int)M, x, 1, 0.0f, y, 1);\n\n\n}\n\n//Interface for CBLAS trnaspose-matrix vector product\nvoid matvec_trans_long( double* y , double* A, double* x, sz_long N, sz_med p ){\t\t\n\n\tcblas_dgemv (CblasRowMajor, CblasTrans, (int) p, (int)N , 1.0f, A,  (int) N , x, 1 , 0.0f, y, 1);\n\n\n\n}\n\n//Interface for CBLAS mutrix matrix product\nvoid matrix_matrix_product(double*C, double* A, double* B, sz_long m, sz_med k , sz_short n){\n\n\tcblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, (int)m, \n\t\t     (int)n, (int)k, 1.0f, A, (int)k, B, (int)n, 0.0f, C, (int)n);\n\n}\n\n\n//Project vector onto simplex by alternating projections onto line and positive quadrant\n//Operation happens in place\nvoid project_to_simplex( double* x, sz_med N ){\n\tdouble sum,a; \n\tsz_short flag;\n\n\tdo{\n\t\tflag=0;\n\t\tsum=0.0f;\n\t\t\n\t\tfor(sz_med i=0; i<N; i++) sum+=x[i];\n\n\t\ta=(sum - 1.0f)/(double)N;\n\n\t\tfor(sz_med i=0; i<N; i++){\n\t\t\tx[i]-=a;\n\t\t\tif(x[i]<= - PROJ_TOL){\n\t\t\t\tx[i]=0.0f;\n\t\t\t\tflag=1;}\n\t\t}\n\n\t}while(flag==1);\n}\n\n\n//find l_max norm between vecors of known length\ndouble max_diff(double* x, double* y , sz_med L){ \n\tdouble dif;\n\tdouble max_dif=0.0f;\n\tfor(sz_med i=0;i<L;i++){\n\t\tdif=fabs( x[i] - y[i] );\n\t\tmax_dif = ( dif > max_dif ) ? dif : max_dif ;\n\t}\n\treturn max_dif;\n}\n\n//Print array (double)\nvoid print_array_1D(double* arr, sz_long N, sz_long M){\n\tsz_long i,j;\n\tprintf(\"Array: \\n\");\n\tfor(i=0;i<N;i++){\n\t\tprintf(\"\\n\");\n\t\tfor(j=0;j<M;j++) printf(\"%lf  \",arr[i*M + j]);\n\t}\n\tprintf(\"\\n\");\n}\n\n//Pradict labels from largest soft label\nvoid predict_labels( class_t* label_out, double* soft_labels, class_t* class,\n\t             sz_long graph_size, sz_short num_class ){\n\tsz_short max_ind;\n\tdouble max_val;\n\n\tfor(sz_long i=0;i<graph_size;i++){\n\t\tmax_val=-100.0f;\n\t\tfor(sz_short j=0;j<num_class;j++){  \n\t\t\tif(max_val<soft_labels[i*num_class + j]){\n\t\t\t\tmax_val=soft_labels[i*num_class + j];\n\t\t\t\tmax_ind=j;}\n\t\t}\n\t\tlabel_out[i]=class[max_ind];\n\t}\n}\n\n//Pradict labels from largest soft label (Soft labels are transposed array)\nvoid predict_labels_type2( class_t* label_out, double* soft_labels, class_t* class,\n\t\t\t   sz_long graph_size, sz_short num_class ){\n\t\t\t   \t\t\t\t   \n\tsz_short max_ind;\n\tdouble max_val;\n\n\tfor(sz_long j=0;j<graph_size;j++){\n\t\tmax_val=-100.0f;\n\t\tfor(sz_short i=0;i<num_class;i++){  \n\t\t\tif(max_val<soft_labels[i*graph_size + j]){\n\t\t\t\tmax_val=soft_labels[i*graph_size + j];\n\t\t\t\tmax_ind=i;}\t\n\t\t}\n\t\tlabel_out[j]=class[max_ind];\t\t\n\t}\n}\n\n//Print the two collumn array of edges\nvoid print_edge_list(const sz_long** edge_list, sz_long len){\n\tprintf(\"EDGE LIST: \\n\");\n\tfor(sz_long i=0;i<len;i++)\n\t\tprintf(\"%\"PRIu64\"  %\"PRIu64\"\\n\", (uint64_t) edge_list[i][0], (uint64_t) edge_list[i][1]);\n}\n\n\n\n\n//Print array (double)\nvoid print_predictions(class_t* arr, sz_long N){ \n\tprintf(\"Predicted labels: \\n\");\n\tfor(sz_long i=0;i<N;i++) printf(\"%\"PRIi16\"\\n\", (int16_t) arr[i]);\n}\n\n//Check if file is valid\nint file_isreg(char *path) {\n    struct stat st;\n\n    if (stat(path, &st) < 0)\n        return -1;\n\n    return S_ISREG(st.st_mode);\n}\n\n\n\n//Elementwise subtract b from a and store in c \nvoid my_array_sub(double* c, double* a, double* b, sz_long N ){\t\n\tfor(sz_long i=0;i<N;i++) c[i] = a[i] -b[i]; \n}\n\n//Max of array \n\nsz_short max_u8( sz_short* a, sz_long N ){\n\tsz_short max= 0;\n\tfor(sz_long i=0; i<N ; i++) max = ( a[i]>max ) ? a[i] : max ; \n\treturn max;\n}\n\nsz_long max_u64( sz_long* a, sz_long N ){\n\tsz_long max= 0;\n\tfor(sz_long i=0; i<N ; i++) max = ( a[i]>max ) ? a[i] : max ; \n\treturn max;\n}\n\n\n\n//Return edge list and count to main \n\nsz_long** give_edge_list( char* file_name, sz_long* count ){ \n\n\tsz_long** buffer= (sz_long **)malloc(EDGE_BUFF_SIZE * sizeof(sz_long *));\n \n\tfor(sz_long i=0;i<EDGE_BUFF_SIZE;i++)\n\t\tbuffer[i]= (sz_long*) malloc(2*sizeof(sz_long));\n\n\tFILE* file= fopen(file_name, \"r\");\n\n\tif(!file) printf(\"ERROR: Cannot open graph file\");\n\n\t// Read adjacency into buffer into buffer and return length count=edges\n\t*count= read_adjacency_to_buffer(buffer,file);\n\tprintf(\"Number of edges: %\"PRIu64\"\\n\", (uint64_t) *count);\n\n\t//print_edge_list( buffer, *count);\n\n\t//Free excess memory\n\tfor(sz_long i=*count+1;i<EDGE_BUFF_SIZE;i++)\n\t{free(buffer[i]);}\n\tbuffer=realloc(buffer,(*count)*sizeof(sz_long*));\n\n\treturn buffer;\n}\n\n\n//Read .txt file into buffer\nsz_long read_adjacency_to_buffer(sz_long** buffer, FILE* file){\n        sz_long count = 0;\n\tfor (; count < EDGE_BUFF_SIZE; ++count)\n\t{\n\t\tint got = fscanf(file, \"%\"SCNu64\"\\t%\"SCNu64\"\\n\", &buffer[count][0] , &buffer[count][1]);\n\t\tif ((got != 2)||( (buffer[count][0]==0) && (buffer[count][1]==0))) break; \n\t\t// Stop scanning if wrong number of tokens (maybe end of file) or zero input\n\t}\n\tfclose(file);\n\treturn count;\n}\n\n\n//Read class.txt file into buffer (ignore first collumn here)\nclass_t* read_labels(char* filename, sz_long* label_count){\n\tsz_long count = 0;\n\tsz_long* indexes = (sz_long*) malloc(sizeof(sz_long)*CLASS_BUFF_SIZE);\n\tclass_t* buffer = (class_t*) malloc(sizeof(class_t)*CLASS_BUFF_SIZE);\n\tFILE* file= fopen(filename, \"r\");\n\n\tif(!file) printf(\"ERROR: Cannot open label file\");\n\n\tfor (; count < CLASS_BUFF_SIZE; ++count)\n\t{\n\t\tint got = fscanf(file, \"%\"SCNu64\"%\"SCNu8\"\", &indexes[count] , &buffer[count]);\n\t\tif (got != 2) break; // wrong number of tokens - maybe end of file\n\t}\n\tfclose(file);\n\n\t*label_count = count;\n\tbuffer = realloc(buffer,sizeof(class_t)*count);\n\tindexes = realloc(indexes,sizeof(sz_long)*count);\n\n\t\n\tmy_relative_sorting( indexes, buffer, count );\n      \t\t\n        \t\t\n\tfree(indexes);\n\treturn buffer;\n}\n\n//Read seed and label file when in operation mode\nsz_long* read_seed_file( char* filename, sz_med* num_seeds, sz_short* num_class, abstract_labels* label_in ){\n\n        //First read file into buffers\n\tsz_long count = 0;\n\tsz_long* index_buffer = (sz_long*) malloc(sizeof(sz_long)*CLASS_BUFF_SIZE);\n\tclass_t* label_buffer = (class_t*) malloc(sizeof(class_t)*CLASS_BUFF_SIZE);\n\tFILE* file= fopen(filename, \"r\");\n\n\tif(!file) printf(\"ERROR: Cannot open seed file\");\n\n\tfor (; count < CLASS_BUFF_SIZE; ++count)\n\t{\n\t\tint got = fscanf(file, \"%\"SCNu64\"%\"SCNd8\"\", &index_buffer[count] , &label_buffer[count]);\n\t\tif (got != 2) break; // wrong number of tokens - maybe end of file\n\t}\n\tfclose(file);\n\tlabel_buffer = realloc(label_buffer,sizeof(class_t)*count);\n\tindex_buffer = realloc(index_buffer,sizeof(sz_long)*count);\n\t\n\t//prepare input labels and seeds for is_multilabel or multi_class\n\t\n\tsz_long* seed_indices;\n\t\n\tif(label_in->is_multilabel){\t\t\n\t\t*num_class = max_u8( (sz_short*) label_buffer, count);\t\t\n\t\tmy_relative_sorting( index_buffer, label_buffer, count );\n\t\tseed_indices = find_unique_from_sorted( index_buffer, count , num_seeds );\n\n\t\tlabel_in->mlabel = init_one_hot(*num_class , *num_seeds);\n\t\tsz_long j=0;\n\t\tfor(sz_long i=0;i<count;i++){\n\t\t\tif(i>0) j = (index_buffer[i] == index_buffer[i-1] ) ? j : j+1;\n\t\t\tlabel_in->mlabel.bin[label_buffer[i]-1][j]=1;\n\t\t}\n\t\t\n\t        free(index_buffer);\n\t\tfree(label_buffer);\t\t\n\t}else{\n\t\tseed_indices = index_buffer;\n\t\tlabel_in->mclass = label_buffer;\n\t\t*num_seeds = (sz_med) count;\n\t}\n\t\n\treturn seed_indices;\n}\t\n\n\n//write predicted labels (or ranking in multilabel case) to output file\nvoid save_predictions(char* filename, abstract_label_output label_out, sz_long len, sz_short num_class){\n\t\n\tFILE* file = fopen(filename, \"w\");\t\n\t\n\tif(!file) printf(\"ERROR: Cannot open outfile\");\n\t\n\tif(label_out.is_multilabel){ \n\t\tval_and_ind line_of_out[num_class];\n\t\tfor(sz_long i=0; i<len; i++){\n\t\t\tfor(sz_short j=0; j<num_class; j++) \n\t\t\t\tline_of_out[j] = (val_and_ind) {.val = label_out.mlabel[j*len + i], .ind=(int)j}; \n\t\t\t\t\n\t\t\tqsort( line_of_out, num_class, sizeof(line_of_out[0]), compare2);\n\t\t\t\n\t\t\tfprintf(file, \"%\"SCNu64\":\\t\", (uint64_t) i+1 );\n\t\t\t\n\t\t\tfor(sz_short j=0; j<num_class; j++) \n\t\t\t\tfprintf(file, \"%\"PRIu16\" \", (uint16_t) line_of_out[j].ind +1 );\n\t\t\t\n\t\t\tfprintf(file, \"\\n\");\n\t\t}\n\t}else{\n\t\tfor(sz_long i=0; i<len; i++)\n\t\t\tfprintf(file, \"%\"SCNu64\"\\t%\"SCNd16\"\\n\", (uint64_t) i+1 , (int16_t) label_out.mclass[i]);\t\n\t}\n\t\n\tfclose(file);\n}\n\n//Read class.txt file into one_hot_matrix (ignore first collumn here)\none_hot_mat read_one_hot_mat(char* filename, sz_long* label_count){\n\tsz_long count = 0;\n\tsz_long* indexes = (sz_long*) malloc(sizeof(sz_long)*CLASS_BUFF_SIZE);\n\tsz_short* buffer = (sz_short*) malloc(sizeof(sz_short)*CLASS_BUFF_SIZE);\n\tFILE* file = fopen(filename, \"r\");\n\n\tif(!file) printf(\"ERROR: Cannot open label file\");\n\n\tfor (; count < CLASS_BUFF_SIZE; ++count)\n\t{\n\t\tint got = fscanf(file, \"%\"SCNu64\"\\t%\"SCNu8\"\", &indexes[count] , &buffer[count]);\n\t\tif (got != 2) break; // wrong number of tokens - maybe end of file\n\t}\n\tfclose(file);\n\n\tbuffer = realloc(buffer,sizeof(sz_short)*count);\n\tindexes = realloc(indexes,sizeof(sz_long)*count);\n\t\n\tsz_short num_class = max_u8( buffer, count);\n\n\tsz_long length = max_u64( indexes, count);\n\t\n//\tprintf(\"LENGTH %\"PRIu64\"\\n\",length);\n\n\tone_hot_mat all_labels = init_one_hot(num_class , length);\n\t\n\tfor(sz_long i=0;i<count;i++) all_labels.bin[buffer[i]-1][indexes[i]-1]=1; \n\n\t*label_count = length;\n      \t\t        \t\t\n\tfree(indexes);\n\tfree(buffer);\n\treturn all_labels;\n}\n\n// Sort A and ind with respect to indexes in ind\nvoid my_relative_sorting( sz_long* ind, class_t* A, sz_long len ){ \n\tsz_long* temp = (sz_long*)malloc(len*sizeof(sz_long));\n\tsz_long* sorted_inds = (sz_long*)malloc(len*sizeof(sz_long));\n\n\n\tfor(sz_long i=0;i<len;i++){ temp[i] = i ;}\n\n\n\tsz_long** zipped_arrays = zip_arrays(ind,temp,len); \n \n\n        qsort( zipped_arrays , len, sizeof(zipped_arrays[0]), compare); \n\n\t\n        unzip_array(zipped_arrays, temp, sorted_inds, len );\n\n        rearange(sorted_inds, (void*) A, \"class_t\" , len );\n\t\n\tfree(temp);\n\tfree(sorted_inds);\n\n}\n\n\n//Zip two arrays into a list of length-2 lists\nsz_long** zip_arrays(sz_long* A, sz_long* B, sz_long len){\n\tsz_long** zipped = (sz_long**)malloc(len*sizeof(sz_long*));\n\t\n\tfor(sz_long i=0;i<len;i++){ \n\t\tzipped[i] = (sz_long*)malloc(2*sizeof(sz_long)); \n                ** (zipped +i) = A[i]; \n                *(* (zipped +i)+1) = B[i]; \n\t}\n\treturn zipped;\t\n}\n\n\n//Unzip two arrays into input pointers and destroy zipped array\nvoid unzip_array(sz_long** zipped, sz_long* unzip_1, sz_long* unzip_2, sz_long len ){\n\t\t\n\tfor(sz_long i=0;i<len;i++){\n\t\tunzip_1[i] = zipped[i][0];\n\t\tunzip_2[i] = zipped[i][1];\n\t\tfree(*(zipped+i));\n\t}\t\n\t\n\tfree(zipped);\n}\n\n//Rearange elements of array A accortding to given indexes\n//Works for any type of array as long as the type is provided\nvoid rearange(sz_long* ind, void* A, char* type , sz_long len ){\n\n\tif(strcmp(type,\"double\")==0){ \n\t\tdouble A_temp[len];\n\t\tmemcpy(A_temp, A, len*sizeof(double));  \n\t\tfor(sz_long i=0;i<len;i++){ *((double*)A + i) = A_temp[ind[i]];}\n\t}else if(strcmp(type,\"sz_long\")==0){\n\t\tsz_long A_temp[len];\n\t\tmemcpy(A_temp, A, len*sizeof(sz_long));  \n\t\tfor(sz_long i=0;i<len;i++){ *((sz_long*)A + i) = A_temp[ind[i]];}\t\t\n\t}else if(strcmp(type,\"uint32_t\")==0){\n\t\tuint32_t A_temp[len];\n\t\tmemcpy(A_temp, A, len*sizeof(uint32_t));  \n\t\tfor(sz_long i=0;i<len;i++){ *((uint32_t*)A + i) = A_temp[ind[i]];}\n\t}else if(strcmp(type,\"sz_med\")==0){\n\t\tsz_med A_temp[len];\n\t\tmemcpy(A_temp, A, len*sizeof(sz_med));  \n\t\tfor(sz_long i=0;i<len;i++){ *((sz_med*)A + i) = A_temp[ind[i]];}\t\t\n\t}else if(strcmp(type,\"sz_short\")==0){\n\t\tsz_short A_temp[len];\n\t\tmemcpy(A_temp, A, len*sizeof(sz_short));  \n\t\tfor(sz_long i=0;i<len;i++){ *((sz_short*)A + i) = A_temp[ind[i]];}\t\t\n\t}else if(strcmp(type,\"int32_t\")==0){\n\t\tint32_t A_temp[len];\n\t\tmemcpy(A_temp, A, len*sizeof(int32_t));  \n\t\tfor(sz_long i=0;i<len;i++){ *((int32_t*)A + i) = A_temp[ind[i]];}\t\t\n\t}else if(strcmp(type,\"int16_t\")==0){\n\t\tint16_t A_temp[len];\n\t\tmemcpy(A_temp, A, len*sizeof(int16_t));  \n\t\tfor(sz_long i=0;i<len;i++){ *((int16_t*)A + i) = A_temp[ind[i]];}\n\t}else if(strcmp(type,\"class_t\")==0){\n\t\tclass_t A_temp[len];\n\t\tmemcpy(A_temp, A, len*sizeof(class_t));  \n\t\tfor(sz_long i=0;i<len;i++){ *((class_t*)A + i) = A_temp[ind[i]];}\n\t}else if(strcmp(type,\"long double\")==0){\n\t\tlong double A_temp[len];\n\t\tmemcpy(A_temp, A, len*sizeof(long double));  \n\t\tfor(sz_long i=0;i<len;i++){ *((long double*)A + i) = A_temp[ind[i]];}  \t\t\n\t}else if(strcmp(type,\"int\")==0){\n\t\tint A_temp[len];\n\t\tmemcpy(A_temp, A, len*sizeof(int));  \n\t\tfor(sz_long i=0;i<len;i++){ *((int*)A + i) = A_temp[ind[i]];}\n\t}else{\n\t\tprintf(\"Unknown rearange type\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\t\t\t\t\t\n\t\n}\n\n\n\n//Remove items of given indexes from array (list)\n// Return result in NEW  list \nsz_long* remove_from_list(const sz_long* list, const sz_long* indexes_to_be_removed, \n\t\t\t   sz_long len, sz_long num_removed ){\n\n\tsz_long* new_list = (sz_long*) malloc((len-num_removed)*sizeof(sz_long));\n\n\tint mask[len];\n\t\n\tmemset(mask, 0, len*sizeof(int));\n\t\n\tfor(sz_long i =0; i<num_removed; i++){ mask[indexes_to_be_removed[i]] =1 ;}\n\n\t\n\tsz_long k=0;\n\tfor(sz_long i =0; i<len; i++){\n\t\tif(mask[i]==0){\n\t\t    new_list[k++] = list[i];\t\t\t\n\t\t}\n\t}\n\t\n\treturn new_list;\n}\n\n\n\n//Find unique elements among known number of entries in buffer\n//Also eturn number of unique entries\nsz_short find_unique(class_t* unique_elements, const class_t* buffer,sz_med N){\n\t \n\tsz_short new,end=1;\n\n\tunique_elements[0]=buffer[0];\n\tfor(sz_med i=0;i<N;i++){\n\t\tnew=1;\n\t\tfor(sz_short j=0;j<end;j++)\n\t\t{if(unique_elements[j]==buffer[i])\n\t\t\tnew=0;}\n\n\t\tif(new)\n\t\t\tunique_elements[end++]=buffer[i];\n\n\t}\n\treturn end;\n}\n\n//Find unique entries from list of sorted (unisgned indexes) \nsz_long* find_unique_from_sorted( sz_long* sorted_buffer, sz_long len , sz_med* num_unique ){\n\tsz_long* unique = (sz_long*) malloc(len*sizeof(sz_long));\n\t*num_unique = 1;\n\t\n\tunique[0] = sorted_buffer[0]; \n\tfor(sz_long i=1;i<len;i++){\n\t\tif(!(sorted_buffer[i] == sorted_buffer[i-1] )){\n\t\t\t*num_unique += 1;\n\t\t\tunique[*num_unique-1] = sorted_buffer[i];\t\n\t\t}\t\t\n\t} \t\n\tunique = realloc(unique,*num_unique*sizeof(sz_long));\n\treturn unique;\n}\n\n// Converts list to one hot binary matrix of one_hot_mat type\n// Label count is number of indexes with known labels\n// label_count<=length\n// If label_count<=length, then rows of the one_hot matrix \n// without a coresponding labeled index will be [0...0]\none_hot_mat list_to_one_hot( sz_long* ind , class_t* labels, sz_short num_class ,\n\t\t\t     class_t* class ,  sz_long label_count ,sz_long length){\n\t\n\tone_hot_mat one_hot = init_one_hot( num_class , length);\n\t\n\tfor(sz_long i=0;i<label_count;i++){ \n\t\tfor(sz_short j=0;j<num_class;j++){ \n\t\t\tif( labels[i] == class[j] ){\n\t\t\t\tone_hot.bin[j][ind[i]]=1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\t\t\n\t\t\n\treturn one_hot;\n}\n\n\n//Allocate one_hot_mat\none_hot_mat init_one_hot(sz_short num_class ,sz_long length){\t\n\tone_hot_mat one_hot;\n\tone_hot.bin = (sz_short**) malloc(num_class*sizeof(sz_short*));\n\n\tfor(sz_short i=0;i<num_class;i++){ \n\t\tone_hot.bin[i] = (sz_short*) malloc(length*sizeof(sz_short)); \n\t\tfor(sz_long j=0;j<length;j++){\t        \n\t\t\tone_hot.bin[i][j] =0 ;\n\t\t}\n\t}\t\t\n\tone_hot.num_class = num_class;\n\tone_hot.length = length;\t\n\treturn one_hot;\n}\n\n\n// Destroy (free) one_hot matrix\nvoid destroy_one_hot(one_hot_mat one_hot){\n\tfor(sz_short i=0;i<one_hot.num_class;i++) free(one_hot.bin[i]); \n\tfree(one_hot.bin);\n}\n\n\n// Return array with number of non-zero entries in each row of one-hot-matrix\nsz_short* return_num_labels_per_node( one_hot_mat one_hot ){\n\tsz_short* num_labels = (sz_short*)malloc(one_hot.length*sizeof(sz_short));\n\tfor(sz_long i=0;i<one_hot.length;i++){\n\t\tnum_labels[i]=0;\n\t\tfor(sz_short j=0;j<one_hot.num_class;j++) num_labels[i]+= one_hot.bin[j][i];\t\t\n\t}\n\treturn num_labels;\n}\n\n\n// Return a one_hot_mat with non-zeros for each row given to \n// the k-largest (specified by num_lpn) corresponding soft labels\n// Does not do sorting and has O(kC) complexity per node instead \n// of O(C logC). Will be slow if C and k large\none_hot_mat top_k_mlabel( double* soft_labels , sz_short* num_lpn, sz_long length, sz_short num_class ){\n\tdouble max_max,max,val;\n\tsz_short max_ind;\n\tone_hot_mat label_out = init_one_hot(num_class ,length);\n\t\t\n\tfor(sz_long i=0; i<length;i++ ){\n\t\tmax_max =1.1f;\n\t\tfor(sz_short k = 0; k<num_lpn[i];k++){\n\t\t\tmax = 0.0f;\n\t\t\tfor(sz_short j=0; j<num_class ;j++ ){\n\t\t\t\tval = soft_labels[j*length +i]; \n\t\t\t\tif( ( val < max_max) && (val > max) ){\n\t\t\t\t\tmax = val;\n\t\t\t\t\tmax_ind = j;\n\t\t\t\t}\t\t\t\n\t\t\t}\t\t\n\t\t\tmax_max = max;\n\t\t\tlabel_out.bin[max_ind][i]=1; \t\t\n\t\t}\n\t}\n\t\n\treturn label_out;\n}\n\n\n// Computes rate of true positive, False positive and false negative\n// A binary mask determines which values I am interested in (usually unlabeled entries..)\ndetector_stats get_detector_stats( sz_short* true_val, sz_short* pred_val, sz_long len, int* mask ){\n\t\n\tdetector_stats stats = {.true_pos = 0.0,\n\t\t\t        .true_neg =0.0,\t\n\t\t\t        .false_pos = 0.0,\n\t\t\t        .false_neg = 0.0};\n\t\n\tsz_long k=0;\n\tfor(sz_long i=0;i<len;i++){\n\t    if(mask[i]!=0){\t\t\n\t    \tk++;\n\t\tif(true_val[i]==1){\n\t\t\tif(pred_val[i]==1){\n\t\t\t\tstats.true_pos+=1.0;\n\t\t\t}else{\n\t\t\t\tstats.false_neg+=1.0;\n\t\t\t}\t\t\t\t\n\t\t}else{\n\t\t\tif(pred_val[i]==1){\n\t\t\t\tstats.false_pos+=1.0;\n\t\t\t}else{\n\t\t\t\tstats.true_neg+=1.0;\n\t\t\t}\n\t\t}\n\t    }\t\n\t}       \n\t\n\tstats.true_pos/=(double) k;\n\tstats.true_neg/=(double) k;\n\tstats.false_pos/=(double) k;\n\tstats.false_neg/=(double) k;\n\t\n\treturn stats;\n}\n\n\n// Harmonic mean of 2 real numbers\ndouble harmonic_mean( double x, double y ){\t\n\tif(x+y == 0.0f){\n\t\tprintf(\"ERROR: Harmonic mean evaluated at 0\\n \");\n\t\texit(EXIT_FAILURE);\n\t}\n\treturn (2.0f*(x*y))/(x+y);\t\n}\n\n\n// Produce micro and macro averaged precision and recall\n// Input is the more simple detector_stats for different classes \nclassifier_stats  get_class_stats(detector_stats* all_stats , sz_short num_class ){\n\n\tclassifier_stats stats = {.micro_precision=0.0f,\n\t\t\t\t  .macro_precision=0.0f,\n\t\t\t\t  .micro_recall=0.0f,\n\t\t\t\t  .macro_recall=0.0f }; \n\t\n\tdouble sum_of_true_pos = 0.0f, micro_prec_denom = 0.0f, micro_recall_denom = 0.0f ;\n\n\tfor(sz_short i=0; i<num_class;i++){\n\t\tsum_of_true_pos += all_stats[i].true_pos;\n\t\tmicro_prec_denom += all_stats[i].true_pos + all_stats[i].false_pos;\t\t\n\t\tmicro_recall_denom += all_stats[i].true_pos + all_stats[i].false_neg;\n\t\t\n\t\tstats.macro_precision += all_stats[i].true_pos/( all_stats[i].true_pos + all_stats[i].false_pos );\n\t\tstats.macro_recall += all_stats[i].true_pos/( all_stats[i].true_pos + all_stats[i].false_neg );\t\t\n\t}\n\t\n\tstats.micro_precision = sum_of_true_pos/micro_prec_denom;\n\tstats.micro_recall = sum_of_true_pos/micro_recall_denom;\n\n\tstats.macro_precision /= (double) num_class;\n\tstats.macro_recall /= (double) num_class;\n        \n\t\n\treturn stats;\n}\n\n\n// Takes array of detector statistics as input and returns array with f-1 scores for every class\n\nvoid get_per_class_f1_scores(double* f1_per_class, detector_stats* all_stats, sz_short num_class ){\n\t\n\tfor(sz_short i=0;i<num_class;i++){ \n\t\tdouble TP = all_stats[i].true_pos;\n\t\tdouble FN = all_stats[i].false_neg;\n\t\tdouble FP = all_stats[i].false_pos;\n\t\tf1_per_class[i] = 2.0*TP / ( 2.0*TP + FN + FP );\n\t}\n}\n\n\n \n// Computes Micro and Macro f1-score\n// Inputs must be one_hot structs\n// f1_scores are only evaluated on the indexes denoted by unlabeled\n\nf1_scores get_averaged_f1_scores( one_hot_mat true_labels, one_hot_mat pred_labels,\n\t                          sz_long* unlabeled , sz_long num_unlabeled ){\n\t\n\tif( (true_labels.num_class != pred_labels.num_class) || (true_labels.length != pred_labels.length) ){\n\t\tprintf(\"Classifier stats ERROR: One-hot matrixes dimensions dont match\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tint mask[true_labels.length];\n\tmemset(mask, 0 , true_labels.length*sizeof(int));\n\tfor(sz_long i=0;i< num_unlabeled; i++ ){ mask[unlabeled[i]]=1; }\n\n        // Start by gathering detection statistics per each class \n\n\tdetector_stats all_stats[true_labels.num_class];\n\n\tfor(sz_short i=0;i<true_labels.num_class;i++){\n\t\tall_stats[i] = get_detector_stats( true_labels.bin[i] , pred_labels.bin[i] , true_labels.length , mask );\n\t}\n\n\t// Use detection stats to get Micro and Macro averaged F1 scores\n\t\n\tf1_scores scores = {.micro = 0.0f,\n\t\t\t    .macro = 0.0f };\n\t\n\tclassifier_stats class_stats = get_class_stats(all_stats , true_labels.num_class );\n\t\n\tdouble f1_per_class[true_labels.num_class];\n\t\n\tget_per_class_f1_scores(f1_per_class, all_stats, true_labels.num_class);\n\t\n\tscores.micro = harmonic_mean(class_stats.micro_precision, class_stats.micro_recall );\n        scores.macro = mean( f1_per_class, (int)true_labels.num_class );\n/*\n        This definition of Macro F1 (using macro averaged precision and recall) does not seem to work well\n\tscores.macro = harmonic_mean(class_stats.macro_precision, class_stats.macro_recall ); //\n*/\t\n\treturn scores;\t\n}\n\n\n\n\n//Compute error rate\n\ndouble accuracy(class_t* true_label, class_t* pred,  sz_long* unlabeled, sz_long num_unlabeled){\n\tdouble sum=0.0;\n\tfor(sz_long i=0;i<num_unlabeled;i++){\n\t\t\tif(true_label[unlabeled[i]]==pred[unlabeled[i]])\n\t\t\t\tsum+=1.0;\n\t\t}\t\t     \n\n\treturn sum/(double)num_unlabeled;\n}\n\n\n\n\n", "meta": {"hexsha": "b37971f90182c8b293ba329799567964eb51b95f", "size": 26338, "ext": "c", "lang": "C", "max_stars_repo_path": "src/my_utils.c", "max_stars_repo_name": "DimBer/SSL_lib", "max_stars_repo_head_hexsha": "8ca9ca6f595a5da718850f3dcf3607c9ebf51c92", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-05-24T03:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-31T15:11:17.000Z", "max_issues_repo_path": "src/my_utils.c", "max_issues_repo_name": "nikolakopoulos/Adaptive-Diffusions-for-SSL", "max_issues_repo_head_hexsha": "d2060a8875950694225611fcda7b757215cf65c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/my_utils.c", "max_forks_repo_name": "nikolakopoulos/Adaptive-Diffusions-for-SSL", "max_forks_repo_head_hexsha": "d2060a8875950694225611fcda7b757215cf65c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T03:55:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-16T08:23:52.000Z", "avg_line_length": 27.0133333333, "max_line_length": 117, "alphanum_fraction": 0.6447718126, "num_tokens": 7919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.37656710076433636}}
{"text": "/*\n * Evan Lezar\n * An implementation of a dense eigensolver that uses the ARPACK Fortran backend.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <omp.h>\n#include <cblas.h>\n// #include <acml.h>\n\n// Include the interfaces to the Fortran routines.\n#include \"interface.h\"\n\n#define ARPACK_CALL 0\n#define SHIFT 1\n#define SGETRF_S 2\n#define SGEMV 9\n\n//!\n//! A data structure used to pass the eigenproblem configuration to Fortran and \n//! back to C again.\nstruct data_struct {\n    float* A;           //! A pointer to the matrix representing the eigenproblem.\n    double sgemv_time;  //! The total time required to calculate the matrix-vector products.\n    int sgemv_calls;    //! The number of times the matrix-vector product was called.\n    int LDA;            //! The leading dimension of the matrix.\n};\ntypedef struct data_struct data_struct;\n\n//! \n//! A utility function to print the structure representing the eigenproblem.\nvoid print_data ( const char* desc, data_struct DATA )\n{\n    printf ( \"%s: A = %p LDA = %d\\n\", desc, DATA.A, DATA.LDA );\n}\n\n//!\n//! Calculate the matrix-vector product  y <- Ax for the eigensystem defined by DATA. This\n//! routine is called from the Fortran backend whenever ARPACK requires a matrix-vector\n//! product to be calculated.\n//! \\param[in] N The dimension of the eigensystem.\n//! \\param[in,out] DATA The structure representing the eigenproblem.\n//! \\param[in] x The vector that must be multiplied by A.\n//! \\param[out] y The vector that must store the result.\nvoid sgemv_wrapper ( int N, data_struct* DATA, float* x, float* y )\n{\n    checkpoint t0 = tic();\n    // read the relevant data from the struct\n    float* A = DATA->A;\n    int LDA = DATA->LDA;\n    // calculate y <-- Ax\n    cblas_sgemv ( CblasColMajor, CblasNoTrans, N, N, 1.0, A, LDA, x, 1, 0.0, y, 1);\n    DATA->sgemv_time += toc ( t0 );\n    DATA->sgemv_calls += 1;\n}\n\n//!\n//! Initialise the struct representing the eigensystem.\nvoid init_data ( data_struct* DATA, float* A, int LDMAT )\n{\n    DATA->A = A;\n    DATA->LDA = LDMAT;\n    DATA->sgemv_calls = 0;\n    DATA->sgemv_time = 0.0;\n}\n\n//!\n//! Solve the actual eigensystem. This takes the eigensystem defined in the structure DATA and allocates\n//! the required temporary workspaces before calling the Fortran backend.\nvoid calculate_eigen_values ( int N, void* DATA, int NEV, float* eigenvalues, float* eigenvectors, char* which )\n{\n    int use_N_ev = 2*NEV;\n    if ( use_N_ev > ( N/2 - 1 ) )\n        use_N_ev = N/2 - 1;\n    // select the number of Arnoldi vectors to generate\n    int NCV = 2*use_N_ev + 1;\n    if ( NCV > N )\n        NCV = N;\n\n    // allocate temporary storage for the vectors\n    float* temp_ev = (float*)malloc ( NCV*2*sizeof(float) );\n    float* temp_vectors = (float*) malloc (N*NCV*sizeof(float));\n    float* temp_residuals = (float*)malloc ( (NCV )*sizeof(float));\n\n    // solve the eigenvalue problem using ARPACK\n    arpack_ssev(N, (void*)DATA, use_N_ev, NCV, temp_ev, temp_vectors, temp_residuals, which );\n    \n    // Copy the resultant eigenvalues to the previously allocated space.\n    memcpy(eigenvalues, temp_ev, NEV*2*sizeof(float));\n    memcpy(eigenvectors, temp_vectors, NEV*N*sizeof(float));\n\n    // free the temporary storage\n    free ( temp_ev );\n    free ( temp_vectors );\n    free ( temp_residuals );\n}\n\n\n//!\n//! Solve the standard eigensystem Ax = lx.eigen\n//! \\param[in] N The number of columns in the matrix A\n//! \\param[in] A The matrix representing the eigensystem to be solved.\n//! \\param[in] NEV The number of eigenvalues to calculate.\n//! \\param[out] eigenvalues A vector of the NEV eigenvalues. Note that the eigenvectors are complex.\n//! \\param[out] eigenvectors An NxNEV matrix with the eigenvectors as columns.\n//! \\param[out] timing_data_10 A 10-vector representing the timing data for various phases of the process.\n//! \\param[out] int_data_10 A 10-vector containing some run information.\n//! \\return A non-zero error code if an error occured.\nint dense_seev ( int N, float* A, int LDMAT, int NEV, float* eigenvalues, float* eigenvectors, double* timing_data_10, int* int_data_10 )\n{\n    checkpoint t0;\n    int result = 0;\n\n    // Initialise the data structure that is passed to the ARPACK routines.\n    data_struct DATA;\n    init_data( &DATA, A, LDMAT );\n\n    t0 = tic();\n    // Call a C wrapper function that allows for the calculation of the NEV largest eigenvalues.\n    calculate_eigen_values ( N, &DATA, NEV, eigenvalues, eigenvectors, \"LM\" );\n    timing_data_10[ARPACK_CALL] = toc( t0 );\n\n    timing_data_10[SGEMV] = DATA.sgemv_time;\n    int_data_10[SGEMV] = DATA.sgemv_calls;\n    return result;\n}\n", "meta": {"hexsha": "c12f20beb3f726b52625835eb9451f3fa9d63f8f", "size": 4631, "ext": "c", "lang": "C", "max_stars_repo_path": "src/dense_cpu.c", "max_stars_repo_name": "elezar/gpu-arpack", "max_stars_repo_head_hexsha": "f9c4edb20c2f1556fea4404679bd8c2d7039af18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T14:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T14:14:16.000Z", "max_issues_repo_path": "src/dense_cpu.c", "max_issues_repo_name": "elezar/gpu-arpack", "max_issues_repo_head_hexsha": "f9c4edb20c2f1556fea4404679bd8c2d7039af18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dense_cpu.c", "max_forks_repo_name": "elezar/gpu-arpack", "max_forks_repo_head_hexsha": "f9c4edb20c2f1556fea4404679bd8c2d7039af18", "max_forks_repo_licenses": ["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.8992248062, "max_line_length": 137, "alphanum_fraction": 0.6879723602, "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3765670983042188}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_cblas.h>\n\n#include \"tests.h\"\n\nvoid\ntest_hpr2 (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int uplo = 121;\n   int N = 1;\n   float alpha[2] = {-1.0f, 0.0f};\n   float Ap[] = { 0.159f, -0.13f };\n   float X[] = { 0.854f, 0.851f };\n   int incX = -1;\n   float Y[] = { 0.526f, -0.267f };\n   int incY = -1;\n   float Ap_expected[] = { -0.284974f, 0.0f };\n   cblas_chpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, \"chpr2(case 1458) real\");\n       gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, \"chpr2(case 1458) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 122;\n   int N = 1;\n   float alpha[2] = {-1.0f, 0.0f};\n   float Ap[] = { 0.159f, -0.13f };\n   float X[] = { 0.854f, 0.851f };\n   int incX = -1;\n   float Y[] = { 0.526f, -0.267f };\n   int incY = -1;\n   float Ap_expected[] = { -0.284974f, 0.0f };\n   cblas_chpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, \"chpr2(case 1459) real\");\n       gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, \"chpr2(case 1459) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 121;\n   int N = 1;\n   float alpha[2] = {-1.0f, 0.0f};\n   float Ap[] = { 0.159f, -0.13f };\n   float X[] = { 0.854f, 0.851f };\n   int incX = -1;\n   float Y[] = { 0.526f, -0.267f };\n   int incY = -1;\n   float Ap_expected[] = { -0.284974f, 0.0f };\n   cblas_chpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, \"chpr2(case 1460) real\");\n       gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, \"chpr2(case 1460) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 122;\n   int N = 1;\n   float alpha[2] = {-1.0f, 0.0f};\n   float Ap[] = { 0.159f, -0.13f };\n   float X[] = { 0.854f, 0.851f };\n   int incX = -1;\n   float Y[] = { 0.526f, -0.267f };\n   int incY = -1;\n   float Ap_expected[] = { -0.284974f, 0.0f };\n   cblas_chpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Ap[2*i], Ap_expected[2*i], flteps, \"chpr2(case 1461) real\");\n       gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], flteps, \"chpr2(case 1461) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 121;\n   int N = 1;\n   double alpha[2] = {-0.3, 0.1};\n   double Ap[] = { 0.772, 0.997 };\n   double X[] = { -0.173, -0.839 };\n   int incX = -1;\n   double Y[] = { 0.941, -0.422 };\n   int incY = -1;\n   double Ap_expected[] = { 0.829742, 0.0 };\n   cblas_zhpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, \"zhpr2(case 1462) real\");\n       gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, \"zhpr2(case 1462) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int uplo = 122;\n   int N = 1;\n   double alpha[2] = {-0.3, 0.1};\n   double Ap[] = { 0.772, 0.997 };\n   double X[] = { -0.173, -0.839 };\n   int incX = -1;\n   double Y[] = { 0.941, -0.422 };\n   int incY = -1;\n   double Ap_expected[] = { 0.829742, 0.0 };\n   cblas_zhpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, \"zhpr2(case 1463) real\");\n       gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, \"zhpr2(case 1463) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 121;\n   int N = 1;\n   double alpha[2] = {-0.3, 0.1};\n   double Ap[] = { 0.772, 0.997 };\n   double X[] = { -0.173, -0.839 };\n   int incX = -1;\n   double Y[] = { 0.941, -0.422 };\n   int incY = -1;\n   double Ap_expected[] = { 0.829742, 0.0 };\n   cblas_zhpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, \"zhpr2(case 1464) real\");\n       gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, \"zhpr2(case 1464) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int uplo = 122;\n   int N = 1;\n   double alpha[2] = {-0.3, 0.1};\n   double Ap[] = { 0.772, 0.997 };\n   double X[] = { -0.173, -0.839 };\n   int incX = -1;\n   double Y[] = { 0.941, -0.422 };\n   int incY = -1;\n   double Ap_expected[] = { 0.829742, 0.0 };\n   cblas_zhpr2(order, uplo, N, alpha, X, incX, Y, incY, Ap);\n   {\n     int i;\n     for (i = 0; i < 1; i++) {\n       gsl_test_rel(Ap[2*i], Ap_expected[2*i], dbleps, \"zhpr2(case 1465) real\");\n       gsl_test_rel(Ap[2*i+1], Ap_expected[2*i+1], dbleps, \"zhpr2(case 1465) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "7fb7dee72012f4310be29a6dc128ae6d18a137ed", "size": 4809, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_hpr2.c", "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 692.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_hpr2.c", "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1096.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_hpr2.c", "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "avg_line_length": 25.579787234, "max_line_length": 84, "alphanum_fraction": 0.5086296527, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.37615440761906216}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#ifndef NOMPI\n#include <mpi.h>\n#endif\n#include <gsl/gsl_math.h>\n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n\n/*! \\file predict.c\n *  \\brief drift particles by a small time interval\n *\n *  This function contains code to implement a drift operation on all the\n *  particles, which represents one part of the leapfrog integration scheme.\n */\n\n\n/*! This function drifts all particles from the current time to the future:\n *  time0 - > time1\n *\n *  If there is no explicit tree construction in the following timestep, the\n *  tree nodes are also drifted and updated accordingly. Note: For periodic\n *  boundary conditions, the mapping of coordinates onto the interval\n *  [0,All.BoxSize] is only done before the domain decomposition, or for\n *  outputs to snapshot files.  This simplifies dynamic tree updates, and\n *  allows the domain decomposition to be carried out only every once in a\n *  while.\n */\nvoid move_particles(int time0, int time1)\n{\n  int i, j;\n  double dt_drift, dt_gravkick, dt_hydrokick, dt_entr;\n  double t0, t1;\n\n\n  t0 = second();\n\n  if(All.ComovingIntegrationOn)\n    {\n      dt_drift = get_drift_factor(time0, time1);\n      dt_gravkick = get_gravkick_factor(time0, time1);\n      dt_hydrokick = get_hydrokick_factor(time0, time1);\n    }\n  else\n    {\n      dt_drift = dt_gravkick = dt_hydrokick = (time1 - time0) * All.Timebase_interval;\n    }\n\n  for(i = 0; i < NumPart; i++)\n    {\n      for(j = 0; j < 3; j++)\n\tP[i].Pos[j] += P[i].Vel[j] * dt_drift;\n\n      if(P[i].Type == 0)\n\t{\n#ifdef PMGRID\n\t  for(j = 0; j < 3; j++)\n\t    SphP[i].VelPred[j] +=\n\t      (P[i].GravAccel[j] + P[i].GravPM[j]) * dt_gravkick + SphP[i].HydroAccel[j] * dt_hydrokick;\n#else\n\t  for(j = 0; j < 3; j++)\n\t    SphP[i].VelPred[j] += P[i].GravAccel[j] * dt_gravkick + SphP[i].HydroAccel[j] * dt_hydrokick;\n#endif\n\t  SphP[i].Density *= exp(-SphP[i].DivVel * dt_drift);\n\t  SphP[i].Hsml *= exp(0.333333333333 * SphP[i].DivVel * dt_drift);\n\n\t  if(SphP[i].Hsml < All.MinGasHsml)\n\t    SphP[i].Hsml = All.MinGasHsml;\n\n\t  dt_entr = (time1 - (P[i].Ti_begstep + P[i].Ti_endstep) / 2) * All.Timebase_interval;\n\n\t  SphP[i].Pressure = (SphP[i].Entropy + SphP[i].DtEntropy * dt_entr) * pow(SphP[i].Density, GAMMA);\n\n#ifdef MORRIS97VISC\n          SphP[i].Alpha += SphP[i].DAlphaDt * dt_drift;\n#endif\n\t}\n    }\n\n  /* if domain-decomp and tree are not going to be reconstructed, update dynamically.  */\n  if(All.NumForcesSinceLastDomainDecomp < All.TotNumPart * All.TreeDomainUpdateFrequency)\n    {\n      for(i = 0; i < Numnodestree; i++)\n\tfor(j = 0; j < 3; j++)\n\t  Nodes[All.MaxPart + i].u.d.s[j] += Extnodes[All.MaxPart + i].vs[j] * dt_drift;\n\n      force_update_len();\n\n      force_update_pseudoparticles();\n    }\n\n  t1 = second();\n\n  All.CPU_Predict += timediff(t0, t1);\n}\n\n\n\n/*! This function makes sure that all particle coordinates (Pos) are\n *  periodically mapped onto the interval [0, BoxSize].  After this function\n *  has been called, a new domain decomposition should be done, which will\n *  also force a new tree construction.\n */\n#ifdef PERIODIC\nvoid do_box_wrapping(void)\n{\n  int i, j;\n  double boxsize[3];\n\n  for(j = 0; j < 3; j++)\n    boxsize[j] = All.BoxSize;\n\n#ifdef LONG_X\n  boxsize[0] *= LONG_X;\n#endif\n#ifdef LONG_Y\n  boxsize[1] *= LONG_Y;\n#endif\n#ifdef LONG_Z\n  boxsize[2] *= LONG_Z;\n#endif\n\n  for(i = 0; i < NumPart; i++)\n    for(j = 0; j < 3; j++)\n      {\n\twhile(P[i].Pos[j] < 0)\n\t  P[i].Pos[j] += boxsize[j];\n\n\twhile(P[i].Pos[j] >= boxsize[j])\n\t  P[i].Pos[j] -= boxsize[j];\n      }\n}\n#endif\n", "meta": {"hexsha": "bec03d609501e025fddbeacb306b24625474e82f", "size": 3560, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/gadget2/src/predict.c", "max_stars_repo_name": "rknop/amuse", "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_issues_repo_path": "src/amuse/community/gadget2/src/predict.c", "max_issues_repo_name": "rknop/amuse", "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 690.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_forks_repo_path": "src/amuse/community/gadget2/src/predict.c", "max_forks_repo_name": "rieder/amuse", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "avg_line_length": 25.7971014493, "max_line_length": 100, "alphanum_fraction": 0.645505618, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3760944415197872}}
{"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk_5_3.c\n * \\brief Source file to optimize Runge-Kutta 5 steps 3rd order methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include <string.h>\n#include <math.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include <libintl.h>\n#include <gsl/gsl_rng.h>\n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_5_3.h\"\n\n#define DEBUG_RK_5_3 0          ///< macro to debug.\n\n/**\n * Function to obtain the coefficients of a 5 steps 3rd order Runge-Kutta \n * method.\n */\nint\nrk_tb_5_3 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *tb, *r;\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_tb_5_3: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t5 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  b21 (tb) = r[2];\n  t3 (tb) = r[3];\n  b31 (tb) = r[4];\n  b32 (tb) = r[5];\n  t4 (tb) = r[6];\n  b41 (tb) = r[7];\n  b42 (tb) = r[8];\n  b43 (tb) = r[9];\n  b54 (tb) = r[10];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = 0.5L - b54 (tb) * t4 (tb);\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = 1.L / 3.L - b54 (tb) * sqr (t4 (tb));\n  A[2] = 0.L;\n  B[2] = b21 (tb) * t1 (tb);\n  C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);\n  D[2] = 1.L / 6.L - b54 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb)\n                                 + b43 (tb) * t3 (tb));\n  solve_3 (A, B, C, D);\n  if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))\n    return 0;\n  b53 (tb) = D[2];\n  b52 (tb) = D[1];\n  b51 (tb) = D[0];\n  rk_b_5 (tb);\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_tb_5_3: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 5 steps 3rd order, 4th order in\n * equations depending only in time, Runge-Kutta method.\n */\nint\nrk_tb_5_3t (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *tb, *r;\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_tb_5_3t: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t5 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  b21 (tb) = r[2];\n  t3 (tb) = r[3];\n  b31 (tb) = r[4];\n  b32 (tb) = r[5];\n  t4 (tb) = r[6];\n  b41 (tb) = r[7];\n  b42 (tb) = r[8];\n  b43 (tb) = r[9];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = t4 (tb);\n  E[0] = 0.5L;\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = D[0] * t4 (tb);\n  E[1] = 1.L / 3.L;\n  A[2] = A[1] * t1 (tb);\n  B[2] = B[1] * t2 (tb);\n  C[2] = C[1] * t3 (tb);\n  D[2] = D[1] * t4 (tb);\n  E[2] = 0.25L;\n  A[3] = 0.L;\n  B[3] = b21 (tb) * t1 (tb);\n  C[3] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);\n  D[3] = b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb) + b43 (tb) * t3 (tb);\n  E[3] = 1.L / 6.L;\n  solve_4 (A, B, C, D, E);\n  if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))\n    return 0;\n  b54 (tb) = E[3];\n  b53 (tb) = E[2];\n  b52 (tb) = E[1];\n  b51 (tb) = E[0];\n  rk_b_5 (tb);\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_tb_5_3t: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 5 steps 2nd-3rd order Runge-Kutta \n * pair.\n */\nint\nrk_tb_5_3p (Optimize * optimize)        ///< Optimize struct.\n{\n  long double *tb;\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_tb_5_3p: start\\n\");\n#endif\n  if (!rk_tb_5_3 (optimize))\n    return 0;\n  tb = optimize->coefficient;\n  e51 (tb) = 0.5L / t1 (tb);\n  e52 (tb) = e53 (tb) = 0.L;\n  rk_e_5 (tb);\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_tb_5_3p: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 5 steps 2nd-3rd order, 3rd-4th order\n * in equations depending only in time, Runge-Kutta pair.\n */\nint\nrk_tb_5_3tp (Optimize * optimize)       ///< Optimize struct.\n{\n  long double *tb;\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_tb_5_3tp: start\\n\");\n#endif\n  if (!rk_tb_5_3t (optimize))\n    return 0;\n  tb = optimize->coefficient;\n  e53 (tb) = 0.L;\n  e52 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb)));\n  if (isnan (e52 (tb)))\n    return 0;\n  e51 (tb) = (0.5L - e52 (tb) * t2 (tb)) / t1 (tb);\n  if (isnan (e51 (tb)))\n    return 0;\n  rk_e_5 (tb);\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_tb_5_3tp: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to calculate the objective function of a 5 steps 3rd order \n * Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_5_3 (RK * rk)   ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_objective_tb_5_3: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_objective_tb_5_3: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_5_3: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 5 steps 3rd order, 4th \n * order in equations depending only in time, Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_5_3t (RK * rk)  ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_objective_tb_5_3t: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (b54 (tb) < 0.L)\n    o += b54 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_objective_tb_5_3t: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_5_3t: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 5 steps 2nd-3rd order \n * Runge-Kutta pair.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_5_3p (RK * rk)  ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_objective_tb_5_3p: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (e50 (tb) < 0.L)\n    o += e50 (tb);\n  if (e51 (tb) < 0.L)\n    o += e51 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_objective_tb_5_3p: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_5_3p: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 5 steps 2nd-3rd order, \n * 3rd-4th order in equations depending only in time, Runge-Kutta pair.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_5_3tp (RK * rk) ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_objective_tb_5_3tp: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (b54 (tb) < 0.L)\n    o += b54 (tb);\n  if (e50 (tb) < 0.L)\n    o += e50 (tb);\n  if (e51 (tb) < 0.L)\n    o += e51 (tb);\n  if (e52 (tb) < 0.L)\n    o += e52 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_5_3\n  fprintf (stderr, \"rk_objective_tb_5_3tp: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_5_3tp: end\\n\");\n#endif\n  return o;\n}\n", "meta": {"hexsha": "857828d71ad9bf7c2b551e3071dbf095e4cbd97f", "size": 10113, "ext": "c", "lang": "C", "max_stars_repo_path": "rk_5_3.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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": "rk_5_3.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk_5_3.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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.3100961538, "max_line_length": 80, "alphanum_fraction": 0.5692672797, "num_tokens": 4079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.37601007979935946}}
{"text": "/*\n * Copyright 2020-2021 OpenDR European 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#ifndef SCANMATCHERPROCESSOR_H\n#define SCANMATCHERPROCESSOR_H\n\n#include <gmapping/log/sensorlog.h>\n#include <gmapping/sensor/sensor_range/rangereading.h>\n#include <gmapping/sensor/sensor_range/rangesensor.h>\n//#include <gsl/gsl_eigen.h>\n#include \"gmapping/scanmatcher/scanmatcher.h\"\n\nnamespace GMapping {\n\n  class ScanMatcherProcessor {\n  public:\n    ScanMatcherProcessor(const ScanMatcherMap &m);\n\n    ScanMatcherProcessor(double xmin, double ymin, double xmax, double ymax, double delta, double patchdelta);\n\n    virtual ~ScanMatcherProcessor();\n\n    virtual void processScan(const RangeReading &reading);\n\n    void setSensorMap(const SensorMap &smap, std::string sensorName = \"FLASER\");\n\n    void init();\n\n    void setMatchingParameters(double urange, double range, double sigma, int kernsize, double lopt, double aopt,\n                               int iterations, bool computeCovariance = false);\n\n    void setRegistrationParameters(double regScore, double critScore);\n\n    OrientedPoint getPose() const;\n\n    inline const ScanMatcherMap &getMap() const { return m_map; }\n\n    inline ScanMatcher &matcher() { return m_matcher; }\n\n    inline void setmaxMove(double mmove) { m_maxMove = mmove; }\n\n    bool useICP;\n\n  protected:\n    ScanMatcher m_matcher;\n    bool m_computeCovariance;\n    bool m_first;\n    SensorMap m_sensorMap;\n    double m_regScore, m_critScore;\n    unsigned int m_beams;\n    double m_maxMove;\n    // state\n    ScanMatcherMap m_map;\n    OrientedPoint m_pose;\n    OrientedPoint m_odoPose;\n    int m_count;\n    // gsl_eigen_symmv_workspace * m_eigenspace;\n  };\n\n};  // namespace GMapping\n\n#endif\n", "meta": {"hexsha": "439fe9689d36cebdf488c9a74407460bbd8f4f09", "size": 2231, "ext": "h", "lang": "C", "max_stars_repo_path": "projects/perception/slam/full_map_posterior_gmapping/src/openslam_gmapping/include/gmapping/scanmatcher/scanmatcherprocessor.h", "max_stars_repo_name": "makistsantekidis/opendr", "max_stars_repo_head_hexsha": "07dee3b59d3487b9c5a93d6946317178a02c9890", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T01:54:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T16:21:24.000Z", "max_issues_repo_path": "projects/perception/slam/full_map_posterior_gmapping/src/openslam_gmapping/include/gmapping/scanmatcher/scanmatcherprocessor.h", "max_issues_repo_name": "makistsantekidis/opendr", "max_issues_repo_head_hexsha": "07dee3b59d3487b9c5a93d6946317178a02c9890", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2021-06-23T10:40:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T07:59:42.000Z", "max_forks_repo_path": "projects/perception/slam/full_map_posterior_gmapping/src/openslam_gmapping/include/gmapping/scanmatcher/scanmatcherprocessor.h", "max_forks_repo_name": "makistsantekidis/opendr", "max_forks_repo_head_hexsha": "07dee3b59d3487b9c5a93d6946317178a02c9890", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-07-04T07:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-12T16:18:47.000Z", "avg_line_length": 29.3552631579, "max_line_length": 113, "alphanum_fraction": 0.7315105334, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.37600990791612615}}
{"text": "#ifndef TRANS_TYPE\n#define TRANS_TYPE\n\n\n#include <gsl/gsl_vector.h>\n\n// corresponding python variable: element of 'list_n_original_diff'\ntypedef struct {\n    gsl_vector *inc1;\n    gsl_vector *inc2;\n    gsl_vector *skp1;\n    gsl_vector *skp2;\n    int inclu_len;\n    int skip_len;\n    int flag;\n    char* id;\n} odiff;\n\n\ntypedef struct {\n    int batch_size;\n    void **datum;\n} batch_datum;\n\n\n// used to represent the reture value of\n// MLE_marginal_iteration and MLE_marginal_iteration_constrain.\n// corresponding python variable: '[current_sum,[psi1,psi2,beta_0,beta_1,var1,var2]]'\ntypedef struct {\n    double sum;\n    struct {\n        gsl_vector *psi1;\n        gsl_vector *psi2;\n        double beta0;\n        double beta1;\n        double var1;\n        double var2;\n    } params;\n} mle_result;\n\n\n// we use a linked list to represent a python list.\n// corresponding python variable: 'list_n_original_diff'\ntypedef struct dnode{\n    odiff* data;\n    struct dnode* next;\n    struct dnode* end;\n} diff_list_node;\n\n\ntypedef struct node {\n    void* data;\n    struct node* next;\n    struct node* end;\n} list_node;\n\n\n// we use fortran l_bfgs_b routine to solve the numerical optimization problem.\n// (i.e. f = 0.0 at the optimal solution.)\n// only the minimal intersection of C's and Fortran's many data types can be relied on:\n// the following are some essential mapping between c type and fortran type\n// counterpart of f2c.h\ntypedef int integer;\ntypedef float real;\ntypedef double doublereal;\ntypedef long int logical;\n\n\n#endif\n", "meta": {"hexsha": "af71f58aa52421122288c759c625d6cb06e79521", "size": 1522, "ext": "h", "lang": "C", "max_stars_repo_path": "rMATS_C/include/type.h", "max_stars_repo_name": "chunjie-sam-liu/rmats-turbo", "max_stars_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 88.0, "max_stars_repo_stars_event_min_datetime": "2020-06-01T20:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T17:34:39.000Z", "max_issues_repo_path": "rMATS_C/include/type.h", "max_issues_repo_name": "chunjie-sam-liu/rmats-turbo", "max_issues_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 163.0, "max_issues_repo_issues_event_min_datetime": "2020-06-03T06:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:39:30.000Z", "max_forks_repo_path": "rMATS_C/include/type.h", "max_forks_repo_name": "chunjie-sam-liu/rmats-turbo", "max_forks_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2020-06-01T20:25:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:14:46.000Z", "avg_line_length": 21.7428571429, "max_line_length": 87, "alphanum_fraction": 0.7003942181, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.3759227297751376}}
{"text": "#ifndef L_Katyusha_H\n#define L_Katyusha_H\n\n\n#include <string>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <stdio.h>      /* printf */\n#include <time.h>\n#include <fstream>\n#include <algorithm>\n#include <iomanip>\n#include <ctime>\n#include <sstream>\n#include <math.h>\n\n\n//This class implements the loopless variance reduced type methods with arbitrary sampling\n\n/*\nThe optimization problem to solve is:\n\nF(x):=\\sum_{i=1}^n 1/n* phi_i(x)+ g(x)\n*/\n\ntemplate<typename L, typename D>\nclass L_Katyusha\n{\n\n\nprotected:\n\n  // involved variables\n\n\n\n\n\n\n\n  std::vector<D> proba_vector;\n\n  std::vector<D>  tilde_proba_vector;\n\n\n  std::vector<D> group_C;\n\n  std::vector<D> index_group_C;\n\n  std::vector<D> maxp_group_C;\n\n  std::vector<D> isolated_I;\n\n  std::vector<D> sump_group_C;\n  std::vector<D> theta_S;   //theta_S in the paper\n\n\n\n\n  std::vector<D> Li;  // the Lipchitz constant of phi_i\n\n\n\n\n  std::vector<D> gk;     // the vector g^k in the paper\n\n  std::vector<D> gradient_f_w;  // gradient of f at w\n  std::vector<D> gradient_f_x;  // gradient of f at x\n  std::vector<D> batch_delta_gradient; //  1/n(G(x^k)-G(w^k))theta_{S_k} I_{S_k} e in the paper\n\n  L c;\n\n  L noverc;\n\n\n\n\n\n  // auxiliary variables\n\n  L nb_of_iters_per_loop;\n\n  L max_nb_loops;\n\n  D max_p;\n\n\n  L nsamples;\n  L nfeatures;\n\n\n  D running_time;\n\n  L nb_loops;\n\n\n\n  L print_every_N;\n\n  vector<L> batch_i;\n  vector<L> my_batch;\n\n  L batch_size;\n\n  L nb_groups;    //number of groups in group sampling\n\n\n\n  string uniform;\n\n  D Lf;\n\n  D L2;\n\n  D sumLi;\n\n\n  D upper_bound;   // upper bound of F(x)-F^*\n\n  D p; // the probability of changing w to x as in the paper\n  L tau;  //number of threads on each node/computer\n\n  D mu;\n\n  D scaler;\n\n\n  L current_nb_iters;\n\n  L nb_iters;\n\n  ofstream samp;\n\n  D theta1;\n  D theta2;\n  D theta3;\n  D eta;  //eta/L in the paper\n  D oneovereta;\n\n  D primal_value;\n\n  std::vector<D> x;\n  std::vector<D> w;\n  std::vector<D> y;\n  std::vector<D> z;\n  std::vector<D> next_x;\n\n\npublic:\n\n\n  gsl_rng * rng;\n  virtual inline D value_of_phi_i(L) {return D(NULL);}\n  virtual inline D value_of_g(){return D(NULL);}\n  virtual inline void prox_of_g(D, vector<D> &, vector<D> &, vector<D> &){}   //prox_of_g(L,x, gr, y) computes y=argmin_u{L/2 ||u-(x-gr/L)||^2+g(u)}\n  virtual inline void set_auxiliary_v(){}\n  virtual inline void update_gradient(){}\n  virtual inline void set_Li_Lf(){}\n  virtual inline void compute_batch_delta_gradient(){}\n  virtual inline void compute_full_gradient(vector<D> &, vector<D> &){}\n\n\n  L_Katyusha()\n  {\n\n  }\n\n\n  void update_x(){\n    for(L i=0; i<nfeatures; i++){\n      x[i]= theta1*z[i]+ theta2*w[i]+ theta3*y[i];\n    }\n  }\n\n  void update_y(){\n    for(L i=0; i<nfeatures; i++){\n      y[i]=theta1*z[i]+ theta2*w[i]+ theta3*y[i];\n    }\n  }\n\n    void update_gk(){\n      batch_delta_gradient.clear();\n      batch_delta_gradient.resize(nfeatures,0);\n      compute_batch_delta_gradient();\n      for(L i=0;i<nfeatures;i++){\n        gk[i]=batch_delta_gradient[i]+gradient_f_w[i];\n      }\n    }\n\n    void update_z(){\n      prox_of_g(oneovereta,z,gk,z);\n    }\n\n    void update_w(){\n      D yi=gsl_rng_uniform(rng);\n      if(yi<=p){\n        w=x;\n        compute_full_gradient(w, gradient_f_w);\n      }\n    }\n\n\n\n    void compute_upper_bound_of_optimality_gap(){\n      compute_full_gradient(x, gradient_f_x);\n      prox_of_g(Lf,x,gradient_f_x,next_x);\n      D tmp=0;\n      for(L i=0;i<nfeatures;i++){\n        tmp+=(next_x[i]-x[i])*(next_x[i]-x[i]);\n        x[i]=next_x[i];\n      }\n      upper_bound=tmp*Lf*Lf/mu;\n   \t}\n\n\n\n    void set_rng()\n    {\n      gsl_rng_env_setup();\n      const gsl_rng_type * T;\n      T = gsl_rng_default;\n      rng = gsl_rng_alloc(T);\n      gsl_rng_set(rng,time(NULL));\n      //gsl_rng_set(rng, 27432042);\n\n    }\n\n\n\n    void set_print_every_N(L i){print_every_N=i;}\n\n\n\n\n    void set_optimal_probability()\n    {\n      tilde_proba_vector.clear();\n      tilde_proba_vector.resize(nsamples,0);\n      proba_vector.clear();\n      proba_vector.resize(nsamples,0);\n      D sum=0;\n      for(L i=0; i<nsamples;i++)\n      {\n        tilde_proba_vector[i]=Li[i];\n        sum+=Li[i];\n      }\n      max_p=0;\n      for(L i=0; i<nsamples;i++)\n      {\n        tilde_proba_vector[i]=tilde_proba_vector[i]/sum;\n        proba_vector[i]=1-pow(1-tilde_proba_vector[i],tau);\n        if(max_p<tilde_proba_vector[i])\n        {\n          max_p=tilde_proba_vector[i];\n        }\n      }\n      cout<<\"sum=\"<<sum<<\"; proba\"<<tilde_proba_vector[0]<<endl;\n    }\n\n\n    void set_group_sampling_probability(){\n      proba_vector.clear();\n      proba_vector.resize(nsamples,0);\n      std::vector<D> q(nsamples);\n      D sumq=0;\n      cout<<\"start setting group sampling probablity\"<<endl;\n      for(L i=0; i<nsamples;i++)\n      {\n        q[i]=Li[i];\n        sumq+=q[i];\n      }\n      D maxq=0;\n      L nb=0;\n      D tmp=0;\n      for(L i=0; i<nsamples;i++)\n      {\n        q[i]=q[i]/sumq*tau;\n        if(q[i]>maxq) maxq=q[i];\n        if(q[i]>1) {\n          nb++; //count the number of elements larger than 1\n          tmp+=q[i]-1;\n        }\n      }\n      cout<<\"maxq=\"<<maxq<<endl;\n      if(maxq<=1){\n        for(L i=0; i<nsamples;i++)\n        {\n          proba_vector[i]=q[i];\n        }\n      }else{\n        for(L i=0; i<nsamples;i++)\n        {\n          if(q[i]>1) q[i]=1;\n          else {\n            D deltaq=min(1-q[i],tmp);\n            tmp=tmp-deltaq;\n            q[i]+=deltaq;\n          }\n          proba_vector[i]=q[i];\n        }\n      }\n    }\n\n\n\n    void set_L2(L p_mod, L u){\n      if(p_mod==0){ //batch sampling mode\n        D tmp=0;\n        D st;\n        for(L i=0;i<nsamples;i++){\n          st=Li[i]/tilde_proba_vector[i];\n          if (st>tmp) tmp=st;\n        }\n        L2=tmp/nsamples/tau;\n        cout<<\"L2=\"<<L2<<\"; \"<<tilde_proba_vector[0]<<endl;\n      }\n      else{ //group sampling mode\n        D tmp=0;\n        D st;\n        for(L i=0;i<nsamples;i++){\n          st=Li[i]/proba_vector[i];\n          if(isolated_I[i]==1) st=st-Li[i];\n          if(st>tmp) tmp=st;\n        }\n        L2=tmp/nsamples;\n      }\n      cout<<\"set_L2=\"<<L2<<endl;\n    }\n\n    void set_uniform_probability(L p_mod)\n    {\n      if(p_mod==0) {\n        //batch sampling (stochastic process as defined in the paper)\n        proba_vector.clear();\n        tilde_proba_vector.clear();\n        tilde_proba_vector.resize(nsamples,1./nsamples);\n        proba_vector.resize(nsamples,1-pow(1-1.0/nsamples,tau));\n        max_p=1.0/nsamples;\n        cout<<\"uniform=\"<<tilde_proba_vector[0]<<endl;\n      }\n      else{ //group sampling\n        D pi=(tau*c+0.0)/nsamples;\n        proba_vector.clear();\n        proba_vector.resize(nsamples,pi);\n      }\n    }\n\n\n\n\n    void sort_p(){\n      vector<pair<D,L> >a;\n      for (L i = 0 ;i < nsamples ; i++) {\n        a.push_back(make_pair(proba_vector[i],i)); // k = value, i = original index\n      }\n      sort(a.begin(),a.end());\n      group_C.clear();\n      group_C.resize(nsamples);\n      isolated_I.clear();\n      isolated_I.resize(nsamples,0);\n      D tmp=0;\n      D maxpi=0;\n      D previous_i=0;\n      index_group_C.clear();\n      index_group_C.push_back(0);\n      maxp_group_C.clear();\n      sump_group_C.clear();\n\n      for (L i = 0 ;i < nsamples ; i++){\n        group_C[i]=a[nsamples-1-i].second;\n        D pi=a[nsamples-1-i].first;\n        if(tmp+pi<=1){\n          if(pi>maxpi) maxpi=pi;\n          tmp+=pi;\n        }\n        else{\n          index_group_C.push_back(i);\n          maxp_group_C.push_back(maxpi);\n          sump_group_C.push_back(tmp);\n          tmp=pi;\n          maxpi=pi;\n          if(i-previous_i==1) isolated_I[group_C[previous_i]]=1;\n          previous_i=i;\n        }\n      }\n      index_group_C.push_back(nsamples);\n      maxp_group_C.push_back(maxpi);\n      sump_group_C.push_back(tmp);\n      nb_groups=sump_group_C.size();\n      if(previous_i==nsamples-1) isolated_I[group_C[previous_i]]=1;\n      cout<<\"size of group=\"<<nb_groups<<endl;\n    }\n\n\n    inline L sampling(L n)\n    {\n      L i=(floor)(gsl_rng_uniform(rng)*n);\n      D y=gsl_rng_uniform(rng);\n      while(y*max_p>tilde_proba_vector[i])\n      {\n        i=(floor)(gsl_rng_uniform(rng)*n);\n        y=gsl_rng_uniform(rng);\n      }\n      return i;\n    }\n\n\n    void set_theta(){\n      theta2=L2/2/max(Lf,L2);\n      if(Lf<=L2/p){\n        D tmp=mu/L2/p;\n        cout<<\"L2=\"<<L2<<endl;\n        cout<<\"tmp=\"<<tmp<<endl;\n        if(tmp>=1){\n          theta1=theta2;\n        }\n        else{\n          theta1=sqrt(tmp)*theta2;\n        }\n      }else\n      theta1=min(sqrt(mu/Lf),p/2);\n      theta3=1-theta1-theta2;\n      eta=1./(theta1*(Lf+2*max(L2,Lf)));\n      oneovereta=theta1*(Lf+2*max(L2,Lf));\n      cout<<\"Lf=\"<<Lf<<\"; L2=\"<<L2<<\"; theta1=\"<<theta1<<\"; theta2=\"<<theta2<<\"; theta3=\"<<theta3<<endl;\n      cout<<\"eta=\"<<eta<<endl;\n    }\n\n\n\n\n    void set_p(D scal_p){\n        p=scal_p*tau/(0.0+nsamples);\n        cout<<\"changing probablity: \"<<p<<endl;\n    }\n\n\n\n\n    void initialize(vector<D> & x0, D val_mu, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p)\n    {\n      cout<<\"start initializing loopless Katyusha\"<<\" u=\"<<u<<endl;\n      c=nb_c;\n      noverc=nsamples/c;\n      if(nb_tau>noverc) perror(\"tau should be less than n over c\");\n      tau=nb_tau;\n      nb_of_iters_per_loop=floor(nsamples/(c*(tau+0.0)));\n      batch_i.clear();\n      batch_i.resize(nsamples,0);\n\n\n      gk.clear();\n      gk.resize(nfeatures,0);\n      upper_bound=std::numeric_limits<double>::max();\n\n      /**setup parameters**/\n      max_nb_loops=max_nb;\n      mu=val_mu;\n      cout<<\"mu=\"<<mu<<endl;\n      set_rng();\n\n      set_Li_Lf();\n\n      running_time=0;\n      /**setup probability**/\n      if(p_mod==0)   // batch sampling (stochastic process as defined in the paper)\n      {\n        if(u==0)   // uniform sampling\n        {\n          set_uniform_probability(p_mod);\n          uniform=\"uniform\";\n        }\n        else{\n          set_optimal_probability();\n          uniform=\"nonuniform\";\n        }\n      }\n      else{  //group sampling\n        if(u==0){\n          set_uniform_probability(p_mod);\n          uniform=\"uniform\";\n        }else{\n          set_group_sampling_probability();\n          uniform=\"nonuniform\";\n        }\n        sort_p();\n        cout<<\"sort p\"<<endl;\n      }\n\n\n      set_L2(p_mod,u);\n      scaler=scal_p;\n      set_p(scal_p);\n      set_thetaS(p_mod);\n      cout<<\"set thetaS\"<<endl;\n\n\n      x.clear();\n      y.clear();\n      z.clear();\n      w.clear();\n      x.resize(nfeatures);\n      y.resize(nfeatures);\n      z.resize(nfeatures);\n      w.resize(nfeatures);\n      next_x.clear();\n      next_x.resize(nfeatures);\n\n      gradient_f_w.clear();\n      gradient_f_w.resize(nfeatures);\n      gradient_f_x.clear();\n      gradient_f_x.resize(nfeatures);\n\n      for(L i=0;i<nfeatures;i++)\n      {\n        x[i]=x0[i];\n        y[i]= x0[i];\n        w[i]=x0[i];\n        z[i]=x0[i];\n      }\n\n      set_theta();\n      cout<<\"set stepsizes\"<<endl;\n\n      current_nb_iters=0;\n      compute_primal_value();\n      cout<<\"primal value=\"<<primal_value<<endl;\n      cout<<\"Initialization  loopless Katyusha is finished!\"<<endl;\n    }\n\n\nvoid compute_primal_value()\n{\n  D res=0;\n  for(L i=0;i<nsamples;i++)\n  {\n    res+=value_of_phi_i(i);\n  }\n  D res2=value_of_g();\n  primal_value= res/nsamples+ res2;\n}\n\n\nvoid compute_and_record_result()\n{\n  if(nb_loops%print_every_N==0){\n    compute_primal_value();\n    cout<<setprecision(9)<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<\";  \"<<running_time<<\" primal value=\"<<primal_value<<endl;\n    samp<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<\" \"<<running_time<<\" \"<<primal_value<<endl;\n  }\n}\n\nvoid compute_and_record_result2()\n{\n  if(nb_loops%print_every_N==0){\n    compute_primal_value();\n    compute_upper_bound_of_optimality_gap();\n    cout<<setprecision(9)<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<\";  \"<<running_time<<\" primal value=\"<<primal_value<<\" upper bound of F(x)-F^*= \"<< upper_bound<< endl;\n    samp<<floor(((0.0+nb_iters)*this->c*tau/(this->nsamples)))<<\" \"<<upper_bound<<\" \"<<running_time<<\" \"<<primal_value<<endl;\n  }\n\n}\n\n\nvoid batch_sampling()\n{\n  batch_size=0;\n  L i;\n  for(L it_t=0;it_t<tau;it_t++)\n  {\n    i=sampling(nsamples);\n    batch_i[batch_size]=i;\n    batch_size++;\n  }\n}\n\n\nvoid set_thetaS(L p_mod){\n  theta_S.clear();\n  theta_S.resize(nsamples,0);\n  if(p_mod==0){\n    for(L i=0;i<nsamples;i++)\n    theta_S[i]=1.0/(tau*tilde_proba_vector[i]);\n  }\n  else{\n    for(L i=0;i<nsamples;i++)\n    theta_S[i]=1.0/proba_vector[i];\n  }\n}\n\nvoid group_sampling(){\n  batch_size=0;\n  std::vector<L> sampled_groups;\n  for(L i=0;i<nb_groups;i++){\n    D y=gsl_rng_uniform(rng);\n    if(y<sump_group_C[i])\n    {\n      sampled_groups.push_back(i);\n      batch_size++;\n    }\n  }\n  for(L t=0;t<batch_size;t++){\n    L group_i=sampled_groups[t];\n    L s1=index_group_C[group_i];\n    L s2=index_group_C[group_i+1];\n    L i=s1+(floor)(gsl_rng_uniform(rng)*(s2-s1));\n    D y=gsl_rng_uniform(rng);\n    D maxpi=maxp_group_C[group_i];\n    while(y*maxpi>proba_vector[group_C[i]])\n    {\n      i=s1+(floor)(gsl_rng_uniform(rng)*(s2-s1));\n      y=gsl_rng_uniform(rng);\n    }\n    batch_i[t]=group_C[i];\n  }\n}\n\n\n\n\nvoid loopless(vector<D> & x0, string filename, D val_mu, L max_nb, L nb_tau, L nb_c, L u, L p_mod, D scal_p)\n{\n  initialize(x0, val_mu, max_nb,  nb_tau, nb_c,  u, p_mod, scal_p);\n  string sampname=\"results/L_Katyusha\"+filename+uniform;\n  if(p_mod==0) sampname=sampname+\"_batch\";\n  else sampname=sampname+\"_group\";\n  string scal_str;\n  stringstream  scal_convert;\n  scal_convert<<scal_p;\n  scal_str=scal_convert.str();\n  sampname+=scal_str;\n  cout<<\"running Loopless Katyusha \"<<\" ; \"<<sampname<<endl;\n  samp.open(sampname.c_str());\n\n  nb_loops=0;\n  nb_iters=0;\n\n  srand48(27432042);\n  //srand(time(NULL));\n\n\n  D start;\n  while(nb_loops<max_nb_loops)\n  {\n    compute_and_record_result();\n\n    nb_loops++;\n\n    start = std::clock();\n\n    for(L it=0;it<nb_of_iters_per_loop;it++)\n    {\n      if(p_mod==0)\n      batch_sampling();\n      else\n      group_sampling();\n\n      start = std::clock();\n      update_x();\n      update_gk();\n      update_z();\n      update_y();\n      update_w();\n      update_gradient();\n      current_nb_iters++;\n      nb_iters++;\n      running_time+= ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n    }\n  }\n}\n\nvoid loopless2(vector<D> & x0, string filename, D val_mu, L max_nb, D epsilon, L nb_tau, L nb_c, L u, L p_mod, D scal_p)\n{\n  cout<<\"max_nb=\"<<max_nb<<endl;\n  initialize(x0, val_mu, max_nb,  nb_tau, nb_c,  u, p_mod, scal_p);\n  string sampname=\"results/L_\"+filename+uniform;\n  if(p_mod==0) sampname=sampname+\"_batch\";\n  else sampname=sampname+\"_group\";\n  string scal_str;\n  stringstream  scal_convert;\n  scal_convert<<scal_p;\n  scal_str=scal_convert.str();\n  sampname+=scal_str;\n  cout<<\"running Loopless Katyusha 2\"<<\" ; \"<<sampname<<endl;\n  samp.open(sampname.c_str());\n\n  nb_loops=0;\n  nb_iters=0;\n\n  cout<<setprecision(9)<<\"initial: \"<< \"primal: \"<<primal_value << endl;\n  samp<<((0.0+nb_iters)*c*tau/(nsamples))<<\" \"<<running_time<<\" \"<<primal_value<<endl;\n  //srand48(27432042);\n  srand(time(NULL));\n\n\n  D start;\n  cout<<\"nb_loops=\"<<nb_loops<<\"; max_nb_loops=\"<<max_nb_loops<<\"; upper bound=\"<<upper_bound<<\"; epsilon=\"<<epsilon<<endl;\n  while(nb_loops<max_nb_loops && upper_bound> epsilon)\n  {\n    compute_and_record_result2();\n    start = std::clock();\n\n    nb_loops++;\n\n    //cout<<\"before the loop time elapsed=\"<<duration<<endl;\n    start = std::clock();\n\n    //cout<<\"nb_of_iters_per_loop=\"<<nb_of_iters_per_loop<<endl;\n    for(L it=0;it<nb_of_iters_per_loop;it++)\n    {\n      if(p_mod==0)\n      batch_sampling();\n      else\n      group_sampling();\n\n      start = std::clock();\n      update_x();\n      update_gk();\n      update_z();\n      update_y();\n      update_w();\n      update_gradient();\n      current_nb_iters++;\n      //cout<< \"test 1\"<< endl;\n      //cout<< \"test 2\"<< endl;\n      nb_iters++;\n      running_time+= ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n    }\n    //cout<< \"epoch \"<< nb_loops<< \" finished\"<< endl;\n    //cout<<\"after the loop time elapsed=\"<<duration<<endl;\n  }\n}\n\n\n\n\n\n\n\n\n};\n\n#endif /* MIN_SMOOTH_CONVEX_H */\n", "meta": {"hexsha": "ca5a0ba212632b796cf86577a7cc9e71a989aef7", "size": 16065, "ext": "h", "lang": "C", "max_stars_repo_path": "IPALM/L_Katyusha.h", "max_stars_repo_name": "lifei16/supplementary_code", "max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IPALM/L_Katyusha.h", "max_issues_repo_name": "lifei16/supplementary_code", "max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPALM/L_Katyusha.h", "max_forks_repo_name": "lifei16/supplementary_code", "max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z", "avg_line_length": 21.5927419355, "max_line_length": 184, "alphanum_fraction": 0.576844071, "num_tokens": 4717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.37583012568832064}}
{"text": "#include \"userFunc.h\"\n#include <math.h>\n#include <gsl/gsl_sf_bessel.h>\n\n/**************************************************************************/\n/* This defines userFunc routines for the Pringle (1981) ring test        */\n/**************************************************************************/\n\nvoid\nuserEOS(const double t, const double dt, const grid *grd, \n\tconst double *col, const double *pres, const double *eInt,\n\tvoid *params,\n\tdouble *gamma, double *delta) {\n  fprintf(stderr, \n\t  \"Warning: userEOS function called but not implemented!\\n\");\n  return;\n}\n\nvoid\nuserAlpha(const double t, const double dt, const grid *grd, \n\t  const double *col, const double *pres, const double *eInt,\n\t  const double *gamma, const double *delta,\n\t  void *params,\n\t  double *alpha) {\n  /* alpha = nu col/pres vphi / r */\n\n  int i;\n  double nu = *((double *) params);\n\n  for (i=0; i<grd->nr; i++)\n    alpha[i] = nu * col[i]/pres[i] * grd->vphi_g[i+1] / grd->r_g[i+1];\n\n}\n\nvoid\nuserMassSrc(const double t, const double dt, const grid *grd,\n\t    const double *col, const double *pres, const double *eInt,\n\t    const double *gamma, const double *delta,\n\t    void *params,\n\t    double *massSrc) {\n  fprintf(stderr, \n\t  \"Warning: userMassSrc function called but not implemented!\\n\");\n  return;\n}\n\nvoid\nuserIntEnSrc(const double t, const double dt, const grid *grd,\n\t     const double *col, const double *pres, const double *eInt,\n\t     const double *gamma, const double *delta,\n\t     void *params, \n\t     double *intEnSrc) {\n  fprintf(stderr, \n\t  \"Warning: userIntEnSrc function called but not implemented!\\n\");\n  return;\n}\n\nvoid\nuserIBC(const double t, const double dt, const grid *grd,\n\tconst double *col, const double *pres, const double *eInt,\n\tconst double *gamma, const double *delta,\n\tconst pres_bc_type ibc_pres, const enth_bc_type ibc_enth,\n\tvoid *params, \n\tdouble *ibc_pres_val, double *ibc_enth_val) {\n  double nu = ((double *) params)[0];\n  double r0 = ((double *) params)[1];\n  double m0 = ((double *) params)[2];\n  double colMin = ((double *) params)[3];\n  double pOverCol = ((double *) params)[4];\n  double x = grd->r_g[0]/r0;\n  double tau = 12.0*nu*t/SQR(r0) + SMALL;\n  double sigma0 = m0/(M_PI*SQR(r0));\n  double sigma;\n\n  sigma = sigma0/(pow(x, 0.25)*tau) * exp(-SQR(x-1.0)/tau) *\n    gsl_sf_bessel_Inu_scaled(0.25, 2*x/tau);\n  sigma = (sigma < colMin) ? colMin : sigma;\n  *ibc_pres_val = -3.0*M_PI*grd->r_g[0]*nu*grd->vphi_g[0]*sigma;\n  *ibc_enth_val = gamma[0]/(gamma[0]-1)*pOverCol;\n}\n\nvoid\nuserOBC(const double t, const double dt, const grid *grd,\n\tconst double *col, const double *pres, const double *eInt,\n\tconst double *gamma, const double *delta,\n\tconst pres_bc_type obc_pres, const enth_bc_type obc_enth,\n\tvoid *params, \n\tdouble *obc_pres_val, double *obc_enth_val) {\n  double nu = ((double *) params)[0];\n  double r0 = ((double *) params)[1];\n  double m0 = ((double *) params)[2];\n  double colMin = ((double *) params)[3];\n  double pOverCol = ((double *) params)[4];\n  double x = grd->r_g[grd->nr+1]/r0;\n  double tau = 12.0*nu*t/SQR(r0) + SMALL;\n  double sigma0 = m0/(M_PI*SQR(r0));\n  double sigma;\n\n  sigma = sigma0/(pow(x, 0.25)*tau) * exp(-SQR(x-1.0)/tau) *\n    gsl_sf_bessel_Inu_scaled(0.25, 2*x/tau);\n  sigma = (sigma < colMin) ? colMin : sigma;\n  *obc_pres_val = -3.0*M_PI*grd->r_g[grd->nr+1]*nu*\n    grd->vphi_g[grd->nr+1]*sigma;\n  *obc_enth_val = gamma[0]/(gamma[0]-1)*pOverCol;\n}\n\n\nvoid\nuserPreTimestep(const double t, const double dt,\n\t\tconst grid *grd, double *col, double *pres,\n\t\tdouble *eInt, double *mBnd, double *eBnd,\n\t\tdouble *mSrc, double *eSrc,\n\t\tvoid *params, const unsigned long nUserOut,\n\t\tdouble *userOut) {\n  fprintf(stderr,\n\t  \"Warning: userPreTimestep function called but not implemented!\\n\");\n  return;\n}\n\nvoid\nuserPostTimestep(const double t, const double dt,\n\t\t const grid *grd, double *col, double *pres,\n\t\t double *eInt, double *mBnd, double *eBnd,\n\t\t double *mSrc, double *eSrc,\n\t\t void *params, const unsigned long nUserOut,\n\t\t double *userOut) {\n  fprintf(stderr,\n\t  \"Warning: userPostTimestep function called but not implemented!\\n\");\n  return;\n}\n\nvoid\nuserCheckRead(\n\t      FILE *fp, grid *grd, const unsigned long nOut,\n\t      double *tOut, double *colOut,\n\t      double *presOut, double *eIntOut, double *mBndOut,\n\t      double *eBndOut, double *mSrcOut, double *eSrcOut,\n\t      const unsigned long nUserOut, double *userOut,\n\t      void *params\n\t      ) {\n  fprintf(stderr,\n\t  \"Warning: userCheckRead function called but not implemented!\\n\");\n  return;\n}\n\nvoid\nuserCheckWrite(\n\t      FILE *fp,\n\t      const grid *grd, const unsigned long nOut,\n\t      const double *tOut, const double *colOut,\n\t      const double *presOut, const double *eIntOut,\n\t      const double *mBndOut, const double *eBndOut,\n\t      const double *mSrcOut, const double *eSrcOut,\n\t      const unsigned long nUserOut, const double *userOut,\n\t      const void *params\n\t      ) {\n  fprintf(stderr,\n\t  \"Warning: userCheckWrite function called but not implemented!\\n\");\n  return;\n}\n", "meta": {"hexsha": "fdb71f804a765b28d4ea00458cba6a866793a348", "size": 5008, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/vader/src/prob/userFunc_ring.c", "max_stars_repo_name": "franciscaconcha/amuse-vader", "max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/amuse/community/vader/src/prob/userFunc_ring.c", "max_issues_repo_name": "franciscaconcha/amuse-vader", "max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/amuse/community/vader/src/prob/userFunc_ring.c", "max_forks_repo_name": "franciscaconcha/amuse-vader", "max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z", "avg_line_length": 31.3, "max_line_length": 76, "alphanum_fraction": 0.6457667732, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.37577765553439657}}
{"text": "/* Copyright (C) 2015 Atsushi Togo */\n/* All rights reserved. */\n\n/* This file is part of phonopy. */\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\n/* * Redistributions in binary form must reproduce the above copyright */\n/*   notice, this list of conditions and the following disclaimer in */\n/*   the documentation and/or other materials provided with the */\n/*   distribution. */\n\n/* * Neither the name of the phonopy project nor the names of its */\n/*   contributors may be used to endorse or promote products derived */\n/*   from this software without specific prior written permission. */\n\n/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */\n/* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */\n/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */\n/* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */\n/* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */\n/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */\n/* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */\n/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */\n/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */\n/* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */\n/* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */\n/* POSSIBILITY OF SUCH DAMAGE. */\n\n#include <lapacke.h>\n#include <phonoc_array.h>\n#include <phonoc_utils.h>\n#include <phonon4_h/real_to_reciprocal.h>\n\nstatic void real_to_reciprocal_elements(lapack_complex_double *fc4_rec_elem,\n\t\t\t\t\tconst double q[12],\n\t\t\t\t\tconst double *fc4,\n\t\t\t\t\tconst Darray *shortest_vectors,\n\t\t\t\t\tconst Iarray *multiplicity,\n\t\t\t\t\tconst int *p2s,\n\t\t\t\t\tconst int *s2p,\n\t\t\t\t\tconst int pi0,\n\t\t\t\t\tconst int pi1,\n\t\t\t\t\tconst int pi2,\n\t\t\t\t\tconst int pi3);\n\n/* fc4_reciprocal[num_patom, num_patom, num_patom, num_patom, 3, 3, 3, 3] */\nvoid real_to_reciprocal4(lapack_complex_double *fc4_reciprocal,\n\t\t\t const double q[12],\n\t\t\t const double *fc4,\n\t\t\t const Darray *shortest_vectors,\n\t\t\t const Iarray *multiplicity,\n\t\t\t const int *p2s_map,\n\t\t\t const int *s2p_map)\n{\n  int i, j, k, l, num_patom;\n  \n  num_patom = multiplicity->dims[1];\n\n  for (i = 0; i < num_patom; i++) {\n    for (j = 0; j < num_patom; j++) {\n      for (k = 0; k < num_patom; k++) {\n\tfor (l = 0; l < num_patom; l++) {\n\t  real_to_reciprocal_elements\n\t    (fc4_reciprocal +\n\t     i * 81 * num_patom * num_patom * num_patom +\n\t     j * 81 * num_patom * num_patom +\n\t     k * 81 * num_patom +\n\t     l * 81,\n\t     q,\n\t     fc4,\n\t     shortest_vectors,\n\t     multiplicity,\n\t     p2s_map,\n\t     s2p_map,\n\t     i, j, k, l);\n\t}\n      }\n    }\n  }\n}\t\t       \n\nstatic void real_to_reciprocal_elements(lapack_complex_double *fc4_rec_elem,\n\t\t\t\t\tconst double q[12],\n\t\t\t\t\tconst double *fc4,\n\t\t\t\t\tconst Darray *shortest_vectors,\n\t\t\t\t\tconst Iarray *multiplicity,\n\t\t\t\t\tconst int *p2s,\n\t\t\t\t\tconst int *s2p,\n\t\t\t\t\tconst int pi0,\n\t\t\t\t\tconst int pi1,\n\t\t\t\t\tconst int pi2,\n\t\t\t\t\tconst int pi3)\n{\n  int i, j, k, l, m, num_satom;\n  lapack_complex_double phase_factor, phase_factors[3];\n  double fc4_rec_real[81], fc4_rec_imag[81];\n  int fc4_elem_address;\n\n  for (i = 0; i < 81; i++) {\n    fc4_rec_real[i] = 0;\n    fc4_rec_imag[i] = 0;\n  }\n  \n  num_satom = multiplicity->dims[0];\n\n  i = p2s[pi0];\n\n  for (j = 0; j < num_satom; j++) {\n    if (s2p[j] != p2s[pi1]) {\n      continue;\n    }\n    phase_factors[0] =\n      get_phase_factor(q, shortest_vectors, multiplicity, pi0, j, 1);\n\n    for (k = 0; k < num_satom; k++) {\n      if (s2p[k] != p2s[pi2]) {\n\tcontinue;\n      }\n      phase_factors[1] =\n\tget_phase_factor(q, shortest_vectors, multiplicity, pi0, k, 2);\n\n      for (l = 0; l < num_satom; l++) {\n\tif (s2p[l] != p2s[pi3]) {\n\t  continue;\n\t}\n\tphase_factors[2] =\n\t  get_phase_factor(q, shortest_vectors, multiplicity, pi0, l, 3);\n\t\n\tfc4_elem_address = (i * 81 * num_satom * num_satom * num_satom +\n\t\t\t    j * 81 * num_satom * num_satom +\n\t\t\t    k * 81 * num_satom +\n\t\t\t    l * 81);\n\n\tphase_factor = phonoc_complex_prod(phase_factors[0], phase_factors[1]);\n\tphase_factor = phonoc_complex_prod(phase_factor, phase_factors[2]);\n\tfor (m = 0; m < 81; m++) {\n\t  fc4_rec_real[m] +=\n\t    lapack_complex_double_real(phase_factor) * fc4[fc4_elem_address + m];\n\t  fc4_rec_imag[m] +=\n\t    lapack_complex_double_imag(phase_factor) * fc4[fc4_elem_address + m];\n\t}\n      }\n    }\n  }\n\n  for (i = 0; i < 81; i++) {\n    fc4_rec_elem[i] =\n      lapack_make_complex_double(fc4_rec_real[i], fc4_rec_imag[i]);\n  }\n}\n", "meta": {"hexsha": "888c30a4cf26a4c5f98a66b9ec321fb432d4661f", "size": 4791, "ext": "c", "lang": "C", "max_stars_repo_path": "c/anharmonic/phonon4/real_to_reciprocal.c", "max_stars_repo_name": "atztogo/forcefit", "max_stars_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-20T23:19:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T23:19:49.000Z", "max_issues_repo_path": "c/anharmonic/phonon4/real_to_reciprocal.c", "max_issues_repo_name": "atztogo/forcefit", "max_issues_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/anharmonic/phonon4/real_to_reciprocal.c", "max_forks_repo_name": "atztogo/forcefit", "max_forks_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T13:53:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-30T08:36:46.000Z", "avg_line_length": 30.5159235669, "max_line_length": 76, "alphanum_fraction": 0.6558129827, "num_tokens": 1384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.37557179923191686}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <gsl/gsl_cdf.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_statistics_double.h>\n#include \"../include/type.h\"\n#include \"../include/util.h\"\n#include \"../include/myfunc.h\"\n#include \"../include/global.h\"\n#include \"../include/cthreadpool.h\"\n\n\nextern double rho;\nextern double cutoff;\nextern clock_t dur;\n\n\n#define ITER_CUTOFF 0.01\n\n\n/**\n * @brief invoke this function before return from\n *        MLE_marginal_iteration and MLE_marginal_iteration_constrain.\n *\n * @param mle\n * @param sum\n * @param psi1\n * @param psi2\n * @param beta0\n * @param beta1\n * @param var1\n * @param var2\n */\nvoid mle_result_set(mle_result* mle, double sum, gsl_vector* psi1, gsl_vector* psi2,\n                    double beta0, double beta1, double var1, double var2) {\n    mle->sum = sum;\n    mle->params.psi1 = psi1;\n    mle->params.psi2 = psi2;\n    mle->params.beta0 = beta0;\n    mle->params.beta1 = beta1;\n    mle->params.var1 = var1;\n    mle->params.var2 = var2;\n    return;\n}\n\n\ndouble myfunc_multivar(const double x[], va_list argv) {\n    gsl_vector *psi1 = va_arg(argv, gsl_vector*);\n    gsl_vector *psi2 = va_arg(argv, gsl_vector*);\n    double var1 = va_arg(argv, double), var2 = va_arg(argv, double);\n    double sum1, sum2;\n\n    // TODO  memcpy replaced.\n    sum1 = cuscumsum(psi1, sum_for_multivar, 1, x[0]);\n    sum2 = cuscumsum(psi2, sum_for_multivar, 1, x[1]);\n    sum1 = sum1/(var1*2), sum2 = sum2/(var2*2);\n\n    return sum1 + sum2 + 0.05 * pow(rho, 2) / (1 - pow(rho, 2)) * \\\n        (pow(gsl_cdf_gaussian_Pinv(x[0], 1), 2) + pow(gsl_cdf_gaussian_Pinv(x[1], 1), 2) - \\\n         2 * rho * gsl_cdf_gaussian_Pinv(x[0], 1) * gsl_cdf_gaussian_Pinv(x[1], 1));\n}\n\nvoid myfunc_multivar_der(const double x[], double res[], va_list argv) {\n    gsl_vector *psi1 = va_arg(argv, gsl_vector*);\n    gsl_vector *psi2 = va_arg(argv, gsl_vector*);\n    double var1 = va_arg(argv, double), var2 = va_arg(argv, double);\n    double sum1, sum2, tmp = pow(rho,2)/(1-pow(rho,2));\n    double ppfx0 = gsl_cdf_gaussian_Pinv(x[0], 1);\n    double ppfx1 = gsl_cdf_gaussian_Pinv(x[1], 1);\n\n    sum1 = cuscumsum(psi1, sum_for_multivar_der, 1, x[0]);\n    sum2 = cuscumsum(psi2, sum_for_multivar_der, 1, x[1]);\n    sum1 = sum1/(var1*2), sum2 = sum2/(var2*2);\n\n    // TODO are there any better way to convert cdf to pdf?\n    res[0] = sum1 + tmp * 0.1*(ppfx0-rho*ppfx1)/gsl_ran_gaussian_pdf(ppfx0, 1);\n    res[1] = sum2 + tmp * 0.1*(ppfx1-rho*ppfx0)/gsl_ran_gaussian_pdf(ppfx1, 1);\n\n    return;\n}\n\n\ndouble myfunc_1_2(const double x[], va_list argv) {\n    int flag = va_arg(argv, int);\n    gsl_vector *psi1 = va_arg(argv, gsl_vector*);\n    gsl_vector *psi2 = va_arg(argv, gsl_vector*);\n    double var1 = va_arg(argv, double), var2 = va_arg(argv, double);\n    double sum1, sum2;\n\n    if (flag == 1) {\n        sum1 = cuscumsum(psi1, sum_for_multivar, 1, x[0]+cutoff);\n        sum2 = cuscumsum(psi2, sum_for_multivar, 1, x[0]);\n    } else {\n        sum1 = cuscumsum(psi1, sum_for_multivar, 1, x[0]);\n        sum2 = cuscumsum(psi2, sum_for_multivar, 1, x[0]+cutoff);\n    }\n    sum1 = sum1/(var1*2), sum2 = sum2/(var2*2);\n\n    return sum1 + sum2 + 0.05 * pow(rho, 2) / (1 - pow(rho, 2)) * \\\n        (pow(gsl_cdf_gaussian_Pinv(x[0]+cutoff, 1), 2) + pow(gsl_cdf_gaussian_Pinv(x[0], 1), 2) - \\\n         2 * rho * gsl_cdf_gaussian_Pinv(x[0]+cutoff, 1) * gsl_cdf_gaussian_Pinv(x[0], 1));\n}\n\n\nvoid myfunc_der_1_2(const double x[], double res[], va_list argv) {\n    int flag = va_arg(argv, int);\n    gsl_vector *psi1 = va_arg(argv, gsl_vector*);\n    gsl_vector *psi2 = va_arg(argv, gsl_vector*);\n    double var1 = va_arg(argv, double), var2 = va_arg(argv, double);\n    double sum1, sum2, tmp = pow(rho,2)/(1-pow(rho,2));\n    double ppfx0 = gsl_cdf_gaussian_Pinv(x[0], 1);\n    double ppfxc = gsl_cdf_gaussian_Pinv(x[0]+cutoff, 1);\n\n    if (flag == 1) {\n        sum1 = cuscumsum(psi1, sum_for_multivar_der, 1, x[0]+cutoff);\n        sum2 = cuscumsum(psi2, sum_for_multivar_der, 1, x[0]);\n    } else {\n        sum1 = cuscumsum(psi1, sum_for_multivar_der, 1, x[0]);\n        sum2 = cuscumsum(psi2, sum_for_multivar_der, 1, x[0]+cutoff);\n    }\n    sum1 = sum1/(var1*2), sum2 = sum2/(var2*2);\n\n    // TODO are there any better way to convert cdf to pdf?\n    res[0] = sum1 + tmp * 0.1*(ppfxc-rho*ppfx0)/gsl_ran_gaussian_pdf(ppfxc, 1);\n    res[1] = sum2 + tmp * 0.1*(ppfx0-rho*ppfxc)/gsl_ran_gaussian_pdf(ppfx0, 1);\n    res[0] += res[1];\n\n    return;\n}\n\n\ndouble myfunc_marginal(const double x[], va_list argv) {\n    gsl_vector* I = va_arg(argv, gsl_vector*), *S = va_arg(argv, gsl_vector*);\n    gsl_vector* psi = va_arg(argv, gsl_vector*);\n    double var = va_arg(argv, double), sum = 0;\n    int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int), idx = 0;\n\n    sum = cuscumsum(psi, sum_for_marginal, 7, &idx, x[0], I, S, var, inclu_len, skip_len);\n\n    return sum;\n}\n\n\nvoid myfunc_marginal_der(const double x[], double res[], va_list argv) {\n    gsl_vector* I = va_arg(argv, gsl_vector*), *S = va_arg(argv, gsl_vector*);\n    gsl_vector* psi = va_arg(argv, gsl_vector*);\n    double var = va_arg(argv, double), sum;\n    int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int), idx = 0;\n\n    sum = cuscumsum(psi, sum_for_marginal_der, 7, &idx, x[0], I, S, var, inclu_len, skip_len);\n    res[0] = sum;\n\n    return;\n}\n\n\ndouble myfunc_marginal_1_2(const double x[], va_list argv) {\n    int flag = va_arg(argv, int);\n    double beta1, beta2;\n    if (flag == 1) {\n        beta1 = x[0] + cutoff, beta2 = x[0];\n    } else {\n        beta1 = x[0], beta2 = x[0] + cutoff;\n    }\n    // TODO parameter ordering\n    return myfunc_marginal(&beta1, argv) + myfunc_marginal(&beta2, argv);\n}\n\n\nvoid myfunc_marginal_1_2_der(const double x[], double res[], va_list argv) {\n    int flag = va_arg(argv, int);\n    double beta1, beta2;\n    double tmp1, tmp2;\n    if (flag == 1) {\n        beta1 = x[0] + cutoff, beta2 = x[0];\n    } else {\n        beta1 = x[0], beta2 = x[0] + cutoff;\n    }\n    // TODO parameter ordering\n    myfunc_marginal_der(&beta1, &tmp1, argv);\n    myfunc_marginal_der(&beta2, &tmp2, argv);\n    res[0] = tmp1 + tmp2;\n\n    return;\n}\n\n\ndouble myfunc_individual(const double x[], va_list argv) {\n    double I = va_arg(argv, double), S = va_arg(argv, double);\n    double beta = va_arg(argv, double), var = va_arg(argv, double);\n    int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int);\n    double new_psi = inclu_len * x[0]/(inclu_len * x[0] + skip_len * (1 - x[0]));\n\n    // TODO This change the result.\n    return pow((logit(x[0]) - logit(beta)), 2)/(2 * var) -\n           (I * log(new_psi) + S * log(1 - new_psi) - log(x[0]) - log(1-x[0]));\n    // return -(I * log(new_psi) + S * log(1 - new_psi) -\n    //         pow((logit(x[0]) - logit(beta)), 2)/(2 * var) + log(x[0] - x[0]*x[0]));\n    // return -(I * log(new_psi) + S * log(1 - new_psi) -\n    //         pow((logit(x[0]) - logit(beta)), 2)/(2 * var) + log(x[0]) + log(1-x[0]));\n}\n\n\nvoid myfunc_individual_der(const double x[], double res[], va_list argv) {\n    double I = va_arg(argv, double), S = va_arg(argv, double);\n    double beta = va_arg(argv, double), var = va_arg(argv, double);\n    int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int);\n    double new_psi = inclu_len * x[0]/(inclu_len * x[0] + skip_len * (1 - x[0]));\n    double new_psi_der = inclu_len * skip_len/pow(inclu_len * x[0] + skip_len * (1 - x[0]), 2);\n\n    res[0] = 1/x[0] + S/(1 - new_psi) * new_psi_der + \\\n             (logit(x[0]) - logit(beta))/(var * x[0] * (1 - x[0])) - (1/(1-x[0]) + I/new_psi * new_psi_der);\n\n    return;\n}\n\n\n#define individual_for_loop() \\\n    for (idx = 0; idx < psi1->size; ++idx) { \\\n        x[0] = gsl_vector_get(psi1, idx); \\\n        cur_sum += l_bfgs_b_wrapper(n, m, x, l, u, nbd, \\\n                                    myfunc_individual, myfunc_individual_der, \\\n                                    factr, pgtol, iprint, 15000, 15000, \\\n                                    6, gsl_vector_get(i1, idx), gsl_vector_get(s1, idx), \\\n                                    beta0, var1, inclu_len, skip_len); \\\n        gsl_vector_set(psi1, idx, x[0]); \\\n    } \\\n    for (idx = 0; idx < psi2->size; ++idx) { \\\n        x[0] = gsl_vector_get(psi2, idx); \\\n        cur_sum += l_bfgs_b_wrapper(n, m, x, l, u, nbd, \\\n                                    myfunc_individual, myfunc_individual_der, \\\n                                    factr, pgtol, iprint, 15000, 15000, \\\n                                    6, gsl_vector_get(i2, idx), gsl_vector_get(s2, idx), \\\n                                    beta1, var2, inclu_len, skip_len); \\\n        gsl_vector_set(psi2, idx, x[0]); \\\n    } \\\n\nint MLE_marginal_iteration(gsl_vector* i1, gsl_vector* i2,\n                           gsl_vector* s1, gsl_vector* s2,\n                           const int inclu_len, const int skip_len,\n                           mle_result* mle) {\n    gsl_vector* psi1 = gsl_vector_alloc(i1->size); // TODO deallocation.\n    gsl_vector* psi2 = gsl_vector_alloc(i2->size);\n    vec2psi(psi1, i1, s1, inclu_len, skip_len);\n    vec2psi(psi2, i2, s2, inclu_len, skip_len);\n    int iter_max = 100, count = 0, i = 0;\n    size_t idx = 0;\n    double prev_sum = 0, cur_sum = 0;\n    double var1 = 10 * gsl_stats_variance(psi1->data, 1, psi1->size) * (psi1->size-1)/(psi1->size);\n    double var2 = 10 * gsl_stats_variance(psi2->data, 1, psi2->size) * (psi2->size-1)/(psi2->size);\n    double beta0, beta1, iter_cutoff = 1;\n    integer n, m = 10, nbd[nmax];\n    doublereal x[nmax], l[nmax], u[nmax], factr=1.0e7, pgtol=1.0e-5, iprint=-1;\n\n    if (var1 <= 0.01 || psi1->size == 1) {\n        var1 = 0.01;\n    }\n    if (var2 <= 0.01 || psi2->size == 1) {\n        var2 = 0.01;\n    }\n\n    // TODO & or && ?\n    // According to original python code 'while((iter_cutoff>0.01)&(count<=iter_maxrun)):',\n    // it's a bit arithmetic '&'. However,  it should be a logical 'and' in such senario.\n    while((iter_cutoff > ITER_CUTOFF) && (count <= iter_max)) {\n        ++count, n = 2;\n        x[0] = gsl_stats_mean(psi1->data, 1, psi1->size);\n        x[1] = gsl_stats_mean(psi2->data, 1, psi2->size);\n        for (i = 0; i < n; ++i) {\n            nbd[i] = 2;\n            l[i] = 0.01;\n            u[i] = 0.99;\n        }\n        l_bfgs_b_wrapper(n, m, x, l, u, nbd,\n                         myfunc_multivar, myfunc_multivar_der, factr, pgtol,\n                         iprint, 15000, 15000, 4, psi1, psi2, var1, var2);\n        beta0 = x[0], beta1 = x[1];\n        n = 1, cur_sum = 0;\n\n        individual_for_loop();\n\n        if (count > 1) {\n            iter_cutoff = fabs(prev_sum - cur_sum);\n        }\n        prev_sum = cur_sum;\n    }\n    if (count > iter_max) {\n        mle_result_set(mle, cur_sum, psi1, psi2, 0, 0, var1, var2);\n        return 0;\n    }\n\n    iter_cutoff = 1, iter_max = 100, count = 0, prev_sum = 0;\n    while((iter_cutoff > ITER_CUTOFF) && (count <= iter_max)) {\n        ++count, n = 1;\n        x[0] = beta0;\n        l_bfgs_b_wrapper(n, m, x, l, u, nbd,\n                         myfunc_marginal, myfunc_marginal_der,\n                         factr, pgtol, iprint, 15000, 15000,\n                         6, i1, s1, psi1, var1, inclu_len, skip_len);\n        beta0 = x[0];\n        x[0] = beta1;\n        l_bfgs_b_wrapper(n, m, x, l, u, nbd,\n                         myfunc_marginal, myfunc_marginal_der,\n                         factr, pgtol, iprint, 15000, 15000,\n                         6, i2, s2, psi2, var2, inclu_len, skip_len);\n        beta1 = x[0];\n\n        cur_sum = 0;\n\n        individual_for_loop();\n\n        if (count > 1) {\n            iter_cutoff = fabs(prev_sum - cur_sum);\n        }\n        prev_sum = cur_sum;\n    }\n\n    gsl_vector_free(psi1);\n    gsl_vector_free(psi2);\n\n    if (count > iter_max) {\n        mle_result_set(mle, cur_sum, psi1, psi2, 0, 0, var1, var2);\n        return 0;\n    }\n\n    mle_result_set(mle, cur_sum, psi1, psi2, beta0, beta1, var1, var2);\n\n    return 0;\n}\n\n\nint MLE_marginal_iteration_constrain(gsl_vector* i1, gsl_vector* i2,\n                                     gsl_vector* s1, gsl_vector* s2,\n                                     const int inclu_len, const int skip_len,\n                                     mle_result* mle) {\n    gsl_vector* psi1 = gsl_vector_alloc(i1->size); // TODO deallocation.\n    gsl_vector* psi2 = gsl_vector_alloc(i2->size);\n    vec2psi(psi1, i1, s1, inclu_len, skip_len);\n    vec2psi(psi2, i2, s2, inclu_len, skip_len);\n    int iter_max = 100, count = 0, i = 0;\n    size_t idx = 0;\n    double prev_sum = 0, cur_sum = 0, iter_cutoff = 1;\n    double var1 = 10 * gsl_stats_variance(psi1->data, 1, psi1->size) * (psi1->size-1)/(psi1->size);\n    double var2 = 10 * gsl_stats_variance(psi2->data, 1, psi2->size) * (psi2->size-1)/(psi2->size);\n    double beta0, beta1;\n    integer n = 1, m = 10, nbd[nmax];\n    doublereal x[nmax], l[nmax], u[nmax], factr=1.0e7, pgtol=1.0e-5, iprint=-1;\n\n    if (var1 <= 0.01 || psi1->size == 1) {\n        var1 = 0.01;\n    }\n    if (var2 <= 0.01 || psi2->size == 1) {\n        var2 = 0.01;\n    }\n\n    // TODO & or && ?\n    // According to original python code 'while((iter_cutoff>0.01)&(count<=iter_maxrun)):',\n    // it's a bit arithmetic '&'. However,  it should be a logical 'and' in such senario.\n    while((iter_cutoff > ITER_CUTOFF) && (count <= iter_max)) {\n        ++count;\n        x[0] = gsl_stats_mean(psi1->data, 1, psi1->size);\n        x[1] = gsl_stats_mean(psi2->data, 1, psi2->size);\n        for (i = 0; i < n; ++i) {\n            nbd[i] = 2;\n            l[i] = 0.001;\n            u[i] = 0.999-cutoff;\n        }\n        if (x[0] > x[1]) {\n            l_bfgs_b_wrapper(n, m, x+1, l, u, nbd,\n                             myfunc_1_2, myfunc_der_1_2, factr, pgtol,\n                             iprint, 15000, 15000, 5, 1, psi1, psi2, var1, var2);\n            beta1 = fmax(fmin(x[1], 1-cutoff), 0);\n            beta0 = beta1 + cutoff;\n        } else {\n            l_bfgs_b_wrapper(n, m, x, l, u, nbd,\n                             myfunc_1_2, myfunc_der_1_2, factr, pgtol,\n                             iprint, 15000, 15000, 5, 2, psi1, psi2, var1, var2);\n            beta0 = fmax(fmin(x[0], 1-cutoff), 0);\n            beta1 = beta0 + cutoff;\n        }\n        cur_sum = 0;\n        for (i = 0; i < n; ++i) {\n            nbd[i] = 2;\n            l[i] = 0.01;\n            u[i] = 0.99;\n        }\n\n        individual_for_loop();\n\n        if (count > 1) {\n            iter_cutoff = fabs(prev_sum - cur_sum);\n        }\n        prev_sum = cur_sum;\n    }\n    if (count > iter_max) {\n        mle_result_set(mle, cur_sum, psi1, psi2, 0, 0, var1, var2);\n        return 0;\n    }\n\n    iter_cutoff = 1, iter_max = 100, count = 0, prev_sum = 0;\n    while((iter_cutoff > ITER_CUTOFF) && (count <= iter_max)) {\n        ++count;\n        for (i = 0; i < n; ++i) {\n            nbd[i] = 2;\n            l[i] = 0.001;\n            u[i] = 0.999-cutoff;\n        }\n        x[0] = beta0;\n        x[1] = beta1;\n        if (gsl_stats_mean(psi1->data, 1, psi1->size) > gsl_stats_mean(psi2->data, 1, psi2->size)) {\n            l_bfgs_b_wrapper(n, m, x+1, l, u, nbd,\n                             myfunc_marginal_1_2, myfunc_marginal_1_2_der, factr, pgtol,\n                             iprint, 15000, 15000, 13, 1, i1, s1, psi1, var1, inclu_len, skip_len,\n                             i2, s2, psi2, var2, inclu_len, skip_len);\n            beta1 = fmax(fmin(x[1], 1-cutoff), 0);\n            beta0 = beta1 + cutoff;\n        } else {\n            l_bfgs_b_wrapper(n, m, x, l, u, nbd,\n                             myfunc_marginal_1_2, myfunc_marginal_1_2_der, factr, pgtol,\n                             iprint, 15000, 15000, 13, 2, i1, s1, psi1, var1, inclu_len, skip_len,\n                             i2, s2, psi2, var2, inclu_len, skip_len);\n            beta0 = fmax(fmin(x[0], 1-cutoff), 0);\n            beta1 = beta0 + cutoff;\n        }\n        cur_sum = 0;\n        for (i = 0; i < n; ++i) {\n            nbd[i] = 2;\n            l[i] = 0.01;\n            u[i] = 0.99;\n        }\n\n        individual_for_loop();\n\n        if (count > 1) {\n            iter_cutoff = fabs(prev_sum - cur_sum);\n        }\n        prev_sum = cur_sum;\n        // printf(\"%.12f, %.12f, %.12f, %.12f\\n\", beta0, beta1, iter_cutoff, prev_sum);\n    }\n\n    gsl_vector_free(psi1);\n    gsl_vector_free(psi2);\n\n    if (count > iter_max) {\n        mle_result_set(mle, cur_sum, psi1, psi2, 0, 0, var1, var2);\n        return 0;\n    }\n\n    mle_result_set(mle, cur_sum, psi1, psi2, beta0, beta1, var1, var2);\n\n    return 0;\n}\n\n\nvoid* thread_wrapper_for_LT(void* arg) {\n    double *ret = (double*)malloc(sizeof(double));\n    odiff *data = (odiff*)arg;\n    *ret = likelihood_test(data->inc1, data->inc2,\n                           data->skp1, data->skp2,\n                           data->inclu_len, data->skip_len,\n                           data->flag, data->id);\n    return (void*)ret;\n}\n\n\nvoid* batch_wrapper_for_LT(void* arg) {\n    batch_datum *args = (batch_datum*)arg;\n    int batch_size = args->batch_size, i;\n    double *ret = (double*)malloc(sizeof(double)*batch_size);\n    odiff *datum = (odiff*)*args->datum;\n    odiff data;\n    for (i = 0; i < batch_size; ++i) {\n        data = datum[i];\n        ret[i] = likelihood_test(data.inc1, data.inc2,\n                                 data.skp1, data.skp2,\n                                 data.inclu_len, data.skip_len,\n                                 data.flag, data.id);\n    }\n    return (void*)ret;\n}\n\n\ndouble likelihood_test(gsl_vector *i1, gsl_vector *i2, gsl_vector *s1, gsl_vector *s2,\n                       int inclu_len, int skip_len, int flag, char* id) {\n    printf(\"Testing %s\\n\", id);\n    if (!flag) {\n        printf(\"1 return from: %s\\n\", id);\n        return 1;\n    } else {\n        mle_result mle;\n        MLE_marginal_iteration(i1, i2, s1, s2, inclu_len, skip_len, &mle);\n        if (fabs(mle.params.beta0 - mle.params.beta1) <= cutoff) {\n            printf(\"2 return from: %s\\n\", id);\n\t\t\treturn 1;\n        } else {\n            mle_result mle_constrain;\n            MLE_marginal_iteration_constrain(i1, i2, s1, s2, inclu_len, skip_len, &mle_constrain);\n            printf(\"3 return from: %s\\n\", id);\n            return 1 - gsl_cdf_chisq_P(2 * (fabs(mle_constrain.sum - mle.sum)), 1);\n        }\n    }\n}\n\n\nint vec2psi(gsl_vector* psi, gsl_vector *inc, gsl_vector *skp,\n            int inclu_len, int skip_len) {\n    size_t idx;\n    for(idx = 0; idx < inc->size; ++idx) {\n        if (gsl_vector_get(inc, idx) + gsl_vector_get(skp, idx) == 0) {\n            gsl_vector_set(psi, idx, 0.5);\n        } else {\n            gsl_vector_set(psi, idx, gsl_vector_get(inc, idx)/\n                    (gsl_vector_get(inc, idx) + inclu_len * gsl_vector_get(skp, idx)/skip_len));\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "fd648a6bf8316b5f24008e19cc5a4fb3caf9f819", "size": 18775, "ext": "c", "lang": "C", "max_stars_repo_path": "rMATS_C/src/myfunc.c", "max_stars_repo_name": "chunjie-sam-liu/rmats-turbo", "max_stars_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 88.0, "max_stars_repo_stars_event_min_datetime": "2020-06-01T20:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T17:34:39.000Z", "max_issues_repo_path": "rMATS_C/src/myfunc.c", "max_issues_repo_name": "chunjie-sam-liu/rmats-turbo", "max_issues_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 163.0, "max_issues_repo_issues_event_min_datetime": "2020-06-03T06:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:39:30.000Z", "max_forks_repo_path": "rMATS_C/src/myfunc.c", "max_forks_repo_name": "chunjie-sam-liu/rmats-turbo", "max_forks_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2020-06-01T20:25:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:14:46.000Z", "avg_line_length": 36.0364683301, "max_line_length": 108, "alphanum_fraction": 0.5503595206, "num_tokens": 6321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7879312006227324, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.375511976654965}}
{"text": "// lu2tlub.c\n//\n//  blocked LU decomposition library for column-major version\n//\n// Time-stamp: <11/05/13 11:35:56 makino>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#ifndef NOBLAS\n#ifdef MKL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n#endif\n\n#include <lu2lib.h>\n\ntypedef double v2df __attribute__((vector_size(16)));\ntypedef union {v2df v; double s[2];}v2u;\n\nvoid timer_init();\n\n#define MAXTHREADS 4\n\nstatic int findpivot0(int n, double a[][n], int current)\n{\n    double amax = fabs(a[0][current]);\n    int i;\n    int p=current;\n    BEGIN_TSC;\n    for(i=current+1;i<n;i++){\n\tif (fabs(a[0][i]) > amax){\n\t    amax = fabs(a[0][i]);\n\t    p = i;\n\t}\n    }\n    END_TSC(t,7);\n    return p;\n}\nstatic int findpivot(int n, double a[][n], int current)\n{\n    int p;\n    int p2;\n    BEGIN_TSC;\n    p = cblas_idamax(n-current, a[0]+current, 1)+current;\n    //    p2 = findpivot0( n, a, current);\n    //    printf(\"n, current, p, p2 = %d %d %d %d\\n\",n, current,p, p2);\n    END_TSC(t,7);\n    return p;\n}\nstatic int findpivot_sequentical(int n, double a[][n], int current)\n{\n    double amax = fabs(a[0][current]);\n    int i;\n    int p=current;\n    for(i=current+1;i<n;i++){\n\tif (fabs(a[0][i]) > amax){\n\t    amax = fabs(a[0][i]);\n\t    p = i;\n\t}\n    }\n    return p;\n}\nstatic int findpivot_omp(int n, double a[][n], int current)\n// factor 2 slower than sequential code even for n=8k....\n// on Core i7 920\n{\n    double amax[MAXTHREADS]={-1.0,-1.0,-1.0,-1.0};\n    int p[MAXTHREADS];\n    double am;\n    int pm;\n    int di= (n-current-1)/4;\n    int k;\n    BEGIN_TSC;\n    if (di > 1024){\n\t//#pragma omp parallel for private(k)\t\n\tfor (k=0;k<MAXTHREADS; k++){\n\t    int i;\n\t    int istart = current+1+k*di;\n\t    int iend = current+1+(k+1)*di;\n\t    if (iend > n) iend = n;\n\t    for(i=istart;i<iend;i++){\n\t\tif (fabs(a[0][i]) > amax[k]){\n\t\t    amax[k] = fabs(a[0][i]);\n\t\t    p[k] = i;\n\t\t}\n\t    }\n\t}\n\tpm =p[0];\n\tam = amax[0];\n\tfor (k=1;k<MAXTHREADS; k++){\n\t    if(amax[k]>am){\n\t\tam = amax[k];\n\t\tpm=p[k];\n\t    }\n\t}\n    }else{\n\tpm=findpivot_sequentical( n,  a, current);\n    }\n    END_TSC(t,7);\n    return pm;\n}\n\nstatic void swaprows(int n, double a[][n], int row1, int row2,\n\t\t     int cstart, int cend)\n{\n    int j;\n    if (row1 != row2){\n\tfor(j=cstart;j<cend;j++){\n\t    double tmp = a[j][row1];\n\t    a[j][row1] = a[j][row2];\n\t    a[j][row2]=tmp;\n\t}\n    }\n}\n\t\t\t   \nstatic void scalerow( int n, double a[n+1][n], double scale,\n\t       int row, int cstart, int cend)\n{\n    int j;\n    for(j=cstart;j<cend;j++) a[j][row]*= scale;\n}\n\n\nstatic void vsmulandsub(int n, double a[n+1][n], int cr, int cc,\n\t\t int c0,  int r0,int r1)\n{\n    int j,k;\n    double * ar = a[cr];\n    k=c0;\n    double s = a[c0][cc];\n    double *al = a[c0];\n    while (r0 & 7){\n\tal[r0] -= ar[r0]*s;\n\tr0++;\n    }\n    while (r1 & 7){\n\tal[r1-1] -= ar[r1-1]*s;\n\tr1--;\n    }\n    v2df * arv = (v2df*) (ar+r0);\n    v2df * alv = (v2df*) (al+r0);\n    v2df ss = (v2df){s,s};\n    //    for(j=r0;j<r1;j++)\n    //\tal[j] -= ar[j]*s;\n    for(j=0;j<(r1-r0)/2;j+=4){\n\talv[j] -= arv[j]*ss;\n\talv[j+1] -= arv[j+1]*ss;\n\talv[j+2] -= arv[j+2]*ss;\n\talv[j+3] -= arv[j+3]*ss;\n\t__builtin_prefetch(alv+j+32,1,3);\n\t__builtin_prefetch(arv+j+32,0,0);\n\n    }\n}\n\nstatic void vvmulandsub(int n, double a[n+1][n], int cr, int cc,\n\t\t int c0, int c1, int r0,int r1)\n{\n    int j,k;\n    double * ar = a[cr];\n#ifdef TIMETEST\n    BEGIN_TSC;\n#endif\n    if (c1-c0 == 1){\n\tvsmulandsub(n,a, cr, cc,c0, r0,r1);\n    }else{\n\tfor (k=c0;k<c1;k++){\n\t    double s = a[k][cc];\n\t    double *al = a[k];\n\t    for(j=r0;j<r1;j++)\n\t\tal[j] -= ar[j]*s;\n\t}\n    }\n#ifdef TIMETEST\n    END_TSC(t,6);\n#endif    \n}\nstatic void mmmulandsub_old(int n, double a[n+1][n], int m0, int m1,\n\t\t int c0, int c1, int r0,int r1)\n{\n    int j,k,l;\n    printf(\"Enter mmul\\n\");\n#ifndef NOBLAS\n    cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,\n\t\t r1-r0, c1-c0, m1-m0, -1.0, &(a[m0][r0]), n,\n\t\t &(a[c0][m0]), n, 1, &(a[c0][r0]), n );\n    // example:\n    // r0, m0 = i+m,i\n    // m0, c0 = i, i+m\n    // r0, c0 = i+m, i+m\n    //r1-r0 = n-i-m\n    // c1-c0 = iend-i-m\n    // m1-m0 = m\n#else\n    for(j=r0;j<r1;j++)\n\tfor (k=c0;k<c1;k++)\n\t    for (l=m0; l<m1; l++)\n\t\ta[k][j] -= a[l][j]*a[k][l];\n#endif    \n}\n\n\nstatic void matmul_for_nk4_0(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int j,k,l;\n    for(l=0;l<4;l+=2){\n\tfor(k=0;k<4;k+=2){\n\t    for(j=0;j<n;j++){\n\t\tc[k][j] -= a[l][j]*b[k][l]+ a[l+1][j]*b[k][l+1];\n\t\tc[k+1][j] -= a[l][j]*b[k+1][l]+ a[l+1][j]*b[k+1][l+1];\n\t    }\n\t}\n    }\n}\nstatic void matmul_for_nk8_0(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int i,j,k,l;\n    const int m=8;\n    double btmp[m][m];\n\n    for(i=0;i<m;i++)for(j=0;j<m;j++)btmp[i][j]=b[i][j];\n#pragma omp parallel for private(l,k,j)\t\n    for(l=0;l<8;l+=2){\n\tfor(k=0;k<8;k+=2){\n\t    for(j=0;j<n;j++){\n\t\tc[k][j] -= a[l][j]*btmp[k][l]+ a[l+1][j]*btmp[k][l+1];\n\t\tc[k+1][j] -= a[l][j]*btmp[k+1][l]+ a[l+1][j]*btmp[k+1][l+1];\n\t    }\n\t}\n    }\n\n}\nstatic void matmul_for_nk8_2(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int i,j,k,l;\n    const int m=8;\n    double btmp[m][m];\n\n    for(i=0;i<m;i++)for(j=0;j<m;j++)btmp[i][j]=b[i][j];\n#pragma omp parallel for private(l,k,j)\t\n    for(k=0;k<8;k+=2){\n\tfor(l=0;l<8;l+=4){\n\t    for(j=0;j<n;j++){\n\t\tc[k][j] -= a[l][j]*btmp[k][l]\n\t\t    + a[l+1][j]*btmp[k][l+1]\n\t\t    + a[l+2][j]*btmp[k][l+2]\n\t\t    + a[l+3][j]*btmp[k][l+3];\n\t\tc[k+1][j] -= a[l][j]*btmp[k+1][l]\n\t\t    + a[l+1][j]*btmp[k+1][l+1]\n\t\t    + a[l+2][j]*btmp[k+1][l+2]\n\t\t    + a[l+3][j]*btmp[k+1][l+3];\n\t\t//\t\tc[k][j] -= a[l][j]*btmp[k][l]+ a[l+1][j]*btmp[k][l+1];\n\t\t//\t\tc[k+1][j] -= a[l][j]*btmp[k+1][l]+ a[l+1][j]*btmp[k+1][l+1];\n\t    }\n\t}\n    }\n\n}\nstatic void matmul_for_nk8_3(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int i,j,k,l;\n    const int m=8;\n    const int mm = 32;\n    double btmp[m][m];\n    double atmp[m][mm];\n\n    for(i=0;i<m;i++)for(j=0;j<m;j++)btmp[i][j]=b[i][j];\n    for(j=0;j<n;j+=mm){\n\tint jj;\n\tfor(i=0;i<m;i++){\n\t    for(k=0;k<mm;k++){\n\t\tatmp[i][k]=a[i][j+k];\n\t    }\n\t}\n\tfor(i=0;i<m;i++){\n\t    int jjend = mm;\n\t    if (jjend+j > n) jjend = n-j;\n\t    for(jj=0;jj<jjend;jj+=2){\n\t\tc[i][j+jj] -= atmp[0][jj]*btmp[i][0]\n\t\t    +atmp[1][jj]*btmp[i][1]\n\t\t    +atmp[2][jj]*btmp[i][2]\n\t\t    +atmp[3][jj]*btmp[i][3]\n\t\t    +atmp[4][jj]*btmp[i][4]\n\t\t    +atmp[5][jj]*btmp[i][5]\n\t\t    +atmp[6][jj]*btmp[i][6]\n\t\t    +atmp[7][jj]*btmp[i][7];\n\t\tc[i][j+jj+1] -= atmp[0][jj+1]*btmp[i][0]\n\t\t    +atmp[1][jj+1]*btmp[i][1]\n\t\t    +atmp[2][jj+1]*btmp[i][2]\n\t\t    +atmp[3][jj+1]*btmp[i][3]\n\t\t    +atmp[4][jj+1]*btmp[i][4]\n\t\t    +atmp[5][jj+1]*btmp[i][5]\n\t\t    +atmp[6][jj+1]*btmp[i][6]\n\t\t    +atmp[7][jj+1]*btmp[i][7];\n\t    }\n\t}\n    }\n\n}\nstatic void matmul_for_nk8_4(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int i,j,k,l;\n    const int m=8;\n    const int mm = 16;\n    double btmp[m][m];\n    v2df b2tmp[m][m];\n    double atmp[m][mm];\n\n    for(i=0;i<m;i++)for(j=0;j<m;j++)b2tmp[i][j]=(v2df){b[i][j],b[i][j]};\n    //#pragma omp parallel for private(j,i,atmp)\n    //use of OMP here does not speed things up\n    for(j=0;j<n;j+=mm){\n\tint jj;\n\tfor(i=0;i<m;i++){\n\t    v2df * dest = (v2df*)(atmp[i]);\n\t    v2df * src = (v2df*)(a[i]+j);\n\t    dest[0]=src[0];\n\t    dest[ 1]=src[ 1];\n\t    dest[ 2]=src[ 2];\n\t    dest[ 3]=src[ 3];\n\t    dest[ 4]=src[ 4];\n\t    dest[ 5]=src[ 5];\n\t    dest[ 6]=src[ 6];\n\t    dest[ 7]=src[ 7];\n\t}\n\tfor(i=0;i<m;i++){\n\t    int jjend = mm;\n\t    __builtin_prefetch(c[i]+j+64,1,0);\n\t    __builtin_prefetch(c[i]+j+80,1,0);\n\t    if (jjend+j > n) jjend = n-j;\n\t    for(jj=0;jj<jjend;jj+=4){\n\t\tv2df* cp = (v2df*)(&c[i][j+jj]);\n\t\tv2df* ap = (v2df*)(atmp[0]+jj);\n\t\tv2df* cpp = (v2df*)(&c[i][j+jj+2]);\n\t\tv2df* app = (v2df*)(atmp[0]+jj+2);\n\t\t*cp -= (*ap)*b2tmp[i][0]\n\t\t    +(*(ap+16))*b2tmp[i][1]\n\t\t    +(*(ap+32))*b2tmp[i][2]\n\t\t    +(*(ap+48))*b2tmp[i][3]\n\t\t    +(*(ap+64))*b2tmp[i][4]\n\t\t    +(*(ap+80))*b2tmp[i][5]\n\t\t    +(*(ap+96))*b2tmp[i][6]\n\t\t    +(*(ap+112))*b2tmp[i][7];\n\t\t*cpp -= (*app)*b2tmp[i][0]\n\t\t    +(*(app+16))*b2tmp[i][1]\n\t\t    +(*(app+32))*b2tmp[i][2]\n\t\t    +(*(app+48))*b2tmp[i][3]\n\t\t    +(*(app+64))*b2tmp[i][4]\n\t\t    +(*(app+80))*b2tmp[i][5]\n\t\t    +(*(app+96))*b2tmp[i][6]\n\t\t    +(*(app+112))*b2tmp[i][7];\n\t    }\n\t}\n    }\n\n}\nstatic void matmul_for_nk8_5(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int i,j,k,l;\n    const int m=8;\n    const int mm = 32;\n    double btmp[m][m];\n    v2df b2tmp[m][m];\n\n    for(i=0;i<m;i++)for(j=0;j<m;j++)b2tmp[i][j]=(v2df){b[i][j],b[i][j]};\n    //#pragma omp parallel for private(j,i)\n    //use of OMP here does not speed things up\n    for(j=0;j<n;j+=mm){\n\tdouble atmp[m][mm];\n\tint jj;\n\tfor(i=0;i<m;i++){\n\t    v2df * dest = (v2df*)(atmp[i]);\n\t    v2df * src = (v2df*)(a[i]+j);\n\t    dest[0]=src[0];\n\t    dest[ 1]=src[ 1];\n\t    dest[ 2]=src[ 2];\n\t    dest[ 3]=src[ 3];\n\t    dest[ 4]=src[ 4];\n\t    dest[ 5]=src[ 5];\n\t    dest[ 6]=src[ 6];\n\t    dest[ 7]=src[ 7];\n\t    dest[ 8]=src[ 8];\n\t    dest[ 9]=src[ 9];\n\t    dest[ 10]=src[ 10];\n\t    dest[ 11]=src[ 11];\n\t    dest[ 12]=src[ 12];\n\t    dest[ 13]=src[ 13];\n\t    dest[ 14]=src[ 14];\n\t    dest[ 15]=src[ 15];\n\t}\n\tfor(i=0;i<m;i++){\n\t    int jjend = mm;\n\t    __builtin_prefetch(c[i]+j+64,1,0);\n\t    __builtin_prefetch(c[i]+j+80,1,0);\n\t    if (jjend+j > n) jjend = n-j;\n\t    for(jj=0;jj<jjend;jj+=4){\n\t\tv2df* cp = (v2df*)(&c[i][j+jj]);\n\t\tv2df* ap = (v2df*)(atmp[0]+jj);\n\t\tv2df* cpp = (v2df*)(&c[i][j+jj+2]);\n\t\tv2df* app = (v2df*)(atmp[0]+jj+2);\n\t\t*cp -= (*ap)*b2tmp[i][0]\n\t\t    +(*(ap+16))*b2tmp[i][1]\n\t\t    +(*(ap+32))*b2tmp[i][2]\n\t\t    +(*(ap+48))*b2tmp[i][3]\n\t\t    +(*(ap+64))*b2tmp[i][4]\n\t\t    +(*(ap+80))*b2tmp[i][5]\n\t\t    +(*(ap+96))*b2tmp[i][6]\n\t\t    +(*(ap+112))*b2tmp[i][7];\n\t\t*cpp -= (*app)*b2tmp[i][0]\n\t\t    +(*(app+16))*b2tmp[i][1]\n\t\t    +(*(app+32))*b2tmp[i][2]\n\t\t    +(*(app+48))*b2tmp[i][3]\n\t\t    +(*(app+64))*b2tmp[i][4]\n\t\t    +(*(app+80))*b2tmp[i][5]\n\t\t    +(*(app+96))*b2tmp[i][6]\n\t\t    +(*(app+112))*b2tmp[i][7];\n\t    }\n\t}\n    }\n\n}\n\nstatic void matmul_for_nk8(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int m0,m1,m2,m3;\n    int s1, s2, s3;\n    int ds = (n/64)*16;\n    s1 = ds;\n    s2 = ds*2;\n    s3 = ds*3;\n    m0 = ds;\n    m1 = ds;\n    m2 = ds;\n    m3 = n-s3;\n    //    fprintf(stderr,\"n, s, m = %d %d %d %d %d %d %d %d\\n\",\n    //    n,s1,s2,s3,m0,m1,m2,m3);\n    \n#pragma omp parallel\n#pragma omp sections\n  {\n#pragma omp section\n      matmul_for_nk8_5(n1,a,n2,b,n3,c,m0);\n#pragma omp section\n      matmul_for_nk8_5(n1,((double*)a)+s1 ,n2,b,n3,((double*)c)+s1,m1);\n#pragma omp section\n      matmul_for_nk8_5(n1,((double*)a)+s2 ,n2,b,n3,((double*)c)+s2,m2);\n#pragma omp section\n      matmul_for_nk8_5(n1,((double*)a)+s3 ,n2,b,n3,((double*)c)+s3,m3);\n  }\n}\n\nstatic void matmul_for_nk4_3(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int i,j,k,l;\n    const int m=4;\n    const int mm = 16;\n    double btmp[m][m];\n    v2df b2tmp[m][m];\n    double atmp[m][mm];\n    v2df atmpt[mm/2][m];\n\n    for(i=0;i<m;i++)for(j=0;j<m;j++)b2tmp[i][j]=(v2df){b[i][j],b[i][j]};\n    //#pragma omp parallel for private(j,i,atmp)\n    //use of OMP here does not speed things up\n    for(j=0;j<n;j+=mm){\n\tint jj;\n\n\tfor(i=0;i<m;i++){\n\t    v2df * dest = (v2df*)(atmp[i]);\n\t    v2df * src = (v2df*)(a[i]+j);\n\t    atmpt[ 0][i]=src[0];\n\t    atmpt[ 1][i]=src[ 1];\n\t    atmpt[ 2][i]=src[ 2];\n\t    atmpt[ 3][i]=src[ 3];\n\t    atmpt[ 4][i]=src[ 4];\n\t    atmpt[ 5][i]=src[ 5];\n\t    atmpt[ 6][i]=src[ 6];\n\t    atmpt[ 7][i]=src[ 7];\n\t}\n\tfor(i=0;i<m;i++){\n\t    int jjend = mm;\n\t    if (jjend+j > n) jjend = n-j;\n\t    v2df* cp = (v2df*)(&c[i][j]);\n\t    v2df* ap = (v2df*)(atmpt[0]);\n\t    v2df* cpp = (v2df*)(&c[i][j+2]);\n\t    v2df* app = (v2df*)(atmpt[1]);\n\t    v2df* bp = b2tmp[i];\n\t    for(jj=0;jj<jjend;jj+=4){\n\t\t*cp -= ap[0]*bp[0]\n\t\t    +ap[1]*bp[1]\n\t\t    +ap[2]*bp[2]\n\t\t    +ap[3]*bp[3];\n\t\t*cpp -= app[0]*bp[0]\n\t\t    +app[1]*bp[1]\n\t\t    +app[2]*bp[2]\n\t\t    +app[3]*bp[3];\n\t\tcp += 2;\n\t\tcpp+= 2;\n\t\tap += m*2;\n\t\tapp+= m*2;\n\t    }\n\t}\n\n    }\n\n}\n\n\nstatic void matmul_for_nk4_4(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int i,j,k,l;\n    const int m=4;\n    const int mm = 32;\n    double btmp[m][m];\n    v2df b2tmp[m][m];\n    double atmp[m][mm];\n\n    for(i=0;i<m;i++)for(j=0;j<m;j++)b2tmp[i][j]=(v2df){b[i][j],b[i][j]};\n    //#pragma omp parallel for private(j,i,atmp)\n    // use of OMP does not speed things up here...\n    for(j=0;j<n;j+=mm){\n\tint jj;\n\tfor(i=0;i<m;i++){\n\t    v2df * dest = (v2df*)(atmp[i]);\n\t    v2df * src = (v2df*)(a[i]+j);\n#if 0\t    \n\t    for(k=0;k<mm;k++)atmp[i][k]=a[i][j+k];\n#endif\n#if 0\t    \n\t    for(k=0;k<mm/2;k++)dest[k]=src[k];\n#endif\n\t    for(k=0;k<mm/2;k+=2){\n\t\tdest[k]=src[k];\n\t\tdest[k+1]=src[k+1];\n\t    }\n\t}\n\tfor(i=0;i<m;i++){\n\t    int jjend = mm;\n\t    v2df * bp = b2tmp[i];\n\t    if (jjend+j > n) jjend = n-j;\n\t    for(jj=0;jj<jjend;jj+=2){\n\t\tv2df* cp = (v2df*)(&c[i][j+jj]);\n\t\tv2df* ap = (v2df*)(atmp[0]+jj);\n\t\tv2df* cpp = (v2df*)(&c[i][j+jj+2]);\n\t\tv2df* app = (v2df*)(atmp[0]+jj+2);\n\t\t*cp -= (*ap)*bp[0]\n\t\t    +(*(ap+16))*bp[1]\n\t\t    +(*(ap+32))*bp[2]\n\t\t    +(*(ap+48))*bp[3];\n#if 0\t\t\n\t\t*cpp -= (*app)*bp[0]\n\t\t    +(*(app+16))*bp[1]\n\t\t    +(*(app+32))*bp[2]\n\t\t    +(*(app+48))*bp[3];\n#endif\t\t\n\t    }\n\t}\n    }\n\n}\nstatic void matmul_for_nk4_1(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int i,j,k,l;\n    const int m=4;\n    const int mm = 32;\n    double btmp[m][m];\n    v2df b2tmp[m][m];\n\n    for(i=0;i<m;i++)for(j=0;j<m;j++)b2tmp[i][j]=(v2df){b[i][j],b[i][j]};\n#pragma omp parallel for private(j,i)\n    // use of OMP does not speed things up here...\n    for(j=0;j<n;j+=mm){\n\tdouble atmp[m][mm];\n\tint jj;\n\tfor(i=0;i<m;i++){\n\t    v2df * dest = (v2df*)(atmp[i]);\n\t    v2df * src = (v2df*)(a[i]+j);\n#if 0\t    \n\t    for(k=0;k<mm;k++)atmp[i][k]=a[i][j+k];\n#endif\n#if 0\t    \n\t    for(k=0;k<mm/2;k++)dest[k]=src[k];\n#endif\n\t    for(k=0;k<mm/2;k+=4){\n\t\tdest[k]=src[k];\n\t\tdest[k+1]=src[k+1];\n\t\tdest[k+2]=src[k+2];\n\t\tdest[k+3]=src[k+3];\n\t    }\n\t}\n\tfor(i=0;i<m;i++){\n\t    int jjend = mm;\n\t    v2df * bp = b2tmp[i];\n\t    if (jjend+j > n) jjend = n-j;\n\t    for(jj=0;jj<jjend;jj+=4){\n\t\tv2df* cp = (v2df*)(&c[i][j+jj]);\n\t\tv2df* ap = (v2df*)(atmp[0]+jj);\n\t\tv2df* cpp = (v2df*)(&c[i][j+jj+2]);\n\t\tv2df* app = (v2df*)(atmp[0]+jj+2);\n\t\t*cp -= (*ap)*bp[0]\n\t\t    +(*(ap+16))*bp[1]\n\t\t    +(*(ap+32))*bp[2]\n\t\t    +(*(ap+48))*bp[3];\n\t\t*cpp -= (*app)*bp[0]\n\t\t    +(*(app+16))*bp[1]\n\t\t    +(*(app+32))*bp[2]\n\t\t    +(*(app+48))*bp[3];\n\t    }\n\t}\n    }\n\n}\nstatic void matmul_for_nk2_0(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int j,k,l;\n    for(j=0;j<n;j++){\n\t    c[0][j] -= a[0][j]*b[0][0]+a[1][j]*b[0][1];\n\t    c[1][j] -= a[0][j]*b[1][0]+a[1][j]*b[1][1];\n    }\n}\nstatic void matmul_for_nk2_1(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int j,k,l;\n\n    for(j=0;j<n;j+=2){\n\t    c[0][j] -= a[0][j]*b[0][0]+a[1][j]*b[0][1];\n\t    c[1][j] -= a[0][j]*b[1][0]+a[1][j]*b[1][1];\n\t    c[0][j+1] -= a[0][j+1]*b[0][0]+a[1][j+1]*b[0][1];\n\t    c[1][j+1] -= a[0][j+1]*b[1][0]+a[1][j+1]*b[1][1];\n    }\n}\nstatic void matmul_for_nk2_2(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int j,k,l;\n\n    register double b00 = b[0][0];\n    register double b01 = b[0][1];\n    register double b10 = b[1][0];\n    register double b11 = b[1][1];\n    for(j=0;j<n;j+=2){\n\t    c[0][j] -= a[0][j]*b00+a[1][j]*b01;\n\t    c[0][j+1] -= a[0][j+1]*b00+a[1][j+1]*b01;\n\t    c[1][j] -= a[0][j]*b10+a[1][j]*b11;\n\t    c[1][j+1] -= a[0][j+1]*b10+a[1][j+1]*b11;\n    }\n\n}\nstatic void matmul_for_nk2(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int j,k,l;\n    register v2df b00 = (v2df){b[0][0],b[0][0]};\n    register v2df b01 = (v2df){b[0][1],b[0][1]};\n    register v2df b10 = (v2df){b[1][0],b[1][0]};\n    register v2df b11 = (v2df){b[1][1],b[1][1]};\n    v2df * a0 = (v2df*) a[0];\n    v2df * a1 = (v2df*) a[1];\n    v2df * c0 = (v2df*) c[0];\n    v2df * c1 = (v2df*) c[1];\n    int nh = n>>1;\n    if (nh & 1){\n\tj=nh-1;\n\tc0[j] -= a0[j]*b00+a1[j]*b01;\n\tc1[j] -= a0[j]*b10+a1[j]*b11;\n\tnh = nh-1;\n    }\n    for(j=0;j<nh;j+=2){\n\tc0[j] -= a0[j]*b00+a1[j]*b01;\n\tc0[j+1] -= a0[j+1]*b00+a1[j+1]*b01;\n\tc1[j] -= a0[j]*b10+a1[j]*b11;\n\tc1[j+1] -= a0[j+1]*b10+a1[j+1]*b11;\n\t//\t__builtin_prefetch((double*)&a0[j+32],0);\n\t//\t__builtin_prefetch((double*)&a1[j+32],0);\n\t//\t__builtin_prefetch((double*)&c0[j+32],1);\n\t//\t__builtin_prefetch((double*)&c1[j+32],1);\n\t//\tasm(\"prefetcht2 %0\"::\"m\"(a0[j+32]):\"memory\");\n\t//\tasm(\"prefetcht2 %0\"::\"m\"(a1[j+32]):\"memory\");\n    }\n}\n\n\nstatic void matmul_for_nk4_5(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n\n    matmul_for_nk2(n1, a, n2, b, n3,c, n);\n    matmul_for_nk2(n1, (double(*)[])  (a[2]), n2,\n\t\t   (double(*)[])  &(b[0][2]), n3,c, n);\n    matmul_for_nk2(n1, a, n2, (double(*)[])  b[2], n3,\n\t\t   (double(*)[])  c[2], n);\n    matmul_for_nk2(n1, (double(*)[])  &(a[2]), n2,\n\t\t   (double(*)[])  &(b[2][2]), n3,\n\t\t   (double(*)[])  c[2], n);\n    \n\n}\n\nstatic void matmul_for_nk4_6(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    register v2df b00 = (v2df){b[0][0],b[0][0]};\n    register v2df b01 = (v2df){b[0][1],b[0][1]};\n    register v2df b02 = (v2df){b[0][2],b[0][2]};\n    register v2df b03 = (v2df){b[0][3],b[0][3]};\n    register v2df b10 = (v2df){b[1][0],b[1][0]};\n    register v2df b11 = (v2df){b[1][1],b[1][1]};\n    register v2df b12 = (v2df){b[1][2],b[1][2]};\n    register v2df b13 = (v2df){b[1][3],b[1][3]};\n    register v2df b20 = (v2df){b[2][0],b[2][0]};\n    register v2df b21 = (v2df){b[2][1],b[2][1]};\n    register v2df b22 = (v2df){b[2][2],b[2][2]};\n    register v2df b23 = (v2df){b[2][3],b[2][3]};\n    register v2df b30 = (v2df){b[3][0],b[3][0]};\n    register v2df b31 = (v2df){b[3][1],b[3][1]};\n    register v2df b32 = (v2df){b[3][2],b[3][2]};\n    register v2df b33 = (v2df){b[3][3],b[3][3]};\n\n    v2df * a0 = (v2df*) a[0];\n    v2df * a1 = (v2df*) a[1];\n    v2df * a2 = (v2df*) a[2];\n    v2df * a3 = (v2df*) a[3];\n    v2df * c0 = (v2df*) c[0];\n    v2df * c1 = (v2df*) c[1];\n    v2df * c2 = (v2df*) c[2];\n    v2df * c3 = (v2df*) c[3];\n    int nh = n>>1;\n    //#pragma omp parallel\n    {\n\t//#pragma omp section\n\t{\n\t    int j;\n\t    //#pragma omp for private (j)\n\t    for(j=0;j<nh;j++){\n\t\tc0[j] -= a0[j]*b00+a1[j]*b01+a2[j]*b02+a3[j]*b03;\n\t\tc1[j] -= a0[j]*b10+a1[j]*b11+a2[j]*b12+a3[j]*b13;\n\t    }\n\t}\n\t//#pragma omp section\n\t{\n\t    int j;\n\t    //#pragma omp for private (j)\n\t    for(j=0;j<nh;j++){\n\t\tc2[j] -= a0[j]*b20+a1[j]*b21+a2[j]*b22+a3[j]*b23;\n\t\tc3[j] -= a0[j]*b30+a1[j]*b31+a2[j]*b32+a3[j]*b33;\n\t    }\n\t}\n    }\n}\nstatic void matmul_for_nk4_7(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    v2df * a0 = (v2df*) a[0];\n    v2df * a1 = (v2df*) a[1];\n    v2df * a2 = (v2df*) a[2];\n    v2df * a3 = (v2df*) a[3];\n    int j;\n    {\n\tint nh = n>>1;\n\tv2df * c0 = (v2df*) c[0];\n\tv2df * c1 = (v2df*) c[1];\n\t v2df b00 = (v2df){b[0][0],b[0][0]};\n\t v2df b01 = (v2df){b[0][1],b[0][1]};\n\t v2df b02 = (v2df){b[0][2],b[0][2]};\n\t v2df b03 = (v2df){b[0][3],b[0][3]};\n\t v2df b10 = (v2df){b[1][0],b[1][0]};\n\t v2df b11 = (v2df){b[1][1],b[1][1]};\n\t v2df b12 = (v2df){b[1][2],b[1][2]};\n\t v2df b13 = (v2df){b[1][3],b[1][3]};\n\tif (nh & 1){\n\t    j=nh-1;\n\t    c0[j] -= a0[j]*b00+a1[j]*b01+a2[j]*b02+a3[j]*b03;\n\t    c1[j] -= a0[j]*b10+a1[j]*b11+a2[j]*b12+a3[j]*b13;\n\t    nh--;\n\t}\n\tfor(j=0;j<nh;j+=2){\n\t    c0[j] -= a0[j]*b00+a1[j]*b01+a2[j]*b02+a3[j]*b03;\n\t    c1[j] -= a0[j]*b10+a1[j]*b11+a2[j]*b12+a3[j]*b13;\n\t    c0[j+1] -= a0[j+1]*b00+a1[j+1]*b01+a2[j+1]*b02+a3[j+1]*b03;\n\t    c1[j+1] -= a0[j+1]*b10+a1[j+1]*b11+a2[j+1]*b12+a3[j+1]*b13;\n\t}\n    }\n    {\n\tint nh = n>>1;\n\tv2df * c2 = (v2df*) c[2];\n\tv2df * c3 = (v2df*) c[3];\n\t v2df b20 = (v2df){b[2][0],b[2][0]};\n\t v2df b21 = (v2df){b[2][1],b[2][1]};\n\t v2df b22 = (v2df){b[2][2],b[2][2]};\n\t v2df b23 = (v2df){b[2][3],b[2][3]};\n\tregister v2df b30 = (v2df){b[3][0],b[3][0]};\n\tregister v2df b31 = (v2df){b[3][1],b[3][1]};\n\tregister v2df b32 = (v2df){b[3][2],b[3][2]};\n\tregister v2df b33 = (v2df){b[3][3],b[3][3]};\n\t\n\tfor(j=0;j<nh;j++){\n\t    c2[j] -= a0[j]*b20+a1[j]*b21+a2[j]*b22+a3[j]*b23;\n\t    c3[j] -= a0[j]*b30+a1[j]*b31+a2[j]*b32+a3[j]*b33;\n\t}\n    }\n}\n\n\nstatic void matmul_for_nk4_8(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    v2df * a0 = (v2df*) a[0];\n    v2df * a1 = (v2df*) a[1];\n    v2df * a2 = (v2df*) a[2];\n    v2df * a3 = (v2df*) a[3];\n    int nh = n>>1;\n    int j;\n\n    int k;\n    v2df * cv;\n    v2df * cvv;\n    register v2df b0;\n    register v2df b1;\n    register v2df b2;\n    register v2df b3;\n    register v2df b4;\n    register v2df b5;\n    register v2df b6;\n    register v2df b7;\n    for(k=0;k<4;k+=2){\n\tcv = (v2df*) c[k];\n\tcvv = (v2df*) c[k+1];\n\tb0 = (v2df){b[k][0],b[k][0]};\n\tb1 = (v2df){b[k][1],b[k][1]};\n\tb2 = (v2df){b[k][2],b[k][2]};\n\tb3 = (v2df){b[k][3],b[k][3]};\n\tb4 = (v2df){b[k+1][0],b[k+1][0]};\n\tb5 = (v2df){b[k+1][1],b[k+1][1]};\n\tb6 = (v2df){b[k+1][2],b[k+1][2]};\n\tb7 = (v2df){b[k+1][3],b[k+1][3]};\n\tfor(j=0;j<nh;j++){\n\t    register v2df aa0 = a0[j];\n\t    register v2df aa1 = a1[j];\n\t    register v2df aa2 = a2[j];\n\t    register v2df aa3 = a3[j];\n\t    register v2df x = aa0*b0;\n\t    x+= aa1*b1;\n\t    x+= aa2*b2;\n\t    x+= aa3*b3;\n\t    cv[j]-=x;\n\t    x = aa0*b4;\n\t    x+= aa1*b5;\n\t    x+= aa2*b6;\n\t    x+= aa3*b7;\n\t    cvv[j] -= x;\n\t}\n    }\n}\n\nstatic void matmul_for_nk4(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int m0,m1,m2,m3;\n    int s1, s2, s3;\n    int ds = (n/32)*8;\n    s1 = ds;\n    s2 = ds*2;\n    s3 = ds*3;\n    m0 = ds;\n    m1 = ds;\n    m2 = ds;\n    m3 = n-s3;\n    //    fprintf(stderr,\"n, s, m = %d %d %d %d %d %d %d %d\\n\",\n    //    n,s1,s2,s3,m0,m1,m2,m3);\n    \n#pragma omp parallel\n#pragma omp sections\n  {\n#pragma omp section\n      matmul_for_nk4_7(n1,a,n2,b,n3,c,m0);\n#pragma omp section\n      matmul_for_nk4_7(n1,((double*)a)+s1 ,n2,b,n3,((double*)c)+s1,m1);\n#pragma omp section\n      matmul_for_nk4_7(n1,((double*)a)+s2 ,n2,b,n3,((double*)c)+s2,m2);\n#pragma omp section\n      matmul_for_nk4_7(n1,((double*)a)+s3 ,n2,b,n3,((double*)c)+s3,m3);\n  }\n}\nstatic void matmul_for_nk8_9(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    matmul_for_nk4(n1, a, n2, b, n3,c, n);\n    matmul_for_nk4(n1, (double(*)[])  (a[4]), n2,\n\t\t   (double(*)[])  &(b[0][4]), n3,c, n);\n    matmul_for_nk4(n1, a, n2, (double(*)[])  b[4], n3,\n\t\t   (double(*)[])  c[4], n);\n    matmul_for_nk4(n1, (double(*)[])  &(a[4]), n2,\n\t\t   (double(*)[])  &(b[4][4]), n3,\n\t\t   (double(*)[])  c[4], n);\n    \n}\n#if 0\nstatic void matmul_for_nk8(int n1, double a[][n1],\n\t\t\t   int n2, double b[][n2],\n\t\t\t   int n3, double c[][n3],\n\t\t\t   int n)\n{\n    int i;\n    int nb=384;\n    for (i=0;i<n;i+=nb){\n\tint iend = i+nb;\n\tif (iend > n) iend = n;\n\tmatmul_for_nk8_worker(n1, (double(*)[]) (a[0]+i),\n\t\t\t      n2,  (double(*)[]) (b[0]+i),\n\t\t\t      n3, (double(*)[]) (c[0]+i),\n\t\t\t      iend-i);\n    }\n}\n#endif\n\nstatic void matmul_for_small_nk_local(int n1, double a[][n1],\n\t\t\t int n2, double b[][n2],\n\t\t\t int n3, double c[][n3],\n\t\t\t int m,\n\t\t\t int kk,\n\t\t\t int n)\n{\n    // simplest version\n    int j,k,l;\n    BEGIN_TSC;\n    if (kk == 2){\n\tmatmul_for_nk2(n1, a, n2, b, n3,c, n);\n\tEND_TSC(t,16);\n\treturn;\n    }\n    if (kk == 4){\n\tmatmul_for_nk4(n1, a, n2, b, n3,c, n);\n\tEND_TSC(t,13);\n\treturn;\n    }\n    if (kk == 8){\n\tmatmul_for_nk8(n1, a, n2, b, n3,c, n);\n\tEND_TSC(t,12);\n\treturn;\n    }\n\t\n    for(j=0;j<n;j++)\n\tfor(k=0;k<m;k++)\n\t    for(l=0;l<kk;l++)\n\t\tc[k][j] -= a[l][j]*b[k][l];\n}\n\nstatic void mmmulandsub(int n, double a[n+1][n], int rshift, int m0, int m1,\n\t\t int c0, int c1, int r0,int r1)\n{\n    int j,k,l;\n#ifdef TIMETEST\n    BEGIN_TSC;\n#endif\n#ifndef NOBLAS\n    if ((m1-m0)<=8){\n\t// =4 is slighly faster than =8 on Ci7 \n\tmatmul_for_small_nk_local(n, (double(*)[])  &(a[m0-rshift][r0]),\n\t\t\t      n, (double(*)[])  &(a[c0-rshift][m0]),\n\t\t\t      n, (double(*)[])  &(a[c0-rshift][r0]),\n\t\t\t      c1-c0,m1-m0,r1-r0);\n    }else{\n\tcblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,\n\t\t     r1-r0, c1-c0, m1-m0, -1.0, &(a[m0-rshift][r0]), n,\n\t\t     &(a[c0-rshift][m0]), n, 1, &(a[c0-rshift][r0]), n );\n    }\n    // example:\n    // r0, m0 = i+m,i\n    // m0, c0 = i, i+m\n    // r0, c0 = i+m, i+m\n    //r1-r0 = n-i-m\n    // c1-c0 = iend-i-m\n    // m1-m0 = m\n#else\n    for(j=r0;j<r1;j++)\n\tfor (k=c0;k<c1;k++)\n\t    for (l=m0; l<m1; l++)\n\t\ta[k-rshift][j] -= a[l-rshift][j]*a[k-rshift][l];\n#endif    \n#ifdef TIMETEST\n    END_TSC(t,4);\n#endif\n}\n\nstatic int nswap;\nstatic void column_decomposition(int n, double a[][n],  int m, int pv[], int i)\n{\n    // shift a so that partial array is okay\n    int  j, k;\n    int ip,ii;\n    double ainv;\n#ifdef TIMETEST\n    BEGIN_TSC;\n#endif\n    for(ip=0;ip<m;ip++){\n\tii=i+ip;\n\tint p = findpivot(n,a,ii);\n\tpv[ip]=p;\n\tswaprows(n,a,p,ii,0,m);\n\tnswap++;\n\t// normalize row ii\n\tainv = 1.0/a[ip][ii];\n\tscalerow(n,a,ainv,ii,0,ip);\n\tscalerow(n,a,ainv,ii,ip+1,m);\n\t// subtract row ii from all lower rows\n\tvvmulandsub(n,  a, ip,ii, ip+1, m, ii+1, n);\n    }\n#ifdef TIMETEST\n    END_TSC(t,5);\n#endif    \n}\t\n\nstatic void process_right_part(int n,\n\t\t\tdouble a[n+1][n],\n\t\t\tint m,\n\t\t\tint pv[],\n\t\t\tint i,\n\t\t\tint iend)\n{\n    int ii;\n    // exchange rows \n    for(ii=i;ii<i+m;ii++){\n\tswaprows(n,a,pv[ii-i],ii,m,iend-i);\n    }\n    \n    // normalize rows\n    for(ii=i;ii<i+m;ii++){\n\tscalerow(n,a,1.0/a[ii-i][ii] ,ii,m,iend-i);\n    }\n    // subtract rows (within i-i+m-1)\n    for(ii=i;ii<i+m;ii++){\n\tvvmulandsub(n,  a, ii-i,ii,  m, iend-i, ii+1, i+m);\n    }\n    \n    // subtract rows i-i+m-1 from all lower rows\n    mmmulandsub(n, a, i, i,i+m, i+m, iend, i+m, n);\n    //    fprintf(stderr,\"process_r, end\\n\");\n    //    usleep(1);\n}\nstatic void column_decomposition_recursive(int n,\n\t\t\t\t    double a[n+1][n],\n\t\t\t\t    int m,\n\t\t\t\t    int pv[],\n\t\t\t\t    int i)\n{\n    int  j, k;\n    int ip,ii;\n    double ainv;\n    //    fprintf(stderr,\"enter t column recursive %d %d\\n\", i, m);\n    if (m <= 2){\n\t// perform non-recursive direct decomposition\n\tcolumn_decomposition(n, a, m, pv,i);\n    }else{\t\n\t// process the left half by recursion\n\t//\tfprintf(stderr,\"call column recursive %d %d\\n\", i, m);\n\tcolumn_decomposition_recursive(n, a, m/2, pv,i);\n\t// process the right half\n\t//\tfprintf(stderr,\"call right part %d %d\\n\", i, m);\n\tprocess_right_part(n,a,m/2,pv,i,i+m);\n\t//\tfprintf(stderr,\"call right recursive %d %d\\n\", i, m);\n\tcolumn_decomposition_recursive(n, a+m/2, m/2, pv+m/2,i+m/2);\n\t// process the swap of rows for the left half\n\t//\tfprintf(stderr,\"call swaprowse %d %d\\n\", i, m);\n\tfor(ii=i+m/2;ii<i+m;ii++){\n\t    swaprows(n,a,pv[ii-i],ii,0,m/2);\n\t}\n\t//\tfprintf(stderr,\"call scalerows %d %d\\n\", i, m);\n\t// normalize rows\n\tfor(ii=i+m/2;ii<i+m;ii++){\n\t    scalerow(n,a,1.0/a[ii-i][ii] ,ii,0,m/2);\n\t}\n    }\n}\n    \nvoid cm_column_decomposition_recursive(int n,\n\t\t\t\t    double a[n+1][n],\n\t\t\t\t    int m,\n\t\t\t\t    int pv[],\n\t\t\t\t    int i)\n{\n    column_decomposition_recursive( n, a, m, pv, i);\n}\nvoid cm_column_decomposition(int n,\n\t\t\t\t    double a[n+1][n],\n\t\t\t\t    int m,\n\t\t\t\t    int pv[],\n\t\t\t\t    int i)\n{\n    column_decomposition( n, a, m, pv, i);\n}\nvoid cm_process_right_part(int n,\n\t\t\t   double a[n+1][n],\n\t\t\t   int m,\n\t\t\t   int pv[],\n\t\t\t   int i,\n\t\t\t   int iend)\n{\n    process_right_part(n, a, m, pv, i,iend);\n}\n\n", "meta": {"hexsha": "bb929044f1b5d873fb51f751e5efaea2c65d29e7", "size": 27780, "ext": "c", "lang": "C", "max_stars_repo_path": "lu2tlib.c", "max_stars_repo_name": "jmakino/lu2", "max_stars_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-07T09:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T05:00:16.000Z", "max_issues_repo_path": "lu2tlib.c", "max_issues_repo_name": "jmakino/lu2", "max_issues_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lu2tlib.c", "max_forks_repo_name": "jmakino/lu2", "max_forks_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-13T15:31:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-13T15:31:32.000Z", "avg_line_length": 24.0311418685, "max_line_length": 79, "alphanum_fraction": 0.48862491, "num_tokens": 12193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.37538094413056294}}
{"text": "#ifndef __BLAS_H__\n#define __BLAS_H__\n\n#define sgemm sgemm_\n#define dgemm dgemm_   \n#define ssteqr ssteqr_\n#define dsteqr dsteqr_\n#define dgemv dgemv_\n#define ddot ddot_\n#define daxpy daxpy_\n#define dscal dscal_\n#define dasum dasum_\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n    //#include <cblas.h>\n    //#include <clapack.h>\n\n    void sgemm_(const char* TRANSA, const char* TRANSB,\n        const int* M, const int* N, const int* K,\n        const float* ALPHA, const float* A, const int* LDA, \n        const float* B, const int* LDB, \n        const float* BETA, float* C, const int* LDC);  \n\n    void dgemm_(const char* TRANSA, const char* TRANSB,\n        const int* M, const int* N, const int* K,\n        const double* ALPHA, const double* A, const int* LDA,\n        const double* B, const int* LDB, \n        const double* BETA, double* C, const int* LDC); \n/*\n    void ssteqr_(char *compz, const int *n, float *d, float *e, \n        float *z, const int *ldz, float *work, const int *info);\n\n    void dsteqr_(char *compz, const int *n, double *d, double *e, \n        double *z, const int *ldz, double *work, const int *info);\n */\n\n     void dgemv_(const char *trans, const int *m, const int *n,\n          const double *alpha, const double *a, const int *lda, \n          const double *x, const int *incx, const double *beta, \n          double *y, const int *incy);\n\n     double ddot_(const int* n, const double* x, const int* incx, \n          const double* y, const int* incy);\n\n\n     void daxpy_(const int* n, const double *alpha, const double* x, \n\tconst int* incx, double* y, const int* incy);\n \n\t void dscal_(const int*n, const double *alpha, const double* x, const int* incx);\n\n\t double dasum_(const int*n, const double *x, const int* incx);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "faa3bb887b93ba95902b4f5d29a9c93ccaa6b91e", "size": 1782, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmark/askit_release/rkdtsrc/include/blas.h", "max_stars_repo_name": "maumueller/rehashing", "max_stars_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T20:08:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T20:48:29.000Z", "max_issues_repo_path": "benchmark/askit_release/rkdtsrc/include/blas.h", "max_issues_repo_name": "maumueller/rehashing", "max_issues_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T09:47:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-09T04:27:39.000Z", "max_forks_repo_path": "benchmark/askit_release/rkdtsrc/include/blas.h", "max_forks_repo_name": "maumueller/rehashing", "max_forks_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T22:29:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T20:02:46.000Z", "avg_line_length": 29.7, "max_line_length": 82, "alphanum_fraction": 0.6391694725, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3753586396133246}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <assert.h>\n#include <string.h>\n#include <time.h>\n#include <sys/time.h>\n#include <gsl/gsl_math.h>\n\n#include \"cosmocalc.h\"\n#include \"haloprofs.h\"\n#include \"weaklens.h\"\n\nvoid test_cosmo(char *path);\n\nint main(int argc, char **argv)\n{\n  cosmoData.useSmoothTransFunc = 0;\n  cosmoData.delta = 200.0;\n  char path[4096];\n  \n  //init cosmology 2\n  cosmoData.cosmoNum = 2;\n  cosmoData.OmegaM = 0.28;\n  cosmoData.OmegaL = 0.72;\n  cosmoData.OmegaB = 0.05;\n  cosmoData.OmegaNu = 0.0;\n  cosmoData.OmegaK = 0.0;\n  cosmoData.h = 0.7;\n  cosmoData.w0 = -1.0;\n  cosmoData.wa = 0.0;\n  cosmoData.SpectralIndex = 0.96;\n  cosmoData.Sigma8 = 0.8;\n\n  sprintf(path,\"./cosmo2\");\n  test_cosmo(path);\n  \n  //init cosmology 1\n  cosmoData.cosmoNum = 1;\n  cosmoData.OmegaM = 0.3;\n  cosmoData.OmegaL = 0.68;\n  cosmoData.OmegaB = 0.05;\n  cosmoData.OmegaNu = 0.0;\n  cosmoData.OmegaK = 1.0 - cosmoData.OmegaM - cosmoData.OmegaL - cosmoData.OmegaNu;\n  cosmoData.h = 0.7;\n  cosmoData.w0 = -0.8;\n  cosmoData.wa = 0.2;\n  cosmoData.SpectralIndex = 0.96;\n  cosmoData.Sigma8 = 0.8;\n  \n  sprintf(path,\"./cosmo1\");\n  test_cosmo(path);\n  \n  return 0;\n}\n\nvoid test_cosmo(char *path)\n{\n  char fname[4096];\n  char fnameo[4096];\n  char str[4096];\n  FILE *fp;\n  FILE *fpout;\n  double z;\n  \n  sprintf(fname,\"%s/codist.dat\",path);\n  sprintf(fnameo,\"%s/codist.dat.matt\",path);\n  fp = fopen(fname,\"r\");\n  if( fp != NULL)\n    {\n      fpout = fopen(fnameo,\"w\");\n      while(fgets(str,4096,fp) != NULL)\n\t{\n\t  if(str[0] == '#')\n\t    continue;\n\t  sscanf(str,\"%le %*e\\n\",&z);\n\t  \n\t  fprintf(fpout,\"%e %e\\n\",z,comvdist(1.0/(1.0+z)));\n\t}\n      fclose(fp);\n      fclose(fpout);\n    }\n  \n  sprintf(fname,\"%s/Evol_z.dat\",path);\n  sprintf(fnameo,\"%s/Evol_z.dat.matt\",path);\n  fp = fopen(fname,\"r\");\n  if(fp != NULL)\n    {\n      fpout = fopen(fnameo,\"w\");\n      while(fgets(str,4096,fp) != NULL)\n\t{\n\t  if(str[0] == '#')\n\t    continue;\n\t  sscanf(str,\"%le %*e\\n\",&z);\n\t  \n\t  //fprintf(stderr,\"weff(%f) = %f, h(a) = %f\\n\",1.0/(1.0+z),weff(1.0/(1.0+z)),hubble_noscale(1.0/(1.0+z)));\n\t  fprintf(fpout,\"%e %e\\n\",z,hubble_noscale(1.0/(1.0+z)));\n\t}\n      fclose(fp);\n      fclose(fpout);\n    }\n}\n", "meta": {"hexsha": "f68930ec925123d789993523f6f9f2b79204623a", "size": 2186, "ext": "c", "lang": "C", "max_stars_repo_path": "src/main.c", "max_stars_repo_name": "beckermr/cosmocalc", "max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "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/main.c", "max_issues_repo_name": "beckermr/cosmocalc", "max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z", "max_forks_repo_path": "src/main.c", "max_forks_repo_name": "beckermr/cosmocalc", "max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z", "avg_line_length": 21.2233009709, "max_line_length": 108, "alphanum_fraction": 0.6006404392, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.37505818566835764}}
{"text": "/* hka chi-square stat estimation \nbased on original Hudson, Kreitman, Aguade 1987 implementation.\n\nThe parameters of the model are calculated by solving the system of equations numerically.\n\nA. D. Kern  6/2005\n*/\n\n#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \"math.h\"\n#include \"string.h\"\n#include \"hka.h\"\n#include \"ctype.h\"\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_multiroots.h>\n\n\n\n/* currently the maximum number of loci is at 10^7, and the maximum locus name is 80 characters long */\nstruct hkaData data[MAXLOCI];\nint locusNumber = 0;\nint lineageNumber = 1;\n\nint main(int argc, char *argv[]){\n  int i = 0;\n  gsl_vector  *chiSquares, *expectedPolyA, *expectedD, *devs;\n  gsl_vector  *params; //0-locusNumber-1 = 4Nu's, locusNumber = tHat, locusNumber + 1 = fHat\n  double x;\n\n  getData(argc, argv);\n  if(lineageNumber > 1){\n    params = gsl_vector_alloc(locusNumber + 2);\n  }\n  else{\n    params = gsl_vector_alloc(locusNumber + 1);\n  }\n\n  //solve the system of equations\n  solveSystem(params);\n \n  //calculate chiSquare Stats\n  chiSquares =gsl_vector_alloc(locusNumber);\n  expectedPolyA = gsl_vector_alloc(locusNumber);\n  expectedD = gsl_vector_alloc(locusNumber);\n  devs =  gsl_vector_alloc(locusNumber);\n\n  x =  calculateHKA(params, chiSquares, expectedPolyA, expectedD);\n\n  //print some stuff\n  if(lineageNumber > 1){\n    printf(\"chiSquared = %f\\nt_hat = %f\\nf_hat = %f\\n\",x, gsl_vector_get(params,locusNumber), gsl_vector_get(params,locusNumber + 1));\n  }\n  else{\n    printf(\"chiSquared = %f\\nt_hat = %f\\nf_hat = 1.0\\n\",x, gsl_vector_get(params,locusNumber));\n  }\n    for(i = 0; i < locusNumber; i++){\n      printf(\"locus %s \\ttheta:\\t %f\\texpSA:\\t %f\\tobsSA:\\t %f\\texpD:\\t %f\\tobsD:\\t %f\\t chiSquared:\\t%f\\n\",data[i].name,   gsl_vector_get(params,i),gsl_vector_get(expectedPolyA,i), data[i].sa, gsl_vector_get(expectedD,i), data[i].d, gsl_vector_get(chiSquares,i));\n  } \n      \n  gsl_vector_free(params);\n  return(0);\n}\n\nvoid usage(){\n  printf(\"usage:\\nhka infile\\n\");\n  exit(1);\n}\n\n\n/* parses the data file and reads in options (currently no options boss) */\nvoid getData(int argc, char *argv[]){\n  FILE *infile;\n  int  l, na, nb, sa, sb, args, flag, i,lineCount;\n  double d;\n  char string[81];  //here's the character length limit\n  char *sArray[30], line[500];\n\n  if (argc < 2){\n    usage();\n  }\n  else{\n    infile = fopen(argv[1],\"r\");\n    if (infile == NULL){\n      fprintf(stderr,\"Error opening infile!!!\\n\");\n      exit(1);\n    }\n    flag = 0;\n    args = 2;\n    while(args < argc){\n      switch(argv[args][1]){\n      case 'm' : //missing data mode\n\tflag = 1;\n      }\n      args++;\n    }\n    if (flag){\n      //missing data mode expect- na, d,lArray, sArray \n      while(fgets(line, 100, infile)){\n\tlineCount = chopByWhite(line,sArray,30);\n\t//\tdata[locusNumber].name = (char) sArray[0];\n\tdata[locusNumber].na = atoi(sArray[1]);\n\tdata[locusNumber].d = (double) atof(sArray[2]);\n\tfor(i = 0; i < data[locusNumber].na - 2; i++){\n\t  data[locusNumber].lArray[i] = atoi(sArray[i+3]);\n\t  data[locusNumber].sArray[i] = atoi(sArray[i+data[locusNumber].na - 1 + 3]);\n\t}\n\t\n\tprintf(\"%d\\n\",data[locusNumber].sArray[2]);\n      }\n    }\n    else{\n      \n      /* collect hka data from infile- expect length, na, nb, sa, sb, d */\n      while(fscanf(infile, \"%80s %d %d %d %d %d %lf\", string,  &l, &na, &nb, &sa, &sb, &d) != EOF){\n\tstrcpy(data[locusNumber].name, string);\n\tdata[locusNumber].length = l;\n\tdata[locusNumber].na = na;\n\tdata[locusNumber].nb = nb;\n\tif (nb > 1){\n\t  lineageNumber = 2;\n\t}\n\tdata[locusNumber].sa = (double) sa;\n\tdata[locusNumber].sb = (double) sb;\n\tdata[locusNumber].d = (double) d;\n\tdata[locusNumber].lArray[0] = 666;\n\tlocusNumber++;\n      }\n    }\n    fclose(infile);\n  }\n}\n\n/* harmSum returns the denominator portion of Watterson's estimator */                         \ndouble harmSum(int n){\n  int i;\n  double sum = 0.0;\n\n  for(i = 1; i < n; i++){\n    sum += 1.0 /  i;\n  }\n  return(sum);\n}\n\n/* harmSumSquare is for calculating the variance of Watterson's estimator */\ndouble harmSumSquare(int n){\n  int i;\n  double sum = 0.0;\n\n  for(i = 1; i < n; i++){\n    sum += 1.0 / ( i * i);\n  }\n  return(sum);\n}\n\n/*setFunction- this sets up the multiroot function for solving */\nint setHKAFunction(const gsl_vector *x, void *p, gsl_vector *f){\n  double sumS, trueS, sumD, trueD, yi, trueYi;\n  double sumSb, trueSb;\n  int i;\n\n  /*set up all the equations. the first are the sum of segSites and sum of divergence respectively */\n  if (lineageNumber == 1){\n    sumS = yi = sumD = trueS = trueD =  0.0;\n    for(i = 0; i < locusNumber; i++){\n      sumS += data[i].length * harmSum(data[i].na) * gsl_vector_get(x,i);\n      sumD += data[i].length * (gsl_vector_get(x,locusNumber) + 1) * gsl_vector_get(x,i); \n      trueS += data[i].sa;\n      trueD += data[i].d;\n    }\n    gsl_vector_set(f,0,fabs(trueS - sumS));\n    gsl_vector_set(f,1,fabs(trueD - sumD));\n    //Sa+D eqns\n    for(i = 0; i < locusNumber - 1; i++){\n      trueYi = data[i].sa + data[i].d;\n      yi = gsl_vector_get(x,i) *\t\t\t\t\t\t\\\n\t((data[i].length * gsl_vector_get(x,locusNumber) +\t\t\\\n\t  data[i].length + (data[i].length * harmSum(data[i].na))));\n      gsl_vector_set(f,i+2,fabs(trueYi - yi));\n    }\n  } \n  else{\n    sumS = sumSb = yi = sumD = trueS = trueSb = trueD =  0.0;\n    for(i = 0; i < locusNumber; i++){\n      sumS += data[i].length * harmSum(data[i].na) * gsl_vector_get(x,i);\n      sumSb += data[i].length * harmSum(data[i].nb) * gsl_vector_get(x,i) * gsl_vector_get(x, locusNumber + 1);\n      sumD += data[i].length * (gsl_vector_get(x,locusNumber) + ((1.0 + gsl_vector_get(x,locusNumber+1)) / 2.0)) * gsl_vector_get(x,i);\n      trueS += data[i].sa;\n      trueSb += data[i].sb;\n      trueD += data[i].d;\n    }\n    gsl_vector_set(f,0,fabs(trueS - sumS));\n    gsl_vector_set(f,1,fabs(trueSb - sumSb));\n    gsl_vector_set(f,2,fabs(trueD - sumD));\n    //Sa+Sb+D eqns\n    for(i = 0; i < locusNumber - 1; i++){\n      trueYi = data[i].sa + data[i].sb + data[i].d;\n      yi = (data[i].length * (gsl_vector_get(x,locusNumber) + ((1.0 + gsl_vector_get(x,locusNumber+1)) / 2.0)) * gsl_vector_get(x,i)) \\\n\t+ ( data[i].length * harmSum(data[i].na) * gsl_vector_get(x,i)) + \\\n\t(data[i].length * harmSum(data[i].nb) * gsl_vector_get(x,i) * gsl_vector_get(x, locusNumber + 1));\n      gsl_vector_set(f,i+3,fabs(trueYi - yi));\n    }\n  }\n  return GSL_SUCCESS;\n}\n\nint solveSystem(gsl_vector *params){\n  const gsl_multiroot_fsolver_type *T;\n  gsl_multiroot_fsolver *s;\n  gsl_vector *x;\n  int status;\n  size_t  iter = 0;\n  void *point=NULL;\n  size_t n;\n\n  if (lineageNumber == 1){\n    n = locusNumber + 1;\n    x = gsl_vector_alloc(locusNumber + 1);\n  }\n  else{\n    n = locusNumber + 2;\n    x = gsl_vector_alloc(locusNumber + 2);\n  }\n \n  gsl_multiroot_function f = {&setHKAFunction, n, point};\n  gsl_vector_set_all(x, 1);\n  T = gsl_multiroot_fsolver_hybrids;\n  s = gsl_multiroot_fsolver_alloc(T, n);\n  gsl_multiroot_fsolver_set(s, &f, x);\n\n  do{\n    iter++;\n    status = gsl_multiroot_fsolver_iterate(s);\n    if(status){\n      break;\n    }\n    status = gsl_multiroot_test_residual(s->f, 1e-7);\n  }\n  while (status == GSL_CONTINUE && iter < 100);\n \n  gsl_vector_memcpy(params, s->x);\n  gsl_vector_free(x);\n  gsl_multiroot_fsolver_free (s);\n\n  return 0;\n}\n\n\n/* calculateHKA- this is the main beast that calculates estimates of t_hat, f(the ratio of popn sizes),\n and theta's for each locus. it returns the chi-square statistic, and takes pointers to the other \n relavent quantities (t_hat, etc.). */ \ndouble calculateHKA(gsl_vector *params,gsl_vector *chiSquares, gsl_vector *expectedPolyA, gsl_vector *expectedD){\n  double  chiSquared, chiSquared_i;\n  double expSA, expSB, varSA, varSB, expD, varD;\n  double hsA, hsB;\n  double devA, devB, devD,fHat;\n  int i;\n\n  if(lineageNumber > 1){\n    fHat = gsl_vector_get(params,locusNumber+1);\n  }\n  else{\n    fHat = 1.0;\n  }\n  chiSquared = 0.0;\n  for(i=0; i < locusNumber; i++){\n    hsA = harmSum(data[i].na);\n    hsB = harmSum(data[i].nb);\n    //calculate expectations and variances at the ith locus\n    expSA = gsl_vector_get(params,i) * data[i].length * hsA;\n    varSA = expSA + ((gsl_vector_get(params,i) * data[i].length) * (gsl_vector_get(params,i) * data[i].length) * harmSumSquare(data[i].na));\n    expSB =  gsl_vector_get(params,i) * fHat * data[i].length * hsB;\n    varSB = expSB + ((gsl_vector_get(params,i) * fHat * data[i].length) * (gsl_vector_get(params,i) * fHat * data[i].length) * harmSumSquare(data[i].nb)); // equals zero if no poly data from speciesB\n    expD = (gsl_vector_get(params,i) * data[i].length) * (gsl_vector_get(params,locusNumber) + (0.5 * (1.0 + fHat)));\n    varD = expD + (((gsl_vector_get(params,i) * data[i].length) * 0.5 * (1.0 + fHat)) * ((gsl_vector_get(params,i) *  data[i].length) * 0.5 * (1.0 + fHat)));\n    \n    //calculate deviations for species_a_theta, species_b_theta, and divergence. \n    // then add to chi-square stat\n    devA = ((data[i].sa - expSA) *  (data[i].sa - expSA)) / varSA;\n    devB = ((data[i].sb - expSB) *  (data[i].sb - expSB)) / varSB;  //careful here will not be number if no poly data for speciesB\n    devD = ((data[i].d - expD) * (data[i].d - expD)) / varD;\n    \n    //is deviation for species B finite?\n    if (isnan(devB)){\n      chiSquared_i = devA + devD;\n    }\n    else{\n      chiSquared_i = devA + devB + devD;\n    }\n    chiSquared += chiSquared_i;\n    gsl_vector_set(chiSquares,i,chiSquared_i);\n    gsl_vector_set(expectedPolyA, i, expSA);\n    gsl_vector_set(expectedD, i, expD);\n  }\n\n  return(chiSquared);\n}                    \n                         \n                         \n/* took this out of Jim Kent's tree */                         \nint chopByWhite(char *in, char *outArray[], int outSize)\n/* Like chopString, but specialized for white space separators. */\n{\nint recordCount = 0;\nchar c;\nfor (;;)\n    {\n    if (outArray != NULL && recordCount >= outSize)\n\tbreak;\n\n    /* Skip initial separators. */\n    while (isspace(*in)) ++in;\n    if (*in == 0)\n\tbreak;\n    \n    /* Store start of word and look for end of word. */    \n    if (outArray != NULL)\n\toutArray[recordCount] = in;\n    recordCount += 1;\n    for (;;)\n        {\n        if ((c = *in) == 0)\n            break;\n        if (isspace(c))\n            break;\n        ++in;\n        }\n    if (*in == 0)\n\tbreak;\n \n    /* Tag end of word with zero. */\n    if (outArray != NULL)\n\t*in = 0;\n    /* And skip over the zero. */\n    in += 1;\n    }\nreturn recordCount;\n}                         \n                                                  \n\n", "meta": {"hexsha": "287d019038e5ad5447b7cead421bb7e372991a6d", "size": 10509, "ext": "c", "lang": "C", "max_stars_repo_path": "hka.c", "max_stars_repo_name": "kern-lab/hka", "max_stars_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-06T02:12:05.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-06T02:12:05.000Z", "max_issues_repo_path": "hka.c", "max_issues_repo_name": "kern-lab/hka", "max_issues_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hka.c", "max_forks_repo_name": "kern-lab/hka", "max_forks_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_forks_repo_licenses": ["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.638483965, "max_line_length": 264, "alphanum_fraction": 0.6133790085, "num_tokens": 3320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.37491962894868525}}
{"text": "/*\n * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer\n *\n * Yan-Rong Li, liyanrong@mail.ihep.ac.cn\n * Jun 30, 2016\n *\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <stdbool.h>\n#include <gsl/gsl_rng.h>\n\n#include \"dnestvars.h\"\n \n/* output files */\nFILE *fsample, *fsample_info;\n\n/* random number generator */\nconst gsl_rng_type * dnest_gsl_T;\ngsl_rng * dnest_gsl_r;\n\nDNestOptions options;\nchar options_file[STR_MAX_LENGTH];\n\n// sampler\nbool save_to_disk;\ndouble compression;\nunsigned int regularisation;\n\nvoid *particles;\nint dnest_size_of_modeltype;\nint particle_offset_size, particle_offset_double;\n\nLikelihoodType *log_likelihoods;\nunsigned int *level_assignments;\n\n// number account of unaccepted times\nunsigned int *account_unaccepts;\n\nint size_levels, size_levels_combine;  \nLevel *levels;\nLevel *copies_of_levels, *levels_combine;\nLikelihoodType *all_above;\nunsigned int count_saves, num_saves, num_saves_restart;\nint dnest_which_particle_update; // which particle to be updated\nint dnest_which_level_update;    // which level to be updated;\nunsigned long long int count_mcmc_steps;\nLikelihoodType *above;\nunsigned int size_above, size_all_above;\n\ndouble post_logz;\nint dnest_num_params;\nchar dnest_sample_postfix[STR_MAX_LENGTH], dnest_sample_tag[STR_MAX_LENGTH], dnest_sample_dir[STR_MAX_LENGTH];\ndouble *dnest_param_range, *dnest_prior_info;\nint *dnest_prior_type;\nvoid *dnest_args;\n\ndouble *limits, *copies_of_limits;\n\nint dnest_thistask, dnest_totaltask;\nint *dnest_perturb_accept;\nint dnest_root;\n\nint dnest_flag_restart=0, dnest_flag_postprc=0, dnest_flag_sample_info=0, dnest_flag_limits=0;\ndouble dnest_post_temp=1.0;\nchar file_restart[STR_MAX_LENGTH], file_save_restart[STR_MAX_LENGTH];\n\n//***********************************************\n/*                  functions                  */\ndouble mod(double y, double x);\nvoid wrap_limit(double *x, double min, double max);\nint mod_int(int y, int x);\nint dnest_cmp(const void *pa, const void *pb);\n\nvoid options_load(char *optfile, DNestOptions *opts);\nvoid setup(int argc, char** argv, DNestFptrSet *fptrset, int num_params, \n           double *param_range, int *prior_type, double *prior_info, \n           char *sample_dir, char *optfile, DNestOptions *opts, void *args);\nvoid finalise();\n\nvoid dnest_run();\nvoid dnest_mcmc_run();\nvoid update_particle(unsigned int which);\nvoid update_level_assignment(unsigned int which);\ndouble log_push(unsigned int which_level);\nbool enough_levels(Level *l, int size_l);\nvoid do_bookkeeping();\nvoid save_levels();\nvoid save_particle();\nvoid save_limits();\nvoid kill_lagging_particles();\nvoid renormalise_visits();\nvoid recalculate_log_X();\nvoid dnest_postprocess(double temperature, char *optfile, DNestOptions *opts);\nvoid postprocess(double temperature);\nvoid initialize_output_file();\nvoid close_output_file();\nvoid dnest_save_restart();\nvoid dnest_restart();\nvoid dnest_restart_action(int iflag);\nvoid dnest_accept_action();\nvoid dnest_kill_action(int i, int i_copy);\nvoid dnest_from_prior(void *model);\ndouble dnest_perturb(void *model);\nvoid dnest_print_particle(FILE *fp, const void *model);\nvoid dnest_read_particle(FILE *fp, void *model);\n/*=====================================================*/\n// users responsible for following functions\nvoid (*print_particle)(FILE *fp, const void *model);\nvoid (*read_particle)(FILE *fp, void *model);\nvoid (*from_prior)(void *model);\ndouble (*log_likelihoods_cal)(const void *model);\ndouble (*log_likelihoods_cal_initial)(const void *model);\ndouble (*log_likelihoods_cal_restart)(const void *model);\ndouble (*perturb)(void *model);\nvoid (*restart_action)(int iflag);\nvoid (*accept_action)();\nvoid (*kill_action)(int i, int i_copy);\n/*=====================================================*/", "meta": {"hexsha": "967369f9f266b0a10198cc7b9eaaa287470c8279", "size": 3806, "ext": "c", "lang": "C", "max_stars_repo_path": "src/dnestvars.c", "max_stars_repo_name": "LiyrAstroph/CDNest", "max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z", "max_issues_repo_path": "src/dnestvars.c", "max_issues_repo_name": "LiyrAstroph/DNest_C", "max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z", "max_forks_repo_path": "src/dnestvars.c", "max_forks_repo_name": "LiyrAstroph/DNest_C", "max_forks_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_forks_repo_licenses": ["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.1967213115, "max_line_length": 110, "alphanum_fraction": 0.7422490804, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3749196223738778}}
{"text": "/*\nCopyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com>\nLicensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n*/\n\n#include <cblas.h>\n#include \"morn_tensor.h\"\n\nvoid _GetRowData0(float *tdata,float *data,int height,int width,int y_locate,int x_locate)\n{\n    if(y_locate<0)       {memset(data,0,width*sizeof(float)); return;}\n    if(y_locate>=height) {memset(data,0,width*sizeof(float)); return;}\n    \n    tdata = tdata+y_locate*width;\n    if(x_locate<0)\n    {\n        memset(data,0,(0-x_locate)*sizeof(float));\n        memcpy(data-x_locate,tdata,(width+x_locate)*sizeof(float));\n        return;\n    }\n    if(x_locate>0)\n    {\n        memcpy(data,tdata+x_locate,(width-x_locate)*sizeof(float));\n        memset(data+width-x_locate,0,x_locate*sizeof(float));\n        return;\n    }\n    memcpy(data,tdata,width*sizeof(float));\n}\nvoid _GetRowData(float *tdata,float *data,int height,int width,int y_locate,int x_locate,int stride)\n{\n    if(y_locate<0)       {memset(data,0,width/stride*sizeof(float)); return;}\n    if(y_locate>=height) {memset(data,0,width/stride*sizeof(float)); return;}\n\n    tdata = tdata+y_locate*width;\n    \n    int i=x_locate;int n=0;\n    for(;i<0                        ;i+=stride) {data[n]=0;       n++;}\n    for(;i<MIN(width,width+x_locate);i+=stride) {data[n]=tdata[i];n++;}\n    for(;i<width+x_locate           ;i+=stride) {data[n]=0;       n++;}\n}\n\nvoid _SetRowData(float *tdata,float *data,int height,int width,int y_locate,int x_locate,int stride)\n{\n    if(y_locate<0)       return;\n    if(y_locate>=height) return;\n\n    tdata = tdata+y_locate*width;\n    \n    int i=x_locate;int n=0;\n    for(;i<0                        ;i+=stride) {                  n++;}\n    for(;i<MIN(width,width+x_locate);i+=stride) {tdata[i]+=data[n];n++;}\n  //for(;i<width+x_locate           ;i+=stride) {                  n++;}\n}\n\nvoid ConvTensorToMatData0(MTensor *tns,int bc,float *mdata,int knl_height,int knl_width)\n{\n    int height = tns->height;\n    int width  = tns->width;\n    int channel= tns->channel;\n\n    // int mheight= knl_height*knl_width*channel+1;\n    int mwidth = width*height;\n\n    int x1=0-(knl_width /2);int x2=x1+knl_width -1;\n    int y1=0-(knl_height/2);int y2=y1+knl_height-1;\n\n    float *tdata = tns->data[bc];\n    for(int c=0;c<channel;c++)\n    {\n        int k=0;\n        {\n            for(int i=x1;i<=x2;i++)\n            {\n                float *data = mdata + k*mwidth;k++;\n                for(int n=y1;n<y1+height;n++) \n                {\n                    _GetRowData0(tdata,data,height,width,n,i); \n                    data+=width;\n                }\n            }\n        }\n        for(int j=y1+1+height-1;j<=y2+height-1;j++)\n        {\n            for(int i=x1;i<=x2;i++)\n            {\n                float *data = mdata + k*mwidth;k++;\n                memcpy(data,data-knl_width*mwidth+width,(mwidth-width)*sizeof(float));\n                _GetRowData0(tdata,data+(mwidth-width),height,width,j,i);\n            }\n        }\n        tdata+=width*height;\n        mdata+=mwidth*knl_height*knl_width;\n    }\n    for(int i=0;i<mwidth;i++) mdata[i]=1.0;\n}\n\nvoid ConvTensorToMatData(MTensor *tns,int bc,float *mdata,int knl_height,int knl_width,int y_stride,int x_stride)\n{\n    if((x_stride==1)&&(y_stride==1)) {ConvTensorToMatData0(tns,bc,mdata,knl_height,knl_width);return;}\n    \n    int height = tns->height;\n    int width  = tns->width;\n    int channel= tns->channel;\n\n    int out_width = width/x_stride;\n    int out_height=height/y_stride;\n    // int mheight= knl_height*knl_width*channel+1;\n    int mwidth = out_width*out_height;\n\n    int x1=0-(knl_width /2);int x2=x1+knl_width -1;\n    int y1=0-(knl_height/2);int y2=y1+knl_height-1;\n\n    float *tdata = tns->data[bc];\n    for(int c=0;c<channel;c++)\n    {\n        int k=0;\n        for(int j=y1;j<=y2;j++)for(int i=x1;i<=x2;i++)\n        {\n            float *data = mdata + k*mwidth;k++;\n            for(int n=j;n<j+height;n+=y_stride) \n            {\n                _GetRowData(tdata,data,height,width,n,i,x_stride); \n                data+=out_width;\n            }\n        }\n        tdata+=width*height;\n        mdata+=mwidth*knl_height*knl_width;\n    }\n    for(int i=0;i<mwidth;i++) mdata[i]=1.0;\n}\n\nvoid ConvMatDataToTensor(float *mdata,MTensor *tns,int bc,int knl_height,int knl_width,int y_stride,int x_stride)\n{\n    int height = tns->height;\n    int width  = tns->width;\n    int channel= tns->channel;\n    \n    int out_width = width/x_stride;\n    int out_height=height/y_stride;\n    // int mheight= knl_height*knl_width*channel+1;\n    int mwidth = out_height*out_width;\n\n    // printf(\"height=%d,width=%d,channel=%d,out_height=%d,out_width=%d\\n\",height,width,channel,out_height,out_width);\n\n    int x1=0-(knl_width /2);int x2=x1+knl_width -1;\n    int y1=0-(knl_height/2);int y2=y1+knl_height-1;\n\n    float *tdata = tns->data[bc];\n\n    for(int c=0;c<channel;c++)\n    {\n        int k=0;\n        for(int j=y1;j<=y2;j++)for(int i=x1;i<=x2;i++)\n        {\n            float *data = mdata + k*mwidth;k++;\n            for(int n=j;n<j+height;n+=y_stride) \n            {\n                _SetRowData(tdata,data,height,width,n,i,x_stride); \n                data+=out_width;\n            }\n        }\n        tdata+=width*height;\n        mdata+=mwidth*knl_height*knl_width;\n    }\n}\n\nstruct TensorConvPara\n{\n    MLayer *prev;\n    \n    int knl_num;\n    int knl_height;\n    int knl_width;\n    \n    int x_stride;\n    int y_stride;\n    \n    int res_valid;\n    \n    float rate;\n    float decay;\n    float momentum;\n};\nvoid *mTensorConvPara(MFile *ini,char *name)\n{\n    struct TensorConvPara *para = (struct TensorConvPara *)mMalloc(sizeof(struct TensorConvPara));\n   \n    para->prev = mNetworkLayer(ini,mINIRead(ini,name,\"prev\"));\n    mException((para->prev == NULL),EXIT,\"invalid prev\");\n    para->res_valid = (strcmp(\"Input\",mLayerType(para->prev))!=0);\n    \n    para->knl_num   = 1; mINIRead(ini,name,\"knl_num\"   ,\"%d\",&(para->knl_num   ));\n    para->knl_height= 1; mINIRead(ini,name,\"knl_height\",\"%d\",&(para->knl_height));\n    para->knl_width = 1; mINIRead(ini,name,\"knl_width\" ,\"%d\",&(para->knl_width ));\n    para->x_stride  = 1; mINIRead(ini,name,\"x_stride\"  ,\"%d\",&(para->x_stride  ));\n    para->y_stride  = 1; mINIRead(ini,name,\"y_stride\"  ,\"%d\",&(para->y_stride  ));\n    \n    para->rate    =0.001;if(mINIRead(ini,name,\"rate\"    ,\"%f\",&(para->rate    ))==NULL) mINIRead(ini,\"para\",\"rate\"    ,\"%f\",&(para->rate    ));\n    para->momentum=0.9  ;if(mINIRead(ini,name,\"momentum\",\"%f\",&(para->momentum))==NULL) mINIRead(ini,\"para\",\"momentum\",\"%f\",&(para->momentum));\n    para->decay   =0.01 ;if(mINIRead(ini,name,\"decay\"   ,\"%f\",&(para->decay   ))==NULL) mINIRead(ini,\"para\",\"decay\"   ,\"%f\",&(para->decay   ));\n    mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,\"invalid para decay\");\n\n    return para;\n}\n\nstruct HandleTensorConv\n{\n    float *mat;\n    float *kernel;\n    float *update;\n};\nvoid endTensorConv(void *info)\n{\n    struct HandleTensorConv *handle = (struct HandleTensorConv *)info;\n    if(handle->mat   != NULL) mFree(handle->mat);\n    if(handle->kernel!= NULL) mFree(handle->kernel);\n    if(handle->update!= NULL) mFree(handle->update);\n}\n#define HASH_TensorConv 0x9087d39c\nvoid TensorConvSet(MLayer *layer)\n{\n    if(layer->state != DFLT) return;\n    // mException(strcmp(\"Conv\",mLayerType(layer)),EXIT,\"invalid layer type\");\n    struct TensorConvPara *para = (struct TensorConvPara *)(layer->para);\n    MTensor *in = para->prev->tns;\n    MTensor *res= para->prev->res;\n    MTensor *out= layer->tns;\n    \n    MHandle *hdl=mHandle(out,TensorConv);\n    struct HandleTensorConv *handle = (struct HandleTensorConv *)(hdl->handle);\n    \n    int out_height= in->height/para->y_stride;\n    int out_width = in->width /para->x_stride;\n    int mwidth = (out_height*out_width);\n    int mheight= para->knl_height*para->knl_width*in->channel+1;\n    int data_size = para->knl_num*mheight;\n    \n    mTensorRedefine(out,in->batch,para->knl_num,out_height,out_width,NULL);\n    if(morn_network_flag == MORN_TRAIN)\n    {\n        if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);\n        else                    \n        {\n            // printf(\"llllllllllllllllllllllllll layer->name=%s\\n\",layer->name);\n            mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);\n        }\n\n        if(morn_network_flag==MORN_TRAIN)\n        {\n            if(handle->update != NULL) mFree(handle->update);\n            handle->update =(float *)mMalloc(data_size*sizeof(float));\n            memset(handle->update,0,data_size*sizeof(float));\n        }\n    }\n    \n    if(handle->kernel !=NULL) mFree(handle->kernel);\n    handle->kernel = (float *)mMalloc(data_size*sizeof(float));\n    \n    if(morn_network_parafile==NULL)\n    {\n        float scale = sqrt(2.0f/mheight);\n        for(int i=0;i<data_size;i++)\n            handle->kernel[i] = mNormalRand(0.0f,1.0f)*scale;\n    }\n    else\n    {\n        mNetworkParaRead(layer,\"kernel\",handle->kernel,data_size*sizeof(float));\n    }\n    \n    if(handle->mat!=NULL) mFree(handle->mat);\n    handle->mat = (float *)mMalloc(mheight*mwidth*sizeof(float));\n    \n    hdl->valid = 1;\n}\n\nvoid mTensorConvForward(MLayer *layer)\n{\n    mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n    struct TensorConvPara *para = (struct TensorConvPara *)(layer->para);\n    \n    MTensor *in = para->prev->tns;\n    MTensor *out=layer->tns;\n    // printf(\"in->data[0][0]=%f\\n\",in->data[0][0]);\n    \n    TensorConvSet(layer);\n    \n    MHandle *hdl=mHandle(out,TensorConv);\n    struct HandleTensorConv *handle = (struct HandleTensorConv *)(hdl->handle);\n    \n    int mwidth = (out->height*out->width);\n    int mheight= para->knl_height*para->knl_width*in->channel+1;\n    \n    float *kernel_data= handle->kernel;\n    float *in_data = handle->mat;\n    \n    for(int b=0;b<in->batch;b++)\n    {\n        // printf(\"ccccccccccccccc in->width=%d\\n\",in->width);\n        ConvTensorToMatData(in,b,in_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);\n        // printf(\"ccccccccccccccc in->width=%d\\n\",in->width);\n        float *out_data = out->data[b];\n\n        // printf(\"\\nweight=\\n\");for(int ii=0;ii<100;ii++) printf(\"%f,\",kernel_data[ii]);\n        // printf(\"\\ndata=\\n\");for(int ii=0;ii<100;ii++) printf(\"%f,\",in_data[ii]*255);\n        // printf(\"\\ndata2352=\\n\");for(int ii=2352;ii<2352+100;ii++) printf(\"%f,\",in_data[ii]*255);\n        // printf(\"\\ndata6272=\\n\");for(int ii=6272;ii<6272+100;ii++) printf(\"%f,\",in_data[ii]*255);\n        // printf(\"\\ndata10192=\\n\");for(int ii=10192;ii<10192+100;ii++) printf(\"%f,\",in_data[ii]*255);\n        // printf(\"\\ndata=\\n\");for(int ii=784*5;ii<784*5+100;ii++) printf(\"%f,\",in_data[ii]*255);\n        // printf(\"\\ndata=\\n\");for(int ii=784*25;ii<784*25+100;ii++) printf(\"%f,\",in_data[ii]*255);\n        // printf(\"\\ndata=\\n\");for(int ii=10000;ii<10000+100;ii++) printf(\"%f,\",in_data[ii]*255);\n\n        // float sum=0;\n        // for(int ii=0;ii<75;ii++)\n        // {\n        //     sum+=(kernel_data[ii]*in_data[mwidth*ii]);\n        //     printf(\"a[ii]=%f,b[n*ii]=%f,sum=%f,ii=%d,ii*mwidth=%d\\n\",kernel_data[ii],in_data[mwidth*ii]*255,sum,ii,ii*mwidth);\n        // }\n        // printf(\"\\nsum=%f\\n\",sum);\n\n        // printf(\"para->knl_num=%d,mwidth=%d,mheight=%d\\n\",para->knl_num,mwidth,mheight);\n        cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,\n                    para->knl_num,mwidth,mheight,\n                    1.0f,\n                    kernel_data,mheight,\n                        in_data,mwidth,\n               0.0f,   out_data,mwidth);\n\n        // printf(\"\\nout=\\n\");for(int ii=00;ii<200;ii++) printf(\"%f,\",out_data[ii]);\n    }\n    \n    layer->state = MORN_FORWARD;\n}\n\nvoid mTensorConvBackward(MLayer *layer)\n{\n    mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n    struct TensorConvPara *para = (struct TensorConvPara *)(layer->para);\n    MTensor *in = para->prev->tns;\n    MTensor *res= para->prev->res;\n    MTensor *out=layer->res;\n    \n    MHandle *hdl=mHandle(layer->tns,TensorConv);\n    struct HandleTensorConv *handle = (struct HandleTensorConv *)(hdl->handle);\n    mException((hdl->valid == 0),EXIT,\"no forward operate\");\n    \n    int mwidth = (out->height*out->width);\n    int mheight= para->knl_height*para->knl_width*in->channel+1;\n    \n    float *kernel_data= handle->kernel;\n    float *update_data= handle->update;\n    float *    in_data= handle->mat;\n    float *   res_data= handle->mat;\n    \n    mNetworkParaWrite(layer,\"kernel\",kernel_data,para->knl_num*mheight*sizeof(float));\n\n    float beta = para->momentum;\n    for(int b=0;b<out->batch;b++)\n    {\n        ConvTensorToMatData(in,b,in_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);\n        float *out_data = out->data[b];\n\n        // printf(\"m=%d,n=%d,k=%d\\n\",para->knl_num,mheight,mwidth);\n        // printf(\"\\ndelta=\\n\");for(int ii=00;ii<200;ii++) printf(\"%f,\",0-2*out_data[ii]);\n        // printf(\"\\nin=\\n\");for(int ii=00;ii<200;ii++) printf(\"%f,\",in_data[ii]);\n        // printf(\"\\nupdate0=\\n\");for(int ii=00;ii<75;ii++) printf(\"%f,\",0-update_data[ii]*2*beta);\n        cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,\n                    para->knl_num,mheight,mwidth,\n                    1.0f,//1.0f/mwidth,\n                       out_data,mwidth,\n                        in_data,mwidth,\n                    beta,\n                    update_data,mheight);\n\n        // printf(\"\\nupdate1=\\n\");for(int ii=00;ii<75;ii++) printf(\"%f,\",0-update_data[ii]*2);\n        // printf(\"\\nupdate=\\n\");for(int ii=760;ii<760+75;ii++) printf(\"%f,\",update_data[ii]);\n        // printf(\"\\nbias_updates=\\n\");for(int ii=0;ii<32;ii++) printf(\"%f,\",update_data[ii*76+75]);\n\n        beta = 1.0;\n    }\n    // for(int i=0;i<28;i++)printf(\"%f,\",in_data[i]);printf(\"\\n\");\n    // for(int i=0;i<8;i++) printf(\"%f,\",kernel_data[i]);\n    // printf(\"aaaaaaaaaaa,para->knl_num=%d,mwidth=%d\\n\",para->knl_num,mwidth);\n    \n    if(para->res_valid)\n    {\n        // if(para->prev->state == MORN_FORWARD)\n        // {\n        //     printf(\"conv res set 0,conv res set 0,conv res set 0,conv res set 0,conv res set 0res->batch=%d\\n\",res->batch);\n        //     for(int b=0;b<res->batch;b++)\n                \n            \n        // }\n\n        for(int b=0;b<in->batch;b++)\n        {\n            float *out_data = out->data[b];\n\n            if(para->prev->state == MORN_FORWARD)\n                memset(res->data[b],0,in->height*in->width*in->channel*sizeof(float));\n                \n            // printf(\"\\nconvdelta=\\n\");for(int ii=200;ii<400;ii++) printf(\"%f,\",out_data[ii]);\n            // printf(\"\\nconvkernel=\\n\");for(int ii=00;ii<200;ii++) printf(\"%f,\",kernel_data[ii]);\n            \n            cblas_sgemm(CblasRowMajor,CblasTrans,CblasNoTrans,\n                        mheight,mwidth,para->knl_num,\n                        1.0f,\n                        kernel_data,mheight,\n                           out_data,mwidth,\n                    0.0,   res_data,mwidth);\n\n            // printf(\"\\nconvdeltaout=\\n\");for(int ii=00;ii<200;ii++) printf(\"%f,\",0-res_data[ii]*2);\n            \n            ConvMatDataToTensor(res_data,res,b,para->knl_height,para->knl_width,para->y_stride,para->x_stride);\n\n            // printf(\"mheight=%d,mwidth=%d\\n\",mheight,mwidth);\n            // printf(\"\\nconvimd=\\n\");for(int ii=200;ii<400;ii++) printf(\"%f,\",res->data[0][ii]);\n        }\n\n        para->prev->state = MORN_BACKWARD;\n    }\n\n    // printf(\"\\nkernel_data0=\\n\");for(int ii=0;ii<200;ii++) printf(\"%f,\",kernel_data[ii]);\n    // printf(\"\\nupdate_data=\\n\");for(int ii=0;ii<200;ii++) printf(\"%f,\",update_data[ii]);\n    // printf(\"%s:update_data=%f,kernel_data=%f,%f\\n\",layer->name,update_data[10],kernel_data[10],kernel_data[10]-(para->rate/(float)(in->batch))*update_data[10]);\n    cblas_saxpby(para->knl_num*mheight,\n                 (0.0f-(para->rate/(float)(in->batch))),update_data,1, \n                 (1.0f-(para->decay*para->rate))       ,kernel_data,1);\n                 \n    // printf(\"\\nkernel_data1=\\n\");for(int ii=0;ii<200;ii++) printf(\"%f,\",kernel_data[ii]);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid GroupConvTensorToMatData(MTensor *tns,int bc,float *mdata,int knl_channel,int knl_height,int knl_width,int c_stride,int y_stride,int x_stride)\n{\n    int height = tns->height;\n    int width  = tns->width;\n    int channel= tns->channel;\n    \n    int out_width  =  width/x_stride;\n    int out_height = height/y_stride;\n    int out_channel=(channel-knl_channel/2+1)/c_stride;\n    int mwidth = knl_height*knl_width*knl_channel+1;\n    int mheight= out_height*out_width;\n    \n    int x0=(width -(out_width -1)*x_stride)/2;\n    int y0=(height-(out_height-1)*y_stride)/2;\n    \n    float *tdata = tns->data[bc];\n    int tsize = tns->height*tns->width;\n    \n    int k,i,j,c;\n    for(k=0;k<out_channel;k++)\n    {\n        for(j=0;j<out_width;j++)\n        {\n            int n=y0           -knl_height/2;\n            int m=x0+j*x_stride-knl_width /2;\n            for(i=0;i<mwidth-1;i+=knl_channel)\n            {\n                int h= i/(knl_width*knl_channel)             +n;if(h<0)h=0;else if(h>=height)h=height-1;\n                int w=(i%(knl_width*knl_channel))/knl_channel+m;if(w<0)w=0;else if(w>= width)w= width-1;\n                for(c=0;c<knl_channel;c++)\n                    mdata[(k*mheight+j)*mwidth+i+c]=tdata[MIN((c+k*c_stride),channel-1)*tsize+h*width+w];\n            }\n            mdata[(k*mheight+j)*mwidth+mwidth-1]=1.0f;\n        }\n        for(j=out_width;j<mheight;j++)\n        {\n            int num=MAX(0,(knl_height-y_stride))*knl_width*knl_channel;\n            if(num>0) memcpy(mdata+(k*mheight+j)*mwidth,mdata+((k*mheight+j)-out_width)*mwidth+y_stride*knl_width*knl_channel,num*sizeof(float));\n            \n            int n=y0+j/out_width*y_stride-knl_height/2;\n            int m=x0+j%out_width*x_stride-knl_width /2;\n            for(i=num;i<mwidth-1;i+=knl_channel)\n            {\n                int h= i/(knl_width*knl_channel)             +n;if(h<0)h=0;else if(h>=height)h=height-1;\n                int w=(i%(knl_width*knl_channel))/knl_channel+m;if(w<0)w=0;else if(w>= width)w= width-1;\n                for(c=0;c<knl_channel;c++)\n                    mdata[(k*mheight+j)*mwidth+i+c]=tdata[MIN((c+k*c_stride),channel-1)*tsize+h*width+w];\n            }\n            mdata[(k*mheight+j)*mwidth+mwidth-1]=1.0f;\n        }\n    }\n}\n\nvoid GroupConvMatDataToTensor(float *mdata,MTensor *tns,int bc,int knl_channel,int knl_height,int knl_width,int c_stride,int y_stride,int x_stride)\n{\n    int height = tns->height;\n    int width  = tns->width;\n    int channel= tns->channel;\n    \n    int out_width = width/x_stride;\n    int out_height=height/y_stride;\n    int out_channel=(channel-knl_channel/2+1)/c_stride;\n    int mwidth = knl_height*knl_width*knl_channel+1;\n    int mheight= out_height*out_width;\n    \n    int x0=(width -(out_width -1)*x_stride)/2;\n    int y0=(height-(out_height-1)*y_stride)/2;\n    \n    float *tdata = tns->data[bc];\n    int tsize = tns->height*tns->width;\n    \n    int k,i,j,c;\n    for(k=0;k<out_channel;k++)for(j=0;j<mheight;j++)\n    {\n        int n=y0+j/out_width*y_stride+knl_height/2+1-knl_height;\n        int m=x0+j%out_width*x_stride+knl_width /2+1-knl_width ;\n        for(i=0;i<mwidth-1;i+=knl_channel)\n        {\n            int h= i/(knl_width*knl_channel)             +n;if(h<0)h=0;else if(h>=height)h=height-1;\n            int w=(i%(knl_width*knl_channel))/knl_channel+m;if(w<0)w=0;else if(w>= width)w= width-1;\n            for(c=0;c<knl_channel;c++)\n                tdata[MIN((c+k*c_stride),channel-1)*tsize+h*width+w]+=mdata[(k*mheight+j)*mwidth+i+c];\n        }\n    }\n}\n\nstruct TensorGroupConvPara\n{\n    MLayer *prev;\n    \n    int knl_num;\n    int knl_height;\n    int knl_width;\n    \n    int x_stride;\n    int y_stride;\n    \n    int res_valid;\n    \n    float rate;\n    float decay;\n    float momentum;\n    \n    int knl_channel;\n    int c_stride;\n};\nvoid *mTensorGroupConvPara(MFile *ini,char *name)\n{\n    struct TensorGroupConvPara *para = (struct TensorGroupConvPara *)mMalloc(sizeof(struct TensorConvPara));\n   \n    char *value = mINIRead(ini,name,\"prev\");\n    para->prev = mNetworkLayer(ini,value);\n    mException((para->prev == NULL),EXIT,\"invalid prev\");\n    \n    para->res_valid = (strcmp(\"Input\",mLayerType(para->prev))!=0);\n    \n    value = mINIRead(ini,name,\"knl_num\");\n    if(value != NULL) para->knl_num= atoi(value);else para->knl_num= 1;\n    \n    value = mINIRead(ini,name,\"knl_channel\");\n    if(value != NULL) para->knl_channel= atoi(value);else para->knl_channel= DFLT;\n    \n    value = mINIRead(ini,name,\"knl_height\");\n    if(value != NULL) para->knl_height= atoi(value);else para->knl_height= 1; \n    \n    value = mINIRead(ini,name,\"knl_width\");\n    if(value != NULL) para->knl_width= atoi(value);else para->knl_width= 1; \n    \n    value = mINIRead(ini,name,\"c_stride\");\n    if(value != NULL) para->c_stride= atoi(value);else para->c_stride= para->knl_channel;\n    \n    value = mINIRead(ini,name,\"x_stride\");\n    if(value != NULL) para->x_stride= atoi(value);else para->x_stride= 1;\n    \n    value = mINIRead(ini,name,\"y_stride\");\n    if(value != NULL) para->y_stride= atoi(value);else para->y_stride= 1;\n    \n    value = mINIRead(ini,name,\"rate\");\n    if(value != NULL) para->rate = atof(value);\n    else\n    {\n        value = mINIRead(ini,\"para\",\"rate\");\n        if(value != NULL) para->rate = atof(value);\n        else              para->rate = 0.001;\n    }\n    \n    value = mINIRead(ini,name,\"decay\");\n    if(value != NULL) para->decay = atof(value);\n    else\n    {\n        value = mINIRead(ini,\"para\",\"decay\");\n        if(value != NULL) para->decay = atof(value);\n        else              para->decay = 0.01;\n    }\n    mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,\"invalid para decay\");\n    \n    value = mINIRead(ini,name,\"momentum\");\n    if(value != NULL) para->momentum = atof(value); \n    else\n    {\n        value = mINIRead(ini,\"para\",\"momentum\");\n        if(value != NULL) para->momentum = atof(value);\n        else              para->momentum = 0.9;\n    }\n\n    return para;\n}\n\nstruct HandleTensorGroupConv\n{\n    float *mat;\n    float *kernel;\n    float *update;\n};\nvoid endTensorGroupConv(void *info)\n{\n    struct HandleTensorGroupConv *handle = (struct HandleTensorGroupConv *)info;\n    if(handle->mat   != NULL) mFree(handle->mat);\n    if(handle->kernel!= NULL) mFree(handle->kernel);\n    if(handle->update!= NULL) mFree(handle->update);\n}\n#define HASH_TensorGroupConv 0x82866393\nvoid TensorGroupConvSet(MLayer *layer)\n{\n    if(layer->state != DFLT) return;\n    \n    struct TensorGroupConvPara *para = (struct TensorGroupConvPara *)(layer->para);\n    if(para->knl_channel<=0) \n    {\n        layer->type_index=mTensorRegisterIndex(\"Conv\");\n        return;\n    }\n    \n    MTensor *in = para->prev->tns;\n    MTensor *res= para->prev->res;\n    MTensor *out= layer->tns;\n    \n    MHandle *hdl=mHandle(out,TensorGroupConv);\n    struct HandleTensorGroupConv *handle = (struct HandleTensorGroupConv *)(hdl->handle);\n    \n    int out_height= in->height/para->y_stride;\n    int out_width = in->width /para->x_stride;\n    int out_channel=(in->channel-para->knl_channel/2+1)/para->c_stride;\n\n    int mheight = (out_height*out_width*out_channel);\n    int mwidth = para->knl_height*para->knl_width*para->knl_channel+1;\n    int data_size = para->knl_num*mwidth;\n    \n    mTensorRedefine(out,in->batch,para->knl_num*out_channel,out_height,out_width,NULL);\n    if(morn_network_flag == MORN_TRAIN)\n    {\n        if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);\n        else                    mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);\n   \n        if(handle->update != NULL) mFree(handle->update);\n        handle->update =(float *)mMalloc(data_size*sizeof(float));\n        memset(handle->update,0,data_size*sizeof(float));\n    }\n    \n    if(handle->kernel !=NULL) mFree(handle->kernel);\n    handle->kernel = (float *)mMalloc(data_size*sizeof(float));\n    \n    if(morn_network_parafile==NULL)\n    {\n        float scale = sqrt(2.0f/mwidth);\n        for(int i=0;i<data_size;i++)\n            handle->kernel[i] = scale*mNormalRand(0.0f,1.0f);\n    }\n    else\n    {\n        mNetworkParaRead(layer,\"kernel\",handle->kernel,data_size*sizeof(float));\n    }\n    \n    if(handle->mat!=NULL) mFree(handle->mat);\n    handle->mat = (float *)mMalloc(mheight*mwidth*sizeof(float));\n    \n    hdl->valid = 1;\n}\n\nvoid mTensorGroupConvForward(MLayer *layer)\n{\n    mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n    struct TensorGroupConvPara *para = (struct TensorGroupConvPara *)(layer->para);\n    if(para->knl_channel<=0) return mTensorConvForward(layer);\n    \n    mException(strcmp(\"GroupConv\",mLayerType(layer)),EXIT,\"invalid layer type\");\n    \n    MTensor *in = para->prev->tns;\n    MTensor *out=layer->tns;\n    \n    TensorGroupConvSet(layer);\n    \n    MHandle *hdl=mHandle(out,TensorGroupConv);\n    struct HandleTensorGroupConv *handle = (struct HandleTensorGroupConv *)(hdl->handle);\n    \n    int out_channel=(in->channel-para->knl_channel/2+1)/para->c_stride;\n    int mheight = (out->height*out->width*out_channel);\n    int mwidth = para->knl_height*para->knl_width*para->knl_channel+1;\n    \n    float *kernel_data= handle->kernel;\n    float *in_data = handle->mat;\n    \n    for(int b=0;b<in->batch;b++)\n    {\n        GroupConvTensorToMatData(in,b,in_data,para->knl_channel,para->knl_height,para->knl_width,para->c_stride,para->y_stride,para->x_stride);\n        float *out_data = out->data[b];\n        \n        in_data[mwidth-1]=1.0f;\n    \n        cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,\n                    para->knl_num,mheight,mwidth,\n                    1.0f,\n                    kernel_data,mwidth,\n                        in_data,mwidth,\n               0.0f,   out_data,mheight);\n    }\n    \n    layer->state = MORN_FORWARD;\n}\n\nvoid mTensorGroupConvBackward(MLayer *layer)\n{\n    mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n    struct TensorGroupConvPara *para = (struct TensorGroupConvPara *)(layer->para);\n    if(para->knl_channel<=0) return mTensorConvBackward(layer);\n    \n    mException(strcmp(\"GroupConv\",mLayerType(layer)),EXIT,\"invalid layer type\");\n    \n    MTensor *in = para->prev->tns;\n    MTensor *res= para->prev->res;\n    MTensor *out=layer->res;\n    \n    MHandle *hdl=mHandle(layer->tns,TensorGroupConv);\n    struct HandleTensorGroupConv *handle = (struct HandleTensorGroupConv *)(hdl->handle);\n    mException((hdl->valid == 0),EXIT,\"no forward operate\");\n    \n    int out_channel=(in->channel-para->knl_channel/2+1)/para->c_stride;\n    int mheight = (out->height*out->width*out_channel);\n    int mwidth = para->knl_height*para->knl_width*para->knl_channel+1;\n    \n    float *kernel_data= handle->kernel;\n    float *update_data= handle->update;\n    float *    in_data= handle->mat;\n    float *   res_data= handle->mat;\n    \n    mNetworkParaWrite(layer,\"kernel\",kernel_data,para->knl_num*mwidth*sizeof(float));\n    \n    for(int b=0;b<in->batch;b++)\n    {\n        GroupConvTensorToMatData(in,b,in_data,para->knl_channel,para->knl_height,para->knl_width,para->c_stride,para->y_stride,para->x_stride);\n        float *out_data = out->data[b];\n        \n        in_data[mwidth-1]=1.0f;\n    \n        cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,\n                    para->knl_num,mwidth,mheight,\n                    1.0f,\n                       out_data,mheight,\n                        in_data,mwidth,\n                    (b==0)?para->momentum:1.0f,\n                    update_data,mwidth);\n    }\n    cblas_saxpby(para->knl_num*mwidth,\n                 (0.0f-(para->rate/(float)(in->batch))),update_data,1, \n                 (1.0f-(para->rate*para->decay))       ,kernel_data,1);\n    \n    if(para->res_valid==0) return;\n    \n    if(para->prev->state == MORN_FORWARD)\n    {\n        for(int b=0;b<res->batch;b++) \n            memset(res->data[b],0,in->height*in->width*in->channel*sizeof(float));\n        para->prev->state = MORN_BACKWARD;\n    }\n    \n    for(int b=0;b<in->batch;b++)\n    {\n        float *out_data = out->data[b];\n        \n        cblas_sgemm(CblasRowMajor,CblasTrans,CblasNoTrans,\n                    mheight,mwidth,para->knl_num,\n                    1.0f,\n                       out_data,mheight,\n                    kernel_data,mwidth,\n                0.0,   res_data,mwidth);\n        \n        GroupConvMatDataToTensor(res_data,res,b,para->knl_channel,para->knl_height,para->knl_width,para->c_stride,para->y_stride,para->x_stride);\n    }\n}", "meta": {"hexsha": "e3ecdae8d493f4c18049a05c1fa17043811df667", "size": 29034, "ext": "c", "lang": "C", "max_stars_repo_path": "src/deep_learning/morn_tensor_conv.c", "max_stars_repo_name": "Shaka0723/Morn", "max_stars_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/deep_learning/morn_tensor_conv.c", "max_issues_repo_name": "Shaka0723/Morn", "max_issues_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/deep_learning/morn_tensor_conv.c", "max_forks_repo_name": "Shaka0723/Morn", "max_forks_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T08:08:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T08:08:02.000Z", "avg_line_length": 37.1278772379, "max_line_length": 501, "alphanum_fraction": 0.5935454984, "num_tokens": 8520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.37469151253082894}}
{"text": "#ifndef GBNET_RVNODE\n#define GBNET_RVNODE\n\n\n#include <string>\n#include <vector>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_histogram.h>\n#include <gsl/gsl_rstat.h>\n\nextern gsl_rng *rng;\n\n\nnamespace gbn\n{\n\n    class RVNode\n    {\n        private:\n\n        protected:\n\n        public:\n\n            unsigned int var_size, n_outcomes, n_stats;\n            bool is_discrete;\n            std::string name, uid, id;\n\n            // // allow for several histograms in a single node.\n            // // useful for multivariate distributions\n            // gsl_histogram ** histogram;\n\n            // online statistics\n            gsl_rstat_workspace ** stats;\n\n            RVNode ();\n            virtual ~RVNode ();\n            RVNode (std::string, std::string, bool, unsigned int, unsigned int);\n\n            void print_id ();\n            void burn_stats();\n\n            virtual double get_own_likelihood ();\n            double get_own_loglikelihood ();\n            virtual double get_children_loglikelihood ();\n            double get_blanket_loglikelihood ();\n\n            virtual void sample (gsl_rng *, bool=false);\n\n            double mean(unsigned int = 0);\n            double variance(unsigned int = 0);\n            double chain_length();\n    };\n}\n\n#endif", "meta": {"hexsha": "14b194ed9d26e9b2663b762aa44ef6c533ce87a0", "size": 1250, "ext": "h", "lang": "C", "max_stars_repo_path": "libgbnet/include/RVNode.h", "max_stars_repo_name": "umbibio/gbnet", "max_stars_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libgbnet/include/RVNode.h", "max_issues_repo_name": "umbibio/gbnet", "max_issues_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libgbnet/include/RVNode.h", "max_forks_repo_name": "umbibio/gbnet", "max_forks_repo_head_hexsha": "0e478d764cfa02eaed3e32d11d03c240c78e2ff6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-10T16:19:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-10T16:19:58.000Z", "avg_line_length": 22.3214285714, "max_line_length": 80, "alphanum_fraction": 0.572, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.37466060905163084}}
{"text": "#include <gsl/gsl_math.h>\n#include <gsl/gsl_cblas.h>\n#include \"cblas.h\"\n\nvoid\ncblas_srotg (float *a, float *b, float *c, float *s)\n{\n#define BASE float\n#include \"source_rotg.h\"\n#undef BASE\n}\n", "meta": {"hexsha": "65b279641e95e91464f5f8681aba86b96f2cd0d1", "size": 191, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-an/cblas/srotg.c", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "gsl-an/cblas/srotg.c", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "gsl-an/cblas/srotg.c", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 15.9166666667, "max_line_length": 52, "alphanum_fraction": 0.7015706806, "num_tokens": 65, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3744900375298139}}
{"text": "#ifndef SCOL_H\n#define SCOL_H\n#include \"Common.h\"\n// SP_IVP.h\n// Spherical Collapse IVP\n//#include <omp.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_deriv.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n#include <cvode/cvode.h>               /* prototypes for CVODE fcts., consts.  */\n#include <nvector/nvector_serial.h>    /* access to serial N_Vector            */\n#include <sunmatrix/sunmatrix_dense.h> /* access to dense SUNMatrix            */\n#include <sunlinsol/sunlinsol_dense.h> /* access to dense SUNLinearSolver      */\n#include <cvode/cvode_direct.h>        /* access to CVDls interface            */\n#include <sundials/sundials_types.h>   /* defs. of realtype, sunindextype      */\n#include <sundials/sundials_math.h>    /* contains the macros ABS, SUNSQR, EXP */\n\n#define Ith(v,i)    NV_Ith_S(v,i-1)         /* Ith numbers components 1..NEQ */\n#define IJth(A,i,j) SM_ELEMENT_D(A,i-1,j-1) /* IJth numbers rows,cols 1..NEQ */\n\n#define NEQ     2                /* number of equations  */\n#define Y1      RCONST(0.0)      /* initial y components */\n#define RTOL    RCONST(1.0e-5)   /* scalar relative tolerance            */\n#define ATOL1   RCONST(1.0e-11)   /* vector absolute tolerance components */\n#define ATOL2   RCONST(1.0e-11)\n#define T00      RCONST(-10.41431317630211772495840705232694745063781738281250)      /* initial time           */\n#define NOUT    1024               /* number of output times */\n#define NOUT_DC    10               /* number of output times */\n\n#define HALF    RCONST(0.5)      /* 0.5                    */\n#define ONE     RCONST(1.0)      /* 1.0                    */\n#define TWO     RCONST(2.0)\n#define THREE   RCONST(3.0)       /* 3.0                    */\n#define DELTA1  RCONST(3e-5)   /* Delta_i1 */\n#define DELTA2  RCONST(0.00012)   /* Delta_i2 */\n#define EPSILON RCONST(1.0e-9)\n#define ZERO    RCONST(0.0)\n#define NINE    RCONST(9.0)\n#define TEN     RCONST(10.0)\n#define Gnewton RCONST(4.302e-09)\n#define coef    RCONST(8987404.41) // 1/H0^2\n\n\n// structures to store spherical collapse calculations\ntypedef struct arrays{\n  int count;\n  double xx[1002];\n  double yy[1002]; } *arrays_T;\n\n\ntypedef struct arrays3D{\n  int count;\n  double xx[1002];\n  double yy[1002];\n  double zz[1002]; } *arrays_T3;\n\n\ntypedef struct usdat {\n  realtype IC;\n  realtype OM;\n  realtype Rth;\n  realtype T1;\n  double par1;\n  double par2;\n  double par3;\n  int mymg;\n  double maxt;\n  gsl_spline *spline;\n  gsl_interp_accel *acc;\n} *UserData;\n\n\nextern int check_flagscol(void *flagvalue, const char *funcname, int opt); //\n\n\nclass SCOL {\npublic:\n\n// used functions in example file\n   double maxP_zeta(double sig2, double dsig2dR, double OM, double Z);\n   double Delta_Lambda(double OM, double Z); //\n   // solves for y_enviornment\n   int yenv(double OM_REAL, double XF, double delta_envi, arrays_T xxyy); // gives the environmental dependence of spherical collapse\n   // solves for y_halo\n   int SphericalCollapse(double *dC, arrays_T3 xxyyzz, UserData data_vec, double TMULT_REAL, double delta_g); // spherical collapse solver\n   // solves for a_virial\n   double myscol(double myscolparams[], double acol, double omega0, double Rthp, double sig1, double sig2, double pars[], int mymg, int yenvf); // solves for virial quantities and stores them in array myscolparams\n\n\n   void PrintOutput(realtype t, realtype y1, realtype y2);\n   void PrintRootInfo(int root_f1); //\n\n   double funcscol(double xi, void *user_data); //\n\n};\n\n#endif\n", "meta": {"hexsha": "e76371f440afb43eba7b66abaae0969a7df34cdf", "size": 3544, "ext": "h", "lang": "C", "max_stars_repo_path": "reactions/src/SCOL.h", "max_stars_repo_name": "PedroCarrilho/ReACT", "max_stars_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T11:34:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T12:48:05.000Z", "max_issues_repo_path": "reactions/src/SCOL.h", "max_issues_repo_name": "PedroCarrilho/ReACT", "max_issues_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_forks_repo_path": "reactions/src/SCOL.h", "max_forks_repo_name": "PedroCarrilho/ReACT", "max_forks_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T15:35:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T15:35:28.000Z", "avg_line_length": 34.4077669903, "max_line_length": 213, "alphanum_fraction": 0.6591422122, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3744869510124263}}
{"text": "/**\n *\n * @file core_zlantr.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.8.0\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @precisions normal z -> c d s\n *\n **/\n#include <lapacke.h>\n#include <math.h>\n#include \"common.h\"\n\n#define LAPACKE_CORRECT_DLANTR\n\n/***************************************************************************//**\n *\n * @ingroup dplasma_cores_complex64\n *\n *  CORE_zlantr returns the value\n *\n *     zlantr = ( max(abs(A(i,j))), NORM = PlasmaMaxNorm\n *              (\n *              ( norm1(A),         NORM = PlasmaOneNorm\n *              (\n *              ( normI(A),         NORM = PlasmaInfNorm\n *              (\n *              ( normF(A),         NORM = PlasmaFrobeniusNorm\n *\n *  where norm1 denotes the one norm of a matrix (maximum column sum),\n *  normI denotes the infinity norm of a matrix (maximum row sum) and\n *  normF denotes the Frobenius norm of a matrix (square root of sum\n *  of squares). Note that max(abs(A(i,j))) is not a consistent matrix\n *  norm.\n *\n *******************************************************************************\n *\n * @param[in] norm\n *          = PlasmaMaxNorm: Max norm\n *          = PlasmaOneNorm: One norm\n *          = PlasmaInfNorm: Infinity norm\n *          = PlasmaFrobeniusNorm: Frobenius norm\n *\n * @param[in] uplo\n *          Specifies whether the matrix A is upper triangular or lower triangular:\n *          = PlasmaUpper: Upper triangle of A is stored;\n *          = PlasmaLower: Lower triangle of A is stored.\n *\n * @param[in] diag\n *          Specifies whether or not A is unit triangular:\n *          = PlasmaNonUnit: A is non unit;\n *          = PlasmaUnit:    A us unit.\n *\n * @param[in] M\n *          The number of rows of the matrix A. M >= 0.\n *          If uplo == PlasmaUpper, M <= N. When M = 0, CORE_zlantr returns 0.\n *\n * @param[in] N\n *          The number of columns of the matrix A. N >= 0.\n *          If uplo == PlasmaLower, N <= M. When N = 0, CORE_zlantr returns 0.\n *\n * @param[in] A\n *          The LDA-by-N matrix A.\n *\n * @param[in] LDA\n *          The leading dimension of the array A. LDA >= max(1,M).\n *\n * @param[in,out] work\n *          Array of dimension (MAX(1,LWORK)), where LWORK >= M when norm =\n *          PlasmaInfNorm, or LWORK >= N when norm = PlasmaOneNorm; otherwise,\n *          work is not referenced.\n *\n * @param[out] normA\n *          On exit, normA is the norm of matrix A.\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zlantr = PCORE_zlantr\n#define CORE_zlantr PCORE_zlantr\n#endif\nvoid CORE_zlantr(PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag,\n                 int M, int N,\n                 const PLASMA_Complex64_t *A, int LDA,\n                 double *work, double *normA)\n{\n#if defined(LAPACKE_CORRECT_DLANTR)\n    *normA = LAPACKE_zlantr_work(\n        LAPACK_COL_MAJOR,\n        lapack_const(norm),\n        lapack_const(uplo),\n        lapack_const(diag),\n        M, N, A, LDA, work);\n#else\n    const PLASMA_Complex64_t *tmpA;\n    double value;\n    int i, j, imax;\n    int idiag = (diag == PlasmaUnit) ? 1 : 0;\n\n    if ( min(M, N) == 0 ) {\n        *normA = 0;\n        return;\n    }\n\n    switch ( norm ) {\n    case PlasmaMaxNorm:\n        if ( diag == PlasmaUnit ) {\n            *normA = 1.;\n        } else {\n            *normA = 0.;\n        }\n\n        if ( uplo == PlasmaUpper ) {\n            M = min(M, N);\n            for (j = 0; j < N; j++) {\n                tmpA = A+(j*LDA);\n                imax = min(j+1-idiag, M);\n\n                for (i = 0; i < imax; i++) {\n                    value = cabs( *tmpA );\n                    *normA = ( value > *normA ) ? value : *normA;\n                    tmpA++;\n                }\n            }\n        } else {\n            N = min(M, N);\n            for (j = 0; j < N; j++) {\n                tmpA = A + j * (LDA+1) + idiag;\n\n                for (i = j+idiag; i < M; i++) {\n                    value = cabs( *tmpA );\n                    *normA = ( value > *normA ) ? value : *normA;\n                    tmpA++;\n                }\n            }\n        }\n        break;\n\n    case PlasmaOneNorm:\n        CORE_ztrasm( PlasmaColumnwise, uplo, diag, M, N,\n                     A, LDA, work );\n        if ( uplo == PlasmaLower )\n            N = min(M,N);\n\n        *normA = 0;\n        for (i = 0; i < N; i++) {\n            *normA = ( work[i] > *normA ) ? work[i] : *normA;\n        }\n        break;\n\n    case PlasmaInfNorm:\n        CORE_ztrasm( PlasmaRowwise, uplo, diag, M, N,\n                     A, LDA, work );\n        if ( uplo == PlasmaUpper )\n            M = min(M,N);\n\n        *normA = 0;\n        for (i = 0; i < M; i++) {\n            *normA = ( work[i] > *normA ) ? work[i] : *normA;\n        }\n        break;\n\n    case PlasmaFrobeniusNorm:\n    {\n        double scale = 0.;\n        double sumsq = 1.;\n        CORE_ztrssq( uplo, diag, M, N,\n                     A, LDA, &scale, &sumsq );\n\n        *normA = scale * sqrt( sumsq );\n    }\n    break;\n    default:\n        coreblas_error(1, \"Illegal value of norm\");\n        return;\n    }\n#endif\n}\n", "meta": {"hexsha": "a0c4c056e0b1d18a3106040669716187ee5a5a7d", "size": 5243, "ext": "c", "lang": "C", "max_stars_repo_path": "src/cores/core_zlantr.c", "max_stars_repo_name": "therault/dplasma", "max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z", "max_issues_repo_path": "src/cores/core_zlantr.c", "max_issues_repo_name": "therault/dplasma", "max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z", "max_forks_repo_path": "src/cores/core_zlantr.c", "max_forks_repo_name": "therault/dplasma", "max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z", "avg_line_length": 28.650273224, "max_line_length": 83, "alphanum_fraction": 0.474346748, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.37438322667604096}}
{"text": "#pragma once\n\n#include \"bits_of_matcha/engine/memory/Buffer.h\"\n#include \"bits_of_matcha/engine/iterations/MatrixwiseBinaryCtx.h\"\n\n#include <cblas.h>\n\n\nnamespace matcha::engine::cpu {\n\nvoid mm(engine::Buffer* a, engine::Buffer* b, engine::Buffer* c, const MatrixwiseBinaryCtx& ctx) {\n  size_t sizeA = ctx.rowsA * ctx.colsA;\n  size_t sizeB = ctx.rowsB * ctx.colsB;\n  size_t sizeC = ctx.rowsA * ctx.colsB;\n\n  dynamic_cast<Buffer*>(a);\n  dynamic_cast<Buffer*>(b);\n  dynamic_cast<Buffer*>(c);\n\n  auto valsA = a->as<float*>();\n  auto valsB = b->as<float*>();\n  auto valsC = c->as<float*>();\n\n  int strides = (int) ctx.prefixStridesA.size();\n\n  std::vector<unsigned> beginA(strides, 0);\n  std::vector<unsigned> beginB(strides, 0);\n  std::vector<unsigned> beginC(strides, 0);\n  auto iterC = valsC;\n\n  int counter = 0;\n  int axis = 1;\n  while (true) {\n//    if (counter++ > 20) exit(69);\n    if (axis < strides - 1) {\n      print(\"==========\");\n      print(\"axis \", axis, \" beginC \", beginC[axis], \" stridesC \", ctx.prefixStridesC[axis - 1]);\n//    print(\"axis: \", axis, \" (strides \", strides, \")\");\n//      print(\"strides: \", ctx.prefixStridesA[axis], \" \", ctx.prefixStridesB[axis], \" -> \", ctx.prefixStridesC[axis]);\n//      print(\"begins: \", beginA[axis], \" \", beginB[axis], \" -> \", beginC[axis]);\n//      print(\"BC: \", beginC[axis], \" \", beginC[axis - 1] + ctx.prefixStridesC[axis - 1]);\n//      print(\"beginC \", beginC[axis]);\n      if (beginC[axis] == beginC[axis - 1] + ctx.prefixStridesC[axis - 1]) {\n//        print(\"-> dec axis\");\n        if (axis == 1) break;\n        axis--;\n      } else {\n        beginA[axis + 1] = beginA[axis];\n        beginB[axis + 1] = beginB[axis];\n        beginC[axis + 1] = beginC[axis];\n        beginA[axis] += ctx.prefixStridesA[axis];\n        beginB[axis] += ctx.prefixStridesB[axis];\n        beginC[axis] += ctx.prefixStridesC[axis];\n//        print(\"-> inc axis\");\n        axis++;\n      }\n    } else {\n      if (axis >= strides) {\n        axis = strides - 1;\n      }\n\n//      print(ctx.prefixStridesC[axis - 1]);\n//      print(beginA[axis]);\n      auto matA = valsA + beginA[axis] * sizeA;\n      auto matB = valsB + beginB[axis] * sizeB;\n      auto loops = axis - 1 >= 0 ? ctx.prefixStridesC[axis - 1] : 1;\n      for (auto itC = 0; itC != loops; itC++) {\n        auto matC = valsC + (beginC[axis] + itC) * sizeC;\n\n//        print(matA - valsA, \" \", matB - valsB, \" -> \", matC - valsC);\n///*\n        cblas_sgemm(\n          CblasRowMajor,\n          CblasNoTrans,\n          CblasNoTrans,\n          (int) ctx.rowsA,\n          (int) ctx.colsB,\n          (int) ctx.colsA,\n          1,\n          matA,\n          (int) ctx.colsA,\n          matB,\n          (int) ctx.colsB,\n          0,\n          matC,\n          (int) ctx.colsB\n        );\n//        */\n\n        matA += sizeA * ctx.prefixStridesA[axis];\n        matB += sizeB * ctx.prefixStridesB[axis];\n      }\n//      print(\"blas\");\n\n      if (axis <= 1) break;\n      axis--;\n    }\n\n  }\n\n\n}\n\n}\n\n", "meta": {"hexsha": "0bd45697f775aedb24de078374143e393df197e2", "size": 2971, "ext": "h", "lang": "C", "max_stars_repo_path": "include/bits_of_matcha/engine/cpu/kernels/mm.h", "max_stars_repo_name": "matcha-ai/matcha", "max_stars_repo_head_hexsha": "c1375fc2bfc9fadcbd643fc1540e3ac470dd9408", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/bits_of_matcha/engine/cpu/kernels/mm.h", "max_issues_repo_name": "matcha-ai/matcha", "max_issues_repo_head_hexsha": "c1375fc2bfc9fadcbd643fc1540e3ac470dd9408", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/bits_of_matcha/engine/cpu/kernels/mm.h", "max_forks_repo_name": "matcha-ai/matcha", "max_forks_repo_head_hexsha": "c1375fc2bfc9fadcbd643fc1540e3ac470dd9408", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-17T12:14:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:14:27.000Z", "avg_line_length": 28.0283018868, "max_line_length": 118, "alphanum_fraction": 0.5368562773, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.37433766669770085}}
{"text": "/**\n *\n * @file core_dgeqp3_norms.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mark Gates\n * @date 2010-11-15\n * @generated d Tue Jan  7 11:44:49 2014\n *\n **/\n#include <lapacke.h>\n#include <math.h>\n#include <cblas.h>\n#include \"common.h\"\n\n#define A(m,n) BLKADDR( A, double, m, n )\n\n/***************************************************************************//**\n *\n * @ingroup CORE_double\n *\n *  CORE_dgeqp3_norms computes the 2-norm of each column of A[ ioff:m, joff:n ]\n *  that is marked with norms2[j] == -1 on entry. Entries that are not marked\n *  are assumed to already contain the correct 2-norm, so that the same routine\n *  can be used for computing the initial norms and for updating bad norms.\n *  The result is stored duplicated in norms1 and norms2.\n *\n *******************************************************************************\n *\n *  @param[in] A\n *          PLASMA descriptor of the matrix A.\n *          On entry, the M-by-N matrix described by the descriptor.\n *\n *  @param[in] ioff\n *          Row offset.\n *\n *  @param[in] joff\n *          Column offset.\n *\n *  @param[in,out] norms1\n *          Vector of size A.n.\n *          On exit, norms1[j] is 2-norm of column j, for j >= joff.\n *\n *  @param[in,out] norms2\n *          Vector of size A.n.\n *          On entry, if norms2[j] == -1, re-compute norm of column j.\n *          On exit, norms2[j] is 2-norm of column j, for j >= joff.\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dgeqp3_norms = PCORE_dgeqp3_norms\n#define CORE_dgeqp3_norms PCORE_dgeqp3_norms\n#define CORE_dgessq PCORE_dgessq\nint\nCORE_dgessq(int M, int N,\n            const double *A, int LDA,\n            double *scale, double *sumsq);\n#endif\nvoid CORE_dgeqp3_norms( PLASMA_desc A, int ioff, int joff, double *norms1, double *norms2 )\n{\n    const double *Ai;\n    int j, ii, ioff2, len, mb, nb, lda;\n    double sumsq, scale;\n\n    if ( A.nt != 1 ) {\n        coreblas_error(1, \"Illegal value of A.nt\");\n        return;\n    }\n\n    nb = min( A.nb, A.n );\n    for( j = joff; j < nb; ++j ) {\n        if ( norms2[j] == -1. ) {\n            scale = 0.;\n            sumsq = 1.;\n            ioff2 = ioff;\n            for( ii = 0; ii < A.mt; ++ii ) {\n                mb = min( A.mb, A.m - ii*A.mb );\n                Ai = A(ii,0);\n                lda = BLKLDD( A, ii );\n                len = mb - ioff2;\n                CORE_dgessq( len, 1, Ai + j*lda + ioff2, lda, &scale, &sumsq );\n                ioff2 = 0;\n            }\n            norms2[j] = scale * sqrt( sumsq );\n            norms1[j] = norms2[j];\n        }\n    }\n}\n", "meta": {"hexsha": "e2525a5eef5ef134d3334e8de2c66cfbb3fbd060", "size": 2710, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_dgeqp3_norms.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_dgeqp3_norms.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_dgeqp3_norms.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.4565217391, "max_line_length": 91, "alphanum_fraction": 0.5284132841, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.37433766083310466}}
{"text": "/**\n *\n * @file core_sgeqp3_update.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mark Gates\n * @date 2010-11-15\n * @generated s Tue Jan  7 11:44:49 2014\n *\n **/\n#include <math.h>\n#include <cblas.h>\n#include <lapacke.h>\n#include \"common.h\"\n\n#define A(m,n) BLKADDR( A, float, m, n )\n\n/***************************************************************************//**\n *\n * @ingroup CORE_float\n *\n * CORE_sgeqp3_update updates row k of one tile of A\n * and subtracts that row from the column norms.\n *\n *******************************************************************************\n *\n * @param[in] Ajj\n *         Diagonal tile (jj,jj) of A.\n *\n * @param[in] lda1\n *         Leading dimension of Ajj.\n *\n * @param[in,out] Ajk\n *         Tile (jj,kk) of A, kk >= jj.\n *         On exit, updates row joff+k (i.e., as if Q was applied to trailing matrix).\n *\n * @param[in] lda2\n *         Leading dimension of Ajk.\n *\n * @param[in] Fk\n *         Tile kk of F.\n *\n * @param[in] ldf\n *         Leading dimension of Fk.\n *\n * @param[in] joff\n *         Row offset.\n *\n * @param[in] k\n *         Update row joff+k, based on having factored k columns.\n *         (That is, joff columns of this tile were factored in previous panels;\n *          k columns have been factored during this panel.)\n *\n * @param[in] koff\n *         Column to start updating.\n *         For diagonal tile, koff=joff+k+1, else koff=0.\n *\n * @param[in] nb\n *         Number of columns in kk-th block-column of A.\n *\n * @param[in,out] norms1\n *         kk-th block of partial column norms vector, dimension nb.\n *         On exit, norms1[koff:nb] -= Ajk[k, koff:nb ].\n *\n * @param[in,out] norms2\n *         kk-th block of original column norms vector, dimension nb.\n *         Unchanged on exit, except if cancellation is detected for\n *         some column j, sets norm2[j] = -1 and sets info = 1.\n *\n * @param[out] info\n *         Set to true if numerical instability (cancellation) is detected\n *         in updating column norms. sgeqp3 handles this error.\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_sgeqp3_update = PCORE_sgeqp3_update\n#define CORE_sgeqp3_update PCORE_sgeqp3_update\n#endif\nvoid CORE_sgeqp3_update( const float *Ajj, int lda1,\n                         float       *Ajk, int lda2,\n                         const float *Fk,  int ldf,\n                         int joff, int k, int koff, int nb,\n                         float *norms1, float *norms2,\n                         int *info )\n{\n    float temp, temp2;\n    float tol3z = sqrt( LAPACKE_slamch_work('e'));\n    const float zone  =  1.0;\n    const float mzone = -1.0;\n    int j;\n\n    /* update row k of A -- this is vector*matrix */\n    /* Ajk[k,j:nb] -= Ajj[k,0:k+1] * Fk[j:nb,0:k+1].T */\n    cblas_sgemm( CblasColMajor, CblasNoTrans, CblasTrans, 1, nb-koff, k+1,\n                 (mzone), &Ajj[joff+k + joff*lda1], lda1,\n                                     &Fk [koff              ], ldf,\n                 (zone),  &Ajk[joff+k + koff*lda2], lda2 );\n\n    for( j = koff; j < nb; ++j ) {\n        if ( norms1[j] != 0. ) {\n            /* NOTE: The following lines follow from the analysis in Lapack Working Note 176. */\n            temp = fabsf( Ajk[joff+k + j*lda2] ) / norms1[j];\n            temp = max( 0., (1. + temp)*(1. - temp) );\n            temp2 = norms1[j] / norms2[j];\n            temp2 = temp * temp2*temp2;\n            norms1[j] = norms1[j]*sqrt( temp );\n            if( temp2 <= tol3z ) {\n                /* flag numerical problem (i.e., cancellation) in updating norm.\n                *  norms1[j] will be re-computed. Above we stored the inaccurate\n                *  value anyway to allow comparison with the accurate value, for\n                *  easier debugging. */\n                norms2[j] = -1;\n                *info = 1;\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "345c1dc722571bd63e92ca83a93aaf8e9bd3afeb", "size": 3964, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_sgeqp3_update.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_sgeqp3_update.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_sgeqp3_update.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.7603305785, "max_line_length": 96, "alphanum_fraction": 0.5292633703, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.3738775111216084}}
{"text": "/* multimin/gsl_multimin.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Modified by Tuomo Keskitalo to include fminimizer and \n   Nelder Mead related lines */\n\n#ifndef __GSL_MULTIMIN_H__\n#define __GSL_MULTIMIN_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_min.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\n/* Definition of an arbitrary real-valued function with gsl_vector input and */\n/* parameters */\nstruct gsl_multimin_function_struct \n{\n  double (* f) (const gsl_vector * x, void * params);\n  size_t n;\n  void * params;\n};\n\ntypedef struct gsl_multimin_function_struct gsl_multimin_function;\n\n#define GSL_MULTIMIN_FN_EVAL(F,x) (*((F)->f))(x,(F)->params)\n\n/* Definition of an arbitrary differentiable real-valued function */\n/* with gsl_vector input and parameters */\nstruct gsl_multimin_function_fdf_struct \n{\n  double (* f) (const gsl_vector  * x, void * params);\n  void (* df) (const gsl_vector * x, void * params,gsl_vector * df);\n  void (* fdf) (const gsl_vector * x, void * params,double *f,gsl_vector * df);\n  size_t n;\n  void * params;\n};\n\ntypedef struct gsl_multimin_function_fdf_struct gsl_multimin_function_fdf;\n\n#define GSL_MULTIMIN_FN_EVAL_F(F,x) (*((F)->f))(x,(F)->params)\n#define GSL_MULTIMIN_FN_EVAL_DF(F,x,g) (*((F)->df))(x,(F)->params,(g))\n#define GSL_MULTIMIN_FN_EVAL_F_DF(F,x,y,g) (*((F)->fdf))(x,(F)->params,(y),(g))\n\nint gsl_multimin_diff (const gsl_multimin_function * f,\n                       const gsl_vector * x, gsl_vector * g);\n\n/* minimization of non-differentiable functions */\n\ntypedef struct \n{\n  const char *name;\n  size_t size;\n  int (*alloc) (void *state, size_t n);\n  int (*set) (void *state, gsl_multimin_function * f,\n              const gsl_vector * x, \n              double * size,\n              const gsl_vector * step_size);\n  int (*iterate) (void *state, gsl_multimin_function * f, \n                  gsl_vector * x, \n                  double * size,\n                  double * fval);\n  void (*free) (void *state);\n}\ngsl_multimin_fminimizer_type;\n\ntypedef struct \n{\n  /* multi dimensional part */\n  const gsl_multimin_fminimizer_type *type;\n  gsl_multimin_function *f;\n\n  double fval;\n  gsl_vector * x;\n  \n  double size;\n\n  void *state;\n}\ngsl_multimin_fminimizer;\n\ngsl_multimin_fminimizer *\ngsl_multimin_fminimizer_alloc(const gsl_multimin_fminimizer_type *T,\n                              size_t n);\n\nint \ngsl_multimin_fminimizer_set (gsl_multimin_fminimizer * s,\n                             gsl_multimin_function * f,\n                             const gsl_vector * x,\n                             const gsl_vector * step_size);\n\nvoid\ngsl_multimin_fminimizer_free(gsl_multimin_fminimizer *s);\n\nconst char * \ngsl_multimin_fminimizer_name (const gsl_multimin_fminimizer * s);\n\nint\ngsl_multimin_fminimizer_iterate(gsl_multimin_fminimizer *s);\n\ngsl_vector * \ngsl_multimin_fminimizer_x (const gsl_multimin_fminimizer * s);\n\ndouble \ngsl_multimin_fminimizer_minimum (const gsl_multimin_fminimizer * s);\n\ndouble\ngsl_multimin_fminimizer_size (const gsl_multimin_fminimizer * s);\n\n/* Convergence test functions */\n\nint\ngsl_multimin_test_gradient(const gsl_vector * g,double epsabs);\n\nint\ngsl_multimin_test_size(const double size ,double epsabs);\n\n/* minimisation of differentiable functions */\n\ntypedef struct \n{\n  const char *name;\n  size_t size;\n  int (*alloc) (void *state, size_t n);\n  int (*set) (void *state, gsl_multimin_function_fdf * fdf,\n              const gsl_vector * x, double * f, \n              gsl_vector * gradient, double step_size, double tol);\n  int (*iterate) (void *state,gsl_multimin_function_fdf * fdf, \n                  gsl_vector * x, double * f, \n                  gsl_vector * gradient, gsl_vector * dx);\n  int (*restart) (void *state);\n  void (*free) (void *state);\n}\ngsl_multimin_fdfminimizer_type;\n\ntypedef struct \n{\n  /* multi dimensional part */\n  const gsl_multimin_fdfminimizer_type *type;\n  gsl_multimin_function_fdf *fdf;\n\n  double f;\n  gsl_vector * x;\n  gsl_vector * gradient;\n  gsl_vector * dx;\n\n  void *state;\n}\ngsl_multimin_fdfminimizer;\n\ngsl_multimin_fdfminimizer *\ngsl_multimin_fdfminimizer_alloc(const gsl_multimin_fdfminimizer_type *T,\n                                size_t n);\n\nint \ngsl_multimin_fdfminimizer_set (gsl_multimin_fdfminimizer * s,\n                               gsl_multimin_function_fdf *fdf,\n                               const gsl_vector * x,\n                               double step_size, double tol);\n\nvoid\ngsl_multimin_fdfminimizer_free(gsl_multimin_fdfminimizer *s);\n\nconst char * \ngsl_multimin_fdfminimizer_name (const gsl_multimin_fdfminimizer * s);\n\nint\ngsl_multimin_fdfminimizer_iterate(gsl_multimin_fdfminimizer *s);\n\nint\ngsl_multimin_fdfminimizer_restart(gsl_multimin_fdfminimizer *s);\n\ngsl_vector * \ngsl_multimin_fdfminimizer_x (gsl_multimin_fdfminimizer * s);\n\ngsl_vector * \ngsl_multimin_fdfminimizer_dx (gsl_multimin_fdfminimizer * s);\n\ngsl_vector * \ngsl_multimin_fdfminimizer_gradient (gsl_multimin_fdfminimizer * s);\n\ndouble \ngsl_multimin_fdfminimizer_minimum (gsl_multimin_fdfminimizer * s);\n\nGSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_steepest_descent;\nGSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_conjugate_pr;\nGSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_conjugate_fr;\nGSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_vector_bfgs;\nGSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_vector_bfgs2;\nGSL_VAR const gsl_multimin_fminimizer_type *gsl_multimin_fminimizer_nmsimplex;\n\n\n__END_DECLS\n\n#endif /* __GSL_MULTIMIN_H__ */\n", "meta": {"hexsha": "53c342da3b5db54c12029f42070101bfda9a414f", "size": 6607, "ext": "h", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/multimin/gsl_multimin.h", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/multimin/gsl_multimin.h", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/multimin/gsl_multimin.h", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 29.2345132743, "max_line_length": 89, "alphanum_fraction": 0.7225669744, "num_tokens": 1771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.37378791726905003}}
{"text": "/*System includes*/\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\n/*GSL includes*/\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_sf.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_roots.h>\n#include <gsl/gsl_statistics_double.h>\n#include <gsl/gsl_fft_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_multimin.h>\n#include <pthread.h>\n\n/*User includes*/\n#include \"../Lib/FileUtils.h\"\n#include \"../Lib/MatrixUtils.h\"\n#include \"MetroIG.h\"\n\nstatic char *usage[] = {\"MetroIG - Fits the compound Poisson Inverse Gaussian\\n\",\n                        \"Required parameters:\\n\",\n\t\t\t\"   -out  filestub      output file stub\\n\",\n\t\t\t\"   -in   filename      parameter file  \\n\",\n                        \"Optional:\\n\",\n\t\t\t\"   -s    integer       generate integer MCMC samples\\n\",\n\t\t\t\"   -seed   long        seed random number generator\\n\",\n\t\t\t\"   -sigmaA float       std. dev. of alpha prop. distn\\n\",\n\t\t\t\"   -sigmaB float       ...          beta             \\n\",\n\t\t\t\"   -sigmaS float       ...          S                \\n\",\n\t\t\t\"   -v                  verbose\\n\"};\n\nstatic int  nLines   = 11;\n\nstatic int  verbose  = FALSE;\n\nint main(int argc, char* argv[])\n{\n  int  i = 0, nNA     = 0;\n  t_Params tParams;\n  t_Data   tData;\n  gsl_vector* ptX = gsl_vector_alloc(3); /*parameter estimates*/\n  t_MetroInit atMetroInit[3];\n  \n  gsl_rng_env_setup();\n     \n  gsl_set_error_handler_off();\n  \n  /*get command line params*/\n  getCommandLineParams(&tParams, argc, argv);\n\n  /*read in abundance distribution*/\n  readAbundanceData(tParams.szInputFile, &tData);\n     \n  /*set initial estimates for parameters*/\n  gsl_vector_set(ptX, 0, INIT_A);\n  gsl_vector_set(ptX, 1, INIT_B);\n  gsl_vector_set(ptX, 2, tData.nL*2);\n\n\n  printf(\"D = %d L = %d Chao = %f\\n\",tData.nL, tData.nJ, chao(&tData));\n\n  minimiseSimplex(ptX, 3, (void*) &tData, &nLogLikelihood);\n\n  outputResults(ptX, &tData);\n   \n  if(tParams.nIter > 0){\n    mcmc(&tParams, &tData, ptX);\n  }\n \n  /*free up allocated memory*/\n  gsl_vector_free(ptX);\n\n  freeAbundanceData(&tData);\n\n  exit(EXIT_SUCCESS);\n}\n\nvoid writeUsage(FILE* ofp)\n{\n  int i = 0;\n  char *line;\n\n  for(i = 0; i < nLines; i++){\n    line = usage[i];\n    fputs(line,ofp);\n  }\n}\n\nchar *extractParameter(int argc, char **argv, char *param,int when)\n{\n  int i = 0;\n\n  while((i < argc) && (strcmp(param,argv[i]))){\n    i++;\n  }\n\n  if(i < argc - 1){\n    return(argv[i + 1]);\n  }\n\n  if((i == argc - 1) && (when == OPTION)){\n    return \"\";\n  }\n\n  if(when == ALWAYS){\n    fprintf(stdout,\"Can't find asked option %s\\n\",param);\n  }\n\n  return (char *) NULL;\n}\n\nvoid getCommandLineParams(t_Params *ptParams,int argc,char *argv[])\n{\n  char *szTemp = NULL;\n  char *cError = NULL;\n\n  /*get parameter file name*/\n  ptParams->szInputFile  = extractParameter(argc,argv, INPUT_FILE,ALWAYS);  \n  if(ptParams->szInputFile == NULL)\n    goto error;\n\n  /*get out file stub*/\n  ptParams->szOutFileStub  = extractParameter(argc,argv,OUT_FILE_STUB,ALWAYS);  \n  if(ptParams->szOutFileStub == NULL)\n    goto error;\n\n  /*get out file stub*/\n  szTemp  = extractParameter(argc,argv,SEED,OPTION);  \n  if(szTemp != NULL){\n    ptParams->lSeed = strtol(szTemp,&cError,10);\n    if(*cError != '\\0'){\n      goto error;\n    }\n  }\n  else{\n    ptParams->lSeed = 0;\n  }\n \n  /*verbosity*/\n  szTemp = extractParameter(argc, argv, VERBOSE, OPTION);\n  if(szTemp != NULL){\n    verbose = TRUE;\n  }\n\n  szTemp  = extractParameter(argc,argv,SAMPLE,OPTION);  \n  if(szTemp != NULL){\n    ptParams->nIter = strtol(szTemp,&cError,10);\n    if(*cError != '\\0'){\n      goto error;\n    }\n  }\n  else{\n    ptParams->nIter = 0;\n  }\n\n  szTemp  = extractParameter(argc,argv,SIGMA_A,OPTION);  \n  if(szTemp != NULL){\n    ptParams->dSigmaA = strtod(szTemp,&cError);\n    if(*cError != '\\0'){\n      goto error;\n    }\n  }\n  else{\n    ptParams->dSigmaA = DEF_SIGMA;\n  }\n  \n  szTemp  = extractParameter(argc,argv,SIGMA_B,OPTION);  \n  if(szTemp != NULL){\n    ptParams->dSigmaB = strtod(szTemp,&cError);\n    if(*cError != '\\0'){\n      goto error;\n    }\n  }\n  else{\n    ptParams->dSigmaB = DEF_SIGMA;\n  }\n\n  \n  szTemp  = extractParameter(argc,argv,SIGMA_S,OPTION);  \n  if(szTemp != NULL){\n    ptParams->dSigmaS = strtod(szTemp,&cError);\n    if(*cError != '\\0'){\n      goto error;\n    }\n  }\n  else{\n    ptParams->dSigmaS = DEF_SIGMA_S;\n  }\n\n  return;\n\n error:\n  writeUsage(stdout);\n  exit(EXIT_FAILURE);\n}\n\nvoid readAbundanceData(const char *szFile, t_Data *ptData)\n{\n  int **aanAbund = NULL;\n  int  i = 0, nNA = 0, nA = 0, nC = 0;\n  int  nL = 0, nJ = 0;\n  char szLine[MAX_LINE_LENGTH];\n  FILE* ifp = NULL;\n\n  ifp = fopen(szFile, \"r\");\n\n  if(ifp){\n    char* szTok   = NULL;\n    char* pcError = NULL;\n\n    fgets(szLine, MAX_LINE_LENGTH, ifp);\n\n    szTok = strtok(szLine, DELIM);\n    \n    nNA = strtol(szTok,&pcError,10);\n    if(*pcError != '\\0'){\n      goto formatError;\n    }\n    \n    aanAbund = (int **) malloc(nNA*sizeof(int*));\n\n    for(i = 0; i < nNA; i++){\n      aanAbund[i] = (int *) malloc(sizeof(int)*2);\n\n      fgets(szLine, MAX_LINE_LENGTH, ifp);\n\n      szTok = strtok(szLine, DELIM);\n\n      nA = strtol(szTok,&pcError,10);\n      if(*pcError != '\\0'){\n\tgoto formatError;\n      }\n\n      szTok = strtok(NULL, DELIM);\n\n      nC = strtol(szTok,&pcError,10);\n      if(*pcError != '\\0'){\n\tgoto formatError;\n      }\n      \n      nL += nC;\n      nJ += nC*nA;\n\n      aanAbund[i][0]  = nA;\n      aanAbund[i][1]  = nC;     \n    }\n  }\n  else{\n    fprintf(stderr, \"Failed to open abundance data file %s aborting\\n\", szFile);\n    fflush(stderr);\n    exit(EXIT_FAILURE);\n  }\n\n  ptData->nJ          = nJ;\n  ptData->nL          = nL;\n  ptData->aanAbund    = aanAbund;\n  ptData->nNA         = nNA;\n  return;\n\n formatError:\n  fprintf(stderr, \"Incorrectly formatted abundance data file\\n\");\n  fflush(stderr);\n  exit(EXIT_FAILURE);\n}\n\nint compare_doubles(const void* a, const void* b) \n{\n  double* arg1 = (double *) a;\n  double* arg2 = (double *) b;\n  if( *arg1 < *arg2 ) return -1;\n  else if( *arg1 == *arg2 ) return 0;\n  else return 1;\n}       \n\ndouble chao(t_Data *ptData)\n{\n  double n1 = 0.0, n2 = 0.0;\n  int **aanAbund = ptData->aanAbund;\n\n  if(aanAbund[0][0] == 1 && aanAbund[1][0] == 2){\n    n1 = (double) aanAbund[0][1]; n2 = (double) aanAbund[1][1];\n  \n    return ((double) ptData->nL) + 0.5*((n1*n1)/n2);\n  }\n  else{\n    return -1.0;\n  }\n}\n\ndouble fX(double x, double dA, double dB, double dNDash)\n{\n  double dTemp1 = (dA*(x - dB)*(x - dB))/x;\n\n  return log(x) - (1.0/dNDash)*(x + dTemp1);\n}\n\ndouble f2X(double x, double dA, double dB, double dNDash)\n{\n  double dRet = 0.0, dTemp = 2.0*dA*dB*dB;\n\n  dRet = (1.0/(x*x))*(1.0 + (1.0/dNDash)*(dTemp/x));\n\n  return -dRet;\n}\n\n\ndouble sd(int n, double dAlpha, double dBeta)\n{\n  double dGamma = -0.5;\n  double dA = 0.5*(-1.0 + sqrt(1.0 + (dAlpha*dAlpha)/(dBeta*dBeta)));\n  double dN = (double) n, dNDash = dN + dGamma - 1.0, dRN = 1.0/dN;\n  double dTemp1 = (0.5*dN)/(1.0 + dA), dTemp2 = 4.0*dRN*dRN*(1.0 + dA)*dA*dBeta*dBeta;\n  double dXStar = dTemp1*(1.0 + sqrt(1.0 + dTemp2));\n  double dFX = fX(dXStar, dA, dBeta, dNDash);\n  double d2FX = -dNDash*f2X(dXStar, dA, dBeta, dNDash);\n  double dLogK = 0.0, dGamma1 = dGamma;\n\n  if(dGamma1 < 0.0){\n    dGamma1 *= -1.0;\n  }\n\n  dLogK = gsl_sf_bessel_lnKnu(dGamma1,2.0*dA*dBeta);\n\n  return -2.0*dA*dBeta -log(2.0) -dLogK -dGamma*log(dBeta) + dNDash*dFX + 0.5*log(2.0*M_PI) - 0.5*log(d2FX);\n}\n\nint bessel(double* pdResult, int n, double dAlpha, double dBeta)\n{\n  double dGamma  = -0.5;\n  double dResult = 0.0;\n  double dOmega = 0.0, dGamma2 = 0.0;\n  double dLogK1 = 0.0, dLogK2 = 0.0;\n  double dN = (double) n, dNu = dGamma + dN;\n  double dTemp1 = 0.0;\n \n  if(dNu < 0.0){\n    dNu = -dNu;\n  }\n\n  if(dGamma < 0.0){\n    dGamma2 = -dGamma;\n  }\n  else{\n    dGamma2 = dGamma;\n  }\n\n  dOmega = sqrt(dBeta*dBeta + dAlpha*dAlpha) - dBeta;\n\n  dLogK2 = gsl_sf_bessel_lnKnu(dNu, dAlpha);\n\n  if(!gsl_finite(dLogK2)){\n    if(dAlpha < 0.1*sqrt(dNu + 1.0)){\n      //printf(\"l \");\n      dLogK2 = gsl_sf_lngamma(dNu) + (dNu - 1.0)*log(2.0) - dNu*log(dAlpha);\n    }\n    else{\n      //printf(\"sd \");\n      (*pdResult) = dResult;\n      return FALSE;\n    }\n  }\n   \n  dLogK1 = dGamma*log(dOmega/dAlpha) -gsl_sf_bessel_lnKnu(dGamma2,dOmega);\n  \n  dTemp1 = log((dBeta*dOmega)/dAlpha);\n\n  dResult = dN*dTemp1 + dLogK2 + dLogK1;\n  (*pdResult) = dResult;\n  return TRUE;\n}\n\ndouble logLikelihood(int n, double dAlpha, double dBeta)\n{\n  double dLogFacN = 0.0;\n  int status      = 0;\n  double dRet     = 0.0;\n\n  if(n < 50){\n    dLogFacN = gsl_sf_fact(n);\n    dLogFacN = log(dLogFacN);\n  }\n  else{\n    dLogFacN = gsl_sf_lngamma(((double) n) + 1.0);\n  }\n\n  status = bessel(&dRet,n, dAlpha,dBeta);\n  if(status == FALSE){\n    dRet = sd(n, dAlpha,dBeta);\n  }\n  \n  return dRet - dLogFacN;\n}\n\ndouble nLogLikelihood(const gsl_vector * x, void * params)\n{\n  double dAlpha  = gsl_vector_get(x,0), dBeta = gsl_vector_get(x,1);\n  int    nS = (int) floor(gsl_vector_get(x, 2));\n  t_Data *ptData = (t_Data *) params;\n  int    i       = 0;\n  double dLogNot0 = 0.0, dLogL   = 0.0;\n  double dLog0 = 0.0, dLog1 = 0.0, dLog2 = 0.0, dLog3 = 0.0;\n  \n  if(dAlpha <= 0.0 || dBeta <= 0.0){\n    return PENALTY;\n  }\n\n  for(i = 0; i < ptData->nNA; i++){\n    double dLogP = 0.0;\n    int    nA    = ptData->aanAbund[i][0];\n\n    dLogP = logLikelihood(nA, dAlpha, dBeta);\n    \n    dLogL += ((double) ptData->aanAbund[i][1])*dLogP;\n\n    dLogL -= gsl_sf_lnfact(ptData->aanAbund[i][1]);\n    \n  }\n\n  dLog0 = logLikelihood(0, dAlpha, dBeta);\n\n  dLog1 = (nS - ptData->nL)*dLog0;\n\n  dLog2 = - gsl_sf_lnfact(nS - ptData->nL);\n\n  dLog3 = gsl_sf_lnfact(nS);\n  \n  dLogL += dLog1 + dLog2 + dLog3;\n\n  /*return*/\n  return -dLogL;\n}\n\ndouble negLogLikelihood(double dAlpha, double dBeta, int nS, void * params)\n{\n  t_Data *ptData = (t_Data *) params;\n  int    i       = 0;\n  double dLogNot0 = 0.0, dLogL   = 0.0;\n  double dLog0 = 0.0, dLog1 = 0.0, dLog2 = 0.0, dLog3 = 0.0;\n  \n  if(dAlpha <= 0.0 || dBeta <= 0.0){\n    return PENALTY;\n  }\n\n  for(i = 0; i < ptData->nNA; i++){\n    double dLogP = 0.0;\n    int    nA    = ptData->aanAbund[i][0];\n\n    dLogP = logLikelihood(nA, dAlpha, dBeta);\n    \n    dLogL += ((double) ptData->aanAbund[i][1])*dLogP;\n\n    dLogL -= gsl_sf_lnfact(ptData->aanAbund[i][1]);\n    \n  }\n\n  dLog0 = logLikelihood(0, dAlpha, dBeta);\n\n  dLog1 = (nS - ptData->nL)*dLog0;\n\n  dLog2 = - gsl_sf_lnfact(nS - ptData->nL);\n\n  dLog3 = gsl_sf_lnfact(nS);\n  \n  dLogL += dLog1 + dLog2 + dLog3;\n\n  /*return*/\n  return -dLogL;\n}\n\nint minimiseSimplex(gsl_vector* ptX, size_t nP, void* pvData, double (*f)(const gsl_vector*, void* params))\n{\n  const gsl_multimin_fminimizer_type *T =\n    gsl_multimin_fminimizer_nmsimplex;\n  gsl_multimin_fminimizer *s = NULL;\n  gsl_vector *ss;\n  gsl_multimin_function minex_func;  \n  size_t iter = 0;\n  int i = 0, status;\n  double size;\n\n  /* Initial vertex size vector */\n  ss = gsl_vector_alloc (nP);\n     \n  /* Set all step sizes to default constant */\n  gsl_vector_set_all(ss, INIT_SIMPLEX_SIZE);\n     \n  gsl_vector_set(ss,nP - 1,INIT_S_SS*gsl_vector_get(ptX,0));\n\n  /* Initialize method and iterate */\n  minex_func.f = f;\n  minex_func.n = nP;\n  minex_func.params = pvData;\n     \n  s = gsl_multimin_fminimizer_alloc (T, nP);\n  gsl_multimin_fminimizer_set(s, &minex_func, ptX, ss);\n     \n  do{\n    iter++;\n    status = gsl_multimin_fminimizer_iterate(s);\n     \n    if(status)\n      break;\n     \n    size = gsl_multimin_fminimizer_size(s);\n    status = gsl_multimin_test_size(size, MIN_SIMPLEX_SIZE);\n     \n    if(status == GSL_SUCCESS){\n      for(i = 0; i < nP; i++){\n\tgsl_vector_set(ptX, i, gsl_vector_get(s->x, i));\n      }\n\n      if(verbose) printf(\"converged to minimum at\\n\");\n    }\n    \n    if(verbose){ \n      printf (\"%5d \", iter);\n    \n      for (i = 0; i < nP; i++) printf(\"%10.3e \", gsl_vector_get(s->x, i));\n    \n      printf(\"f() = %7.3f size = %.3f\\n\", s->fval, size);\n    }\n  }\n  while(status == GSL_CONTINUE && iter < MAX_SIMPLEX_ITER);\n     \n  for(i = 0; i < nP; i++){\n    gsl_vector_set(ptX, i, gsl_vector_get(s->x, i));\n  }\n\n  gsl_vector_free(ss);\n  gsl_multimin_fminimizer_free (s);\n\n  return status;\n}\n\nvoid freeAbundanceData(t_Data *ptData)\n{\n  int i = 0;\n\n  for(i = 0; i < ptData->nNA; i++){\n    free(ptData->aanAbund[i]);\n  }\n  free(ptData->aanAbund);\n}\n\nvoid getProposal(gsl_rng *ptGSLRNG, gsl_vector *ptXDash, gsl_vector *ptX, int* pnSDash, int nS, t_Params *ptParams)\n{\n  double dDeltaS =  gsl_ran_gaussian(ptGSLRNG, ptParams->dSigmaS);\n  double dDeltaA =  gsl_ran_gaussian(ptGSLRNG, ptParams->dSigmaA);\n  double dDeltaB =  gsl_ran_gaussian(ptGSLRNG, ptParams->dSigmaB);\n  int    nSDash = 0;\n\n  gsl_vector_set(ptXDash, 0, gsl_vector_get(ptX,0) + dDeltaA);\n  gsl_vector_set(ptXDash, 1, gsl_vector_get(ptX,1) + dDeltaB);\n  \n  //printf(\"%e %e %e\\n\",dDeltaA,dDeltaB,dDeltaG);\n\n  nSDash = nS + (int) floor(dDeltaS);\n  if(nSDash < 1){\n    nSDash = 1;\n  }\n  (*pnSDash) = nSDash;\n}\n\nvoid outputResults(gsl_vector *ptX, t_Data *ptData)\n{\n  double dAlpha = 0.0, dBeta = 0.0, dS = 0.0, dL = 0.0;\n\n  dAlpha = gsl_vector_get(ptX, 0);\n\n  dBeta  = gsl_vector_get(ptX, 1);\n  \n  dS = gsl_vector_get(ptX, 2);\n\n  dL = nLogLikelihood(ptX, ptData);\n\n  printf(\"\\nML simplex: a = %.2f b = %.2f S = %.2f NLL = %.2f\\n\",dAlpha, dBeta, dS, dL);\n}\n\nvoid* metropolis (void * pvInitMetro)\n{\n  t_MetroInit *ptMetroInit  = (t_MetroInit *) pvInitMetro;\n  gsl_vector  *ptX          = ptMetroInit->ptX;\n  t_Data      *ptData       = ptMetroInit->ptData;\n  t_Params    *ptParams     = ptMetroInit->ptParams;\n  gsl_vector  *ptXDash      = gsl_vector_alloc(3); /*proposal*/\n  char *szSampleFile = (char *) malloc(MAX_LINE_LENGTH*sizeof(char));\n  const gsl_rng_type *T;\n  gsl_rng            *ptGSLRNG;\n  FILE    *sfp = NULL;\n  int nS = 0, nSDash = 0, nIter = 0;\n  double dRand = 0.0, dNLL = 0.0;\n  void   *pvRet = NULL;\n\n  /*set up random number generator*/\n  T        = gsl_rng_default;\n  ptGSLRNG = gsl_rng_alloc (T); \n\n  nS = (int) floor(gsl_vector_get(ptX,2));\n  \n  dNLL = negLogLikelihood(gsl_vector_get(ptX,0), gsl_vector_get(ptX,1), nS,(void*) ptData);\n\n  sprintf(szSampleFile,\"%s_%d%s\", ptParams->szOutFileStub, ptMetroInit->nThread, SAMPLE_FILE_SUFFIX);\n\n  sfp = fopen(szSampleFile, \"w\");\n  if(!sfp){\n    exit(EXIT_FAILURE);\n  }\n\n  /*seed random number generator*/\n  gsl_rng_set(ptGSLRNG, ptMetroInit->lSeed);\n\n  /*now perform simple Metropolis algorithm*/\n  while(nIter < ptParams->nIter){\n    double dA = 0.0, dNLLDash = 0.0;\n\n    getProposal(ptGSLRNG, ptXDash, ptX, &nSDash, nS, ptParams);\n  \n    dNLLDash = negLogLikelihood(gsl_vector_get(ptXDash,0), gsl_vector_get(ptXDash,1), nSDash, (void*) ptData);\n    //printf(\"X' %e %e %e %d %f\\n\", gsl_vector_get(ptXDash,0), gsl_vector_get(ptXDash,1), gsl_vector_get(ptXDash,2), nSDash, dNLLDash);\n    //printf(\"X %e %e %e %d %f\\n\", gsl_vector_get(ptX,0), gsl_vector_get(ptX,1), gsl_vector_get(ptX,2), nS, dNLL);\n    dA = exp(dNLL - dNLLDash);\n    if(dA > 1.0){\n      dA = 1.0;\n    }\n\n    dRand = gsl_rng_uniform(ptGSLRNG);\n\n    if(dRand < dA){\n      gsl_vector_memcpy(ptX, ptXDash);\n      nS = nSDash;\n      dNLL = dNLLDash;\n      ptMetroInit->nAccepted++;\n    }\n    \n    if(nIter % SLICE == 0){\n      fprintf(sfp, \"%d,%e,%e,%d,%f\\n\",nIter,gsl_vector_get(ptX, 0), gsl_vector_get(ptX, 1), nS, dNLL);    \n      fflush(sfp);\n    }\n\n    nIter++;\n  }\n\n  fclose(sfp);\n\n  /*free up allocated memory*/\n  gsl_vector_free(ptXDash);\n  free(szSampleFile);\n  gsl_rng_free(ptGSLRNG);\n\n  return pvRet;\n}\n\nvoid writeThread(t_MetroInit *ptMetroInit)\n{\n  gsl_vector *ptX = ptMetroInit->ptX;\n    printf(\"%d: a = %.2f b = %.2f S = %.2f\\n\", ptMetroInit->nThread, \n\t   gsl_vector_get(ptX, 0),\n\t   gsl_vector_get(ptX, 1),\n\t   gsl_vector_get(ptX, 2));\n}\n\nvoid mcmc(t_Params *ptParams, t_Data *ptData, gsl_vector* ptX)\n{\n  pthread_t thread1, thread2, thread3;\n  int       iret1  , iret2  , iret3;\n  gsl_vector *ptX1 = gsl_vector_alloc(3), \n             *ptX2 = gsl_vector_alloc(3), \n             *ptX3 = gsl_vector_alloc(3);\n  t_MetroInit atMetroInit[3];\n\n  printf(\"\\nMCMC iter = %d sigmaA = %.2f sigmaB = %.2f sigmaS = %.2f\\n\",\n\t   ptParams->nIter, ptParams->dSigmaA, ptParams->dSigmaB, ptParams->dSigmaS);\n\n  gsl_vector_memcpy(ptX1, ptX);\n\n  gsl_vector_set(ptX2, 0, gsl_vector_get(ptX,0) + 2.0*ptParams->dSigmaA);\n  gsl_vector_set(ptX2, 1, gsl_vector_get(ptX,1) + 2.0*ptParams->dSigmaB);\n  gsl_vector_set(ptX2, 2, gsl_vector_get(ptX,2) + 2.0*ptParams->dSigmaS);    \n\n  gsl_vector_set(ptX3, 0, gsl_vector_get(ptX,0) - 2.0*ptParams->dSigmaA);\n  gsl_vector_set(ptX3, 1, gsl_vector_get(ptX,1) - 2.0*ptParams->dSigmaB);\n  if(gsl_vector_get(ptX,2) - 2.0*ptParams->dSigmaS > (double) ptData->nL){\n\tgsl_vector_set(ptX3, 2, gsl_vector_get(ptX,2) - 2.0*ptParams->dSigmaS);\n  }\n  else{\n\tgsl_vector_set(ptX3, 2, (double) ptData->nL);\n  }\n  atMetroInit[0].ptParams = ptParams;\n  atMetroInit[0].ptData   = ptData;\n  atMetroInit[0].ptX      = ptX1;\n  atMetroInit[0].nThread  = 0;\n  atMetroInit[0].lSeed    = ptParams->lSeed;\n  atMetroInit[0].nAccepted = 0;\n\n  atMetroInit[1].ptParams = ptParams;\n  atMetroInit[1].ptData   = ptData;\n  atMetroInit[1].ptX      = ptX2;\n  atMetroInit[1].nThread  = 1;\n  atMetroInit[1].lSeed    = ptParams->lSeed + 1;\n  atMetroInit[1].nAccepted = 0;\n\n  atMetroInit[2].ptParams = ptParams;\n  atMetroInit[2].ptData   = ptData;\n  atMetroInit[2].ptX      = ptX3;\n  atMetroInit[2].nThread  = 2;\n  atMetroInit[2].lSeed    = ptParams->lSeed + 2;\n  atMetroInit[2].nAccepted = 0;\n\n  writeThread(&atMetroInit[0]);\n  writeThread(&atMetroInit[1]);\n  writeThread(&atMetroInit[2]);\n\n  iret1 = pthread_create(&thread1, NULL, metropolis, (void*) &atMetroInit[0]);\n  iret2 = pthread_create(&thread2, NULL, metropolis, (void*) &atMetroInit[1]);\n  iret3 = pthread_create(&thread3, NULL, metropolis, (void*) &atMetroInit[2]);\n  pthread_join(thread1, NULL);\n  pthread_join(thread2, NULL);\n  pthread_join(thread3, NULL);\n\n\n  printf(\"%d: accept. ratio %d/%d = %f\\n\", atMetroInit[0].nThread, \n\t atMetroInit[0].nAccepted, ptParams->nIter,((double) atMetroInit[0].nAccepted)/((double) ptParams->nIter));\n\n  printf(\"%d: accept. ratio %d/%d = %f\\n\", atMetroInit[1].nThread, \n\t atMetroInit[1].nAccepted, ptParams->nIter,((double) atMetroInit[1].nAccepted)/((double) ptParams->nIter));\n\n  printf(\"%d: accept. ratio %d/%d = %f\\n\", atMetroInit[2].nThread,\n\t atMetroInit[2].nAccepted, ptParams->nIter, ((double) atMetroInit[2].nAccepted)/((double) ptParams->nIter));\n      \n  gsl_vector_free(ptX1); gsl_vector_free(ptX2); gsl_vector_free(ptX3);\n}\n", "meta": {"hexsha": "420ecc5f246e90c29f763efda733d1f18003c9a6", "size": 18491, "ext": "c", "lang": "C", "max_stars_repo_path": "MetroIG/MetroIG.c", "max_stars_repo_name": "chrisquince/DiversityEstimates", "max_stars_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-18T17:56:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-19T13:22:59.000Z", "max_issues_repo_path": "MetroIG/MetroIG.c", "max_issues_repo_name": "chrisquince/DiversityEstimates", "max_issues_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MetroIG/MetroIG.c", "max_forks_repo_name": "chrisquince/DiversityEstimates", "max_forks_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_forks_repo_licenses": ["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.9878378378, "max_line_length": 135, "alphanum_fraction": 0.6147855714, "num_tokens": 6625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.3737575507124135}}
{"text": "/* multifit/gsl_multifit.h\r\n * \r\n * Copyright (C) 2000, 2007 Brian Gough\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * 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 this program; 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#ifndef __GSL_MULTIFIT_H__\r\n#define __GSL_MULTIFIT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n#  if !defined( GSL_DLL )\r\n#    define GSL_FUN extern\r\n#  elif defined( BUILD_GSL_DLL )\r\n#    define GSL_FUN extern __declspec(dllexport)\r\n#  else\r\n#    define GSL_FUN extern __declspec(dllimport)\r\n#  endif\r\n#endif\r\n\r\n#include <stdlib.h>\r\n#include <gsl/gsl_math.h>\r\n#include <gsl/gsl_vector.h>\r\n#include <gsl/gsl_matrix.h>\r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef struct \r\n{\r\n  size_t n; /* number of observations */\r\n  size_t p; /* number of parameters */\r\n  gsl_matrix * A;\r\n  gsl_matrix * Q;\r\n  gsl_matrix * QSI;\r\n  gsl_vector * S;\r\n  gsl_vector * t;\r\n  gsl_vector * xt;\r\n  gsl_vector * D;\r\n} \r\ngsl_multifit_linear_workspace;\r\n\r\nGSL_FUN gsl_multifit_linear_workspace *\r\ngsl_multifit_linear_alloc (size_t n, size_t p);\r\n\r\nGSL_FUN void\r\ngsl_multifit_linear_free (gsl_multifit_linear_workspace * work);\r\n\r\nGSL_FUN int\r\ngsl_multifit_linear (const gsl_matrix * X,\r\n                     const gsl_vector * y,\r\n                     gsl_vector * c,\r\n                     gsl_matrix * cov,\r\n                     double * chisq,\r\n                     gsl_multifit_linear_workspace * work);\r\n\r\nGSL_FUN int\r\ngsl_multifit_linear_svd (const gsl_matrix * X,\r\n                         const gsl_vector * y,\r\n                         double tol,\r\n                         size_t * rank,\r\n                         gsl_vector * c,\r\n                         gsl_matrix * cov,\r\n                         double *chisq, \r\n                         gsl_multifit_linear_workspace * work);\r\n\r\nGSL_FUN int\r\ngsl_multifit_wlinear (const gsl_matrix * X,\r\n                      const gsl_vector * w,\r\n                      const gsl_vector * y,\r\n                      gsl_vector * c,\r\n                      gsl_matrix * cov,\r\n                      double * chisq,\r\n                      gsl_multifit_linear_workspace * work);\r\n\r\nGSL_FUN int\r\ngsl_multifit_wlinear_svd (const gsl_matrix * X,\r\n                          const gsl_vector * w,\r\n                          const gsl_vector * y,\r\n                          double tol,\r\n                          size_t * rank,\r\n                          gsl_vector * c,\r\n                          gsl_matrix * cov,\r\n                          double *chisq, \r\n                          gsl_multifit_linear_workspace * work);\r\n\r\nGSL_FUN int\r\ngsl_multifit_linear_est (const gsl_vector * x,\r\n                         const gsl_vector * c,\r\n                         const gsl_matrix * cov, double *y, double *y_err);\r\n\r\nGSL_FUN int\r\ngsl_multifit_linear_residuals (const gsl_matrix *X, const gsl_vector *y,\r\n                               const gsl_vector *c, gsl_vector *r);\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MULTIFIT_H__ */\r\n", "meta": {"hexsha": "401c2cb0bcabead87f652cd28154e622679a71ea", "size": 3733, "ext": "h", "lang": "C", "max_stars_repo_path": "deps/include/gsl/gsl_multifit.h", "max_stars_repo_name": "berkus/music-cs", "max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/include/gsl/gsl_multifit.h", "max_issues_repo_name": "berkus/music-cs", "max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/include/gsl/gsl_multifit.h", "max_forks_repo_name": "berkus/music-cs", "max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242", "max_forks_repo_licenses": ["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.1083333333, "max_line_length": 82, "alphanum_fraction": 0.58585588, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3735928447002456}}
{"text": "/* specfunc/exp.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_gamma.h>\n#include <gsl/gsl_sf_exp.h>\n\n#include \"error.h\"\n\n/* Evaluate the continued fraction for exprel.\n * [Abramowitz+Stegun, 4.2.41]\n */\nstatic\nint\nexprel_n_CF(const double N, const double x, gsl_sf_result * result)\n{\n  const double RECUR_BIG = GSL_SQRT_DBL_MAX;\n  const int maxiter = 5000;\n  int n = 1;\n  double Anm2 = 1.0;\n  double Bnm2 = 0.0;\n  double Anm1 = 0.0;\n  double Bnm1 = 1.0;\n  double a1 = 1.0;\n  double b1 = 1.0;\n  double a2 = -x;\n  double b2 = N+1;\n  double an, bn;\n\n  double fn;\n\n  double An = b1*Anm1 + a1*Anm2;   /* A1 */\n  double Bn = b1*Bnm1 + a1*Bnm2;   /* B1 */\n  \n  /* One explicit step, before we get to the main pattern. */\n  n++;\n  Anm2 = Anm1;\n  Bnm2 = Bnm1;\n  Anm1 = An;\n  Bnm1 = Bn;\n  An = b2*Anm1 + a2*Anm2;   /* A2 */\n  Bn = b2*Bnm1 + a2*Bnm2;   /* B2 */\n\n  fn = An/Bn;\n\n  while(n < maxiter) {\n    double old_fn;\n    double del;\n    n++;\n    Anm2 = Anm1;\n    Bnm2 = Bnm1;\n    Anm1 = An;\n    Bnm1 = Bn;\n    an = ( GSL_IS_ODD(n) ? ((n-1)/2)*x : -(N+(n/2)-1)*x );\n    bn = N + n - 1;\n    An = bn*Anm1 + an*Anm2;\n    Bn = bn*Bnm1 + an*Bnm2;\n\n    if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) {\n      An /= RECUR_BIG;\n      Bn /= RECUR_BIG;\n      Anm1 /= RECUR_BIG;\n      Bnm1 /= RECUR_BIG;\n      Anm2 /= RECUR_BIG;\n      Bnm2 /= RECUR_BIG;\n    }\n\n    old_fn = fn;\n    fn = An/Bn;\n    del = old_fn/fn;\n    \n    if(fabs(del - 1.0) < 2.0*GSL_DBL_EPSILON) break;\n  }\n\n  result->val = fn;\n  result->err = 4.0*(n+1.0)*GSL_DBL_EPSILON*fabs(fn);\n\n  if(n == maxiter)\n    GSL_ERROR (\"error\", GSL_EMAXITER);\n  else\n    return GSL_SUCCESS;\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_exp_e(const double x, gsl_sf_result * result)\n{\n  if(x > GSL_LOG_DBL_MAX) {\n    OVERFLOW_ERROR(result);\n  }\n  else if(x < GSL_LOG_DBL_MIN) {\n    UNDERFLOW_ERROR(result);\n  }\n  else {\n    result->val = exp(x);\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n}\n\nint gsl_sf_exp_e10_e(const double x, gsl_sf_result_e10 * result)\n{\n  if(x > INT_MAX-1) {\n    OVERFLOW_ERROR_E10(result);\n  }\n  else if(x < INT_MIN+1) {\n    UNDERFLOW_ERROR_E10(result);\n  }\n  else {\n    const int N = (x > GSL_LOG_DBL_MAX || x < GSL_LOG_DBL_MIN) ? (int) floor(x/M_LN10) : 0;\n    result->val = exp(x-N*M_LN10);\n    result->err = 2.0 * (fabs(x)+1.0) * GSL_DBL_EPSILON * fabs(result->val);\n    result->e10 = N;\n    return GSL_SUCCESS;\n  }\n}\n\n\nint gsl_sf_exp_mult_e(const double x, const double y, gsl_sf_result * result)\n{\n  const double ay  = fabs(y);\n\n  if(y == 0.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(   ( x < 0.5*GSL_LOG_DBL_MAX   &&   x > 0.5*GSL_LOG_DBL_MIN)\n          && (ay < 0.8*GSL_SQRT_DBL_MAX  &&  ay > 1.2*GSL_SQRT_DBL_MIN)\n    ) {\n    const double ex = exp(x);\n    result->val = y * ex;\n    result->err = (2.0 + fabs(x)) * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    const double ly  = log(ay);\n    const double lnr = x + ly;\n\n    if(lnr > GSL_LOG_DBL_MAX - 0.01) {\n      OVERFLOW_ERROR(result);\n    }\n    else if(lnr < GSL_LOG_DBL_MIN + 0.01) {\n      UNDERFLOW_ERROR(result);\n    }\n    else {\n      const double sy   = GSL_SIGN(y);\n      const double M    = floor(x);\n      const double N    = floor(ly);\n      const double a    = x  - M;\n      const double b    = ly - N;\n      const double berr = 2.0 * GSL_DBL_EPSILON * (fabs(ly) + fabs(N));\n      result->val  = sy * exp(M+N) * exp(a+b);\n      result->err  = berr * fabs(result->val);\n      result->err += 2.0 * GSL_DBL_EPSILON * (M + N + 1.0) * fabs(result->val);\n      return GSL_SUCCESS;\n    }\n  }\n}\n\n\nint gsl_sf_exp_mult_e10_e(const double x, const double y, gsl_sf_result_e10 * result)\n{\n  const double ay  = fabs(y);\n\n  if(y == 0.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    result->e10 = 0;\n    return GSL_SUCCESS;\n  }\n  else if(   ( x < 0.5*GSL_LOG_DBL_MAX   &&   x > 0.5*GSL_LOG_DBL_MIN)\n          && (ay < 0.8*GSL_SQRT_DBL_MAX  &&  ay > 1.2*GSL_SQRT_DBL_MIN)\n    ) {\n    const double ex = exp(x);\n    result->val = y * ex;\n    result->err = (2.0 + fabs(x)) * GSL_DBL_EPSILON * fabs(result->val);\n    result->e10 = 0;\n    return GSL_SUCCESS;\n  }\n  else {\n    const double ly  = log(ay);\n    const double l10_val = (x + ly)/M_LN10;\n\n    if(l10_val > INT_MAX-1) {\n      OVERFLOW_ERROR_E10(result);\n    }\n    else if(l10_val < INT_MIN+1) {\n      UNDERFLOW_ERROR_E10(result);\n    }\n    else {\n      const double sy  = GSL_SIGN(y);\n      const int    N   = (int) floor(l10_val);\n      const double arg_val = (l10_val - N) * M_LN10;\n      const double arg_err = 2.0 * GSL_DBL_EPSILON * (fabs(x) + fabs(ly) + M_LN10*fabs(N));\n\n      result->val  = sy * exp(arg_val);\n      result->err  = arg_err * fabs(result->val);\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      result->e10 = N;\n\n      return GSL_SUCCESS;\n    }\n  }\n}\n\n\nint gsl_sf_exp_mult_err_e(const double x, const double dx,\n                             const double y, const double dy,\n                             gsl_sf_result * result)\n{\n  const double ay  = fabs(y);\n\n  if(y == 0.0) {\n    result->val = 0.0;\n    result->err = fabs(dy * exp(x));\n    return GSL_SUCCESS;\n  }\n  else if(   ( x < 0.5*GSL_LOG_DBL_MAX   &&   x > 0.5*GSL_LOG_DBL_MIN)\n          && (ay < 0.8*GSL_SQRT_DBL_MAX  &&  ay > 1.2*GSL_SQRT_DBL_MIN)\n    ) {\n    double ex = exp(x);\n    result->val  = y * ex;\n    result->err  = ex * (fabs(dy) + fabs(y*dx));\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    const double ly  = log(ay);\n    const double lnr = x + ly;\n\n    if(lnr > GSL_LOG_DBL_MAX - 0.01) {\n      OVERFLOW_ERROR(result);\n    }\n    else if(lnr < GSL_LOG_DBL_MIN + 0.01) {\n      UNDERFLOW_ERROR(result);\n    }\n    else {\n      const double sy  = GSL_SIGN(y);\n      const double M   = floor(x);\n      const double N   = floor(ly);\n      const double a   = x  - M;\n      const double b   = ly - N;\n      const double eMN = exp(M+N);\n      const double eab = exp(a+b);\n      result->val  = sy * eMN * eab;\n      result->err  = eMN * eab * 2.0*GSL_DBL_EPSILON;\n      result->err += eMN * eab * fabs(dy/y);\n      result->err += eMN * eab * fabs(dx);\n      return GSL_SUCCESS;\n    }\n  }\n}\n\n\nint gsl_sf_exp_mult_err_e10_e(const double x, const double dx,\n                             const double y, const double dy,\n                             gsl_sf_result_e10 * result)\n{\n  const double ay  = fabs(y);\n\n  if(y == 0.0) {\n    result->val = 0.0;\n    result->err = fabs(dy * exp(x));\n    result->e10 = 0;\n    return GSL_SUCCESS;\n  }\n  else if(   ( x < 0.5*GSL_LOG_DBL_MAX   &&   x > 0.5*GSL_LOG_DBL_MIN)\n          && (ay < 0.8*GSL_SQRT_DBL_MAX  &&  ay > 1.2*GSL_SQRT_DBL_MIN)\n    ) {\n    const double ex = exp(x);\n    result->val  = y * ex;\n    result->err  = ex * (fabs(dy) + fabs(y*dx));\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    result->e10 = 0;\n    return GSL_SUCCESS;\n  }\n  else {\n    const double ly  = log(ay);\n    const double l10_val = (x + ly)/M_LN10;\n\n    if(l10_val > INT_MAX-1) {\n      OVERFLOW_ERROR_E10(result);\n    }\n    else if(l10_val < INT_MIN+1) {\n      UNDERFLOW_ERROR_E10(result);\n    }\n    else {\n      const double sy  = GSL_SIGN(y);\n      const int    N   = (int) floor(l10_val);\n      const double arg_val = (l10_val - N) * M_LN10;\n      const double arg_err = dy/fabs(y) + dx + 2.0*GSL_DBL_EPSILON*fabs(arg_val);\n\n      result->val  = sy * exp(arg_val);\n      result->err  = arg_err * fabs(result->val);\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      result->e10 = N;\n\n      return GSL_SUCCESS;\n    }\n  }\n}\n\n\nint gsl_sf_expm1_e(const double x, gsl_sf_result * result)\n{\n  const double cut = 0.002;\n\n  if(x < GSL_LOG_DBL_MIN) {\n    result->val = -1.0;\n    result->err = GSL_DBL_EPSILON;\n    return GSL_SUCCESS;\n  }\n  else if(x < -cut) {\n    result->val = exp(x) - 1.0;\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x < cut) {\n    result->val = x * (1.0 + 0.5*x*(1.0 + x/3.0*(1.0 + 0.25*x*(1.0 + 0.2*x))));\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  } \n  else if(x < GSL_LOG_DBL_MAX) {\n    result->val = exp(x) - 1.0;\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    OVERFLOW_ERROR(result);\n  }\n}\n\n\nint gsl_sf_exprel_e(const double x, gsl_sf_result * result)\n{\n  const double cut = 0.002;\n\n  if(x < GSL_LOG_DBL_MIN) {\n    result->val = -1.0/x;\n    result->err = GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x < -cut) {\n    result->val = (exp(x) - 1.0)/x;\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x < cut) {\n    result->val = (1.0 + 0.5*x*(1.0 + x/3.0*(1.0 + 0.25*x*(1.0 + 0.2*x))));\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  } \n  else if(x < GSL_LOG_DBL_MAX) {\n    result->val = (exp(x) - 1.0)/x;\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    OVERFLOW_ERROR(result);\n  }\n}\n\n\nint gsl_sf_exprel_2_e(double x, gsl_sf_result * result)\n{\n  const double cut = 0.002;\n\n  if(x < GSL_LOG_DBL_MIN) {\n    result->val = -2.0/x*(1.0 + 1.0/x);\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x < -cut) {\n    result->val = 2.0*(exp(x) - 1.0 - x)/(x*x);\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x < cut) {\n    result->val = (1.0 + 1.0/3.0*x*(1.0 + 0.25*x*(1.0 + 0.2*x*(1.0 + 1.0/6.0*x))));\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  } \n  else if(x < GSL_LOG_DBL_MAX) {\n    result->val = 2.0*(exp(x) - 1.0 - x)/(x*x);\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    OVERFLOW_ERROR(result);\n  }\n}\n\n\nint\ngsl_sf_exprel_n_CF_e(const double N, const double x, gsl_sf_result * result)\n{\n  return exprel_n_CF(N, x, result);\n}\n\nint\ngsl_sf_exprel_n_e(const int N, const double x, gsl_sf_result * result)\n{\n  if(N < 0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x == 0.0) {\n    result->val = 1.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(fabs(x) < GSL_ROOT3_DBL_EPSILON * N) {\n    result->val = 1.0 + x/(N+1) * (1.0 + x/(N+2));\n    result->err = 2.0 * GSL_DBL_EPSILON;\n    return GSL_SUCCESS;\n  }\n  else if(N == 0) {\n    return gsl_sf_exp_e(x, result);\n  }\n  else if(N == 1) {\n    return gsl_sf_exprel_e(x, result);\n  }\n  else if(N == 2) {\n    return gsl_sf_exprel_2_e(x, result);\n  }\n  else {\n    if(x > N && (-x + N*(1.0 + log(x/N)) < GSL_LOG_DBL_EPSILON)) {\n      /* x is much larger than n.\n       * Ignore polynomial part, so\n       * exprel_N(x) ~= e^x N!/x^N\n       */\n      gsl_sf_result lnf_N;\n      double lnr_val;\n      double lnr_err;\n      double lnterm;\n      gsl_sf_lnfact_e(N, &lnf_N);\n      lnterm = N*log(x);\n      lnr_val  = x + lnf_N.val - lnterm;\n      lnr_err  = GSL_DBL_EPSILON * (fabs(x) + fabs(lnf_N.val) + fabs(lnterm));\n      lnr_err += lnf_N.err;\n      return gsl_sf_exp_err_e(lnr_val, lnr_err, result);\n    }\n    else if(x > N) {\n      /* Write the identity\n       *   exprel_n(x) = e^x n! / x^n (1 - Gamma[n,x]/Gamma[n])\n       * then use the asymptotic expansion\n       * Gamma[n,x] ~ x^(n-1) e^(-x) (1 + (n-1)/x + (n-1)(n-2)/x^2 + ...)\n       */\n      double ln_x = log(x);\n      gsl_sf_result lnf_N;\n      double lg_N;\n      double lnpre_val;\n      double lnpre_err;\n      gsl_sf_lnfact_e(N, &lnf_N);    /* log(N!)       */\n      lg_N  = lnf_N.val - log(N);       /* log(Gamma(N)) */\n      lnpre_val  = x + lnf_N.val - N*ln_x;\n      lnpre_err  = GSL_DBL_EPSILON * (fabs(x) + fabs(lnf_N.val) + fabs(N*ln_x));\n      lnpre_err += lnf_N.err;\n      if(lnpre_val < GSL_LOG_DBL_MAX - 5.0) {\n        int stat_eG;\n        gsl_sf_result bigG_ratio;\n        gsl_sf_result pre;\n        int stat_ex = gsl_sf_exp_err_e(lnpre_val, lnpre_err, &pre);\n        double ln_bigG_ratio_pre = -x + (N-1)*ln_x - lg_N;\n        double bigGsum = 1.0;\n        double term = 1.0;\n        int k;\n        for(k=1; k<N; k++) {\n          term *= (N-k)/x;\n          bigGsum += term;\n        }\n        stat_eG = gsl_sf_exp_mult_e(ln_bigG_ratio_pre, bigGsum, &bigG_ratio);\n        if(stat_eG == GSL_SUCCESS) {\n          result->val  = pre.val * (1.0 - bigG_ratio.val);\n          result->err  = pre.val * (2.0*GSL_DBL_EPSILON + bigG_ratio.err);\n          result->err += pre.err * fabs(1.0 - bigG_ratio.val);\n          result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n          return stat_ex;\n        }\n        else {\n          result->val = 0.0;\n          result->err = 0.0;\n          return stat_eG;\n        }\n      }\n      else {\n        OVERFLOW_ERROR(result);\n      }\n    }\n    else if(x > -10.0*N) {\n      return exprel_n_CF(N, x, result);\n    }\n    else {\n      /* x -> -Inf asymptotic:\n       * exprel_n(x) ~ e^x n!/x^n - n/x (1 + (n-1)/x + (n-1)(n-2)/x + ...)\n       *             ~ - n/x (1 + (n-1)/x + (n-1)(n-2)/x + ...)\n       */\n      double sum  = 1.0;\n      double term = 1.0;\n      int k;\n      for(k=1; k<N; k++) {\n        term *= (N-k)/x;\n        sum  += term;\n      }\n      result->val = -N/x * sum;\n      result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      return GSL_SUCCESS;\n    }\n  }\n}\n\n\nint\ngsl_sf_exp_err_e(const double x, const double dx, gsl_sf_result * result)\n{\n  const double adx = fabs(dx);\n\n  /* CHECK_POINTER(result) */\n\n  if(x + adx > GSL_LOG_DBL_MAX) {\n    OVERFLOW_ERROR(result);\n  }\n  else if(x - adx < GSL_LOG_DBL_MIN) {\n    UNDERFLOW_ERROR(result);\n  }\n  else {\n    const double ex  = exp(x);\n    const double edx = exp(adx);\n    result->val  = ex;\n    result->err  = ex * GSL_MAX_DBL(GSL_DBL_EPSILON, edx - 1.0/edx);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n}\n\n\nint\ngsl_sf_exp_err_e10_e(const double x, const double dx, gsl_sf_result_e10 * result)\n{\n  const double adx = fabs(dx);\n\n  /* CHECK_POINTER(result) */\n\n  if(x + adx > INT_MAX - 1) {\n    OVERFLOW_ERROR_E10(result);\n  }\n  else if(x - adx < INT_MIN + 1) {\n    UNDERFLOW_ERROR_E10(result);\n  }\n  else {\n    const int    N  = (int)floor(x/M_LN10);\n    const double ex = exp(x-N*M_LN10);\n    result->val = ex;\n    result->err = ex * (2.0 * GSL_DBL_EPSILON * (fabs(x) + 1.0) + adx);\n    result->e10 = N;\n    return GSL_SUCCESS;\n  }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_exp(const double x)\n{\n  EVAL_RESULT(gsl_sf_exp_e(x, &result));\n}\n\ndouble gsl_sf_exp_mult(const double x, const double y)\n{\n  EVAL_RESULT(gsl_sf_exp_mult_e(x, y, &result));\n}\n\ndouble gsl_sf_expm1(const double x)\n{\n  EVAL_RESULT(gsl_sf_expm1_e(x, &result));\n}\n\ndouble gsl_sf_exprel(const double x)\n{\n  EVAL_RESULT(gsl_sf_exprel_e(x, &result));\n}\n\ndouble gsl_sf_exprel_2(const double x)\n{\n  EVAL_RESULT(gsl_sf_exprel_2_e(x, &result));\n}\n\ndouble gsl_sf_exprel_n(const int n, const double x)\n{\n  EVAL_RESULT(gsl_sf_exprel_n_e(n, x, &result));\n}\n", "meta": {"hexsha": "3045b2523fc05c2bfd29c23bd08cdda509c9d5ba", "size": 16030, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/exp.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/exp.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/exp.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 26.0650406504, "max_line_length": 91, "alphanum_fraction": 0.570617592, "num_tokens": 5527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3734539053432079}}
{"text": "/*\nCopyright (c) 2015, Patrick Weltevrede\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include <time.h>\n#include <sys/time.h>\n#include <math.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_cdf.h>\n#include \"psrsalsa.h\"\nlong randomUnsignedInt()\n{\n  time_t seconds;\n  struct timeval precisetime;\n  time(&seconds);\n  gettimeofday(&precisetime,0x0);\n  return (long)seconds*(long)precisetime.tv_usec;\n}\nvoid randomize_idnum(long *idnum)\n{\n  *idnum = -randomUnsignedInt();\n}\nint find_peak_correlation(float *data1, float *data2, int ndata, int zeropad, int circularpad, int duplicate, int remove_baseline, int *lag, float *correl_max, verbose_definition verbose)\n{\n  int i, lag_max;\n  int npoints;\n  float *paddata1, *paddata2, *ans, ans_max, ans_min;\n  if(duplicate)\n    duplicate = ndata;\n  if(verbose.verbose) {\n    for(i = 0; i < verbose.indent; i++)\n      printf(\" \");\n    printf(\"%d points in the data\\n\", ndata);\n    if(zeropad != 0) {\n      for(i = 0; i < verbose.indent; i++)\n printf(\" \");\n      printf(\"Padding at least %d points before and after data\\n\", zeropad);\n    }\n    if(duplicate) {\n      for(i = 0; i < verbose.indent; i++)\n printf(\" \");\n      printf(\"Duplicating data to avoid wrap problems enabled.\\n\");\n    }\n  }\n  i = (int) (log10(1.0 * (ndata+2*zeropad+duplicate))/0.301031);\n  npoints = pow(2.0,(i+1));\n  if(verbose.verbose) {\n    for(i = 0; i < verbose.indent; i++)\n      printf(\" \");\n    printf(\"Going to zero-pad it to %d points\\n\", npoints);\n  }\n  paddata1 = (float *)malloc(npoints*sizeof(float));\n  paddata2 = (float *)malloc(npoints*sizeof(float));\n  ans = (float *)malloc(2*npoints*sizeof(float));\n  if(paddata1 == NULL || paddata2 == NULL || ans == NULL) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR find_peak_correlation: Memory allocation error.\");\n    return 0;\n  }\n  zeropad = (npoints - duplicate - ndata)/2;\n  for(i = 0; i < ndata; i++) {\n    paddata1[i+zeropad] = data1[i];\n    paddata2[i+zeropad] = data2[i];\n    if(duplicate) {\n      paddata1[i+ndata+zeropad] = data1[i];\n      paddata2[i+ndata+zeropad] = data2[i];\n    }\n  }\n  for(i = 0; i < zeropad; i++) {\n    paddata1[i] = data1[i-zeropad+ndata];\n    paddata2[i] = data2[i-zeropad+ndata];\n  }\n  for(i = ndata+duplicate+zeropad; i < npoints; i++) {\n    paddata1[i] = data1[i-duplicate-zeropad-ndata];\n    paddata2[i] = data2[i-duplicate-zeropad-ndata];\n  }\n  if(crosscorrelation_fft(paddata1, paddata2, npoints, ans, remove_baseline, verbose) == 0) {\n    fflush(stdout);\n    printerror(verbose.debug, \"ERROR find_peak_correlation: Cross correlation failed.\");\n    return 0;\n  }\n  lag_max = 0;\n  ans_max = ans[0];\n  ans_min = ans[0];\n  for(i = 1; i < npoints; i++) {\n    if(ans[i] > ans_max) {\n      ans_max = ans[i];\n      lag_max = i;\n    }\n    if(ans[i] < ans_min)\n      ans_min = ans[i];\n  }\n  if(lag_max >= npoints/2)\n    lag_max -= npoints;\n  *correl_max = ans_max/ans_min;\n  *lag = lag_max;\n  if(verbose.verbose) {\n    for(i = 0; i < verbose.indent; i++)\n      printf(\" \");\n    printf(\"Found a lag of %d (correlation %f higher)\\n\", *lag, *correl_max);\n  }\n  free(paddata1);\n  free(paddata2);\n  free(ans);\n  return 1;\n}\nlong calculate_bin_number(double x, double dx, double min_x, int centered_at_zero, double extra_phase)\n{\n  long bin, step, binzero;\n  if(min_x < 0)\n    step = -min_x/dx+10;\n  else\n    step = 0;\n  bin = ( x+(step+0.5*centered_at_zero-extra_phase)*dx)/dx;\n  binzero = (min_x+(step+0.5*centered_at_zero-extra_phase)*dx)/dx;\n  bin -= binzero;\n  return bin;\n}\ndouble calculate_bin_location(long binnr, double dx, double min_x, int centered_at_zero, double extra_phase)\n{\n  long step, binzero;\n  double x;\n  if(min_x < 0)\n    step = -min_x/dx+10;\n  else\n    step = 0;\n  binzero = (min_x+(step+0.5*centered_at_zero-extra_phase)*dx)/dx;\n  binnr = binnr + binzero;\n  x = binnr*dx - (step+0.5*centered_at_zero-extra_phase)*dx;\n  x += 0.5*dx;\n  return x;\n}\ndouble calculate_required_bin_width(double x, long binnr, double min_x, int centered_at_zero, double extra_phase, verbose_definition verbose)\n{\n  long lastbin, ok, timesinloop;\n  double dx, offset;\n  dx = (x - min_x)/(double)(binnr+0.5);\n  timesinloop = 0;\n  offset = 0;\n  do {\n    ok = 1;\n    dx = (x - min_x)/(double)(binnr+0.5) + offset;\n    lastbin = calculate_bin_number(x, dx, min_x, centered_at_zero, extra_phase);\n    if(lastbin < binnr) {\n      offset += (x-min_x-0.5*dx)/(double)(binnr+0.5) - dx;\n      ok = 0;\n    }else if(lastbin > binnr) {\n      offset += (x-min_x+0.5*dx)/(double)(binnr+0.5) -dx;\n      ok = 0;\n    }\n    timesinloop++;\n    if(timesinloop > 10) {\n      printerror(verbose.debug, \"ERROR calculate_required_bin_width: Cannot find suitable binsize.\\n\");\n      return dx;\n    }\n  }while(ok == 0);\n  return dx;\n}\nint set_binning_histogram(double min_x_data, double max_x_data, int rangex_set, double rangex_min, double rangex_max, int nrbins_specified, long nrbins, int centered_at_zero, double extra_phase, double *min_x, double *max_x, double *dx, verbose_definition verbose)\n{\n  int reset;\n  do {\n    reset = 0;\n    *min_x = min_x_data;\n    *max_x = max_x_data;\n    if(rangex_set) {\n      *min_x = rangex_min;\n      *max_x = rangex_max;\n    }\n    if(nrbins_specified) {\n      *dx = calculate_required_bin_width(*max_x, nrbins-1, *min_x, centered_at_zero, extra_phase, verbose);\n      if(verbose.verbose)\n fprintf(stdout, \"Going to use binsize %e.\\n\", *dx);\n    }\n    {\n      long firstbin;\n      firstbin = calculate_bin_number(*min_x, *dx, *min_x, centered_at_zero, extra_phase);\n      if(firstbin != 0) {\n printerror(verbose.debug, \"ERROR set_binning_histogram: Expected first bin to be number zero (it is %ld).\\n\", firstbin);\n return 2;\n      }\n    }\n    long i;\n    double diff;\n    i = calculate_bin_number(*max_x, *dx, *min_x, centered_at_zero, extra_phase);\n    diff = *max_x - calculate_bin_location(i, *dx, *min_x, centered_at_zero, extra_phase);\n    diff = diff/(*dx);\n    if(verbose.debug) {\n      printf(\"Current set max value (%e) is falling at phase=%e w.r.t. centre of last generated bin.\\n\", *max_x, diff);\n    }\n    if(diff > -0.501 && diff < -0.499) {\n      if(rangex_set) {\n rangex_max -= 0.5*(*dx);\n printwarning(verbose.debug, \"WARNING set_binning_histogram: Adjusting maximum value of the specified range to %e to avoid rounding errors. Going to reset choosen binning.\", rangex_max);\n reset = 1;\n      }\n    }\n    if(diff > 0.499 && diff < 0.501) {\n      if(rangex_set) {\n rangex_max += 0.5*(*dx);\n printwarning(verbose.debug, \"WARNING set_binning_histogram: Adjusting maximum value of the specified range to %e to avoid rounding errors. Going to reset choosen binning.\", rangex_max);\n reset = 1;\n      }else {\n *max_x += 0.5*(*dx);\n if(nrbins_specified) {\n   printwarning(verbose.debug, \"WARNING set_binning_histogram: Nr of bins might be different from what was requested to avoid rounding errors.\");\n }\n      }\n    }\n    i = calculate_bin_number(*min_x, *dx, *min_x, centered_at_zero, extra_phase);\n    diff = *min_x - calculate_bin_location(i, *dx, *min_x, centered_at_zero, extra_phase);\n    diff = diff/(*dx);\n    if(verbose.debug) {\n      printf(\"Current set min value (%e) is falling at phase=%e w.r.t. centre of first generated bin.\\n\", *min_x, diff);\n    }\n    if(diff > -0.501 && diff < -0.499) {\n      if(rangex_set) {\n rangex_min -= 0.5*(*dx);\n printwarning(verbose.debug, \"WARNING set_binning_histogram: Adjusting minimum value of the specified range to %e to avoid rounding errors. Going to reset choosen binning.\", rangex_min);\n reset = 1;\n      }else {\n *min_x -= 0.5*(*dx);\n if(nrbins_specified) {\n   printwarning(verbose.debug, \"WARNING set_binning_histogram: Nr of bins might be different from what was requested to avoid rounding errors.\");\n }\n      }\n    }\n    if(diff > 0.499 && diff < 0.501) {\n      if(rangex_set) {\n rangex_min += 0.5*(*dx);\n printwarning(verbose.debug, \"WARNING set_binning_histogram: Adjusting minimum value of the specified range to %e to avoid rounding errors. Going to reset choosen binning.\", rangex_min);\n reset = 1;\n      }\n    }\n    if(reset) {\n      printwarning(verbose.debug, \"WARNING set_binning_histogram: Re-adjusting choosen binning.\\n\", rangex_max);\n    }\n  }while(reset == 1);\n  return 0;\n}\ndouble kstest_cdf_flat(double x, double min_x, double max_x)\n{\n  if(x <= min_x)\n    return 0;\n  if(x >= max_x)\n    return 1;\n  return (x-min_x)/(max_x-min_x);\n}\ndouble kstest_cdf_sin(double x)\n{\n  if(x <= 0)\n    return 0;\n  if(x >= 90)\n    return 1;\n  return 1-cos(x*M_PI/180.0);\n}\nvoid kstest(double *data1, long n1, double *data2, long n2, int cdf_type, double input_value1, double input_value2, double (*cdf)(double), double *max_diff, double *prob, verbose_definition verbose)\n{\n  long i1, i2;\n  double effective_n, ks_statistic, sign, cur_term, last_term, coeff;\n  int converged;\n  gsl_sort(data1, 1, n1);\n  if(n2 > 0 && data2 != NULL)\n    gsl_sort(data2, 1, n2);\n  *max_diff = 0;\n  if(n2 > 0 && data2 != NULL) {\n    i1 = 0;\n    i2 = 0;\n    while(i1 < n1 && i2 < n2) {\n      double diff;\n      if(data1[i1] == data2[i2]) {\n i1++;\n i2++;\n      }else if(data1[i1] < data2[i2]) {\n i1++;\n      }else {\n i2++;\n      }\n      diff = fabs(i1/(double)n1 - i2/(double)n2);\n      if(diff > *max_diff)\n *max_diff = diff;\n    }\n    effective_n=n1*n2/(double)(n1+n2);\n  }else {\n    double cdf_right, cdf_left, cdf_model;\n    cdf_left = 0;\n    for(i1 = 0; i1 < n1; i1++) {\n      cdf_right = (i1+1)/(double)n1;\n      if(cdf_type == 0) {\n cdf_model = (*cdf)(data1[i1]);\n      }else if(cdf_type == 1) {\n cdf_model = kstest_cdf_flat(data1[i1], data1[0], data1[n1-1]);\n if(i1 == 0) {\n   printwarning(verbose.debug, \"WARNING kstest: Probability will be overestimated, since the minimum/maximum of the uniform distribution is based on the input values.\");\n }\n      }else if(cdf_type == 3) {\n cdf_model = kstest_cdf_flat(data1[i1], input_value1, input_value2);\n      }else if(cdf_type == 2) {\n cdf_model = kstest_cdf_sin(data1[i1]);\n      }else {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR kstest: Undefined type of cdf is specified.\");\n exit(0);\n      }\n      if(fabs(cdf_right-cdf_model) > *max_diff)\n *max_diff = fabs(cdf_right-cdf_model);\n      if(fabs(cdf_left-cdf_model) > *max_diff)\n *max_diff = fabs(cdf_left-cdf_model);\n      cdf_left = cdf_right;\n    }\n    effective_n=n1;\n  }\n  if(effective_n < 4) {\n    printwarning(verbose.debug, \"WARNING kstest: Number of data-points is too low to make use of approximations used in this implementation of the KS-test.\");\n  }\n  effective_n=sqrt(effective_n);\n  ks_statistic = (*max_diff)*(effective_n+0.12+0.11/effective_n);\n  coeff = -2.0*ks_statistic*ks_statistic;\n  *prob = 0;\n  sign = 1;\n  last_term = 0;\n  converged = 0;\n  for(i1 = 1; i1 <= 100; i1++) {\n    cur_term = sign*2.0*exp(coeff*i1*i1);\n    *prob += cur_term;\n    if(fabs(cur_term) <= 1e-5*fabs(last_term) || fabs(cur_term) <= 1e-10*(*prob)) {\n      converged = 1;\n      break;\n    }\n    last_term = cur_term;\n    sign = -sign;\n  }\n  if(!converged)\n    *prob = 1;\n  if(verbose.verbose) {\n    printf(\"KS-test statistic max_diff: %lf = %e\\n\", *max_diff, *max_diff);\n    printf(\"KS-test probability:        %lf = %e\\nA small probability means the two sets of points are drawn from a different distribution.\\n\", *prob, *prob);\n    printf(\"The null hypothesis \");\n    if(n2 > 0 && data2 != NULL) {\n      printf(\"(data sets are drawn from the same distribution) \");\n    }else {\n      printf(\"(data set is drawn from the specified distribution) \");\n    }\n#if GSL_VERSION_NUMBER >= 104\n    printf(\"can be rejected at the %.2lf sigma level.\\n\", gsl_cdf_gaussian_Pinv(0.5*(1.0-*prob)+0.5, 1.0));\n#else\n    printf(\"can be rejected at the XXXX sigma level (need GSL >= 1.4 to get this number).\\n\");\n#endif\n  }\n}\n", "meta": {"hexsha": "109b189caa6cc68848181c78224f6222bbe6578b", "size": 13087, "ext": "c", "lang": "C", "max_stars_repo_path": "src/lib/statistics.c", "max_stars_repo_name": "weltevrede/psrsalsa", "max_stars_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z", "max_issues_repo_path": "src/lib/statistics.c", "max_issues_repo_name": "weltevrede/psrsalsa", "max_issues_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z", "max_forks_repo_path": "src/lib/statistics.c", "max_forks_repo_name": "weltevrede/psrsalsa", "max_forks_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z", "avg_line_length": 36.1519337017, "max_line_length": 755, "alphanum_fraction": 0.6629479636, "num_tokens": 3924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3733251087757725}}
{"text": "// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess\n// 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// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the\n//    following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions\n//    and the following disclaimer in the documentation and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n// CAUSED AND ON ANY THEORY OF LIABILITY, 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 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/** \\file sht.h\n *\n *  \\brief Contains declaration and particular implementation of sirius::SHT class.\n */\n\n#ifndef __SHT_H__\n#define __SHT_H__\n\n#include <math.h>\n#include <stddef.h>\n#include <gsl/gsl_sf_coupling.h>\n#include <gsl/gsl_sf_legendre.h>\n#include <string.h>\n#include <vector>\n#include <algorithm>\n\n#include \"typedefs.h\"\n#include \"utils.h\"\n#include \"linalg.hpp\"\n#include \"lebedev_grids.hpp\"\n\nnamespace sirius {\n\n/// Spherical harmonics transformations and related oprtations.\n/** This class is responsible for the generation of complex and real spherical harmonics, generation of transformation\n *  matrices, transformation between spectral and real-space representations, generation of Gaunt and Clebsch-Gordan\n *  coefficients and calculation of spherical harmonic derivatives */\nclass SHT // TODO: better name\n{\n    private:\n\n        /// Maximum \\f$ \\ell \\f$ of spherical harmonics.\n        int lmax_;\n\n        /// Maximum number of \\f$ \\ell, m \\f$ components.\n        int lmmax_;\n\n        /// Number of real-space \\f$ (\\theta, \\phi) \\f$ points on the sphere.\n        int num_points_;\n\n        /// Cartesian coordinates of points (normalized to 1).\n        mdarray<double, 2> coord_;\n\n        /// \\f$ (\\theta, \\phi) \\f$ angles of points.\n        mdarray<double, 2> tp_;\n\n        /// Point weights.\n        std::vector<double> w_;\n\n        /// Backward transformation from Ylm to spherical coordinates.\n        mdarray<double_complex, 2> ylm_backward_;\n\n        /// Forward transformation from spherical coordinates to Ylm.\n        mdarray<double_complex, 2> ylm_forward_;\n\n        /// Backward transformation from Rlm to spherical coordinates.\n        mdarray<double, 2> rlm_backward_;\n\n        /// Forward transformation from spherical coordinates to Rlm.\n        mdarray<double, 2> rlm_forward_;\n\n        /// Type of spherical grid (0: Lebedev-Laikov, 1: uniform).\n        int mesh_type_;\n\n    public:\n\n        /// Default constructor.\n        SHT(int lmax__)\n            : lmax_(lmax__)\n            , mesh_type_(0)\n        {\n            lmmax_ = (lmax_ + 1) * (lmax_ + 1);\n\n            if (mesh_type_ == 0) {\n                num_points_ = Lebedev_Laikov_npoint(2 * lmax_);\n            }\n            if (mesh_type_ == 1) {\n                num_points_ = lmmax_;\n            }\n\n            std::vector<double> x(num_points_);\n            std::vector<double> y(num_points_);\n            std::vector<double> z(num_points_);\n\n            coord_ = mdarray<double, 2>(3, num_points_);\n\n            tp_ = mdarray<double, 2>(2, num_points_);\n\n            w_.resize(num_points_);\n\n            if (mesh_type_ == 0) Lebedev_Laikov_sphere(num_points_, &x[0], &y[0], &z[0], &w_[0]);\n            if (mesh_type_ == 1) uniform_coverage();\n\n            ylm_backward_ = mdarray<double_complex, 2>(lmmax_, num_points_);\n\n            ylm_forward_ = mdarray<double_complex, 2>(num_points_, lmmax_);\n\n            rlm_backward_ = mdarray<double, 2>(lmmax_, num_points_);\n\n            rlm_forward_ = mdarray<double, 2>(num_points_, lmmax_);\n\n            for (int itp = 0; itp < num_points_; itp++) {\n                if (mesh_type_ == 0) {\n                    coord_(0, itp) = x[itp];\n                    coord_(1, itp) = y[itp];\n                    coord_(2, itp) = z[itp];\n\n                    auto vs = spherical_coordinates(vector3d<double>(x[itp], y[itp], z[itp]));\n                    tp_(0, itp) = vs[1];\n                    tp_(1, itp) = vs[2];\n                    spherical_harmonics(lmax_, vs[1], vs[2], &ylm_backward_(0, itp));\n                    spherical_harmonics(lmax_, vs[1], vs[2], &rlm_backward_(0, itp));\n                    for (int lm = 0; lm < lmmax_; lm++) {\n                        ylm_forward_(itp, lm) = std::conj(ylm_backward_(lm, itp)) * w_[itp] * fourpi;\n                        rlm_forward_(itp, lm) = rlm_backward_(lm, itp) * w_[itp] * fourpi;\n                    }\n                }\n                if (mesh_type_ == 1) {\n                    double t = tp_(0, itp);\n                    double p = tp_(1, itp);\n\n                    coord_(0, itp) = sin(t) * cos(p);\n                    coord_(1, itp) = sin(t) * sin(p);\n                    coord_(2, itp) = cos(t);\n\n                    spherical_harmonics(lmax_, t, p, &ylm_backward_(0, itp));\n                    spherical_harmonics(lmax_, t, p, &rlm_backward_(0, itp));\n\n                    for (int lm = 0; lm < lmmax_; lm++) {\n                        ylm_forward_(lm, itp) = ylm_backward_(lm, itp);\n                        rlm_forward_(lm, itp) = rlm_backward_(lm, itp);\n                    }\n                }\n            }\n\n            if (mesh_type_ == 1) {\n                linalg<CPU>::geinv(lmmax_, ylm_forward_);\n                linalg<CPU>::geinv(lmmax_, rlm_forward_);\n            }\n\n            #if (__VERIFICATION > 0)\n            {\n                double dr = 0;\n                double dy = 0;\n\n                for (int lm = 0; lm < lmmax_; lm++)\n                {\n                    for (int lm1 = 0; lm1 < lmmax_; lm1++)\n                    {\n                        double t = 0;\n                        double_complex zt(0, 0);\n                        for (int itp = 0; itp < num_points_; itp++)\n                        {\n                            zt += ylm_forward_(itp, lm) * ylm_backward_(lm1, itp);\n                            t += rlm_forward_(itp, lm) * rlm_backward_(lm1, itp);\n                        }\n\n                        if (lm == lm1)\n                        {\n                            zt -= 1.0;\n                            t -= 1.0;\n                        }\n                        dr += std::abs(t);\n                        dy += std::abs(zt);\n                    }\n                }\n                dr = dr / lmmax_ / lmmax_;\n                dy = dy / lmmax_ / lmmax_;\n\n                if (dr > 1e-15 || dy > 1e-15)\n                {\n                    std::stringstream s;\n                    s << \"spherical mesh error is too big\" << std::endl\n                      << \"  real spherical integration error \" << dr << std::endl\n                      << \"  complex spherical integration error \" << dy;\n                    WARNING(s.str())\n                }\n\n                std::vector<double> flm(lmmax_);\n                std::vector<double> ftp(num_points_);\n                for (int lm = 0; lm < lmmax_; lm++)\n                {\n                    std::memset(&flm[0], 0, lmmax_ * sizeof(double));\n                    flm[lm] = 1.0;\n                    backward_transform(lmmax_, &flm[0], 1, lmmax_, &ftp[0]);\n                    forward_transform(&ftp[0], 1, lmmax_, lmmax_, &flm[0]);\n                    flm[lm] -= 1.0;\n\n                    double t = 0.0;\n                    for (int lm1 = 0; lm1 < lmmax_; lm1++) t += std::abs(flm[lm1]);\n\n                    t /= lmmax_;\n\n                    if (t > 1e-15)\n                    {\n                        std::stringstream s;\n                        s << \"test of backward / forward real SHT failed\" << std::endl\n                          << \"  total error \" << t;\n                        WARNING(s.str());\n                    }\n                }\n            }\n            #endif\n        }\n\n        /// Perform a backward transformation from spherical harmonics to spherical coordinates.\n        /** \\f[\n         *      f(\\theta, \\phi, r) = \\sum_{\\ell m} f_{\\ell m}(r) Y_{\\ell m}(\\theta, \\phi)\n         *  \\f]\n         *\n         *  \\param [in] ld Size of leading dimension of flm.\n         *  \\param [in] flm Raw pointer to \\f$ f_{\\ell m}(r) \\f$.\n         *  \\param [in] nr Number of radial points.\n         *  \\param [in] lmmax Maximum number of lm- harmonics to take into sum.\n         *  \\param [out] ftp Raw pointer to \\f$ f(\\theta, \\phi, r) \\f$.\n         */\n        template <typename T>\n        void backward_transform(int ld, T const* flm, int nr, int lmmax, T* ftp);\n\n        /// Perform a forward transformation from spherical coordinates to spherical harmonics.\n        /** \\f[\n         *      f_{\\ell m}(r) = \\iint  f(\\theta, \\phi, r) Y_{\\ell m}^{*}(\\theta, \\phi) \\sin \\theta d\\phi d\\theta =\n         *        \\sum_{i} f(\\theta_i, \\phi_i, r) Y_{\\ell m}^{*}(\\theta_i, \\phi_i) w_i\n         *  \\f]\n         *\n         *  \\param [in] ftp Raw pointer to \\f$ f(\\theta, \\phi, r) \\f$.\n         *  \\param [in] nr Number of radial points.\n         *  \\param [in] lmmax Maximum number of lm- coefficients to generate.\n         *  \\param [in] ld Size of leading dimension of flm.\n         *  \\param [out] flm Raw pointer to \\f$ f_{\\ell m}(r) \\f$.\n         */\n        template <typename T>\n        void forward_transform(T const* ftp, int nr, int lmmax, int ld, T* flm);\n\n        /// Convert form Rlm to Ylm representation.\n        static void convert(int lmax__, double const* f_rlm__, double_complex* f_ylm__)\n        {\n            int lm = 0;\n            for (int l = 0; l <= lmax__; l++) {\n                for (int m = -l; m <= l; m++) {\n                    if (m == 0) {\n                        f_ylm__[lm] = f_rlm__[lm];\n                    } else {\n                        int lm1 = Utils::lm_by_l_m(l, -m);\n                        f_ylm__[lm] = ylm_dot_rlm(l, m, m) * f_rlm__[lm] + ylm_dot_rlm(l, m, -m) * f_rlm__[lm1];\n                    }\n                    lm++;\n                }\n            }\n        }\n\n        /// Convert from Ylm to Rlm representation.\n        static void convert(int lmax__, double_complex const* f_ylm__, double* f_rlm__)\n        {\n            int lm = 0;\n            for (int l = 0; l <= lmax__; l++) {\n                for (int m = -l; m <= l; m++) {\n                    if (m == 0) {\n                        f_rlm__[lm] = std::real(f_ylm__[lm]);\n                    } else {\n                        int lm1 = Utils::lm_by_l_m(l, -m);\n                        f_rlm__[lm] = std::real(rlm_dot_ylm(l, m, m) * f_ylm__[lm] + rlm_dot_ylm(l, m, -m) * f_ylm__[lm1]);\n                    }\n                    lm++;\n                }\n            }\n        }\n\n        //void rlm_forward_iterative_transform(double *ftp__, int lmmax, int ncol, double* flm)\n        //{\n        //    Timer t(\"sirius::SHT::rlm_forward_iterative_transform\");\n        //\n        //    assert(lmmax <= lmmax_);\n\n        //    mdarray<double, 2> ftp(ftp__, num_points_, ncol);\n        //    mdarray<double, 2> ftp1(num_points_, ncol);\n        //\n        //    blas<cpu>::gemm(1, 0, lmmax, ncol, num_points_, 1.0, &rlm_forward_(0, 0), num_points_, &ftp(0, 0), num_points_, 0.0,\n        //                    flm, lmmax);\n        //\n        //    for (int i = 0; i < 2; i++)\n        //    {\n        //        rlm_backward_transform(flm, lmmax, ncol, &ftp1(0, 0));\n        //        double tdiff = 0.0;\n        //        for (int ir = 0; ir < ncol; ir++)\n        //        {\n        //            for (int itp = 0; itp < num_points_; itp++)\n        //            {\n        //                ftp1(itp, ir) = ftp(itp, ir) - ftp1(itp, ir);\n        //                //tdiff += fabs(ftp1(itp, ir));\n        //            }\n        //        }\n        //\n        //        for (int itp = 0; itp < num_points_; itp++)\n        //        {\n        //            tdiff += fabs(ftp1(itp, ncol - 1));\n        //        }\n        //        std::cout << \"iter : \" << i << \" avg. MT diff = \" << tdiff / num_points_ << std::endl;\n        //        blas<cpu>::gemm(1, 0, lmmax, ncol, num_points_, 1.0, &rlm_forward_(0, 0), num_points_, &ftp1(0, 0), num_points_, 1.0,\n        //                        flm, lmmax);\n        //    }\n        //}\n\n        /// Transform Cartesian coordinates [x,y,z] to spherical coordinates [r,theta,phi]\n        static vector3d<double> spherical_coordinates(vector3d<double> vc)\n        {\n            vector3d<double> vs;\n\n            const double eps{1e-12};\n\n            vs[0] = vc.length();\n\n            if (vs[0] <= eps) {\n                vs[1] = 0.0;\n                vs[2] = 0.0;\n            } else {\n                vs[1] = std::acos(vc[2] / vs[0]); // theta = cos^{-1}(z/r)\n\n                if (std::abs(vc[0]) > eps || std::abs(vc[1]) > eps) {\n                    vs[2] = std::atan2(vc[1], vc[0]); // phi = tan^{-1}(y/x)\n                    if (vs[2] < 0.0) {\n                        vs[2] += twopi;\n                    }\n                } else {\n                    vs[2] = 0.0;\n                }\n            }\n\n            return vs;\n        }\n\n        /// Generate complex spherical harmonics Ylm\n        static void spherical_harmonics(int lmax, double theta, double phi, double_complex* ylm)\n        {\n            double x = std::cos(theta);\n            std::vector<double> result_array(lmax + 1);\n\n            for (int l = 0; l <= lmax; l++) {\n                for (int m = 0; m <= l; m++) {\n                    double_complex z = std::exp(double_complex(0.0, m * phi));\n                    ylm[Utils::lm_by_l_m(l, m)] = gsl_sf_legendre_sphPlm(l, m, x) * z;\n                    if (m % 2) {\n                        ylm[Utils::lm_by_l_m(l, -m)] = -std::conj(ylm[Utils::lm_by_l_m(l, m)]);\n                    } else {\n                        ylm[Utils::lm_by_l_m(l, -m)] = std::conj(ylm[Utils::lm_by_l_m(l, m)]);\n                    }\n                }\n            }\n        }\n\n        /// Generate real spherical harmonics Rlm\n        /** Mathematica code:\n         *  \\verbatim\n         *  R[l_, m_, th_, ph_] :=\n         *   If[m > 0, std::sqrt[2]*ComplexExpand[Re[SphericalHarmonicY[l, m, th, ph]]],\n         *   If[m < 0, std::sqrt[2]*ComplexExpand[Im[SphericalHarmonicY[l, m, th, ph]]],\n         *   If[m == 0, ComplexExpand[Re[SphericalHarmonicY[l, 0, th, ph]]]]]]\n         *  \\endverbatim\n         */\n        static void spherical_harmonics(int lmax, double theta, double phi, double* rlm)\n        {\n            int lmmax = (lmax + 1) * (lmax + 1);\n            std::vector<double_complex> ylm(lmmax);\n            spherical_harmonics(lmax, theta, phi, &ylm[0]);\n\n            double const t = std::sqrt(2.0);\n\n            rlm[0] = y00;\n\n            for (int l = 1; l <= lmax; l++) {\n                for (int m = -l; m < 0; m++) {\n                    rlm[Utils::lm_by_l_m(l, m)] = t * ylm[Utils::lm_by_l_m(l, m)].imag();\n                }\n\n                rlm[Utils::lm_by_l_m(l, 0)] = ylm[Utils::lm_by_l_m(l, 0)].real();\n\n                for (int m = 1; m <= l; m++) {\n                    rlm[Utils::lm_by_l_m(l, m)] = t * ylm[Utils::lm_by_l_m(l, m)].real();\n                }\n            }\n        }\n\n        /// Compute element of the transformation matrix from complex to real spherical harmonics.\n        /** Real spherical harmonic can be written as a linear combination of complex harmonics:\n\n            \\f[\n                R_{\\ell m}(\\theta, \\phi) = \\sum_{m'} a^{\\ell}_{m' m}Y_{\\ell m'}(\\theta, \\phi)\n            \\f]\n            where\n            \\f[\n                a^{\\ell}_{m' m} = \\langle Y_{\\ell m'} | R_{\\ell m} \\rangle\n            \\f]\n            which gives the name to this function.\n\n            Transformation from real to complex spherical harmonics is conjugate transpose:\n\n            \\f[\n                Y_{\\ell m}(\\theta, \\phi) = \\sum_{m'} a^{\\ell*}_{m m'}R_{\\ell m'}(\\theta, \\phi)\n            \\f]\n\n            Mathematica code:\n            \\verbatim\n            b[m1_, m2_] :=\n             If[m1 == 0, 1,\n             If[m1 < 0 && m2 < 0, -I/Sqrt[2],\n             If[m1 > 0 && m2 < 0, (-1)^m1*I/Sqrt[2],\n             If[m1 < 0 && m2 > 0, (-1)^m2/Sqrt[2],\n             If[m1 > 0 && m2 > 0, 1/Sqrt[2]]]]]]\n\n            a[m1_, m2_] := If[Abs[m1] == Abs[m2], b[m1, m2], 0]\n\n            Rlm[l_, m_, t_, p_] := Sum[a[m1, m]*SphericalHarmonicY[l, m1, t, p], {m1, -l, l}]\n            \\endverbatim\n         */\n        static inline double_complex ylm_dot_rlm(int l, int m1, int m2)\n        {\n            double const isqrt2 = 1.0 / std::sqrt(2);\n\n            assert(l >= 0 && std::abs(m1) <= l && std::abs(m2) <= l);\n\n            if (!((m1 == m2) || (m1 == -m2))) {\n                return double_complex(0, 0);\n            }\n\n            if (m1 == 0) {\n                return double_complex(1, 0);\n            }\n\n            if (m1 < 0) {\n                if (m2 < 0) {\n                    return -double_complex(0, isqrt2);\n                } else {\n                    return std::pow(-1.0, m2) * double_complex(isqrt2, 0);\n                }\n            } else {\n                if (m2 < 0) {\n                    return std::pow(-1.0, m1) * double_complex(0, isqrt2);\n                } else {\n                    return double_complex(isqrt2, 0);\n                }\n            }\n        }\n\n        static inline double_complex rlm_dot_ylm(int l, int m1, int m2)\n        {\n            return std::conj(ylm_dot_rlm(l, m2, m1));\n        }\n\n        /// Gaunt coefficent of three complex spherical harmonics.\n        /**\n         *  \\f[\n         *    \\langle Y_{\\ell_1 m_1} | Y_{\\ell_2 m_2} | Y_{\\ell_3 m_3} \\rangle\n         *  \\f]\n         */\n        static double gaunt_ylm(int l1, int l2, int l3, int m1, int m2, int m3)\n        {\n            assert(l1 >= 0);\n            assert(l2 >= 0);\n            assert(l3 >= 0);\n            assert(m1 >= -l1 && m1 <= l1);\n            assert(m2 >= -l2 && m2 <= l2);\n            assert(m3 >= -l3 && m3 <= l3);\n\n            return std::pow(-1.0, std::abs(m1)) * std::sqrt(double(2 * l1 + 1) * double(2 * l2 + 1) * double(2 * l3 + 1) / fourpi) *\n                   gsl_sf_coupling_3j(2 * l1, 2 * l2, 2 * l3, 0, 0, 0) *\n                   gsl_sf_coupling_3j(2 * l1, 2 * l2, 2 * l3, -2 * m1, 2 * m2, 2 * m3);\n        }\n\n        /// Gaunt coefficent of three real spherical harmonics.\n        /**\n         *  \\f[\n         *    \\langle R_{\\ell_1 m_1} | R_{\\ell_2 m_2} | R_{\\ell_3 m_3} \\rangle\n         *  \\f]\n         */\n        static double gaunt_rlm(int l1, int l2, int l3, int m1, int m2, int m3)\n        {\n            assert(l1 >= 0);\n            assert(l2 >= 0);\n            assert(l3 >= 0);\n            assert(m1 >= -l1 && m1 <= l1);\n            assert(m2 >= -l2 && m2 <= l2);\n            assert(m3 >= -l3 && m3 <= l3);\n\n            double d = 0;\n            for (int k1 = -l1; k1 <= l1; k1++) {\n                for (int k2 = -l2; k2 <= l2; k2++) {\n                    for (int k3 = -l3; k3 <= l3; k3++) {\n                        d += std::real(std::conj(SHT::ylm_dot_rlm(l1, k1, m1)) *\n                                                 SHT::ylm_dot_rlm(l2, k2, m2) *\n                                                 SHT::ylm_dot_rlm(l3, k3, m3)) * SHT::gaunt_ylm(l1, l2, l3, k1, k2, k3);\n                    }\n                }\n            }\n            return d;\n        }\n\n        /// Gaunt coefficent of two real spherical harmonics with a complex one.\n        /**\n         *  \\f[\n         *    \\langle R_{\\ell_1 m_1} | Y_{\\ell_2 m_2} | R_{\\ell_3 m_3} \\rangle\n         *  \\f]\n         */\n        static double gaunt_rlm_ylm_rlm(int l1, int l2, int l3, int m1, int m2, int m3)\n        {\n            assert(l1 >= 0);\n            assert(l2 >= 0);\n            assert(l3 >= 0);\n            assert(m1 >= -l1 && m1 <= l1);\n            assert(m2 >= -l2 && m2 <= l2);\n            assert(m3 >= -l3 && m3 <= l3);\n\n            double d = 0;\n            for (int k1 = -l1; k1 <= l1; k1++) {\n                for (int k3 = -l3; k3 <= l3; k3++) {\n                    d += std::real(std::conj(SHT::ylm_dot_rlm(l1, k1, m1)) *\n                                   SHT::ylm_dot_rlm(l3, k3, m3)) * SHT::gaunt_ylm(l1, l2, l3, k1, m2, k3);\n                }\n            }\n            return d;\n        }\n\n        /// Gaunt coefficent of two complex and one real spherical harmonics.\n        /**\n         *  \\f[\n         *    \\langle Y_{\\ell_1 m_1} | R_{\\ell_2 m_2} | Y_{\\ell_3 m_3} \\rangle\n         *  \\f]\n         */\n        static double_complex gaunt_hybrid(int l1, int l2, int l3, int m1, int m2, int m3)\n        {\n            assert(l1 >= 0);\n            assert(l2 >= 0);\n            assert(l3 >= 0);\n            assert(m1 >= -l1 && m1 <= l1);\n            assert(m2 >= -l2 && m2 <= l2);\n            assert(m3 >= -l3 && m3 <= l3);\n\n            if (m2 == 0) {\n                return double_complex(gaunt_ylm(l1, l2, l3, m1, m2, m3), 0.0);\n            } else {\n                return (ylm_dot_rlm(l2, m2, m2) * gaunt_ylm(l1, l2, l3, m1, m2, m3) +\n                        ylm_dot_rlm(l2, -m2, m2) * gaunt_ylm(l1, l2, l3, m1, -m2, m3));\n            }\n        }\n\n        void uniform_coverage()\n        {\n            tp_(0, 0) = pi;\n            tp_(1, 0) = 0;\n\n            for (int k = 1; k < num_points_ - 1; k++) {\n                double hk = -1.0 + double(2 * k) / double(num_points_ - 1);\n                tp_(0, k) = std::acos(hk);\n                double t = tp_(1, k - 1) + 3.80925122745582 / std::sqrt(double(num_points_)) / std::sqrt(1 - hk * hk);\n                tp_(1, k) = std::fmod(t, twopi);\n            }\n\n            tp_(0, num_points_ - 1) = 0;\n            tp_(1, num_points_ - 1) = 0;\n        }\n\n        /// Return Clebsch-Gordan coefficient.\n        /** Clebsch-Gordan coefficients arise when two angular momenta are combined into a\n         *  total angular momentum.\n         */\n        static inline double clebsch_gordan(int l1, int l2, int l3, int m1, int m2, int m3)\n        {\n            assert(l1 >= 0);\n            assert(l2 >= 0);\n            assert(l3 >= 0);\n            assert(m1 >= -l1 && m1 <= l1);\n            assert(m2 >= -l2 && m2 <= l2);\n            assert(m3 >= -l3 && m3 <= l3);\n\n            return std::pow(-1, l1 - l2 + m3) * std::sqrt(double(2 * l3 + 1)) *\n                   gsl_sf_coupling_3j(2 * l1, 2 * l2, 2 * l3, 2 * m1, 2 * m2, -2 * m3);\n        }\n\n        inline double_complex ylm_backward(int lm,  int itp) const\n        {\n            return ylm_backward_(lm, itp);\n        }\n\n        inline double rlm_backward(int lm,  int itp) const\n        {\n            return rlm_backward_(lm, itp);\n        }\n\n        inline double coord(int x, int itp) const\n        {\n            return coord_(x, itp);\n        }\n\n        inline vector3d<double> coord(int idx__) const\n        {\n            return vector3d<double>(coord_(0, idx__), coord_(1, idx__), coord(2, idx__));\n        }\n\n        inline double theta(int idx__) const\n        {\n            return tp_(0, idx__);\n        }\n\n        inline double phi(int idx__) const\n        {\n            return tp_(1, idx__);\n        }\n\n        inline int num_points() const\n        {\n            return num_points_;\n        }\n\n        inline int lmax() const\n        {\n            return lmax_;\n        }\n\n        inline int lmmax() const\n        {\n            return lmmax_;\n        }\n\n        static void wigner_d_matrix(int l, double beta, mdarray<double, 2>& d_mtrx__)\n        {\n            long double cos_b2 = std::cos((long double)beta / 2.0L);\n            long double sin_b2 = std::sin((long double)beta / 2.0L);\n\n            for (int m1 = -l; m1 <= l; m1++) {\n                for (int m2 = -l; m2 <= l; m2++) {\n                    long double d = 0;\n                    for (int j = 0; j <= std::min(l + m1, l - m2); j++) {\n                        if ((l - m2 - j) >= 0 && (l + m1 - j) >= 0 && (j + m2 - m1) >= 0) {\n                            long double g = (std::sqrt(Utils::factorial(l + m1)) / Utils::factorial(l - m2 - j)) *\n                                            (std::sqrt(Utils::factorial(l - m1)) / Utils::factorial(l + m1 - j)) *\n                                            (std::sqrt(Utils::factorial(l - m2)) / Utils::factorial(j + m2 - m1)) *\n                                            (std::sqrt(Utils::factorial(l + m2)) / Utils::factorial(j));\n                            d += g * std::pow(-1, j) * std::pow(cos_b2, 2 * l + m1 - m2 - 2 * j) * std::pow(sin_b2, 2 * j + m2 - m1);\n                        }\n                    }\n                    d_mtrx__(m1 + l, m2 + l) = (double)d;\n                }\n            }\n        }\n\n        static void rotation_matrix_l(int l, vector3d<double> euler_angles, int proper_rotation,\n                                      double_complex* rot_mtrx__, int ld)\n        {\n            mdarray<double_complex, 2> rot_mtrx(rot_mtrx__, ld, 2 * l + 1);\n\n            mdarray<double, 2> d_mtrx(2 * l + 1, 2 * l + 1);\n            wigner_d_matrix(l, euler_angles[1], d_mtrx);\n\n            for (int m1 = -l; m1 <= l; m1++) {\n                for (int m2 = -l; m2 <= l; m2++) {\n                    rot_mtrx(m1 + l, m2 + l) = std::exp(double_complex(0, -euler_angles[0] * m1 - euler_angles[2] * m2)) *\n                                               d_mtrx(m1 + l, m2 + l) * std::pow(proper_rotation, l);\n                }\n            }\n        }\n\n        static void rotation_matrix_l(int l, vector3d<double> euler_angles, int proper_rotation,\n                                      double* rot_mtrx__, int ld)\n        {\n            mdarray<double, 2> rot_mtrx_rlm(rot_mtrx__, ld, 2 * l + 1);\n            mdarray<double_complex, 2> rot_mtrx_ylm(2 * l + 1, 2 * l + 1);\n\n            mdarray<double, 2> d_mtrx(2 * l + 1, 2 * l + 1);\n            wigner_d_matrix(l, euler_angles[1], d_mtrx);\n\n            for (int m1 = -l; m1 <= l; m1++)\n            {\n                for (int m2 = -l; m2 <= l; m2++)\n                {\n                    rot_mtrx_ylm(m1 + l, m2 + l) = std::exp(double_complex(0, -euler_angles[0] * m1 - euler_angles[2] * m2)) *\n                                                   d_mtrx(m1 + l, m2 + l) * std::pow(proper_rotation, l);\n                }\n            }\n            for (int m1 = -l; m1 <= l; m1++)\n            {\n                auto i13 = (m1 == 0) ? std::vector<int>({0}) : std::vector<int>({-m1, m1});\n\n                for (int m2 = -l; m2 <= l; m2++)\n                {\n                    auto i24 = (m2 == 0) ? std::vector<int>({0}) : std::vector<int>({-m2, m2});\n\n                    for (int m3: i13)\n                    {\n                        for (int m4: i24)\n                        {\n                            rot_mtrx_rlm(m1 + l, m2 + l) += std::real(rlm_dot_ylm(l, m1, m3) *\n                                                                      rot_mtrx_ylm(m3 + l, m4 + l) *\n                                                                      ylm_dot_rlm(l, m4, m2));\n                        }\n                    }\n                }\n            }\n        }\n\n        template <typename T>\n        static void rotation_matrix(int              lmax,\n                                    vector3d<double> euler_angles,\n                                    int              proper_rotation,\n                                    mdarray<T, 2>&   rotm)\n        {\n            rotm.zero();\n\n            for (int l = 0; l <= lmax; l++) {\n                rotation_matrix_l(l, euler_angles, proper_rotation, &rotm(l * l, l * l), rotm.ld());\n            }\n        }\n\n        /// Compute derivative of real-spherical harmonic with respect to theta angle.\n        static void dRlm_dtheta(int lmax, double theta, double phi, mdarray<double, 1>& data)\n        {\n            assert(lmax <= 8);\n\n            data[0]=0;\n\n            if (lmax==0) return;\n\n            auto cos_theta = SHT::cosxn(lmax, theta);\n            auto sin_theta = SHT::sinxn(lmax, theta);\n            auto cos_phi = SHT::cosxn(lmax, phi);\n            auto sin_phi = SHT::sinxn(lmax, phi);\n\n            data[1]=-(std::sqrt(3/pi)*cos_theta[0]*sin_phi[0])/2.;\n\n            data[2]=-(std::sqrt(3/pi)*sin_theta[0])/2.;\n\n            data[3]=-(std::sqrt(3/pi)*cos_phi[0]*cos_theta[0])/2.;\n\n            if (lmax==1) return;\n\n            data[4]=-(std::sqrt(15/pi)*cos_phi[0]*cos_theta[0]*sin_phi[0]*sin_theta[0]);\n\n            data[5]=-(std::sqrt(15/pi)*cos_theta[1]*sin_phi[0])/2.;\n\n            data[6]=(-3*std::sqrt(5/pi)*cos_theta[0]*sin_theta[0])/2.;\n\n            data[7]=-(std::sqrt(15/pi)*cos_phi[0]*cos_theta[1])/2.;\n\n            data[8]=(std::sqrt(15/pi)*cos_phi[1]*sin_theta[1])/4.;\n\n            if (lmax==2) return;\n\n            data[9]=(-3*std::sqrt(35/(2.*pi))*cos_theta[0]*sin_phi[2]*std::pow(sin_theta[0],2))/4.;\n\n            data[10]=(std::sqrt(105/pi)*sin_phi[1]*(sin_theta[0] - 3*sin_theta[2]))/16.;\n\n            data[11]=-(std::sqrt(21/(2.*pi))*(cos_theta[0] + 15*cos_theta[2])*sin_phi[0])/16.;\n\n            data[12]=(-3*std::sqrt(7/pi)*(sin_theta[0] + 5*sin_theta[2]))/16.;\n\n            data[13]=-(std::sqrt(21/(2.*pi))*cos_phi[0]*(cos_theta[0] + 15*cos_theta[2]))/16.;\n\n            data[14]=-(std::sqrt(105/pi)*cos_phi[1]*(sin_theta[0] - 3*sin_theta[2]))/16.;\n\n            data[15]=(-3*std::sqrt(35/(2.*pi))*cos_phi[2]*cos_theta[0]*std::pow(sin_theta[0],2))/4.;\n\n            if (lmax==3) return;\n\n            data[16]=(-3*std::sqrt(35/pi)*cos_theta[0]*sin_phi[3]*std::pow(sin_theta[0],3))/4.;\n\n            data[17]=(-3*std::sqrt(35/(2.*pi))*(1 + 2*cos_theta[1])*sin_phi[2]*std::pow(sin_theta[0],2))/4.;\n\n            data[18]=(3*std::sqrt(5/pi)*sin_phi[1]*(2*sin_theta[1] - 7*sin_theta[3]))/16.;\n\n            data[19]=(-3*std::sqrt(5/(2.*pi))*(cos_theta[1] + 7*cos_theta[3])*sin_phi[0])/8.;\n\n            data[20]=(-15*(2*sin_theta[1] + 7*sin_theta[3]))/(32.*std::sqrt(pi));\n\n            data[21]=(-3*std::sqrt(5/(2.*pi))*cos_phi[0]*(cos_theta[1] + 7*cos_theta[3]))/8.;\n\n            data[22]=(3*std::sqrt(5/pi)*cos_phi[1]*(-2*sin_theta[1] + 7*sin_theta[3]))/16.;\n\n            data[23]=(-3*std::sqrt(35/(2.*pi))*cos_phi[2]*(1 + 2*cos_theta[1])*std::pow(sin_theta[0],2))/4.;\n\n            data[24]=(3*std::sqrt(35/pi)*cos_phi[3]*cos_theta[0]*std::pow(sin_theta[0],3))/4.;\n\n            if (lmax==4) return;\n\n            data[25]=(-15*std::sqrt(77/(2.*pi))*cos_theta[0]*sin_phi[4]*std::pow(sin_theta[0],4))/16.;\n\n            data[26]=(-3*std::sqrt(385/pi)*(3 + 5*cos_theta[1])*sin_phi[3]*std::pow(sin_theta[0],3))/32.;\n\n            data[27]=(-3*std::sqrt(385/(2.*pi))*cos_theta[0]*(1 + 15*cos_theta[1])*sin_phi[2]*std::pow(sin_theta[0],2))/32.;\n\n            data[28]=(std::sqrt(1155/pi)*sin_phi[1]*(2*sin_theta[0] + 3*(sin_theta[2] - 5*sin_theta[4])))/128.;\n\n            data[29]=-(std::sqrt(165/pi)*(2*cos_theta[0] + 21*(cos_theta[2] + 5*cos_theta[4]))*sin_phi[0])/256.;\n\n            data[30]=(-15*std::sqrt(11/pi)*(2*sin_theta[0] + 7*(sin_theta[2] + 3*sin_theta[4])))/256.;\n\n            data[31]=-(std::sqrt(165/pi)*cos_phi[0]*(2*cos_theta[0] + 21*(cos_theta[2] + 5*cos_theta[4])))/256.;\n\n            data[32]=(std::sqrt(1155/pi)*cos_phi[1]*(-2*sin_theta[0] - 3*sin_theta[2] + 15*sin_theta[4]))/128.;\n\n            data[33]=(-3*std::sqrt(385/(2.*pi))*cos_phi[2]*(17*cos_theta[0] + 15*cos_theta[2])*std::pow(sin_theta[0],2))/64.;\n\n            data[34]=(3*std::sqrt(385/pi)*cos_phi[3]*(3 + 5*cos_theta[1])*std::pow(sin_theta[0],3))/32.;\n\n            data[35]=(-15*std::sqrt(77/(2.*pi))*cos_phi[4]*cos_theta[0]*std::pow(sin_theta[0],4))/16.;\n\n            if (lmax==5) return;\n\n            data[36]=(-3*std::sqrt(3003/(2.*pi))*cos_theta[0]*sin_phi[5]*std::pow(sin_theta[0],5))/16.;\n\n            data[37]=(-3*std::sqrt(1001/(2.*pi))*(2 + 3*cos_theta[1])*sin_phi[4]*std::pow(sin_theta[0],4))/16.;\n\n            data[38]=(-3*std::sqrt(91/pi)*cos_theta[0]*(7 + 33*cos_theta[1])*sin_phi[3]*std::pow(sin_theta[0],3))/32.;\n\n            data[39]=(-3*std::sqrt(1365/(2.*pi))*(7 + 14*cos_theta[1] + 11*cos_theta[3])*sin_phi[2]*std::pow(sin_theta[0],2))/64.;\n\n            data[40]=(std::sqrt(1365/(2.*pi))*sin_phi[1]*(17*sin_theta[1] + 12*sin_theta[3] - 99*sin_theta[5]))/512.;\n\n            data[41]=-(std::sqrt(273/pi)*(5*cos_theta[1] + 24*cos_theta[3] + 99*cos_theta[5])*sin_phi[0])/256.;\n\n            data[42]=(-21*std::sqrt(13/pi)*(5*sin_theta[1] + 12*sin_theta[3] + 33*sin_theta[5]))/512.;\n\n            data[43]=-(std::sqrt(273/pi)*cos_phi[0]*(5*cos_theta[1] + 24*cos_theta[3] + 99*cos_theta[5]))/256.;\n\n            data[44]=(std::sqrt(1365/(2.*pi))*cos_phi[1]*(-17*sin_theta[1] - 12*sin_theta[3] + 99*sin_theta[5]))/512.;\n\n            data[45]=(-3*std::sqrt(1365/(2.*pi))*cos_phi[2]*(7 + 14*cos_theta[1] + 11*cos_theta[3])*std::pow(sin_theta[0],2))/64.;\n\n            data[46]=(3*std::sqrt(91/pi)*cos_phi[3]*(47*cos_theta[0] + 33*cos_theta[2])*std::pow(sin_theta[0],3))/64.;\n\n            data[47]=(-3*std::sqrt(1001/(2.*pi))*cos_phi[4]*(2 + 3*cos_theta[1])*std::pow(sin_theta[0],4))/16.;\n\n            data[48]=(3*std::sqrt(3003/(2.*pi))*cos_phi[5]*cos_theta[0]*std::pow(sin_theta[0],5))/16.;\n\n            if (lmax==6) return;\n\n            data[49]=(-21*std::sqrt(715/pi)*cos_theta[0]*sin_phi[6]*std::pow(sin_theta[0],6))/64.;\n\n            data[50]=(-3*std::sqrt(5005/(2.*pi))*(5 + 7*cos_theta[1])*sin_phi[5]*std::pow(sin_theta[0],5))/64.;\n\n            data[51]=(-3*std::sqrt(385/pi)*cos_theta[0]*(29 + 91*cos_theta[1])*sin_phi[4]*std::pow(sin_theta[0],4))/128.;\n\n            data[52]=(-3*std::sqrt(385/pi)*(81 + 148*cos_theta[1] + 91*cos_theta[3])*sin_phi[3]*std::pow(sin_theta[0],3))/256.;\n\n            data[53]=(-3*std::sqrt(35/pi)*cos_theta[0]*(523 + 396*cos_theta[1] + 1001*cos_theta[3])*sin_phi[2]*std::pow(sin_theta[0],2))/512.;\n\n            data[54]=(3*std::sqrt(35/(2.*pi))*sin_phi[1]*(75*sin_theta[0] + 171*sin_theta[2] + 55*sin_theta[4] - 1001*sin_theta[6]))/2048.;\n\n            data[55]=-(std::sqrt(105/pi)*(25*cos_theta[0] + 243*cos_theta[2] + 825*cos_theta[4] + 3003*cos_theta[6])*sin_phi[0])/4096.;\n\n            data[56]=(-7*std::sqrt(15/pi)*(25*sin_theta[0] + 81*sin_theta[2] + 165*sin_theta[4] + 429*sin_theta[6]))/2048.;\n\n            data[57]=-(std::sqrt(105/pi)*cos_phi[0]*(25*cos_theta[0] + 243*cos_theta[2] + 825*cos_theta[4] + 3003*cos_theta[6]))/4096.;\n\n            data[58]=(-3*std::sqrt(35/(2.*pi))*cos_phi[1]*(75*sin_theta[0] + 171*sin_theta[2] + 55*sin_theta[4] - 1001*sin_theta[6]))/2048.;\n\n            data[59]=(-3*std::sqrt(35/pi)*cos_phi[2]*(1442*cos_theta[0] + 1397*cos_theta[2] + 1001*cos_theta[4])*std::pow(sin_theta[0],2))/1024.;\n\n            data[60]=(3*std::sqrt(385/pi)*cos_phi[3]*(81 + 148*cos_theta[1] + 91*cos_theta[3])*std::pow(sin_theta[0],3))/256.;\n\n            data[61]=(-3*std::sqrt(385/pi)*cos_phi[4]*(149*cos_theta[0] + 91*cos_theta[2])*std::pow(sin_theta[0],4))/256.;\n\n            data[62]=(3*std::sqrt(5005/(2.*pi))*cos_phi[5]*(5 + 7*cos_theta[1])*std::pow(sin_theta[0],5))/64.;\n\n            data[63]=(-21*std::sqrt(715/pi)*cos_phi[6]*cos_theta[0]*std::pow(sin_theta[0],6))/64.;\n\n            if (lmax==7) return;\n\n            data[64]=(-3*std::sqrt(12155/pi)*cos_theta[0]*sin_phi[7]*std::pow(sin_theta[0],7))/32.;\n\n            data[65]=(-3*std::sqrt(12155/pi)*(3 + 4*cos_theta[1])*sin_phi[6]*std::pow(sin_theta[0],6))/64.;\n\n            data[66]=(-3*std::sqrt(7293/(2.*pi))*cos_theta[0]*(2 + 5*cos_theta[1])*sin_phi[5]*std::pow(sin_theta[0],5))/16.;\n\n            data[67]=(-3*std::sqrt(17017/pi)*(11 + 19*cos_theta[1] + 10*cos_theta[3])*sin_phi[4]*std::pow(sin_theta[0],4))/128.;\n\n            data[68]=(-3*std::sqrt(1309/pi)*cos_theta[0]*(43 + 52*cos_theta[1] + 65*cos_theta[3])*sin_phi[3]*std::pow(sin_theta[0],3))/128.;\n\n            data[69]=(-3*std::sqrt(19635/pi)*(21 + 42*cos_theta[1] + 39*cos_theta[3] + 26*cos_theta[5])*sin_phi[2]*std::pow(sin_theta[0],2))/512.;\n\n            data[70]=(-3*std::sqrt(595/(2.*pi))*(-8 + 121*cos_theta[1] + 143*cos_theta[5])*sin_phi[1]*sin_theta[1])/512.;\n\n            data[71]=(-3*std::sqrt(17/pi)*(35*cos_theta[1] + 154*cos_theta[3] + 429*cos_theta[5] + 1430*cos_theta[7])*sin_phi[0])/2048.;\n\n            data[72]=(-9*std::sqrt(17/pi)*(70*sin_theta[1] + 154*sin_theta[3] + 286*sin_theta[5] + 715*sin_theta[7]))/4096.;\n\n            data[73]=(-3*std::sqrt(17/pi)*cos_phi[0]*(35*cos_theta[1] + 154*cos_theta[3] + 429*cos_theta[5] + 1430*cos_theta[7]))/2048.;\n\n            data[74]=(3*std::sqrt(595/(2.*pi))*cos_phi[1]*(-16*sin_theta[1] - 22*sin_theta[3] + 143*sin_theta[7]))/1024.;\n\n            data[75]=(-3*std::sqrt(19635/pi)*cos_phi[2]*(21 + 42*cos_theta[1] + 39*cos_theta[3] + 26*cos_theta[5])*std::pow(sin_theta[0],2))/512.;\n\n            data[76]=(3*std::sqrt(1309/pi)*cos_phi[3]*(138*cos_theta[0] + 117*cos_theta[2] + 65*cos_theta[4])*std::pow(sin_theta[0],3))/256.;\n\n            data[77]=(-3*std::sqrt(17017/pi)*cos_phi[4]*(11 + 19*cos_theta[1] + 10*cos_theta[3])*std::pow(sin_theta[0],4))/128.;\n\n            data[78]=(3*std::sqrt(7293/(2.*pi))*cos_phi[5]*(9*cos_theta[0] + 5*cos_theta[2])*std::pow(sin_theta[0],5))/32.;\n\n            data[79]=(-3*std::sqrt(12155/pi)*cos_phi[6]*(3 + 4*cos_theta[1])*std::pow(sin_theta[0],6))/64.;\n\n            data[80]=(3*std::sqrt(12155/pi)*cos_phi[7]*cos_theta[0]*std::pow(sin_theta[0],7))/32.;\n        }\n\n        ///  Compute derivative of real-spherical harmonic with respect to phi angle and divide by sin(theta).\n        static void dRlm_dphi_sin_theta(int lmax, double theta, double phi, mdarray<double, 1>& data)\n        {\n            assert(lmax <= 8);\n\n            data[0]=0;\n\n            if (lmax==0) return;\n\n            auto cos_theta = SHT::cosxn(lmax, theta);\n            auto sin_theta = SHT::sinxn(lmax, theta);\n            auto cos_phi = SHT::cosxn(lmax, phi);\n            auto sin_phi = SHT::sinxn(lmax, phi);\n\n            data[1]=-(std::sqrt(3/pi)*cos_phi[0])/2.;\n\n            data[2]=0;\n\n            data[3]=(std::sqrt(3/pi)*sin_phi[0])/2.;\n\n            if (lmax==1) return;\n\n            data[4]=-(std::sqrt(15/pi)*cos_phi[1]*sin_theta[0])/2.;\n\n            data[5]=-(std::sqrt(15/pi)*cos_phi[0]*cos_theta[0])/2.;\n\n            data[6]=0;\n\n            data[7]=(std::sqrt(15/pi)*cos_theta[0]*sin_phi[0])/2.;\n\n            data[8]=-(std::sqrt(15/pi)*cos_phi[0]*sin_phi[0]*sin_theta[0]);\n\n            if (lmax==2) return;\n\n            data[9]=(-3*std::sqrt(35/(2.*pi))*cos_phi[2]*std::pow(sin_theta[0],2))/4.;\n\n            data[10]=-(std::sqrt(105/pi)*cos_phi[1]*sin_theta[1])/4.;\n\n            data[11]=-(std::sqrt(21/(2.*pi))*cos_phi[0]*(3 + 5*cos_theta[1]))/8.;\n\n            data[12]=0;\n\n            data[13]=(std::sqrt(21/(2.*pi))*(3 + 5*cos_theta[1])*sin_phi[0])/8.;\n\n            data[14]=-(std::sqrt(105/pi)*cos_phi[0]*cos_theta[0]*sin_phi[0]*sin_theta[0]);\n\n            data[15]=(3*std::sqrt(35/(2.*pi))*sin_phi[2]*std::pow(sin_theta[0],2))/4.;\n\n            if (lmax==3) return;\n\n            data[16]=(-3*std::sqrt(35/pi)*cos_phi[3]*std::pow(sin_theta[0],3))/4.;\n\n            data[17]=(-9*std::sqrt(35/(2.*pi))*cos_phi[2]*cos_theta[0]*std::pow(sin_theta[0],2))/4.;\n\n            data[18]=(-3*std::sqrt(5/pi)*cos_phi[1]*(3*sin_theta[0] + 7*sin_theta[2]))/16.;\n\n            data[19]=(-3*std::sqrt(5/(2.*pi))*cos_phi[0]*(9*cos_theta[0] + 7*cos_theta[2]))/16.;\n\n            data[20]=0;\n\n            data[21]=(3*std::sqrt(5/(2.*pi))*cos_theta[0]*(1 + 7*cos_theta[1])*sin_phi[0])/8.;\n\n            data[22]=(-3*std::sqrt(5/pi)*sin_phi[1]*(3*sin_theta[0] + 7*sin_theta[2]))/16.;\n\n            data[23]=(9*std::sqrt(35/(2.*pi))*cos_theta[0]*sin_phi[2]*std::pow(sin_theta[0],2))/4.;\n\n            data[24]=(-3*std::sqrt(35/pi)*sin_phi[3]*std::pow(sin_theta[0],3))/4.;\n\n            if (lmax==4) return;\n\n            data[25]=(-15*std::sqrt(77/(2.*pi))*cos_phi[4]*std::pow(sin_theta[0],4))/16.;\n\n            data[26]=(-3*std::sqrt(385/pi)*cos_phi[3]*cos_theta[0]*std::pow(sin_theta[0],3))/4.;\n\n            data[27]=(-3*std::sqrt(385/(2.*pi))*cos_phi[2]*(7 + 9*cos_theta[1])*std::pow(sin_theta[0],2))/32.;\n\n            data[28]=-(std::sqrt(1155/pi)*cos_phi[1]*(2*sin_theta[1] + 3*sin_theta[3]))/32.;\n\n            data[29]=-(std::sqrt(165/pi)*cos_phi[0]*(15 + 28*cos_theta[1] + 21*cos_theta[3]))/128.;\n\n            data[30]=0;\n\n            data[31]=(std::sqrt(165/pi)*(15 + 28*cos_theta[1] + 21*cos_theta[3])*sin_phi[0])/128.;\n\n            data[32]=-(std::sqrt(1155/pi)*sin_phi[1]*(2*sin_theta[1] + 3*sin_theta[3]))/32.;\n\n            data[33]=(3*std::sqrt(385/(2.*pi))*(7 + 9*cos_theta[1])*sin_phi[2]*std::pow(sin_theta[0],2))/32.;\n\n            data[34]=(-3*std::sqrt(385/pi)*cos_theta[0]*sin_phi[3]*std::pow(sin_theta[0],3))/4.;\n\n            data[35]=(15*std::sqrt(77/(2.*pi))*sin_phi[4]*std::pow(sin_theta[0],4))/16.;\n\n            if (lmax==5) return;\n\n            data[36]=(-3*std::sqrt(3003/(2.*pi))*cos_phi[5]*std::pow(sin_theta[0],5))/16.;\n\n            data[37]=(-15*std::sqrt(1001/(2.*pi))*cos_phi[4]*cos_theta[0]*std::pow(sin_theta[0],4))/16.;\n\n            data[38]=(-3*std::sqrt(91/pi)*cos_phi[3]*(9 + 11*cos_theta[1])*std::pow(sin_theta[0],3))/16.;\n\n            data[39]=(-3*std::sqrt(1365/(2.*pi))*cos_phi[2]*(21*cos_theta[0] + 11*cos_theta[2])*std::pow(sin_theta[0],2))/64.;\n\n            data[40]=-(std::sqrt(1365/(2.*pi))*cos_phi[1]*(10*sin_theta[0] + 27*sin_theta[2] + 33*sin_theta[4]))/256.;\n\n            data[41]=-(std::sqrt(273/pi)*cos_phi[0]*(50*cos_theta[0] + 45*cos_theta[2] + 33*cos_theta[4]))/256.;\n\n            data[42]=0;\n\n            data[43]=(std::sqrt(273/pi)*cos_theta[0]*(19 + 12*cos_theta[1] + 33*cos_theta[3])*sin_phi[0])/128.;\n\n            data[44]=-(std::sqrt(1365/(2.*pi))*sin_phi[1]*(10*sin_theta[0] + 27*sin_theta[2] + 33*sin_theta[4]))/256.;\n\n            data[45]=(3*std::sqrt(1365/(2.*pi))*cos_theta[0]*(5 + 11*cos_theta[1])*sin_phi[2]*std::pow(sin_theta[0],2))/32.;\n\n            data[46]=(-3*std::sqrt(91/pi)*(9 + 11*cos_theta[1])*sin_phi[3]*std::pow(sin_theta[0],3))/16.;\n\n            data[47]=(15*std::sqrt(1001/(2.*pi))*cos_theta[0]*sin_phi[4]*std::pow(sin_theta[0],4))/16.;\n\n            data[48]=(-3*std::sqrt(3003/(2.*pi))*sin_phi[5]*std::pow(sin_theta[0],5))/16.;\n\n            if (lmax==6) return;\n\n            data[49]=(-21*std::sqrt(715/pi)*cos_phi[6]*std::pow(sin_theta[0],6))/64.;\n\n            data[50]=(-9*std::sqrt(5005/(2.*pi))*cos_phi[5]*cos_theta[0]*std::pow(sin_theta[0],5))/16.;\n\n            data[51]=(-15*std::sqrt(385/pi)*cos_phi[4]*(11 + 13*cos_theta[1])*std::pow(sin_theta[0],4))/128.;\n\n            data[52]=(-3*std::sqrt(385/pi)*cos_phi[3]*(27*cos_theta[0] + 13*cos_theta[2])*std::pow(sin_theta[0],3))/32.;\n\n            data[53]=(-9*std::sqrt(35/pi)*cos_phi[2]*(189 + 308*cos_theta[1] + 143*cos_theta[3])*std::pow(sin_theta[0],2))/512.;\n\n            data[54]=(-3*std::sqrt(35/(2.*pi))*cos_phi[1]*(75*sin_theta[1] + 132*sin_theta[3] + 143*sin_theta[5]))/512.;\n\n            data[55]=-(std::sqrt(105/pi)*cos_phi[0]*(350 + 675*cos_theta[1] + 594*cos_theta[3] + 429*cos_theta[5]))/2048.;\n\n            data[56]=0;\n\n            data[57]=(std::sqrt(105/pi)*(350 + 675*cos_theta[1] + 594*cos_theta[3] + 429*cos_theta[5])*sin_phi[0])/2048.;\n\n            data[58]=(-3*std::sqrt(35/(2.*pi))*sin_phi[1]*(75*sin_theta[1] + 132*sin_theta[3] + 143*sin_theta[5]))/512.;\n\n            data[59]=(9*std::sqrt(35/pi)*(189 + 308*cos_theta[1] + 143*cos_theta[3])*sin_phi[2]*std::pow(sin_theta[0],2))/512.;\n\n            data[60]=(-3*std::sqrt(385/pi)*cos_theta[0]*(7 + 13*cos_theta[1])*sin_phi[3]*std::pow(sin_theta[0],3))/16.;\n\n            data[61]=(15*std::sqrt(385/pi)*(11 + 13*cos_theta[1])*sin_phi[4]*std::pow(sin_theta[0],4))/128.;\n\n            data[62]=(-9*std::sqrt(5005/(2.*pi))*cos_theta[0]*sin_phi[5]*std::pow(sin_theta[0],5))/16.;\n\n            data[63]=(21*std::sqrt(715/pi)*sin_phi[6]*std::pow(sin_theta[0],6))/64.;\n\n            if (lmax==7) return;\n\n            data[64]=(-3*std::sqrt(12155/pi)*cos_phi[7]*std::pow(sin_theta[0],7))/32.;\n\n            data[65]=(-21*std::sqrt(12155/pi)*cos_phi[6]*cos_theta[0]*std::pow(sin_theta[0],6))/64.;\n\n            data[66]=(-3*std::sqrt(7293/(2.*pi))*cos_phi[5]*(13 + 15*cos_theta[1])*std::pow(sin_theta[0],5))/64.;\n\n            data[67]=(-15*std::sqrt(17017/pi)*cos_phi[4]*(11*cos_theta[0] + 5*cos_theta[2])*std::pow(sin_theta[0],4))/256.;\n\n            data[68]=(-3*std::sqrt(1309/pi)*cos_phi[3]*(99 + 156*cos_theta[1] + 65*cos_theta[3])*std::pow(sin_theta[0],3))/256.;\n\n            data[69]=(-3*std::sqrt(19635/pi)*cos_phi[2]*(126*cos_theta[0] + 91*cos_theta[2] + 39*cos_theta[4])*std::pow(sin_theta[0],2))/1024.;\n\n            data[70]=(-3*std::sqrt(595/(2.*pi))*cos_phi[1]*(35*sin_theta[0] + 11*(9*sin_theta[2] + 13*(sin_theta[4] + sin_theta[6]))))/2048.;\n\n            data[71]=(-3*std::sqrt(17/pi)*cos_phi[0]*(1225*cos_theta[0] + 11*(105*cos_theta[2] + 91*cos_theta[4] + 65*cos_theta[6])))/4096.;\n\n            data[72]=0;\n\n            data[73]=(3*std::sqrt(17/pi)*cos_theta[0]*(178 + 869*cos_theta[1] + 286*cos_theta[3] + 715*cos_theta[5])*sin_phi[0])/2048.;\n\n            data[74]=(-3*std::sqrt(595/(2.*pi))*sin_phi[1]*(35*sin_theta[0] + 11*(9*sin_theta[2] + 13*(sin_theta[4] + sin_theta[6]))))/2048.;\n\n            data[75]=(3*std::sqrt(19635/pi)*cos_theta[0]*(37 + 52*cos_theta[1] + 39*cos_theta[3])*sin_phi[2]*std::pow(sin_theta[0],2))/512.;\n\n            data[76]=(-3*std::sqrt(1309/pi)*(99 + 156*cos_theta[1] + 65*cos_theta[3])*sin_phi[3]*std::pow(sin_theta[0],3))/256.;\n\n            data[77]=(15*std::sqrt(17017/pi)*(11*cos_theta[0] + 5*cos_theta[2])*sin_phi[4]*std::pow(sin_theta[0],4))/256.;\n\n            data[78]=(-3*std::sqrt(7293/(2.*pi))*(13 + 15*cos_theta[1])*sin_phi[5]*std::pow(sin_theta[0],5))/64.;\n\n            data[79]=(21*std::sqrt(12155/pi)*cos_theta[0]*sin_phi[6]*std::pow(sin_theta[0],6))/64.;\n\n            data[80]=(-3*std::sqrt(12155/pi)*sin_phi[7]*std::pow(sin_theta[0],7))/32.;\n        }\n\n        /// convert 3x3 transformation matrix to SU2 2x2 matrix\n        /// Create quaternion components from the 3x3 matrix. The components are just a w = Cos(\\Omega/2)\n        /// and {x,y,z} = unit rotation vector multiplied by Sin[\\Omega/2]\n        /// see https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation\n        /// and https://en.wikipedia.org/wiki/Rotation_group_SO(3)#Quaternions_of_unit_norm\n        static mdarray<double_complex, 2> rotation_matrix_su2(const matrix3d<double>& m)\n        {\n            double det = m.det() > 0 ? 1.0 : -1.0;\n\n            matrix3d<double> mat = m * det;\n            mdarray<double_complex, 2> su2mat(2, 2);\n\n            su2mat.zero();\n\n            /* make quaternion components*/\n            double w = sqrt( std::max( 0., 1. + mat(0,0) + mat(1,1) + mat(2,2) ) ) / 2.;\n            double x = sqrt( std::max( 0., 1. + mat(0,0) - mat(1,1) - mat(2,2) ) ) / 2.;\n            double y = sqrt( std::max( 0., 1. - mat(0,0) + mat(1,1) - mat(2,2) ) ) / 2.;\n            double z = sqrt( std::max( 0., 1. - mat(0,0) - mat(1,1) + mat(2,2) ) ) / 2.;\n            x = std::copysign( x, mat(2,1) - mat(1,2) );\n            y = std::copysign( y, mat(0,2) - mat(2,0) );\n            z = std::copysign( z, mat(1,0) - mat(0,1) );\n\n            su2mat(0, 0) = double_complex( w, -z);\n            su2mat(1, 1) = double_complex( w,  z);\n            su2mat(0, 1) = double_complex(-y, -x);\n            su2mat(1, 0) = double_complex( y, -x);\n\n            return std::move(su2mat);\n        }\n\n        /// Compute the derivatives of real spherical harmonics over the components of cartesian vector.\n        /** The following derivative is computed:\n         *  \\f[\n         *    \\frac{\\partial R_{\\ell m}(\\theta_r, \\phi_r)}{\\partial r_{\\mu}} =\n         *      \\frac{\\partial R_{\\ell m}(\\theta_r, \\phi_r)}{\\partial \\theta_r} \\frac{\\partial \\theta_r}{\\partial r_{\\mu}} +\n         *      \\frac{\\partial R_{\\ell m}(\\theta_r, \\phi_r)}{\\partial \\phi_r} \\frac{\\partial \\phi_r}{\\partial r_{\\mu}}\n         *  \\f]\n         *  The derivatives of angles are:\n         *  \\f[\n         *     \\frac{\\partial \\theta_r}{\\partial r_{x}} = \\frac{\\cos(\\phi_r) \\cos(\\theta_r)}{r} \\\\\n         *     \\frac{\\partial \\theta_r}{\\partial r_{y}} = \\frac{\\cos(\\theta_r) \\sin(\\phi_r)}{r} \\\\\n         *     \\frac{\\partial \\theta_r}{\\partial r_{z}} = -\\frac{\\sin(\\theta_r)}{r}\n         *  \\f]\n         *  and\n         *  \\f[\n         *     \\frac{\\partial \\phi_r}{\\partial r_{x}} = -\\frac{\\sin(\\phi_r)}{\\sin(\\theta_r) r} \\\\\n         *     \\frac{\\partial \\phi_r}{\\partial r_{y}} = \\frac{\\cos(\\phi_r)}{\\sin(\\theta_r) r} \\\\\n         *     \\frac{\\partial \\phi_r}{\\partial r_{z}} = 0\n         *  \\f]\n         *  The derivative of \\f$ \\phi \\f$ has discontinuities at \\f$ \\theta = 0, \\theta=\\pi \\f$. This, however, is not a problem, because\n         *  multiplication by the the derivative of \\f$ R_{\\ell m} \\f$ removes it. The following functions have to be hardcoded:\n         *  \\f[\n         *    \\frac{\\partial R_{\\ell m}(\\theta, \\phi)}{\\partial \\theta} \\\\\n         *    \\frac{\\partial R_{\\ell m}(\\theta, \\phi)}{\\partial \\phi} \\frac{1}{\\sin(\\theta)}\n         *  \\f]\n         *\n         *  Mathematica script for spherical harmonic derivatives:\n            \\verbatim\n            Rlm[l_, m_, th_, ph_] :=\n             If[m > 0, Sqrt[2]*ComplexExpand[Re[SphericalHarmonicY[l, m, th, ph]]],\n               If[m < 0, Sqrt[2]*ComplexExpand[Im[SphericalHarmonicY[l, m, th, ph]]],\n                 If[m == 0, ComplexExpand[Re[SphericalHarmonicY[l, 0, th, ph]]]]\n               ]\n             ]\n            Do[Print[FullSimplify[D[Rlm[l, m, theta, phi], theta]]], {l, 0, 4}, {m, -l, l}]\n            Do[Print[FullSimplify[TrigExpand[D[Rlm[l, m, theta, phi], phi]/Sin[theta]]]], {l, 0, 4}, {m, -l, l}]\n            \\endverbatim\n        */\n        static void dRlm_dr(int lmax__, vector3d<double>& r__, mdarray<double, 2>& data__)\n        {\n            /* get spherical coordinates of the Cartesian vector */\n            auto vrs = spherical_coordinates(r__);\n\n            if (vrs[0] < 1e-12) {\n                data__.zero();\n                return;\n            }\n\n            int lmmax = (lmax__ + 1) * (lmax__ + 1);\n\n            double theta = vrs[1];\n            double phi   = vrs[2];\n\n            vector3d<double> dtheta_dr({std::cos(phi) * std::cos(theta), std::cos(theta) * std::sin(phi), -std::sin(theta)});\n            vector3d<double> dphi_dr({-std::sin(phi), std::cos(phi), 0.0});\n\n            mdarray<double, 1> dRlm_dt(lmmax);\n            mdarray<double, 1> dRlm_dp_sin_t(lmmax);\n\n            dRlm_dtheta(lmax__, theta, phi, dRlm_dt);\n            dRlm_dphi_sin_theta(lmax__, theta, phi, dRlm_dp_sin_t);\n\n            for (int mu = 0; mu < 3; mu++) {\n                for (int lm = 0; lm < lmmax; lm++) {\n                    data__(lm, mu) = (dRlm_dt[lm] * dtheta_dr[mu] + dRlm_dp_sin_t[lm] * dphi_dr[mu]) / vrs[0];\n                }\n            }\n        }\n\n        /// Generate \\f$ \\cos(m x) \\f$ for m in [1, n] using recursion.\n        static mdarray<double, 1> cosxn(int n__, double x__)\n        {\n            assert(n__ > 0);\n            mdarray<double, 1> data(n__);\n            data[0] = std::cos(x__);\n            if (n__ > 1) {\n                data[1] = std::cos(2 * x__);\n                for (int i = 2; i < n__; i++) {\n                    data[i] = 2 * data[0] * data[i - 1] - data[i - 2];\n                }\n            }\n            return std::move(data);\n        }\n\n        /// Generate \\f$ \\sin(m x) \\f$ for m in [1, n] using recursion.\n        static mdarray<double, 1> sinxn(int n__, double x__)\n        {\n            assert(n__ > 0);\n            mdarray<double, 1> data(n__);\n            auto cosx = std::cos(x__);\n            data[0] = std::sin(x__);\n            if (n__ > 1) {\n                data[1] = std::sin(2 * x__);\n                for (int i = 2; i < n__; i++) {\n                    data[i] = 2 * cosx * data[i - 1] - data[i - 2];\n                }\n            }\n            return std::move(data);\n        }\n};\n\ntemplate <>\ninline void SHT::backward_transform<double>(int ld, double const* flm, int nr, int lmmax, double* ftp)\n{\n    assert(lmmax <= lmmax_);\n    assert(ld >= lmmax);\n    linalg<CPU>::gemm(1, 0, num_points_, nr, lmmax, &rlm_backward_(0, 0), lmmax_, flm, ld, ftp, num_points_);\n}\n\ntemplate <>\ninline void SHT::backward_transform<double_complex>(int ld, double_complex const* flm, int nr, int lmmax, double_complex* ftp)\n{\n    assert(lmmax <= lmmax_);\n    assert(ld >= lmmax);\n    linalg<CPU>::gemm(1, 0, num_points_, nr, lmmax, &ylm_backward_(0, 0), lmmax_, flm, ld, ftp, num_points_);\n}\n\ntemplate <>\ninline void SHT::forward_transform<double>(double const* ftp, int nr, int lmmax, int ld, double* flm)\n{\n    assert(lmmax <= lmmax_);\n    assert(ld >= lmmax);\n    linalg<CPU>::gemm(1, 0, lmmax, nr, num_points_, &rlm_forward_(0, 0), num_points_, ftp, num_points_, flm, ld);\n}\n\ntemplate <>\ninline void SHT::forward_transform<double_complex>(double_complex const* ftp, int nr, int lmmax, int ld, double_complex* flm)\n{\n    assert(lmmax <= lmmax_);\n    assert(ld >= lmmax);\n    linalg<CPU>::gemm(1, 0, lmmax, nr, num_points_, &ylm_forward_(0, 0), num_points_, ftp, num_points_, flm, ld);\n}\n\n}\n\n#endif // __SHT_H__\n", "meta": {"hexsha": "ba9e0c7b24a9bab75cee5df44dbe70b50275233d", "size": 53414, "ext": "h", "lang": "C", "max_stars_repo_path": "src/sht.h", "max_stars_repo_name": "ckae95/SIRIUS", "max_stars_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "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/sht.h", "max_issues_repo_name": "ckae95/SIRIUS", "max_issues_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sht.h", "max_forks_repo_name": "ckae95/SIRIUS", "max_forks_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33", "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.8605015674, "max_line_length": 146, "alphanum_fraction": 0.4894596922, "num_tokens": 17201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.37332510877577246}}
{"text": "/*\n** Read input data into array\n**\n** G.Lohmann, MPI-KYB, 2018\n*/\n#include <viaio/Vlib.h>\n#include <viaio/VImage.h>\n#include <viaio/mu.h>\n#include <viaio/option.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_math.h>\n\n\n/*\n** get global mean regressor\n*/\nvoid GlobalMean(gsl_matrix *Data,gsl_matrix *covariates,int column)\n{\n  int i=0,j=0;\n  int nt = Data->size2;\n\n  double sum=0,nx=(double)Data->size1;\n  for (i=0; i<nt; i++) {\n    for (j=0; j<Data->size1; j++) {\n      sum += gsl_matrix_get(Data,j,i);\n    }\n    gsl_matrix_set(covariates,i,column,sum/nx);\n  }\n\n  /* normalize */\n  double u=0,s1=0,s2=0,mx=(double)Data->size2;\n  for (i=0; i<nt; i++) {\n    u = gsl_matrix_get(covariates,i,column);\n    s1 += u;\n    s2 += u*u;\n  }\n  double mean = s1/mx;\n  double var = (s2 - mx * mean * mean) / (mx - 1.0);\n  double sd = sqrt(var);\n\n  for (i=0; i<nt; i++) {\n    u = gsl_matrix_get(covariates,i,column);\n    gsl_matrix_set(covariates,i,column,(u-mean/sd));\n  }\n}\n\n\n\n/* normalize time courses */\nvoid VRowNormalize(gsl_matrix *Data)\n{\n  size_t i,j;\n  double u=0,s1=0,s2=0,mean=0,sd=0;\n  double nx=(double)Data->size2;\n\n  for (i=0; i<Data->size1; i++) {\n    s1 = s2 = 0;\n    for (j=0; j<Data->size2; j++) {\n      u = gsl_matrix_get(Data,i,j);\n      s1 += u;\n      s2 += u*u;\n    }\n    mean = s1/nx;\n    sd = sqrt((s2 - nx * mean * mean) / (nx - 1.0));\n    \n    for (j=0; j<Data->size2; j++) {\n      u = gsl_matrix_get(Data,i,j);\n      gsl_matrix_set(Data,i,j,(u-mean)/sd);\n    }\n  }\n}\n\n\n/* get timing information */\nvoid VGetTimeInfos(VAttrList *list,int nlists,double *mtr,float *run_duration)\n{\n  VImage src=NULL;\n  VAttrListPosn posn;\n  int k,ntimesteps=0;\n  VLong itr=0;\n  double tr=-1.0;\n\n  int ntt=0;\n  for (k=0; k<nlists; k++) {\n    ntt = 0;\n    for (VFirstAttr (list[k], & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n      if (VGetAttrRepn (& posn) != VImageRepn) continue;\n      VGetAttrValue (& posn, NULL,VImageRepn, & src);\n      if (tr < 0) {\n\tif (VGetAttr(VImageAttrList(src),\"repetition_time\",NULL,VLongRepn,&itr) != VAttrFound) \n\t  VError(\" TR info missing in header\");\n\ttr = (double) itr / 1000.0;\n      }\n      ntt = VImageNBands(src);\n      run_duration[k] = tr*(float)ntt;\n    }\n    ntimesteps += ntt;\n  }\n  if (tr < 0) VError(\" TR info missing\");\n  *mtr = tr;\n}\n\n\n\n/* read data block */\ngsl_matrix *VReadImageData(VAttrList *list,int nlists)\n{\n  VAttrListPosn posn;\n  int i=0,k,ntt=0,slice,row,col,nrows=0,ncols=0,ntimesteps=0;\n  double u=0,s1=0,s2=0,nx=0,sd=0,mean=0,tiny=1.0e-8;\n\n  int nslices = VAttrListNumImages(list[0]);\n\n  /* alloc src image */\n  VImage **src = (VImage **) VCalloc(nlists,sizeof(VImage *));\n  int *nt = (int *) VCalloc(nlists,sizeof(int));\n  for (k=0; k<nlists; k++) {\n    src[k] = (VImage *) VCalloc(nslices,sizeof(VImage));\n    i = 0;\n    for (VFirstAttr (list[k], & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n      if (VGetAttrRepn (& posn) != VImageRepn) continue;\n      if (i >= nslices) VError(\" inconsistent number of slices, %d %d %d\",k,i,nslices);\n      VGetAttrValue (& posn, NULL,VImageRepn, & src[k][i]);\n      i++;\n    }\n  }\n\n  /* get image dimensions */\n  nrows = VImageNRows(src[0][0]);\n  ncols = VImageNColumns(src[0][0]);\n  ntimesteps = 0;\n  for (k=0; k<nlists; k++) {\n    ntt = VImageNBands(src[k][0]);\n    ntimesteps += ntt;\n    nt[k] = ntt;\n    if (nrows != VImageNRows(src[k][0])) VError(\" inconsistent number of rows \");\n    if (ncols != VImageNColumns(src[k][0])) VError(\" inconsistent number of columns \");\n  }\n\n  /* number of nonzero voxels */\n  size_t nvox=0;\n  for (slice=0; slice<nslices; slice++) {\n    for (row=0; row<nrows; row++) {\n      for (col=0; col<ncols; col++) {\n\tu = VGetPixel(src[0][slice],0,row,col);\n\tif (gsl_isnan(u) || gsl_isinf(u)) continue;\n\tif (fabs(u) < TINY) continue;\n\tnvox++;\n      }\n    }\n  }\n\n  /* alloc new data struct */\n  gsl_matrix *Data = gsl_matrix_calloc(nvox,ntimesteps);\n  if (!Data) VError(\" error allocating Data\");\n\n  \n  /* fill map and data */\n  for (k=0; k<nlists; k++) {\n\n    ntt = 0;\n    for (i=0; i<k; i++) ntt += nt[i];\t  \n\n    nvox=0;\n    for (slice=0; slice<nslices; slice++) {\n      for (row=0; row<nrows; row++) {\n\tfor (col=0; col<ncols; col++) {\n\t  u = VGetPixel(src[0][slice],0,row,col);\n\t  if (gsl_isnan(u) || gsl_isinf(u)) continue;\n\t  if (fabs(u) < TINY) continue;\n\n\t  s1=s2=nx=0;\n\t  for (i=0; i<nt[k]; i++) {\n\t    u = VGetPixel(src[k][slice],i,row,col);\n\t    s1 += u;\n\t    s2 += u*u;\t    \n\t    nx++;\n\t  }\n\t  mean = s1/nx;\n\t  sd = sqrt((s2 - nx * mean * mean) / (nx - 1.0));\n\t  if (sd < tiny) {\n\t    u = 0.0;\n\t    for (i=0; i<nt[k]; i++) {\n\t      gsl_matrix_set(Data,nvox,ntt+i,u);\n\t    }\n\t  }\n\t  else {\n\t    for (i=0; i<nt[k]; i++) {\n\t      u = VGetPixel(src[k][slice],i,row,col);\n\t      u = (u-mean)/sd;\n\t      gsl_matrix_set(Data,nvox,ntt+i,u);\n\t    }\n\t  }\n\t  nvox++;\n\t}\n      }\n    }\n  }\n  VFree(nt);\n  return Data;\n}\n\n\n/* get map of voxel addresses */\nVImage VoxelMap(VAttrList list)\n{ \n  VAttrListPosn posn;\n  int i=0,slice,row,col,nrows=0,ncols=0;\n\n  int nslices = VAttrListNumImages(list);\n\n  /* alloc src image */\n  i = nrows = ncols = 0;\n  VImage *src = (VImage *) VCalloc(nslices,sizeof(VImage));\n  i = 0;\n  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {\n    if (VGetAttrRepn (& posn) != VImageRepn) continue;\n    if (i >= nslices) VError(\" inconsistent number of slices, %d %d\",i,nslices);\n    VGetAttrValue (& posn, NULL,VImageRepn, & src[i]);\n    if (VImageNRows(src[i])  > nrows)  nrows = VImageNRows(src[i]);\n    if (VImageNColumns(src[i]) > ncols) ncols = VImageNColumns(src[i]);\n    i++;\n  }\n\n\n  /* number of nonzero voxels */\n  double u=0;\n  size_t nvox=0;\n  for (slice=0; slice<nslices; slice++) {\n    for (row=0; row<nrows; row++) {\n      for (col=0; col<ncols; col++) {\n\tu = VGetPixel(src[slice],0,row,col);\n\tif (fabs(u) < TINY) continue;\n\tnvox++;\n      }\n    }\n  }\n  if (nvox < 1) VError(\" No non-zero voxels in input image\");\n\n\n  /* voxel addresses */\n  VImage map = VCreateImage(1,4,nvox,VShortRepn);\n  if (map == NULL) VError(\" error allocating addr map\");\n  VFillImage(map,VAllBands,0);\n  VCopyImageAttrs (src[0],map);\n  VSetAttr(VImageAttrList(map),\"nvoxels\",NULL,VLongRepn,(VLong)nvox);\n  VSetAttr(VImageAttrList(map),\"nslices\",NULL,VLongRepn,(VLong)nslices);\n  VSetAttr(VImageAttrList(map),\"nrows\",NULL,VLongRepn,(VLong)nrows);\n  VSetAttr(VImageAttrList(map),\"ncols\",NULL,VLongRepn,(VLong)ncols);\n  VPixel(map,0,3,0,VShort) = nslices;\n  VPixel(map,0,3,1,VShort) = nrows;\n  VPixel(map,0,3,2,VShort) = ncols;\n\n\n  /* fill map */\n  nvox=0;\n  for (slice=0; slice<nslices; slice++) {\n    for (row=0; row<nrows; row++) {\n      for (col=0; col<ncols; col++) {\n\tu = VGetPixel(src[slice],0,row,col);\n\tif (fabs(u) < TINY) continue;\n\tVPixel(map,0,0,nvox,VShort) = slice;\n\tVPixel(map,0,1,nvox,VShort) = row;\n\tVPixel(map,0,2,nvox,VShort) = col;\n\tnvox++;\n      }\n    }\n  }\n  return map;\n}\n", "meta": {"hexsha": "80e285b7e08a1aa5d78a7ecf7c52559acf32f9ed", "size": 7004, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_prewhitening/ReadData.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_prewhitening/ReadData.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_prewhitening/ReadData.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 25.1039426523, "max_line_length": 88, "alphanum_fraction": 0.587949743, "num_tokens": 2511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.37332240685346474}}
{"text": "/**\n * @file beamformer.h\n * @brief Beamforming in the subband domain.\n * @author John McDonough and Kenichi Kumatani\n */\n#ifndef BEAMFORMER_H\n#define BEAMFORMER_H\n\n#include <stdio.h>\n#include <assert.h>\n#include <float.h>\n\n#include <gsl/gsl_block.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_fft_complex.h>\n#include <common/refcount.h>\n#include \"common/jexception.h\"\n\n#include \"stream/stream.h\"\n#include \"beamformer/spectralinfoarray.h\"\n#include \"modulated/modulated.h\"\n\n#define SSPEED 343740.0\n\nclass BeamformerWeights {\npublic:\n  BeamformerWeights( unsigned fftLen, unsigned chanN, bool halfBandShift, unsigned NC = 1 );\n  ~BeamformerWeights();\n\n  void calcMainlobe(  float samplerate, const gsl_vector* delays,  bool isGSC );\n  void calcMainlobe2( float samplerate, const gsl_vector* delaysT, const gsl_vector* delaysJ, bool isGSC );\n  void calcMainlobeN( float samplerate, const gsl_vector* delaysT, const gsl_matrix* delaysIs, unsigned NC, bool isGSC );\n  void calcSidelobeCancellerP_f( unsigned fbinX, const gsl_vector* packedWeight );\n  void calcSidelobeCancellerU_f( unsigned fbinX, const gsl_vector_complex* wa );\n  void calcBlockingMatrix( unsigned fbinX );\n\n  bool write_fir_coeff(const String& fn, unsigned winType);\n\n#ifdef ENABLE_LEGACY_BTK_API\n  bool writeFIRCoeff(const String& fn, unsigned winType);\n#endif\n\n  void setSidelobeCanceller_f( unsigned fbinX, gsl_vector_complex* wl_f ){\n    gsl_vector_complex_memcpy( wl_[fbinX], wl_f );\n  }\n  void setQuiescentVector( unsigned fbinX, gsl_vector_complex *wq_f, bool isGSC=false );\n  void setQuiescentVectorAll( gsl_complex z, bool isGSC=false );\n  void setTimeAlignment();\n\n  bool     isHalfBandShift() const {return(halfBandShift_);}\n  unsigned NC() const {return(NC_);}\n  unsigned fftLen() const {return(fftLen_);}\n  unsigned chanN() const {return(chanN_);}\n\n  gsl_vector_complex** arrayManifold() const { return (ta_); }\n  gsl_vector_complex* wq_f( unsigned fbinX ) const { return wq_[fbinX]; }\n  gsl_vector_complex* wl_f( unsigned fbinX ) const { return wl_[fbinX]; }\n  gsl_vector_complex** wq() const { return (wq_); }\n  gsl_matrix_complex** B() const { return (B_); }\n  gsl_vector_complex** wa() const { return (wa_); }\n  gsl_vector_complex** CSDs() const { return CSDs_; }\n  gsl_vector_complex* wp1() const { return wp1_; }\n\nprivate:\n  void alloc_weights_();\n  void free_weights_();\n\n  unsigned fftLen_;\n  unsigned chanN_;\n  bool halfBandShift_;\n  unsigned NC_; // the numbef of constraints\n  gsl_vector_complex** wq_; // a quiescent weight vector for each frequency bin, wq_[fbinX][chanN]\n  gsl_matrix_complex** B_;  // a blocking matrix for each frequency bin,         B_[fbinX][chanN][chanN-NC]\n  gsl_vector_complex** wa_; // an active weight vector for each frequency bin,   wa_[fbinX][chanN-NC]\n  gsl_vector_complex** wl_; // wl_[fbinX] = B_[fbinX] * wa_[fbinX]\n  gsl_vector_complex** ta_; // do time alignment for multi-channel waves. It is also called an array manifold. _ta[fbinX][chanN].\n  gsl_vector_complex*  wp1_;  // a weight vector of postfiltering,   _wp[fbinX]\n  gsl_vector_complex** CSDs_; // cross spectral density for the post-filtering\n};\n\ntypedef refcount_ptr<BeamformerWeights>     BeamformerWeightsPtr;\n\n\n// ----- definition for class `SubbandBeamformer' -----\n// \nclass SubbandBeamformer : public VectorComplexFeatureStream {\n public:\n  SubbandBeamformer(unsigned fftLen = 512, bool halfBandShift = false, const String& nm = \"SubbandBeamformer\");\n  ~SubbandBeamformer();\n\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void reset();\n\n  unsigned fftLen() const { return fftLen_; }\n  unsigned fftLen2() const { return fftLen2_; }\n  unsigned chanN() const { return channelList_.size(); }\n  virtual unsigned dim() const { return chanN();}\n\n  bool is_end() const {return is_end_;}\n  const gsl_vector_complex* snapshot_array_f(unsigned fbinX) const { return (snapshot_array_->snapshot(fbinX)); }\n  virtual SnapShotArrayPtr  snapshot_array() const { return(snapshot_array_); }\n  void         set_channel(VectorComplexFeatureStreamPtr& chan);\n  virtual void clear_channel();\n\n#ifdef ENABLE_LEGACY_BTK_API\n  bool isEnd() { return is_end(); }\n  const gsl_vector_complex* snapShotArray_f(unsigned fbinX){ return snapshot_array_f(fbinX); }\n  virtual SnapShotArrayPtr  getSnapShotArray(){ return(snapshot_array()); }\n  void         setChannel(VectorComplexFeatureStreamPtr& chan){ set_channel(chan); }\n  virtual void clearChannel(){ clear_channel(); }\n#endif\n\nprotected:\n  typedef list<VectorComplexFeatureStreamPtr>\tChannelList_;\n  typedef ChannelList_::iterator\t\tChannelIterator_;\n\n  SnapShotArrayPtr\t\t\t\tsnapshot_array_;\n  unsigned\t\t\t\t\tfftLen_;\n  unsigned\t\t\t\t\tfftLen2_;\n  bool\t\t\t\t\t\thalfBandShift_;\n  ChannelList_\t\t\t\t\tchannelList_;\n};\n\n// ----- definition for class `SubbandDS' -----\n// \n\nclass SubbandDS : public SubbandBeamformer {\n public:\n  SubbandDS(unsigned fftLen = 512, bool halfBandShift = false, const String& nm = \"SubbandDS\");\n  ~SubbandDS();\n\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void reset();\n  virtual void clear_channel();\n  virtual const gsl_vector_complex *get_weights(unsigned fbinX) const { return bfweight_vec_[0]->wq_f(fbinX); }\n  virtual BeamformerWeights* beamformer_weight_object(unsigned srcX=0) const { return bfweight_vec_[srcX]; }\n\n  virtual void calc_array_manifold_vectors(float samplerate, const gsl_vector* delays);\n  virtual void calc_array_manifold_vectors_2(float samplerate, const gsl_vector* delaysT, const gsl_vector* delaysJ);\n  virtual void calc_array_manifold_vectors_n(float samplerate, const gsl_vector* delaysT, const gsl_matrix* delaysJ, unsigned NC=2);\n\n#ifdef ENABLE_LEGACY_BTK_API\n  virtual void clearChannel(){ clear_channel(); }\n  virtual const gsl_vector_complex *getWeights(unsigned fbinX) const { return get_weights(fbinX); }\n  virtual BeamformerWeights* getBeamformerWeightObject(unsigned srcX=0) const { return beamformer_weight_object(srcX); }\n  virtual void calcArrayManifoldVectors(float sampleRate, const gsl_vector* delays){\n    calc_array_manifold_vectors(sampleRate, delays);\n  }\n  virtual void calcArrayManifoldVectors2(float sampleRate, const gsl_vector* delaysT, const gsl_vector* delaysJ){\n    calc_array_manifold_vectors_2(sampleRate, delaysT, delaysJ);\n  }\n  virtual void calcArrayManifoldVectorsN(float sampleRate, const gsl_vector* delaysT, const gsl_matrix* delaysJ, unsigned NC=2){\n    calc_array_manifold_vectors_n(sampleRate, delaysT, delaysJ, NC);\n  }\n#endif /* #ifdef ENABLE_LEGACY_BTK_API */\n\nprotected:\n  void alloc_image_();\n  void alloc_bfweight_(int nSrc, int NC);\n\n  vector<BeamformerWeights *>                   bfweight_vec_; // weights of a beamformer per source.\n};\n\n#define NO_PROCESSING 0x00\n#define SCALING_MDP   0x01\nclass SubbandGSC : public SubbandDS {\npublic:\n  SubbandGSC(unsigned fftLen = 512, bool halfBandShift = false, const String& nm = \"SubbandGSC\")\n    : SubbandDS( fftLen, halfBandShift, nm ),normalize_weight_(false){}\n  ~SubbandGSC();\n\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n\n  void normalize_weight(bool flag){ normalize_weight_ = flag; }\n  void set_quiescent_weights_f(unsigned fbinX, const gsl_vector_complex* srcWq);\n  void set_active_weights_f(unsigned fbinX, const gsl_vector* packedWeight);\n  void zero_active_weights();\n  void calc_gsc_weights(float samplerate, const gsl_vector* delaysT);\n  void calc_gsc_weights_2(float samplerate, const gsl_vector* delaysT, const gsl_vector* delaysJ);\n  void calc_gsc_weights_n(float samplerate, const gsl_vector* delaysT, const gsl_matrix* delaysJ, unsigned NC=2);\n\n  bool write_fir_coeff(const String& fn, unsigned winType=1);\n  gsl_matrix_complex* blocking_matrix(unsigned srcX, unsigned fbinX){\n    return (bfweight_vec_[srcX]->B())[fbinX];\n  }\n\n#ifdef ENABLE_LEGACY_BTK_API\n  void normalizeWeight(bool flag){ normalize_weight(flag); }\n  void setQuiescentWeights_f(unsigned fbinX, const gsl_vector_complex * srcWq){ set_quiescent_weights_f(fbinX, srcWq); }\n  void setActiveWeights_f(unsigned fbinX, const gsl_vector* packedWeight){ set_active_weights_f(fbinX, packedWeight); }\n  void zeroActiveWeights(){ zero_active_weights(); }\n  void calcGSCWeights(float sampleRate, const gsl_vector* delaysT){ calc_gsc_weights(sampleRate, delaysT); }\n  void calcGSCWeights2(float sampleRate, const gsl_vector* delaysT, const gsl_vector* delaysJ){ calc_gsc_weights_2(sampleRate, delaysT, delaysJ); }\n  void calcGSCWeightsN(float sampleRate, const gsl_vector* delaysT, const gsl_matrix* delaysJ, unsigned NC=2){ calc_gsc_weights_n(sampleRate, delaysT, delaysJ, NC); }\n  bool writeFIRCoeff(const String& fn, unsigned winType=1){ return write_fir_coeff(fn, winType); }\n  gsl_matrix_complex* getBlockingMatrix(unsigned srcX, unsigned fbinX){ return blocking_matrix(srcX, fbinX); }\n#endif /* #ifdef ENABLE_LEGACY_BTK_API */\n\nprotected:\n  bool normalize_weight_;\n};\n\n/**\n   @class SubbandGSCRLS\n   @brief implementation of recursive least squares of a GSC\n   @usage\n   1. calcGSCWeights()\n   2. initPrecisionMatrix() or setPrecisionMatrix()\n   3. update_sctive_weight_vecotrs( false ) if you want to stop adapting the active weight vectors.\n   @note notations are  based on Van Trees, \"Optimum Array Processing\", pp. 766-767.\n */\ntypedef enum {\n  CONSTANT_NORM           = 0x01,\n  THRESHOLD_LIMITATION    = 0x02,\n  NO_QUADRATIC_CONSTRAINT = 0x00\n} QuadraticConstraintType;\n\n// ----- definition for class `SubbandGSCRLS' -----\n// \n\nclass SubbandGSCRLS : public SubbandGSC {\n public:\n  SubbandGSCRLS(unsigned fftLen = 512, bool halfBandShift = false, float mu = 0.9, float sigma2=0.0, const String& nm = \"SubbandGSCRLS\");\n  ~SubbandGSCRLS();\n\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void reset();\n\n  void init_precision_matrix(float sigma2 = 0.01);\n  void set_precision_matrix(unsigned fbinX, gsl_matrix_complex *Pz);\n  void update_active_weight_vecotrs(bool flag){ is_wa_updated_ = flag; }\n  void set_quadratic_constraint(float alpha, int qctype=1){ alpha_=alpha; qctype_=(QuadraticConstraintType)qctype; }\n\n#ifdef ENABLE_LEGACY_BTK_API\n  void initPrecisionMatrix(float sigma2 = 0.01){ init_precision_matrix(sigma2); }\n  void setPrecisionMatrix(unsigned fbinX, gsl_matrix_complex *Pz){ set_precision_matrix(fbinX, Pz); }\n  void updateActiveWeightVecotrs(bool flag){ update_active_weight_vecotrs(flag); }\n  void setQuadraticConstraint(float alpha, int qctype=1){ set_quadratic_constraint(alpha, qctype); }\n#endif /* #ifdef ENABLE_LEGACY_BTK_API */\n\nprivate:\n  void update_active_weight_vector2_(int frame_no); /* the case of the half band shift = False */\n  bool alloc_subbandGSCRLS_image_();\n  void free_subbandGSCRLS_image_();\n\n  gsl_vector_complex** gz_; /* Gain vectors */\n  gsl_matrix_complex** Pz_; /* Precision matrices */\n  gsl_vector_complex* Zf_;  /* output of the blocking matrix at each frequency */\n  gsl_vector_complex* wa_;\n  float  mu_;              /* Exponential factor for the covariance matrix */\n  float* diagonal_weights_;\n  float  alpha_;            /* Weight for the quadratic constraint*/\n  QuadraticConstraintType qctype_;\n  bool is_wa_updated_;\n\n  /* work space for updating active weight vectors */\n  gsl_vector_complex* PzH_Z_;\n  gsl_matrix_complex* _I;\n  gsl_matrix_complex* mat1_;\n};\n\n// ----- definition for class `SubbandMMI' -----\n//\n\nclass SubbandMMI : public SubbandDS {\npublic:\n  SubbandMMI(unsigned fftLen = 512, bool halfBandShift = false, unsigned targetSourceX=0, unsigned nSource=2, int pfType=0, float alpha=0.9, const String& nm = \"SubbandMMI\")\n    : SubbandDS( fftLen, halfBandShift, nm ),\n    targetSourceX_(targetSourceX),\n    nSource_(nSource),\n    pftype_(pfType),\n    alpha_(alpha),\n    use_binary_mask_(false),\n    binary_mask_type_(0),\n    interference_outputs_(NULL),\n    avg_output_(NULL)\n  {}\n\n  ~SubbandMMI();\n\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n\n  void use_binary_mask(float avgFactor=-1.0, unsigned fwidth=1, unsigned type=0);\n  void calc_weights(  float samplerate, const gsl_matrix* delays);\n  void calc_weights_n( float samplerate, const gsl_matrix* delays, unsigned NC=2);\n  void set_hi_active_weights_f(unsigned fbinX, const gsl_vector* pkdWa, const gsl_vector* pkdwb, int option=0);\n  void set_active_weights_f(unsigned fbinX, const gsl_matrix* packedWeights, int option=0);\n\n#ifdef ENABLE_LEGACY_BTK_API\n  void useBinaryMask(float avgFactor=-1.0, unsigned fwidth=1, unsigned type=0){ use_binary_mask(avgFactor, fwidth, type); }\n  void calcWeights(  float sampleRate, const gsl_matrix* delays){ calc_weights(sampleRate, delays); }\n  void calcWeightsN( float sampleRate, const gsl_matrix* delays, unsigned NC=2){ calc_weights_n(sampleRate, delays, NC); }\n  void setHiActiveWeights_f(unsigned fbinX, const gsl_vector* pkdWa, const gsl_vector* pkdwb, int option=0){\n    set_hi_active_weights_f(fbinX, pkdWa, pkdwb, option);\n  }\n  void setActiveWeights_f(unsigned fbinX, const gsl_matrix* packedWeights, int option=0){\n    set_active_weights_f(fbinX, packedWeights, option);\n  }\n#endif /* #ifdef ENABLE_LEGACY_BTK_API */\n\nprivate:\n  void calc_interference_outputs_();\n  void binary_masking_( gsl_vector_complex** interferenceOutputs, unsigned targetSourceX, gsl_vector_complex* output );\n\n  unsigned                                      targetSourceX_; // the n-th source will be emphasized\n  unsigned                                      nSource_;       // the number of sound sources\n  int                                           pftype_;\n  float                                        alpha_;\n  bool                                          use_binary_mask_; // true if you use a binary mask\n  unsigned                                      binary_mask_type_;// 0:use GSC's outputs, 1:use outputs of the upper branch.\n  gsl_vector_complex**                          interference_outputs_;\n  gsl_vector_complex*                           avg_output_;\n  float                                        avg_factor_;\n  unsigned                                      fwidth_;\n};\n\n\n// ----- definition for class `SubbandMVDR' -----\n//\n\n/**\n   @class SubbandMVDR \n\n   @usage\n   1. setChannel()\n   2. calc_array_manifold_vectors(), calc_array_manifold_vectors2() or calc_array_manifold_vectorsN().\n   3. set_noise_spatial_spectral_matrix() or set_diffuse_noise_model()\n   4. calc_mvdr_weights()\n */\nclass SubbandMVDR : public SubbandDS {\n public:\n  /**\n     @brief Basic MVDR beamformer implementation\n     @param int fftLen[in]\n     @param bool halfBandShift[in]\n   */\n  SubbandMVDR(unsigned fftLen = 512, bool halfBandShift = false, const String& nm = \"SubbandMVDR\");\n  ~SubbandMVDR();\n\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n  virtual void clear_channel();\n  bool calc_mvdr_weights(float samplerate, float dThreshold = 1.0E-8, bool calcInverseMatrix = true);\n  const gsl_vector_complex* mvdr_weights(unsigned fbinX) const { return wmvdr_[fbinX]; }\n\n  const gsl_matrix_complex *noise_spatial_spectral_matrix(unsigned fbinX) const { return R_[fbinX]; }\n  bool set_noise_spatial_spectral_matrix(unsigned fbinX, gsl_matrix_complex* Rnn);\n  bool set_diffuse_noise_model(const gsl_matrix* micPositions, float samplerate, float sspeed = 343740.0); /* micPositions[][x,y,z] */\n  void set_all_diagonal_loading(float diagonalWeight);\n  void set_diagonal_looading(unsigned fbinX, float diagonalWeight);\n  /**\n     @brief Divide each non-diagonal elemnt by 1 + mu instead of diagonal loading. mu can be interpreted as the ratio of the sensor noise to the ambient noise power.\n     @param float mu[in]\n   */\n  void divide_all_nondiagonal_elements(float mu){\n    for(unsigned fbinX=0;fbinX<=fftLen_/2;fbinX++)\n      divide_nondiagonal_elements( fbinX, mu );\n  }\n  void divide_nondiagonal_elements(unsigned fbinX, float mu);\n  gsl_matrix_complex**  noise_spatial_spectral_matrix() const { return R_; }\n\n#ifdef ENABLE_LEGACY_BTK_API\n  void clearChannel(){ clear_channel(); }\n  bool calcMVDRWeights( float sampleRate, float dThreshold = 1.0E-8, bool calcInverseMatrix = true ){ return calc_mvdr_weights(sampleRate, dThreshold, calcInverseMatrix); }\n  const gsl_vector_complex* getMVDRWeights(unsigned fbinX){ return mvdr_weights(fbinX); }\n  const gsl_matrix_complex *getNoiseSpatialSpectralMatrix(unsigned fbinX){ return noise_spatial_spectral_matrix(fbinX); }\n  bool setNoiseSpatialSpectralMatrix(unsigned fbinX, gsl_matrix_complex* Rnn){ return set_noise_spatial_spectral_matrix(fbinX, Rnn); }\n  bool setDiffuseNoiseModel(const gsl_matrix* micPositions, float sampleRate, float sspeed = 343740.0){ return set_diffuse_noise_model(micPositions, sampleRate, sspeed); }\n  void setAllLevelsOfDiagonalLoading(float diagonalWeight){ set_all_diagonal_loading(diagonalWeight); }\n  void setLevelOfDiagonalLoading(unsigned fbinX, float diagonalWeight){ set_diagonal_looading(fbinX, diagonalWeight); }\n  void divideAllNonDiagonalElements( float mu ){ divide_all_nondiagonal_elements(mu); }\n  void divideNonDiagonalElements( unsigned fbinX, float mu ){ divide_nondiagonal_elements(fbinX, mu); }\n  gsl_matrix_complex**  getNoiseSpatialSpectralMatrix(){ return noise_spatial_spectral_matrix(); }\n#endif /* #ifdef ENABLE_LEGACY_BTK_API */\n\nprotected:\n  gsl_matrix_complex**                           R_; /* Noise spatial spectral matrices */\n  gsl_matrix_complex**                           invR_;\n  gsl_vector_complex**                           wmvdr_;\n  float*                                         diagonal_weights_;\n};\n\n// ----- definition for class `SubbandMVDRGSC' -----\n//\n\n/**\n   @class SubbandMVDRGSC \n\n   @usage\n   1. setChannel()\n   2. calc_array_manifold_vectors(), calc_array_manifold_vectors2() or calc_array_manifold_vectorsN().\n   3. set_noise_spatial_spectral_matrix() or set_diffuse_noise_model()\n   4. calc_mvdr_weights()\n   5. calc_blocking_matrix1() or calc_blocking_matrix2()\n   6. set_active_weights_f()\n */\nclass SubbandMVDRGSC : public SubbandMVDR {\n public:\n  /**\n     @brief MVDR beamforming implementation\n     @param int fftLen[in]\n     @param bool halfBandShift[in]\n   */\n  SubbandMVDRGSC(unsigned fftLen = 512, bool halfBandShift = false, const String& nm = \"SubbandMVDR\");\n  ~SubbandMVDRGSC();\n\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n\n  void set_active_weights_f(unsigned fbinX, const gsl_vector* packedWeight);\n  void zero_active_weights();\n  bool calc_blocking_matrix1(float samplerate, const gsl_vector* delaysT);\n  bool calc_blocking_matrix2();\n  void upgrade_blocking_matrix();\n  const gsl_vector_complex* blocking_matrix_output(int outChanX=0);\n\n#ifdef ENABLE_LEGACY_BTK_API\n  void setActiveWeights_f(unsigned fbinX, const gsl_vector* packedWeight){ set_active_weights_f(fbinX, packedWeight); }\n  void zeroActiveWeights(){ zero_active_weights(); }\n  bool calcBlockingMatrix1(float sampleRate, const gsl_vector* delaysT){ return calc_blocking_matrix1(sampleRate, delaysT); }\n  bool calcBlockingMatrix2(){ return calc_blocking_matrix2(); }\n  void upgradeBlockingMatrix(){ upgrade_blocking_matrix(); }\n  const gsl_vector_complex* blockingMatrixOutput(int outChanX=0){ return blocking_matrix_output(outChanX); }\n#endif\n\nprotected:\n  bool normalize_weight_;\n};\n\ntypedef Inherit<SubbandBeamformer, VectorComplexFeatureStreamPtr> SubbandBeamformerPtr;\ntypedef Inherit<SubbandDS, SubbandBeamformerPtr> SubbandDSPtr;\ntypedef Inherit<SubbandGSC, SubbandDSPtr> SubbandGSCPtr;\ntypedef Inherit<SubbandGSCRLS, SubbandGSCPtr> SubbandGSCRLSPtr;\ntypedef Inherit<SubbandMMI, SubbandDSPtr> SubbandMMIPtr;\ntypedef Inherit<SubbandMVDR, SubbandDSPtr> SubbandMVDRPtr;\ntypedef Inherit<SubbandMVDRGSC, SubbandMVDRPtr> SubbandMVDRGSCPtr;\n\n// ----- members for class `SubbandOrthogonalizer' -----\n//\n\nclass SubbandOrthogonalizer : public VectorComplexFeatureStream {\npublic:\n  SubbandOrthogonalizer(SubbandMVDRGSCPtr &beamformer, int outChanX=0, const String& nm = \"SubbandOrthogonalizer\");\n  ~SubbandOrthogonalizer();\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n\nprivate:\n  SubbandMVDRGSCPtr beamformer_;\n  int outChanX_;\n};\n\ntypedef Inherit<SubbandOrthogonalizer, VectorComplexFeatureStreamPtr> SubbandOrthogonalizerPtr;\n\nclass SubbandBlockingMatrix : public SubbandGSC {\npublic:\n  SubbandBlockingMatrix(unsigned fftLen=512, bool halfBandShift=false, const String& nm = \"SubbandBlockingMatrix\")\n    :SubbandGSC(fftLen, halfBandShift, nm ){;}\n\n  ~SubbandBlockingMatrix();\n  virtual const gsl_vector_complex* next(int frame_no = -5);\n};\n\n// ----- definition for class DOAEstimatorSRPBase' -----\n//\nclass DOAEstimatorSRPBase {\npublic:\n  DOAEstimatorSRPBase( unsigned nBest, unsigned fbinMax );\n  virtual ~DOAEstimatorSRPBase();\n\n  const gsl_vector *nbest_rps() const { return nBestRPs_; }\n  const gsl_matrix *nbest_doas() const { return argMaxDOAs_;}\n  const gsl_matrix *response_power_matrix() const { return rpMat_;}\n  float energy() const {return energy_;}\n  void  final_nbest_hypotheses(){get_nbest_hypotheses_from_accrp_();}\n  void  set_energy_threshold(float engeryThreshold){ engery_threshold_ = engeryThreshold; }\n  void  set_frequency_range(unsigned fbinMin, unsigned fbinMax){ fbinMin_ = fbinMin; fbinMax_ = fbinMax;}\n  void  init_accs(){ init_accs_(); }\n  void  set_search_param(float minTheta=-M_PI/2, float maxTheta=M_PI/2,\n                         float minPhi=-M_PI/2,   float maxPhi=M_PI/2,\n                         float widthTheta=0.1,   float widthPhi=0.1);\n\n#ifdef ENABLE_LEGACY_BTK_API\n  const gsl_vector *getNBestRPs(){ return nbest_rps(); }\n  const gsl_matrix *getNBestDOAs(){ return nbest_doas(); }\n  const gsl_matrix *getResponsePowerMatrix(){ return response_power_matrix(); }\n  float getEnergy(){return energy();}\n  void getFinalNBestHypotheses(){ final_nbest_hypotheses(); }\n  void setEnergyThreshold(float engeryThreshold){ set_energy_threshold(engeryThreshold); }\n  void setFrequencyRange(unsigned fbinMin, unsigned fbinMax){ set_frequency_range(fbinMin, fbinMax); }\n  void initAccs(){ init_accs(); }\n  void setSearchParam(float minTheta=-M_PI/2, float maxTheta=M_PI/2,\n                      float minPhi=-M_PI/2,   float maxPhi=M_PI/2,\n                      float widthTheta=0.1, float widthPhi=0.1)\n  {\n    set_search_param(minTheta, maxTheta, minPhi, maxPhi, widthTheta, widthPhi);\n  }\n#endif\n\nprotected:\n  void clear_table_();\n  virtual void get_nbest_hypotheses_from_accrp_();\n  virtual void init_accs_();\n\n  float widthTheta_;\n  float widthPhi_;\n  float minTheta_;\n  float maxTheta_;\n  float minPhi_;\n  float maxPhi_;\n  unsigned nTheta_;\n  unsigned nPhi_;\n  unsigned fbinMin_;\n  unsigned fbinMax_;\n  unsigned nBest_;\n  bool   table_initialized_;\n\n  gsl_vector *accRPs_;\n  gsl_vector *nBestRPs_;\n  gsl_matrix *argMaxDOAs_;\n  vector<gsl_vector_complex **> svTbl_; // [][fftL2+1][_dim]\n  gsl_matrix         *rpMat_;\n\n  float engery_threshold_;\n  float energy_;\n\n#ifdef  __MBDEBUG__\n  void allocDebugWorkSapce();\n#endif /* #ifdef __MBDEBUG__ */\n};\n\n// ----- definition for class DOAEstimatorSRPDSBLA' -----\n// \n/**\n   @brief estimate the direction of arrival based on the maximum steered response power\n\n   @usage\n   1. construct an object\n   2. set the geometry of the linear array\n   3. call next()\n */\nclass DOAEstimatorSRPDSBLA :\n  public DOAEstimatorSRPBase, public SubbandDS {\npublic:\n  DOAEstimatorSRPDSBLA( unsigned nBest, unsigned samplerate, unsigned fftLen, const String& nm=\"DOAEstimatorSRPDSBLA\" );\n  ~DOAEstimatorSRPDSBLA();\n\n  const gsl_vector_complex* next(int frame_no = -5);\n  void reset();\n\n  void set_array_geometry(gsl_vector *positions);\n\n#ifdef ENABLE_LEGACY_BTK_API\n  void setArrayGeometry(gsl_vector *positions){ set_array_geometry(positions); }\n#endif\n\nprotected:\n  virtual void   calc_steering_unit_table_();\n  virtual float calc_response_power_( unsigned uttX );\n\nprivate:\n  virtual void set_look_direction_( int nChan, float theta );\n\n  unsigned    samplerate_;\n  gsl_matrix *arraygeometry_; // [micX][x,y,z]\n};\n\ntypedef refcount_ptr<DOAEstimatorSRPBase> DOAEstimatorSRPBasePtr;\ntypedef Inherit<DOAEstimatorSRPDSBLA, SubbandDSPtr> DOAEstimatorSRPDSBLAPtr;\n\n// ----- definition for functions' -----\n//\n\nfloat calc_energy(SnapShotArrayPtr snapShotArray, unsigned fbinMin, unsigned fbinMax, unsigned fftLen2, bool  halfBandShift=false);\n\nvoid calc_gsc_output(const gsl_vector_complex* snapShot,\n                     gsl_vector_complex* wl_f, gsl_vector_complex* wq_f,\n                     gsl_complex *pYf, bool normalizeWeight=false );\n\nbool pseudoinverse( gsl_matrix_complex *A, gsl_matrix_complex *invA, float dThreshold =  1.0E-8 );\n\nvoid calc_all_delays(float x, float y, float z, const gsl_matrix* mpos, gsl_vector* delays);\n\nvoid calc_product(gsl_vector_complex* synthesisSamples, gsl_matrix_complex* gs_W, gsl_vector_complex* product);\n\n#ifdef ENABLE_LEGACY_BTK_API\ninline void calcAllDelays(float x, float y, float z, const gsl_matrix* mpos, gsl_vector* delays)\n{\n  calc_all_delays(x, y, z, mpos, delays);\n}\n\ninline void calcProduct(gsl_vector_complex* synthesisSamples, gsl_matrix_complex* gs_W, gsl_vector_complex* product)\n{\n  calc_product(synthesisSamples, gs_W, product);\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "0223f214753cdd9f91fb7eedc608da37400c8ba0", "size": 25107, "ext": "h", "lang": "C", "max_stars_repo_path": "btk20_src/beamformer/beamformer.h", "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_issues_repo_path": "btk20_src/beamformer/beamformer.h", "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_forks_repo_path": "btk20_src/beamformer/beamformer.h", "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "avg_line_length": 41.9148580968, "max_line_length": 173, "alphanum_fraction": 0.7464452145, "num_tokens": 6547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.373322400014211}}
{"text": "/* filter/test.c\n * \n * Copyright (C) 2018 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_statistics.h>\n#include <gsl/gsl_test.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_filter.h>\n\n/* compare two vectors */\nstatic void\ncompare_vectors(const double tol, const gsl_vector * v, const gsl_vector * expected,\n                const char * desc)\n{\n  const size_t n = v->size;\n  size_t i;\n\n  for (i = 0; i < n; ++i)\n    {\n      double vi = gsl_vector_get(v, i);\n      double ui = gsl_vector_get(expected, i);\n\n      gsl_test_rel(vi, ui, tol, \"%s i=%zu\", desc, i);\n    }\n}\n\n/* generate random vector with elements in [-1,1] */\nstatic void\nrandom_vector(gsl_vector * v, gsl_rng * r)\n{\n  size_t i;\n\n  for (i = 0; i < v->size; ++i)\n    {\n      double vi = 2.0 * gsl_rng_uniform(r) - 1.0; /* in [-1,1] */\n      gsl_vector_set(v, i, vi);\n    }\n}\n\n#include \"test_impulse.c\"\n#include \"test_gaussian.c\"\n#include \"test_median.c\"\n#include \"test_rmedian.c\"\n\nint\nmain()\n{\n  gsl_rng * r = gsl_rng_alloc(gsl_rng_default);\n\n  test_gaussian(r);\n\n  test_impulse(r);\n  test_median(r);\n  test_rmedian(r);\n\n  gsl_rng_free(r);\n\n  exit (gsl_test_summary());\n}\n", "meta": {"hexsha": "2318e02905dd508bf69d818ffb6d3e5999e271dc", "size": 2034, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/filter/test.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/filter/test.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/filter/test.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 24.5060240964, "max_line_length": 84, "alphanum_fraction": 0.6769911504, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.37318909508506304}}
{"text": "/*\n * BRAINS\n * (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling\n * Yan-Rong Li, liyanrong@ihep.ac.cn\n * Thu, Aug 4, 2016\n */\n\n/*!\n *  \\file reconstruct_sa.c\n *  \\brief reconstruct sa and RM data.\n */\n\n#ifdef SA\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <float.h>\n#include <gsl/gsl_interp.h>\n\n#include \"brains.h\"\n\nvoid *best_model_sa;      /*!< best model */\nvoid *best_model_std_sa;  /*!< standard deviation of the best model */\n\n/*!\n * postprocessing.\n */\nvoid postprocess_sa()\n{\n  char posterior_sample_file[BRAINS_MAX_STR_LENGTH];\n  int num_ps, i, j, k;\n  double *pm, *pmstd;\n  void *posterior_sample, *post_model;\n  int size_of_modeltype = num_params * sizeof(double);\n  \n  best_model_sa = malloc(size_of_modeltype);\n  best_model_std_sa = malloc(size_of_modeltype);\n\n  if(thistask == roottask)\n  {\n    // initialize smoothing workspace\n    char fname[200];\n    FILE *fp, *fline, *fsa;\n\n    sa_smooth_init(n_vel_sa_data, vel_sa_data, parset.sa_InstRes);\n\n    // get number of lines in posterior sample file\n    get_posterior_sample_file(dnest_options_file, posterior_sample_file);\n\n    //file for posterior sample\n    fp = fopen(posterior_sample_file, \"r\");\n    if(fp == NULL)\n    {\n      fprintf(stderr, \"# Error: Cannot open file %s.\\n\", posterior_sample_file);\n      exit(0);\n    }\n     \n    //file for line reconstruction\n    sprintf(fname, \"%s/%s\", parset.file_dir, \"data/sa_line_rec.txt\");\n    fline = fopen(fname, \"w\");\n    if(fline == NULL)\n    {\n      fprintf(stderr, \"# Error: Cannot open file %s.\\n\", fname);\n      exit(0);\n    }\n\n    //file for phase\n    sprintf(fname, \"%s/%s\", parset.file_dir, \"data/sa_phase_rec.txt\");\n    fsa = fopen(fname, \"w\");\n    if(fsa == NULL)\n    {\n      fprintf(stderr, \"# Error: Cannot open file %s.\\n\", fname);\n      exit(0);\n    }\n\n    // read number of lines\n    if(fscanf(fp, \"# %d\", &num_ps) < 1)\n    {\n      fprintf(stderr, \"# Error: Cannot read file %s.\\n\", posterior_sample_file);\n      exit(0);\n    }\n    printf(\"# Number of points in posterior sample: %d\\n\", num_ps);\n\n    post_model = malloc(size_of_modeltype);\n    posterior_sample = malloc(num_ps * size_of_modeltype);\n\n    force_update = 1;\n    which_parameter_update = -1; // force to update the transfer function\n    which_particle_update = 0;\n    \n    for(i=0; i<num_ps; i++)\n    {\n      // read lines\n      for(j=0; j<num_params; j++)\n      {\n        if(fscanf(fp, \"%lf\", (double *)post_model + j) < 1)\n        {\n          fprintf(stderr, \"# Error: Cannot read file %s.\\n\", posterior_sample_file);\n          exit(0);\n        }\n      }\n      fscanf(fp, \"\\n\");\n\n      //store model\n      memcpy(posterior_sample+i*size_of_modeltype, post_model, size_of_modeltype);\n    \n      calculate_sa_from_blrmodel(post_model, 0);\n      \n      //if( i % (num_ps/10+1) == 0)  \n      {\n        // output sa line\n        for(j=0; j<n_vel_sa_data; j++)\n        {\n          fprintf(fline, \"%e %e\\n\", wave_sa_data[j], Fline_sa[j]);\n        }\n        fprintf(fline, \"\\n\");\n\n        // output sa phase\n        for(k=0; k<n_base_sa_data; k++)\n        {\n          for(j=0; j<n_vel_sa_data; j++)\n          {\n            fprintf(fsa, \"%e %e\\n\", wave_sa_data[j], phase_sa[k*n_vel_sa_data + j]/(PhaseFactor * wave_sa_data[j]) );\n          }\n        }\n        fprintf(fsa, \"\\n\");\n      }\n    }\n\n    fclose(fp);\n    fclose(fline);\n    fclose(fsa);\n\n    sa_smooth_end();\n\n    pm = (double *)best_model_sa;\n    pmstd = (double *)best_model_std_sa;\n    for(j=0; j<num_params; j++)\n    {\n      pm[j] = pmstd[j] = 0.0;\n    }\n    for(i=0; i<num_ps; i++)\n    {\n      for(j =0; j<num_params; j++)\n        pm[j] += *((double *)posterior_sample + i*num_params + j );\n    }\n\n    for(j=0; j<num_params; j++)\n      pm[j] /= num_ps;\n\n    for(i=0; i<num_ps; i++)\n    {\n      for(j=0; j<num_params; j++)\n        pmstd[j] += pow( *((double *)posterior_sample + i*num_params + j ) - pm[j], 2.0 );\n    }\n\n    for(j=0; j<num_params; j++)\n    {\n      if(num_ps > 1)\n        pmstd[j] = sqrt(pmstd[j]/(num_ps-1.0));\n      else\n        pmstd[j] = 0.0;\n    }\n\n    for(j = 0; j<num_params_sa; j++)\n      printf(\"Best params %d %f +- %f\\n\", j, *((double *)best_model_sa + j), \n                                             *((double *)best_model_std_sa+j) ); \n \n    free(post_model);\n    free(posterior_sample);\n  }\n  return;\n}\n\n/*!\n * this function run dnest sampleing, reconstruct light curves using the best estimates for parameters.\n */\nvoid reconstruct_sa()\n{\n  int i, argc=0;\n  char **argv;\n\n  //configure restart of dnest\n  argv = malloc(9*sizeof(char *));\n  for(i=0; i<9; i++)\n  {\n    argv[i] = malloc(BRAINS_MAX_STR_LENGTH*sizeof(char));\n  }\n  //setup argc and argv\n  strcpy(argv[argc++], \"dnest\");\n  strcpy(argv[argc++], \"-s\");\n  strcpy(argv[argc], parset.file_dir);\n  strcat(argv[argc++], \"/data/restartsa_dnest.txt\");\n\n  if(parset.flag_restart == 1)\n  {\n    strcpy(argv[argc++], \"-r\");\n    strcpy(argv[argc], parset.file_dir);\n    strcat(argv[argc], \"/\");\n    strcat(argv[argc++], \"data/restartsa_dnest.txt\");\n  }\n  if(parset.flag_postprc == 1)\n  {\n    strcpy(argv[argc++], \"-p\");\n  }\n  if(parset.flag_temp == 1)\n  {\n    sprintf(argv[argc++], \"-t%f\", parset.temperature);\n  }\n  if(parset.flag_sample_info == 1)\n  {\n    strcpy(argv[argc++], \"-c\");\n  }\n  \n  //level-dependent sampling\n  {\n    strcpy(argv[argc++], \"-l\");\n  }\n  \n  reconstruct_sa_init();\n\n  sa_smooth_init(n_vel_sa_data, vel_sa_data, parset.sa_InstRes);\n  dnest_sa(argc, argv);\n  sa_smooth_end();\n\n  if(parset.flag_exam_prior != 1 && parset.flag_para_name != 1)\n  {\n    postprocess_sa();\n\n    if(thistask == roottask)\n    {\n      FILE *fp;\n      char fname[200];\n      int j, k;\n\n      force_update = 1;\n      which_parameter_update = -1; // force to update the transfer function\n      which_particle_update = 0;\n      \n      sa_smooth_init(n_vel_sa_data, vel_sa_data, parset.sa_InstRes);\n      calculate_sa_from_blrmodel(best_model_sa, 1);\n      sa_smooth_end();\n\n      sprintf(fname, \"%s/%s\", parset.file_dir, \"data/psa_line.txt\");\n      fp = fopen(fname, \"w\");\n      if(fp == NULL)\n      {\n        fprintf(stderr, \"# Error: Cannot open file %s.\\n\", fname);\n        exit(0);\n      }\n      // output sa line\n      for(j=0; j<n_vel_sa_data; j++)\n      {\n        fprintf(fp, \"%e %e\\n\", wave_sa_data[j], Fline_sa[j]);\n      }\n      fclose(fp);\n\n      //file for phase\n      sprintf(fname, \"%s/%s\", parset.file_dir, \"data/psa_phase.txt\");\n      fp = fopen(fname, \"w\");\n      if(fp == NULL)\n      {\n        fprintf(stderr, \"# Error: Cannot open file %s.\\n\", fname);\n        exit(0);\n      }\n      for(k=0; k<n_base_sa_data; k++)\n      {\n        for(j=0; j<n_vel_sa_data; j++)\n        {\n          fprintf(fp, \"%e %e\\n\", wave_sa_data[j], phase_sa[k*n_vel_sa_data + j]/(PhaseFactor * wave_sa_data[j]) );\n        }\n        fprintf(fp, \"\\n\");\n      }\n      fclose(fp);\n    }\n  }\n\n  reconstruct_sa_end();\n\n  //clear up argv\n  for(i=0; i<9; i++)\n  {\n    free(argv[i]);\n  }\n  free(argv);\n\n  return;\n}\n\nvoid reconstruct_sa_init()\n{ \n  sprintf(dnest_options_file, \"%s/%s\", parset.file_dir, \"src/OPTIONSSA\");\n  if(thistask == roottask)\n  {\n    get_num_particles(dnest_options_file);\n  }\n  MPI_Bcast(&parset.num_particles, 1, MPI_INT, roottask, MPI_COMM_WORLD);\n\n  phase_sa = malloc(n_base_sa_data * n_vel_sa_data * sizeof(double));\n  Fline_sa = malloc(n_vel_sa_data * sizeof(double));\n\n  /* cloud sample related */\n  clouds_weight = malloc(parset.n_cloud_per_task * sizeof(double));\n  clouds_alpha = malloc(parset.n_cloud_per_task * sizeof(double));\n  clouds_beta = malloc(parset.n_cloud_per_task * sizeof(double));\n  clouds_vel = malloc(parset.n_cloud_per_task * parset.n_vel_per_cloud * sizeof(double));\n\n  workspace_phase = malloc( (3*n_vel_sa_data)* sizeof(double));\n\n  if(parset.flag_save_clouds && thistask == roottask)\n  {\n    if(parset.n_cloud_per_task <= 1000)\n      icr_cloud_save = 1;\n    else\n      icr_cloud_save = parset.n_cloud_per_task/1000;\n\n    char fname[200];\n    sprintf(fname, \"%s/%s\", parset.file_dir, parset.cloud_out_file);\n    fcloud_out = fopen(fname, \"w\");\n    if(fcloud_out == NULL)\n    {\n      fprintf(stderr, \"# Error: Cannot open file %s\\n\", fname);\n      exit(-1);\n    }\n  }\n  return;\n}\n\nvoid reconstruct_sa_end()\n{\n  int i;\n\n  free(phase_sa);\n  free(Fline_sa);\n\n  for(i=0; i<num_params; i++)\n  {\n    free(par_range_model[i]);\n    free(par_prior_gaussian[i]);\n  }\n  free(par_range_model);\n  free(par_prior_gaussian);\n  free(par_prior_model);\n\n  free(par_fix);\n  free(par_fix_val);\n  free(best_model_sa);\n  free(best_model_std_sa);\n  \n  /* clouds sample related */\n  free(clouds_weight);\n  free(clouds_alpha);\n  free(clouds_beta);\n  free(clouds_vel);\n  \n  free(workspace_phase);\n\n  if(parset.flag_save_clouds && thistask==roottask)\n  {\n    fclose(fcloud_out);\n  }\n  if(thistask == roottask)\n  {\n    printf(\"Ends reconstruct_sa.\\n\");\n  }\n  return;\n}  \n\n/*!\n * this function calculate probability.\n * \n * At each MCMC step, only one parameter is updated, which only changes some values; thus,\n * optimization that reuses the unchanged values can improve computation efficiency.\n */\ndouble prob_sa(const void *model)\n{\n  double prob_sa = 0.0, var2, dy;\n  int i, j;\n   \n  calculate_sa_from_blrmodel(model, 0);\n\n  for(j=0; j<n_epoch_sa_data; j++)\n  {\n    for(i=0; i<n_vel_sa_data; i++)\n    {\n      dy = Fline_sa[i] - Fline_sa_data[i + j*n_vel_sa_data];\n      var2 = Flerrs_sa_data[i+j*n_vel_sa_data]*Flerrs_sa_data[i+j*n_vel_sa_data];\n      prob_sa += -0.5 * (dy*dy)/var2 - 0.5*log(var2 * 2.0*PI);\n    }\n  }\n\n  for(j=0; j<n_base_sa_data; j++)\n  {\n    for(i=0; i<n_vel_sa_data; i++)\n    {\n      dy = phase_sa[j*n_vel_sa_data + i] - phase_sa_data[j*n_vel_sa_data + i];\n      var2 = pherrs_sa_data[j*n_vel_sa_data + i] * pherrs_sa_data[j*n_vel_sa_data + i];\n      prob_sa += -0.5 * (dy*dy)/var2 - 0.5*log(var2 * 2.0*PI);\n    }\n  }\n\n  return prob_sa;\n}\n\n#endif", "meta": {"hexsha": "d83c3e0e4539d0d3921573fb47abc90ee24b59cb", "size": 9871, "ext": "c", "lang": "C", "max_stars_repo_path": "src/reconstruct_sa.c", "max_stars_repo_name": "yzxamos/BRAINS", "max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/reconstruct_sa.c", "max_issues_repo_name": "yzxamos/BRAINS", "max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reconstruct_sa.c", "max_forks_repo_name": "yzxamos/BRAINS", "max_forks_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_forks_repo_licenses": ["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.2530712531, "max_line_length": 117, "alphanum_fraction": 0.5958869415, "num_tokens": 2902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3730687920123746}}
{"text": "#include \"linear.h\"\n#include <assert.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <float.h>\n#include <lauxlib.h>\n#include <cblas.h>\n#include <lapacke.h>\n\n/* matrix orders */\nstatic const char * const ORDERS[] = { \"row\", \"col\", NULL };\n\n/* checks an order */\nstatic CBLAS_ORDER checkorder (lua_State *L, int index) {\n\n\tswitch (luaL_checkoption(L, index, \"row\", ORDERS)) {\n\tcase 0:\n\t\treturn CblasRowMajor;\n\n\tcase 1:\n\t\treturn CblasColMajor;\n\t}\n\n\t/* not reached */\n\tassert(0);\n\treturn (CBLAS_ORDER)0;\n}\n\n/* checks a transpose */\nstatic CBLAS_TRANSPOSE checktranspose (lua_State *L, int index) {\n\tstatic const char * const TRANSPOSES[] = { \"notrans\", \"trans\", NULL };\n\n\tswitch (luaL_checkoption(L, index, \"notrans\", TRANSPOSES)) {\n\tcase 0:\n\t\treturn CblasNoTrans;\n\n\tcase 1:\n\t\treturn CblasTrans;\n\t}\n\n\t/* not reached */\n\tassert(0);\n\treturn (CBLAS_TRANSPOSE)0;\n}\n\n/* translates a transpose for LAPACK */\nstatic char lapacktranspose (CBLAS_TRANSPOSE transpose) {\n\tswitch (transpose) {\n\tcase CblasNoTrans:\n\t\treturn 'N';\n\n\tcase CblasTrans:\n\t\treturn 'T';\n\n\tdefault:\n\t\t/* not reached */\n\t\tassert(0);\n\t\treturn '\\0';\n\t}\n}\n\n/* returns an int value from a table */\nstatic int intvalue (lua_State *L, const char *key, int dfl) {\n\tint result, isinteger;\n\n\tlua_getfield(L, -1, key);\n\tif (!lua_isnil(L, -1)) {\n\t\tresult = lua_tointegerx(L, -1, &isinteger);\n\t\tif (!isinteger) {\n\t\t\tluaL_error(L, \"bad field \" LUA_QS, key);\n\t\t}\n\t} else {\n\t\tif (dfl < 0) {\n\t\t\tluaL_error(L, \"missing field \" LUA_QS, key);\n\t\t}\n\t\tresult = dfl;\n\t}\n\tlua_pop(L, 1);\n\treturn result;\n}\n\n/* returns an option value from a table */\nstatic int optionvalue (lua_State *L, const char *key, const char *dfl,\n\t\tconst char *options[]) {\n\tconst char *str;\n\tint i;\n\t\n\tlua_getfield(L, -1, key);\n\tif (!lua_isnil(L, -1)) {\n\t\tstr = lua_tostring(L, -1);\n\t\tif (str == NULL) {\n\t\t\tluaL_error(L, \"bad field \" LUA_QS, key);\n\t\t}\n\t} else {\n\t\tif (dfl == NULL) {\n\t\t\tluaL_error(L, \"missing field \" LUA_QS, key);\n\t\t}\n\t\tstr = dfl;\n\t}\n\tlua_pop(L, 1);\n\tfor (i = 0; options[i] != NULL; i++) {\n\t\tif (strcmp(options[i], str) == 0) {\n\t\t\treturn i;\n\t\t}\n\t}\n\tluaL_error(L, \"bad option \" LUA_QS \" in field \" LUA_QS, str, key);\n\treturn 0; /* not reached */\n}\n\n/* raises a linear argument error */\nstatic int argerror (lua_State *L, int index) {\n\treturn luaL_argerror(L, index, lua_pushfstring(L, \"vector, or matrix \"\n\t\t\t\"expected, got %s\", luaL_typename(L, index)));\n}\n\n/* pushes a new vector onto the stack */\nstatic struct vector *newvector (lua_State *L, int size) {\n\treturn lualinear_newvector(L, size);\n}\n\n/* pushes an existing vector onto the stack */\nstatic struct vector *wrapvector (lua_State *L, int size, float *values) {\n\treturn lualinear_wrapvector(L, size, values);\n}\n\n/* creates a new vector */\nstatic int vector (lua_State *L) {\n\tint size;\n\n\t/* process arguments */\n\tsize = luaL_checkinteger(L, 1);\n\tluaL_argcheck(L, size >= 1, 1, \"bad dimension\");\n\n\t/* create */\n\tnewvector(L, size);\n\treturn 1;\n}\n\n/* vector length implementation */\nstatic int vector_len (lua_State *L) {\n\tstruct vector *x;\n\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tlua_pushinteger(L, x->size);\n\treturn 1;\n}\n\n/* vector index implementation */\nstatic int vector_index (lua_State *L) {\n\tstruct vector *x;\n\tint index;\n\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tindex = luaL_checkinteger(L, 2);\n\tluaL_argcheck(L, index >= 1 && index <= x->size, 2, \"bad index\");\n\tlua_pushnumber(L, x->values[(size_t)(index - 1) * x->inc]);\n\treturn 1;\n}\n\n/* matrix vector newindex implementation */\nstatic int vector_newindex (lua_State *L) {\n\tstruct vector *x;\n\tint index;\n\tfloat value;\n\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tindex = luaL_checkinteger(L, 2);\n\tluaL_argcheck(L, index >= 1 && index <= x->size, 2, \"bad index\");\n\tvalue = luaL_checknumber(L, 3);\n\tx->values[(size_t)(index - 1) * x->inc] = value;\n\treturn 0;\n}\n\n/* vector next function */\nstatic int vector_next (lua_State *L) {\n\tstruct vector *x;\n\tint index;\n\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tindex = luaL_checkinteger(L, 2);\n\tif (index >= 0 && index < x->size) {\n\t\tlua_pushinteger(L, index + 1);\n\t\tlua_pushnumber(L, x->values[(size_t)index]);\n\t\treturn 2;\n\t}\n\tlua_pushnil(L);\n\treturn 1;\n}\n\n/* vector ipairs function */\nstatic int vector_ipairs (lua_State *L) {\n\tluaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tlua_pushcfunction(L, vector_next);\n\tlua_pushvalue(L, 1);\n\tlua_pushinteger(L, 0);\n\treturn 3;\n}\n\n/* returns the string representation of a vector */\nstatic int vector_tostring (lua_State *L) {\n\tstruct vector *x;\n\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tlua_pushfstring(L, \"vector: %p\", x);\n\treturn 1;\n}\n\n/* frees a vector */\nstatic int vector_free (lua_State *L) {\n\tstruct vector *x;\n\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tif (x->ref == LUA_NOREF) {\n\t\tfree(x->values);\n\t} else {\n\t\tluaL_unref(L, LUA_REGISTRYINDEX, x->ref);\n\t}\n\treturn 0;\n}\n\n/* pushes a new matrix onto the stack */\nstatic struct matrix *newmatrix (lua_State *L, int rows, int cols,\n\t\tCBLAS_ORDER order) {\n\treturn lualinear_newmatrix(L, rows, cols, order);\n}\n\n/* pushes an existing matrix onto the stack */\nstatic struct matrix *wrapmatrix (lua_State *L, int rows, int cols,\n\t\tCBLAS_ORDER order, float *values) {\n\treturn lualinear_wrapmatrix(L, rows, cols, order, values);\n}\n\n/* creates a new matrix */\nstatic int matrix (lua_State *L) {\n\tint rows, cols;\n\tCBLAS_ORDER order;\n\n\t/* process arguments */\n\trows = luaL_checkinteger(L, 1);\n\tluaL_argcheck(L, rows >= 1, 1, \"bad dimension\");\n\tcols = luaL_checkinteger(L, 2);\n\tluaL_argcheck(L, cols >= 1, 2, \"bad dimension\");\n\torder = checkorder(L, 3);\n\n\t/* create */\n\tnewmatrix(L, rows, cols, order);\n\treturn 1;\n}\n\n/* returns the length of a matrix */\nstatic int matrix_len (lua_State *L) {\n\tstruct matrix *X;\n\n\tX = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tswitch (X->order) {\n\tcase CblasRowMajor:\n\t\tlua_pushinteger(L, X->rows);\n\t\tbreak;\n\n\tcase CblasColMajor:\n\t\tlua_pushinteger(L, X->cols);\n\t\tbreak;\n\t}\n\treturn 1;\n}\n\n/* matrix index implementation */\nstatic int matrix_index (lua_State *L) {\n\tstruct matrix *X;\n\tint index, size;\n\tstruct vector *x;\n\n\t/* process arguments */\n\tX = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tindex = luaL_checkinteger(L, 2);\n\tluaL_argcheck(L, index >= 1, 2, \"bad index\");\n\tswitch (X->order) {\n\tcase CblasRowMajor:\n\t\tluaL_argcheck(L, index <= X->rows, 2, \"bad index\");\n\t\tsize = X->cols;\n\t\tbreak;\n\n\tcase CblasColMajor:\n\t\tluaL_argcheck(L, index <= X->cols, 2, \"bad index\");\n\t\tsize = X->rows;\n\t\tbreak;\n\n\tdefault:\n\t\t/* not reached */\n\t\tsize = -1; \n\t\tassert(0);\n\t}\n\n\t/* create vector */\n\tx = wrapvector(L, size, &X->values[(size_t)(index - 1) * X->ld]);\n\tlua_pushvalue(L, 1);\n\tx->ref = luaL_ref(L, LUA_REGISTRYINDEX);\n\treturn 1;\n}\n\n/* matrix next function */\nstatic int matrix_next (lua_State *L) {\n\tstruct matrix *X;\n\tint index, majorsize, minorsize;\n\tstruct vector *x;\n\n\tX = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tindex = luaL_checkinteger(L, 2);\n\tswitch (X->order) {\n\tcase CblasRowMajor:\n\t\tmajorsize = X->rows;\n\t\tminorsize = X->cols;\n\t\tbreak;\n\n\tcase CblasColMajor:\n\t\tmajorsize = X->cols;\n\t\tminorsize = X->rows;\n\t\tbreak;\n\n\tdefault:\n\t\t/* not reached */\n\t\tassert(0);\n\t\treturn 0;\n\t}\n\tif (index >= 0 && index < majorsize) {\n\t\tlua_pushinteger(L, index + 1);\n\t\tx = wrapvector(L, minorsize, &X->values[(size_t)index * X->ld]);\n\t\tlua_pushvalue(L, 1);\n\t\tx->ref = luaL_ref(L, LUA_REGISTRYINDEX);\n\t\treturn 2;\n\t}\n\tlua_pushnil(L);\n\treturn 1;\n}\n\n/* matrix ipairs function */\nstatic int matrix_ipairs (lua_State *L) {\n\tluaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tlua_pushcfunction(L, matrix_next);\n\tlua_pushvalue(L, 1);\n\tlua_pushinteger(L, 0);\n\treturn 3;\n}\n\n/* returns the string representation of a matrix */\nstatic int matrix_tostring (lua_State *L) {\n\tstruct matrix *X;\n\n\tX = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tlua_pushfstring(L, \"matrix: %p\", X);\n\treturn 1;\n}\n\n/* frees a matrix */\nstatic int matrix_free (lua_State *L) {\n\tstruct matrix *X;\n\n\tX = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tif (X->ref == LUA_NOREF) {\n\t\tfree(X->values);\n\t} else {\n\t\tluaL_unref(L, LUA_REGISTRYINDEX, X->ref);\n\t}\n\treturn 0;\n}\n\n/* returns the type of a linear object */\nstatic int type (lua_State *L) {\n\tif (luaL_testudata(L, 1, LUALINEAR_VECTOR_METATABLE) != NULL) {\n\t\tlua_pushliteral(L, \"vector\");\n\t\treturn 1;\n\t}\n\tif (luaL_testudata(L, 1, LUALINEAR_MATRIX_METATABLE) != NULL) {\n\t\tlua_pushliteral(L, \"matrix\");\n\t\treturn 1;\n\t}\n\tlua_pushnil(L);\n\treturn 1;\n}\n\n/* returns the size of a linear object */\nstatic int size (lua_State *L) {\n\tstruct vector *x;\n\tstruct matrix *X;\n\n\tx = luaL_testudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tif (x != NULL) {\n\t\tlua_pushinteger(L, x->size);\n\t\treturn 1;\n\t}\n\tX = luaL_testudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tif (X != NULL) {\n\t\tlua_pushinteger(L, X->rows);\n\t\tlua_pushinteger(L, X->cols);\n\t\tlua_pushstring(L, ORDERS[X->order == CblasRowMajor ? 0 : 1]);\n\t\treturn 3;\n\t}\n\treturn argerror(L, 1);\n}\n\n/* transposed vector */\nstatic int tvector (lua_State *L) {\n\tstruct matrix *X;\n\tint index, size;\n\tstruct vector *x;\n\n\t/* process arguments */\n\tX = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tindex = luaL_checkinteger(L, 2);\n\tluaL_argcheck(L, index >= 1, 2, \"bad index\");\n\tswitch (X->order) {\n\tcase CblasRowMajor:\n\t\tluaL_argcheck(L, index <= X->cols, 2, \"bad index\");\n\t\tsize = X->rows;\n\t\tbreak;\n\n\tcase CblasColMajor:\n\t\tluaL_argcheck(L, index <= X->rows, 2, \"bad index\");\n\t\tsize = X->cols;\n\t\tbreak;\n\n\tdefault:\n\t\t/* not reached */\n\t\tsize = -1; \n\t\tassert(0);\n\t}\n\n\t/* create vector */\n\tx = wrapvector(L, size, &X->values[index - 1]);\n\tx->inc = X->ld;\n\tlua_pushvalue(L, 1);\n\tx->ref = luaL_ref(L, LUA_REGISTRYINDEX);\n\treturn 1;\n}\n\n/* subvector or submatrix */\nstatic int sub (lua_State *L) {\n\tstruct vector *x, *s;\n\tstruct matrix *X, *S;\n\n\t/* process arguments */\n\tx = luaL_testudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tif (x != NULL) {\n\t\tint start, end;\n\n\t\tstart = luaL_optinteger(L, 2, 1);\n\t\tluaL_argcheck(L, start >= 1 && start <= x->size, 2,\n\t\t\t\t\"bad index\");\n\t\tend = luaL_optinteger(L, 3, x->size);\n\t\tluaL_argcheck(L, end >= start && end <= x->size, 3,\n\t\t\t\t\"bad index\");\n\t\ts = wrapvector(L, end - start + 1, &x->values[\n\t\t\t\t(size_t)(start - 1) * x->inc]);\n\t\ts->inc = x->inc;\n\t\tlua_pushvalue(L, 1);\n\t\ts->ref = luaL_ref(L, LUA_REGISTRYINDEX);\n\t\treturn 1;\n\t}\n\tX = luaL_testudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tif (X != NULL) {\n\t\tint rowstart, rowend, colstart, colend;\n\n\t\tswitch (X->order){\n\t\tcase CblasRowMajor:\n\t\t\trowstart = luaL_optinteger(L, 2, 1);\n\t\t\tluaL_argcheck(L, rowstart >= 1 && rowstart <= X->rows,\n\t\t\t\t\t2, \"bad index\");\n\t\t\tcolstart = luaL_optinteger(L, 3, 1);\n\t\t\tluaL_argcheck(L, colstart >= 1 && colstart <= X->cols,\n\t\t\t\t\t3, \"bad index\");\n\t\t\trowend = luaL_optinteger(L, 4, X->rows);\n\t\t\tluaL_argcheck(L, rowend >= rowstart && rowend\n\t\t\t\t\t<= X->rows, 4, \"bad index\");\n\t\t\tcolend = luaL_optinteger(L, 5, X->cols);\n\t\t\tluaL_argcheck(L, colend >= colstart && colend\n\t\t\t\t\t<= X->cols, 5, \"bad index\");\n\t\t\tS = wrapmatrix(L, rowend - rowstart + 1, colend\n\t\t\t\t\t- colstart + 1, X->order, &X->values[\n\t\t\t\t\t(size_t)(rowstart - 1) * X->ld\n\t\t\t\t\t+ colstart - 1]);\n\t\t\tbreak;\n\t\t\n\t\tcase CblasColMajor:\n\t\t\tcolstart = luaL_optinteger(L, 2, 1);\n\t\t\tluaL_argcheck(L, colstart >= 1 && colstart <= X->cols,\n\t\t\t\t\t2, \"bad index\");\n\t\t\trowstart = luaL_optinteger(L, 3, 1);\n\t\t\tluaL_argcheck(L, rowstart >= 1 && rowstart <= X->rows,\n\t\t\t\t\t3, \"bad index\");\n\t\t\tcolend = luaL_optinteger(L, 4, X->cols);\n\t\t\tluaL_argcheck(L, colend >= colstart && colend\n\t\t\t\t\t<= X->cols, 4, \"bad index\");\n\t\t\trowend = luaL_optinteger(L, 5, X->rows);\n\t\t\tluaL_argcheck(L, rowend >= rowstart && rowend\n\t\t\t\t\t<= X->rows, 5, \"bad index\");\n\t\t\tS = wrapmatrix(L, rowend - rowstart + 1, colend\n\t\t\t\t\t- colstart + 1, X->order, &X->values[\n\t\t\t\t\t(size_t)(colstart - 1) * X->ld\n\t\t\t\t\t+ rowstart - 1]);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t/* not reached */\n\t\t\tassert(0);\n\t\t\treturn 0;\n\t\t}\n\t\tS->ld = X->ld;\n\t\tlua_pushvalue(L, 1);\n\t\tS->ref = luaL_ref(L, LUA_REGISTRYINDEX);\n\t\treturn 1;\n\t}\n\treturn argerror(L, 1);\n}\n\n/* unwinds matrices into a vector */\nstatic int unwind (lua_State *L) {\n\tstruct vector *x;\n\tint index, i, j, k;\n\tsize_t base;\n\tstruct matrix *X;\n\n\tif (lua_gettop(L) == 0) {\n\t\treturn luaL_error(L, \"wrong number of arguments\");\n\t}\n\tx = luaL_checkudata(L, lua_gettop(L), LUALINEAR_VECTOR_METATABLE);\n\tindex = 1;\n\ti = 0;\n\twhile (i < x->size) {\n\t\tX = luaL_checkudata(L, index, LUALINEAR_MATRIX_METATABLE);\n\t\tluaL_argcheck(L, X->rows * X->cols <= x->size - i, index,\n\t\t\t\t\"matrix too large\");\n\t\tswitch (X->order) {\n\t\tcase CblasRowMajor:\n\t\t\tfor (j = 0; j < X->rows; j++) {\n\t\t\t\tbase = (size_t)j * X->ld;\n\t\t\t\tfor (k = 0; k < X->cols; k++) {\n\t\t\t\t\tx->values[(size_t)i * x->inc]\n\t\t\t\t\t\t\t= X->values[base + k];\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase CblasColMajor:\n\t\t\tfor (j = 0; j < X->cols; j++) {\n\t\t\t\tbase = (size_t)j * X->ld;\n\t\t\t\tfor (k = 0; k < X->rows; k++) {\n\t\t\t\t\tx->values[(size_t)i * x->inc]\n\t\t\t\t\t\t\t= X->values[base + k];\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tindex++;\n\t}\n\treturn 0;\n}\n\n/* reshapes a vector into matrices */\nstatic int reshape (lua_State *L) {\n\tstruct vector *x;\n\tint index, i, j, k;\n\tsize_t base;\n\tstruct matrix *X;\n\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tindex = 2;\n\ti = 0;\n\twhile (i < x->size) {\n\t\tX = luaL_checkudata(L, index, LUALINEAR_MATRIX_METATABLE);\n\t\tluaL_argcheck(L, X->rows * X->cols <= x->size - i, index,\n\t\t\t\t\"matrix too large\");\n\t\tswitch (X->order) {\n\t\tcase CblasRowMajor:\n\t\t\tfor (j = 0; j < X->rows; j++) {\n\t\t\t\tbase = (size_t)j * X->ld;\n\t\t\t\tfor (k = 0; k < X->cols; k++) {\n\t\t\t\t\tX->values[base + k] = x->values[\n\t\t\t\t\t\t\t(size_t)i * x->inc];\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase CblasColMajor:\n\t\t\tfor (j = 0; j < X->cols; j++) {\n\t\t\t\tbase = (size_t)j * X->ld;\n\t\t\t\tfor (k = 0; k < X->rows; k++) {\n\t\t\t\t\tX->values[base + k] = x->values[\n\t\t\t\t\t\t\t(size_t)i * x->inc];\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tindex++;\n\t}\n\treturn 0;\n}\n\n/* converts a vector or matrix to a table */\nstatic int totable (lua_State *L) {\n\tstruct vector *x;\n\tstruct matrix *X;\n\tint i, j;\n\tconst float *value;\n\n\t/* check and process arguments */\n\tx = luaL_testudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tif (x != NULL) {\n\t\tlua_createtable(L, 0, 3);\n\t\tlua_pushliteral(L, \"vector\");\n\t\tlua_setfield(L, -2, \"type\");\n\t\tlua_pushinteger(L, x->size);\n\t\tlua_setfield(L, -2, \"length\");\n\t\tlua_createtable(L, x->size, 0);\n\t\tvalue = x->values;\n\t\tfor (i = 0; i < x->size; i++) {\n\t\t\tlua_pushnumber(L, *value);\n\t\t\tlua_rawseti(L, -2, i + 1);\n\t\t\tvalue += x->inc;\n\t\t}\n\t\tlua_setfield(L, -2, \"values\");\n\t\treturn 1;\n\t}\n\tX = luaL_testudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tif (X != NULL) {\n\t\tlua_createtable(L, 0, 5);\n\t\tlua_pushliteral(L, \"matrix\");\n\t\tlua_setfield(L, -2, \"type\");\n\t\tlua_pushinteger(L, X->rows);\n\t\tlua_setfield(L, -2, \"rows\");\n\t\tlua_pushinteger(L, X->cols);\n\t\tlua_setfield(L, -2, \"cols\");\n\t\tswitch (X->order) {\n\t\tcase CblasRowMajor:\n\t\t\tlua_pushliteral(L, \"rowmajor\");\n\t\t\tlua_setfield(L, -2, \"order\");\n\t\t\tlua_createtable(L, X->rows, 0);\n\t\t\tfor (i = 0; i < X->rows; i++) {\n\t\t\t\tlua_createtable(L, X->cols, 0);\n\t\t\t\tvalue = &X->values[(size_t)i * X->ld];\n\t\t\t\tfor (j = 0; j < X->cols; j++) {\n\t\t\t\t\tlua_pushnumber(L, *value++);\n\t\t\t\t\tlua_rawseti(L, -2, j + 1);\n\t\t\t\t}\n\t\t\t\tlua_rawseti(L, -2, i + 1);\n\t\t\t}\n\t\t\tlua_setfield(L, -2, \"values\");\n\t\t\tbreak;\n\n\t\tcase CblasColMajor:\n\t\t\tlua_pushliteral(L, \"colmajor\");\n\t\t\tlua_setfield(L, -2, \"order\");\n\t\t\tlua_createtable(L, X->cols, 0);\n\t\t\tfor (i = 0; i < X->cols; i++) {\n\t\t\t\tlua_createtable(L, X->rows, 0);\n\t\t\t\tvalue = &X->values[(size_t)i * X->ld];\n\t\t\t\tfor (j = 0; j < X->rows; j++) {\n\t\t\t\t\tlua_pushnumber(L, *value++);\n\t\t\t\t\tlua_rawseti(L, -2, j + 1);\n\t\t\t\t}\n\t\t\t\tlua_rawseti(L, -2, i + 1);\n\t\t\t}\n\t\t\tlua_setfield(L, -2, \"values\");\n\t\t\tbreak;\n\t\t}\n\t\treturn 1;\n\t}\n\treturn argerror(L, 1);\n}\n\n/* converts a table to a vector or matrix */\nstatic int tolinear (lua_State *L) {\n\tstatic const char *types[] = { \"vector\", \"matrix\", NULL };\n\tstatic const char *orders[] = { \"rowmajor\", \"colmajor\", NULL };\n\tstruct vector *x;\n\tstruct matrix *X;\n\tint size, rows, cols, major, minor;\n\tCBLAS_ORDER order;\n\tint i, j;\n\tint isnum;\n\tfloat *value;\n\n\t/* check arguments */\n\tluaL_checktype(L, 1, LUA_TTABLE);\n\tlua_settop(L, 1);\n\n\t/* handle types */\n\tswitch (optionvalue(L, \"type\", NULL, types)) {\n\tcase 0: /* vector */\n\t\tsize = intvalue(L, \"length\", -1);\n\t\tif (size < 1) {\n\t\t\treturn luaL_error(L, \"bad field \" LUA_QS, \"length\");\n\t\t}\n\t\tx = newvector(L, size);\n\t\tlua_getfield(L, 1, \"values\");\n\t\tif (lua_type(L, -1) != LUA_TTABLE) {\n\t\t\treturn luaL_error(L, \"bad field \" LUA_QS, \"values\");\n\t\t}\n\t\tvalue = x->values;\n\t\tfor (i = 0; i < size; i++) {\n\t\t\tlua_rawgeti(L, -1, i + 1);\n\t\t\t*value++ = lua_tonumberx(L, -1, &isnum);\n\t\t\tif (!isnum) {\n\t\t\t\treturn luaL_error(L, \"bad value at index %d\",\n\t\t\t\t\t\ti + 1);\n\t\t\t}\n\t\t\tlua_pop(L, 1);\n\t\t}\n\t\tlua_pop(L, 1);\n\t\treturn 1;\n\n\tcase 1: /* matrix */\n\t\trows = intvalue(L, \"rows\", -1);\n\t\tif (rows < 1) {\n\t\t\treturn luaL_error(L, \"bad field \" LUA_QS, \"rows\");\n\t\t}\n\t\tcols = intvalue(L, \"cols\", -1);\n\t\tif (cols < 1) {\n\t\t\treturn luaL_error(L, \"bad field \" LUA_QS, \"cols\");\n\t\t}\n\t\tswitch (optionvalue(L, \"order\", NULL, orders)) {\n\t\tcase 0:\n\t\t\torder = CblasRowMajor;\n\t\t\tmajor = rows;\n\t\t\tminor = cols;\n\t\t\tbreak;\n\n\t\tcase 1:\n\t\t\torder = CblasColMajor;\n\t\t\tmajor = cols;\n\t\t\tminor = rows;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t/* not reched */\n\t\t\tassert(0);\n\t\t\treturn 0;\n\t\t}\n\t\tX = newmatrix(L, rows, cols, order);\n\t\tlua_getfield(L, 1, \"values\");\n\t\tif (lua_type(L, -1) != LUA_TTABLE) {\n\t\t\treturn luaL_error(L, \"bad field \" LUA_QS, \"values\");\n\t\t}\n\t\tfor (i = 0; i < major; i++) {\n\t\t\tvalue = &X->values[i * X->ld];\n\t\t\tlua_rawgeti(L, -1, i + 1);\n\t\t\tif (lua_type(L, -1) != LUA_TTABLE) {\n\t\t\t\treturn luaL_error(L, \"bad value at index %d\",\n\t\t\t\t\t\ti + 1);\n\t\t\t}\n\t\t\tfor (j = 0; j < minor; j++) {\n\t\t\t\tlua_rawgeti(L, -1, j + 1);\n\t\t\t\t*value++ = lua_tonumberx(L, -1, &isnum);\n\t\t\t\tif (!isnum) {\n\t\t\t\t\treturn luaL_error(L, \"bad value at \"\n\t\t\t\t\t\t\t\"index (%d,%d)\", i + 1,\n\t\t\t\t\t\t\tj + 1);\n\t\t\t\t}\n\t\t\t\tlua_pop(L, 1);\n\t\t\t}\n\t\t\tlua_pop(L, 1);\n\t\t}\n\t\tlua_pop(L, 1);\n\t\treturn 1;\n\t}\n\n\t/* not reached */\n\tassert(0);\n\treturn 0;\n}\n\n/* invokes the DOT subprogram (x' y) */\nstatic int dot (lua_State *L) {\n\tstruct vector *x, *y;\n\tfloat dot;\n\n\t/* check and process arguments */\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\ty = luaL_checkudata(L, 2, LUALINEAR_VECTOR_METATABLE);\n\tluaL_argcheck(L, y->size == x->size, 2, \"dimension mismatch\");\n\n\t/* invoke subprogram */\n\tdot = cblas_sdot(x->size, x->values, x->inc, y->values, y->inc);\n\tlua_pushnumber(L, dot);\n\treturn 1;\n}\n\n/* invokes the NRM2 subprogram (||x||_2) */\nstatic int nrm2 (lua_State *L) {\n\tstruct vector *x;\n\tfloat nrm2;\n\n\t/* check and process arguments */\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\n\t/* invoke subprogram */\n\tnrm2 = cblas_snrm2(x->size, x->values, x->inc);\n\tlua_pushnumber(L, nrm2);\n\treturn 1;\n}\n\n/* invokes the ASUM subprogram (sigma |x|) */\nstatic int asum (lua_State *L) {\n\tstruct vector *x;\n\tfloat asum;\n\n\t/* check and process arguments */\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\n\t/* invoke subprogram */\n\tasum = cblas_sasum(x->size, x->values, x->inc);\n\tlua_pushnumber(L, asum);\n\treturn 1;\n}\n\n/* invokes the IAMAX subprogram (argmax |x|) */\nstatic int iamax (lua_State *L) {\n\tstruct vector *x;\n\tint iamax;\n\n\t/* check and process arguments */\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\n\t/* invoke subprogram */\n\tiamax = cblas_isamax(x->size, x->values, x->inc);\n\tlua_pushinteger(L, iamax + 1);\n\treturn 1;\n}\n\n/* sum implementation */\nstatic float _sum (const float *values, int size, int inc) {\n\tfloat sum;\n\tint i;\n\n\tsum = 0.0;\n\t#pragma omp parallel for private(i) schedule(auto) \\\n\t\t\t if(size >= LUALINEAR_OMP_MINSIZE) reduction(+:sum)\n\tfor (i = 0; i < size; i++) {\n\t\tsum += values[(size_t)i * inc];\n\t}\n\treturn sum;\n}\n\n/* sum implementation (sigma x_i) */\nstatic int sum (lua_State *L) {\n\tstruct vector *x, *y;\n\tstruct matrix *X;\n\tint i;\n\n\t/* check and process arguments */\n\tx = luaL_testudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tif (x != NULL) {\n\t\tlua_pushnumber(L, _sum(x->values, x->size, x->inc));\n\t\treturn 1;\n\t}\n\tX = luaL_testudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tif (X != NULL) {\n\t\ty = luaL_checkudata(L, 2, LUALINEAR_VECTOR_METATABLE);\n\t\tswitch (checktranspose(L, 3)) {\n\t\tcase CblasNoTrans:\n\t\t\tswitch (X->order) {\n\t\t\tcase CblasRowMajor:\n\t\t\t\tluaL_argcheck(L, y->size == X->rows, 2,\n\t\t\t\t\t\t\"dimension mismatch\");\n\t\t\t\tfor (i = 0; i < X->rows; i++) {\n\t\t\t\t\ty->values[(size_t)i * y->inc] = _sum(\n\t\t\t\t\t\t\t&X->values[(size_t)i\n\t\t\t\t\t\t\t* X->ld], X->cols, 1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CblasColMajor:\n\t\t\t\tluaL_argcheck(L, y->size == X->cols, 2,\n\t\t\t\t\t\t\"dimension mismatch\");\n\t\t\t\tfor (i = 0; i < X->cols; i++) {\n\t\t\t\t\ty->values[(size_t)i * y->inc] = _sum(\n\t\t\t\t\t\t\t&X->values[(size_t)i\n\t\t\t\t\t\t\t* X->ld], X->rows, 1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase CblasTrans:\n\t\t\tswitch (X->order) {\n\t\t\tcase CblasRowMajor:\n\t\t\t\tluaL_argcheck(L, y->size == X->cols, 2,\n\t\t\t\t\t\t\"dimension mismatch\");\n\t\t\t\tfor (i = 0; i < X->cols; i++) {\n\t\t\t\t\ty->values[(size_t)i * y->inc] = _sum(\n\t\t\t\t\t\t\t&X->values[(size_t)i],\n\t\t\t\t\t\t\tX->rows, X->ld);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CblasColMajor:\n\t\t\t\tluaL_argcheck(L, y->size == X->rows, 2,\n\t\t\t\t\t\t\"dimension mismatch\");\n\t\t\t\tfor (i = 0; i < X->rows; i++) {\n\t\t\t\t\ty->values[(size_t)i * y->inc] = _sum(\n\t\t\t\t\t\t\t&X->values[(size_t)i],\n\t\t\t\t\t\t\tX->cols, X->ld);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t/* not reached */\n\t\t\tassert(0);\n\t\t\tbreak;\n\t\t}\n\t\treturn 0;\n\t}\n\treturn argerror(L, 1);\n}\n\n/* xy function */\ntypedef void(*xyfunction)(int, float *, int, float *, int, float);\n\n/* invokes an (x,y) subproram */\nstatic int xy (lua_State *L, xyfunction s, int hasy, int hasalpha) {\n\tint index, i;\n\tfloat alpha;\n\tstruct vector *x, *y;\n\tstruct matrix *X, *Y;\n\n\t/* check and process arguments */\n\tindex = 2;\n\tx = luaL_testudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tif (x != NULL) {\n\t\tif (hasy) {\n\t\t\ty = luaL_testudata(L, 2, LUALINEAR_VECTOR_METATABLE);\n\t\t\tY = luaL_testudata(L, 2, LUALINEAR_MATRIX_METATABLE);\n\t\t\tif (y == NULL && Y == NULL) {\n\t\t\t\treturn argerror(L, 2);\n\t\t\t}\n\t\t\tindex++;\n\t\t} else {\n\t\t\ty = x;\n\t\t\tY = NULL;\n\t\t}\n\t\tif (hasalpha) {\n\t\t\talpha = luaL_optnumber(L, index, 1.0);\n\t\t\tindex++;\n\t\t} else {\n\t\t\talpha = 0.0;\n\t\t}\n\t\tif (y != NULL) {\n\t\t\t/* invoke subprogram on vector-vector */\n\t\t\tluaL_argcheck(L, y->size == x->size, 2,\n\t\t\t\t\t\"dimension mismatch\");\n\t\t\ts(x->size, x->values, x->inc, y->values, y->inc, alpha);\n\t\t\treturn 0;\n\t\t}\n\n\t\t/* invoke subprogram on vector-matrix */\n\t\tswitch (checktranspose(L, index)) {\n\t\tcase CblasNoTrans:\n\t\t\tswitch (Y->order) {\n\t\t\tcase CblasRowMajor:\n\t\t\t\tluaL_argcheck(L, 1, x->size == Y->cols,\n\t\t\t\t\t\t\"dimension mismatch\");\n\t\t\t\tfor (i = 0; i < Y->rows; i++) {\n\t\t\t\t\ts(x->size, x->values, x->inc,\n\t\t\t\t\t\t\t&Y->values[(size_t)i\n\t\t\t\t\t\t\t* Y->ld], 1, alpha);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CblasColMajor:\n\t\t\t\tluaL_argcheck(L, 1, x->size == Y->rows,\n\t\t\t\t\t\t\"dimension mismatch\");\n\t\t\t\tfor (i = 0; i < Y->cols; i++) {\n\t\t\t\t\ts(x->size, x->values, x->inc,\n\t\t\t\t\t\t\t&Y->values[(size_t)i\n\t\t\t\t\t\t\t* Y->ld], 1, alpha);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase CblasTrans:\n\t\t\tswitch (Y->order) {\n\t\t\tcase CblasRowMajor:\n\t\t\t\tluaL_argcheck(L, 1, x->size == Y->rows,\n\t\t\t\t\t\t\"dimension mismatch\");\n\t\t\t\tfor (i = 0; i < Y->rows; i++) {\n\t\t\t\t\ts(x->size, x->values, x->inc,\n\t\t\t\t\t\t\t&Y->values[(size_t)i],\n\t\t\t\t\t\t\tY->ld, alpha);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase CblasColMajor:\n\t\t\t\tluaL_argcheck(L, 1, x->size == Y->cols,\n\t\t\t\t\t\t\"dimension mismatch\");\n\t\t\t\tfor (i = 0; i < Y->cols; i++) {\n\t\t\t\t\ts(x->size, x->values, x->inc,\n\t\t\t\t\t\t\t&Y->values[(size_t)i],\n\t\t\t\t\t\t\tY->ld, alpha);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t/* not reached */\n\t\t\tassert(0);\n\t\t}\n\t\treturn 0;\n\t}\n\tX = luaL_testudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tif (X != NULL) {\n\t\tif (hasy) {\n\t\t\tY = luaL_checkudata(L, 2, LUALINEAR_MATRIX_METATABLE);\n\t\t\tluaL_argcheck(L, X->order == Y->order, 2,\n\t\t\t\t\t\"order mismatch\");\n\t\t\tluaL_argcheck(L, X->rows == Y->rows && X->cols\n\t\t\t\t\t== Y->cols, 2, \"dimension mismatch\");\n\t\t\tindex++;\n\t\t} else {\n\t\t\tY = X;\n\t\t}\n\t\tif (hasalpha) {\n\t\t\talpha = luaL_optnumber(L, index, 1.0);\n\t\t\tindex++;\n\t\t} else {\n\t\t\talpha = 0.0;\n\t\t}\n\n\t\t/* invoke subprogram on matrix-matrix */\n\t\tswitch (X->order) {\n\t\tcase CblasRowMajor:\n\t\t\tfor (i = 0; i < X->rows; i++) {\n\t\t\t\ts(X->cols, &X->values[(size_t)i * X->ld], 1,\n\t\t\t\t\t\t&Y->values[(size_t)i * Y->ld],\n\t\t\t\t\t\t1, alpha);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase CblasColMajor:\n\t\t\tfor (i = 0; i < X->cols; i++) {\n\t\t\t\ts(X->rows, &X->values[(size_t)i * X->ld], 1,\n\t\t\t\t\t\t&Y->values[(size_t)i * Y->ld],\n\t\t\t\t\t\t1, alpha);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\treturn 0;\n\t}\n\treturn argerror(L, 1);\n}\n\n/* wraps the SWAP subprogram */\nstatic void _swap (int size, float *x, int incx, float *y, int incy,\n\t\tfloat alpha) {\n\t(void)alpha;\n\tcblas_sswap(size, x, incx, y, incy);\n}\n\n/* invokes the SWAP subprogram (y <-> x) */\nstatic int swap (lua_State *L) {\n\treturn xy(L, _swap, 1, 0);\n}\n\n/* wraps the COPY subprogram */\nstatic void _copy (int size, float *x, int incx, float *y, int incy,\n\t\tfloat alpha) {\n\t(void)alpha;\n\tcblas_scopy(size, x, incx, y, incy);\n}\n\n/* invokes the COPY subprogram (y <- x) */\nstatic int copy (lua_State *L) {\n\treturn xy(L, _copy, 1, 0);\n}\n\n/* wraps the AXPY subprogram */\nstatic void _axpy (int size, float *x, int incx, float *y, int incy,\n\t\tfloat alpha) {\n\tcblas_saxpy(size, alpha, x, incx, y, incy);\n}\n\n/* invokes the AXPY subprogram (y <- alpha x + y) */\nstatic int axpy (lua_State *L) {\n\treturn xy(L, _axpy, 1, 1);\n}\n\n/* wraps the SCAL subprogram */\nstatic void _scal (int size, float *x, int incx, float *y, int incy,\n\t\t\tfloat alpha) {\n\t(void)y;\n\t(void)incy;\n\tcblas_sscal(size, alpha, x, incx);\n}\n\n/* invokes the SCAL subprogram (x <- alpha x) */\nstatic int scal (lua_State *L) {\n\treturn xy(L, _scal, 0, 1);\n}\n\n/* set operation implementation */\nstatic void _set (int size, float *x, int incx, float *y, int incy,\n\t\t\tfloat alpha) {\n\tint i;\n\n\t(void)y;\n\t(void)incy;\n\t#pragma omp parallel for private(i) schedule(auto) \\\n\t\t\tif(size >= LUALINEAR_OMP_MINSIZE)\n\tfor (i = 0; i < size; i++) {\n\t\tx[(size_t)i * incx] = alpha;\n\t}\n}\n\n/* performs a set operation (x <- alpha) */\nstatic int set (lua_State *L) {\n\treturn xy(L, _set, 0, 1);\n}\n\n/* uniform RNG implementation */\nstatic void _uniform (int size, float *x, int incx, float *y, int incy,\n\t\tfloat alpha) {\n\tint i;\n\n\t(void)y;\n\t(void)incy;\n\t(void)alpha;\n\tfor (i = 0; i < size; i++) {\n\t\t*x = (float)random() * (1.0 / ((float)RAND_MAX + 1.0));\n\t\tx += incx;\n\t}\n}\n\n/* performs a uniform operation (x <- uniform) */\nstatic int uniform (lua_State *L) {\n\treturn xy(L, _uniform, 0, 0);\n}\n\n/* normal RNG implementation */\nstatic void _normal (int size, float *x, int incx, float *y, int incy,\n\t\tfloat alpha) {\n\tint i;\n\tfloat u1, u2, r, s, c;\n\n\t(void)y;\n\t(void)incy;\n\t(void)alpha;\n\tfor (i = 0; i < size - 1; i += 2) {\n\t\tdo {\n\t\t\tu1 = (float)random() * (1.0 / (float)RAND_MAX);\n\t\t\tu2 = (float)random() * (1.0 / (float)RAND_MAX);\n\t\t} while (u1 <= -DBL_MAX);\n\t\tr = sqrt(-2.0 * logf(u1));\n\t\tsincosf(2 * M_PI * u2, &s, &c);\n\t\t*x = r * c;\n\t\tx += incx;\n\t\t*x = r * s;\n\t\tx += incx;\n\t}\n\tif (i < size) {\n\t\tdo {\n\t\t\tu1 = (float)random() * (1.0 / (float)RAND_MAX);\n\t\t\tu2 = (float)random() * (1.0 / (float)RAND_MAX);\n\t\t} while (u1 <= -DBL_MAX);\n\t\t*x = sqrtf(-2.0 * logf(u1)) * cosf(2 * M_PI * u2);\n\t\tx += incx;\n\t}\n}\n\n/* performs a normal operation (x <- normal) */\nstatic int normal (lua_State *L) {\n\treturn xy(L, _normal, 0, 0);\n}\n\n/* inc operation implementation */\nstatic void _inc (int size, float *x, int incx, float *y, int incy,\n\t\t\tfloat alpha) {\n\tint i;\n\n\t(void)y;\n\t(void)incy;\n\t#pragma omp parallel for private(i) schedule(auto) \\\n\t\t\tif(size >= LUALINEAR_OMP_MINSIZE)\n\tfor (i = 0; i < size; i++) {\n\t\tx[(size_t)i * incx] += alpha;\n\t}\n}\n\n/* performs a inc operation (x <- x + alpha) */\nstatic int inc (lua_State *L) {\n\treturn xy(L, _inc, 0, 1);\n}\n\n/* element-wise multiplication implementation, alpha = 1 */\nstatic void _mul1 (int size, float *x, int incx, float *y, int incy,\n\t\tfloat alpha) {\n\tint i;\n\n\t(void)alpha;\n\t#pragma omp parallel for private(i) schedule(auto) \\\n\t\t\tif(size >= LUALINEAR_OMP_MINSIZE)\n\tfor (i = 0; i < size; i++) {\n\t\ty[(size_t)i * incy] *= x[(size_t)i * incx];\n\t}\n}\n\n/* element-wise multiplication implementation, alpha = -1 */\nstatic void _mulm1 (int size, float *x, int incx, float *y, int incy,\n\t\tfloat alpha) {\n\tint i;\n\n\t(void)alpha;\n\t#pragma omp parallel for private(i) schedule(auto) \\\n\t\t\tif(size >= LUALINEAR_OMP_MINSIZE)\n\tfor (i = 0; i < size; i++) {\n\t\ty[(size_t)i * incy] /= x[(size_t)i * incx];\n\t}\n}\n\n/* element-wise multiplication implementation, alpha = any */\nstatic void _mul (int size, float *x, int incx, float *y, int incy,\n\t\tfloat alpha) {\n\tint i;\n\n\t#pragma omp parallel for private(i) schedule(auto) \\\n\t\t\tif(size >= LUALINEAR_OMP_MINSIZE)\n\tfor (i = 0; i < size; i++) {\n\t\ty[(size_t)i * incy] *= pow(x[(size_t)i * incx], alpha);\n\t}\n}\n\n/* performs element-wise multiplication (y <- x^alpha .* y) */\nstatic int mul (lua_State *L) {\n\tfloat alpha;\n\n\talpha = luaL_optnumber(L, 3, 1.0);\n\tif (alpha == 1.0) {\n\t\treturn xy(L, _mul1, 1, 1);\n\t}\n\tif (alpha == -1.0) {\n\t\treturn xy(L, _mulm1, 1, 1);\n\t}\n\treturn xy(L, _mul, 1, 1);\n}\n\n/* power raising operation implementation */\nstatic void _pow (int size, float *x, int incx, float *y, int incy,\n\t\t\tfloat alpha) {\n\tint i;\n\n\t(void)y;\n\t(void)incy;\n\t#pragma omp parallel for private(i) schedule(auto) \\\n\t\t\tif(size >= LUALINEAR_OMP_MINSIZE)\n\tfor (i = 0; i < size; i++) {\n\t\tx[(size_t)i * incx] = pow(x[(size_t)i * incx], alpha);\n\t}\n}\n\n/* performs element-wise power raising (x <- x^alpha) */\nstatic int powx (lua_State *L) {\n\treturn xy(L, _pow, 0, 1);\n}\n\n/* apply function */\ntypedef float(*applyfunction)(float);\n\n/* applies a function to a value */\nstatic int apply (lua_State *L, applyfunction apply, int parallel) {\n\tstruct vector *x;\n\tstruct matrix *X;\n\tint i, j;\n\tsize_t base;\n\n\tif (lua_type(L, 1) == LUA_TNUMBER) {\n\t\tlua_pushnumber(L, apply(lua_tonumber(L, 1)));\n\t\treturn 1;\n\t}\n\tx = luaL_testudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\tif (x != NULL) {\n\t\t#pragma omp parallel for private(i) schedule(auto) \\\n\t\t\t\tif(parallel && x->size >= LUALINEAR_OMP_MINSIZE)\n\t\tfor (i = 0; i < x->size; i++) {\n\t\t\tx->values[(size_t)i * x->inc] =\n\t\t\t\t\tapply(x->values[(size_t)i\n\t\t\t\t\t* x->inc]);\n\t\t}\n\t\treturn 0;\n\t}\n\tX = luaL_testudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tif (X != NULL) {\n\t\tswitch (X->order) {\n\t\tcase CblasRowMajor:\n\t\t\tfor (i = 0; i < X->rows; i++) {\n\t\t\t\tbase = (size_t)i * X->ld;\n\t\t\t\t#pragma omp parallel for private(j) \\\n\t\t\t\t\t\tschedule(auto) \\\n\t\t\t\t\t\tif(parallel && X->cols \\\n\t\t\t\t\t\t>= LUALINEAR_OMP_MINSIZE)\n\t\t\t\tfor (j = 0; j < X->cols; j++) {\n\t\t\t\t\tX->values[base + j] = apply(\n\t\t\t\t\t\t\tX->values[base\n\t\t\t\t\t\t\t+ j]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase CblasColMajor:\n\t\t\tfor (i = 0; i < X->cols; i++) {\n\t\t\t\tbase = (size_t)i * X->ld;\n\t\t\t\t#pragma omp parallel for private(j) \\\n\t\t\t\t\t\tschedule(auto) \\\n\t\t\t\t\t\tif(parallel && X->rows \\\n\t\t\t\t\t\t>= LUALINEAR_OMP_MINSIZE)\n\t\t\t\tfor (j = 0; j < X->rows; j++) {\n\t\t\t\t\tX->values[base + j] = apply(\n\t\t\t\t\t\t\tX->values[base\n\t\t\t\t\t\t\t+ j]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\treturn 0;\n\t}\n\treturn luaL_argerror(L, 1, lua_pushfstring(L, \"number, vector, or \"\n\t\t\t\"matrix expected, got %s\", luaL_typename(L, 1)));\n\n}\n\n/* sign function implementation */\nstatic float _sign (float x) {\n\tif (x > 0) {\n\t\treturn 1;\n\t}\n\tif (x < 0) {\n\t\treturn -1;\n\t}\n\treturn x;\n}\n\n/* sign function */\nstatic int sign (lua_State *L) {\n\treturn apply(L, _sign, 1);\n}\n\n/* abs function implementation */\nstatic float _abs (float x) {\n\treturn fabs(x);\n}\n\n/* abs function */\nstatic int absx (lua_State *L) {\n\treturn apply(L, _abs, 1);\n}\n\n/* exp function */\nstatic int expx (lua_State *L) {\n\treturn apply(L, expf, 1);\n}\n\n/* log function */\nstatic int logx (lua_State *L) {\n\treturn apply(L, logf, 1);\n}\n\n/* logistic function implementation */\nstatic float _logistic (float z) {\n\treturn 1.0 / (1.0 + expf(-z));\n}\n\n/* logistic function */\nstatic int logistic (lua_State *L) {\n\treturn apply(L, _logistic, 1);\n}\n\n/* tanh function */\nstatic int tanhx (lua_State *L) {\n\treturn apply(L, tanhf, 1);\n}\n\n/* softplus function implementation */\nstatic float _softplus (float x) {\n\treturn logf(1 + expf(x));\n}\n\n/* softplus function */\nstatic int softplus (lua_State *L) {\n\treturn apply(L, _softplus, 1);\n}\n\n/* rectifier function implementation */\nstatic float _rectifier (float x) {\n\treturn x > 0.0 ? x : 0.0;\n}\n\n/* rectifier function */\nstatic int rectifier (lua_State *L) {\n\treturn apply(L, _rectifier, 1);\n}\n\n/* current Lua state */\nstatic __thread lua_State *TL;\n\n/* apply function implementation */\nstatic float _apply (float x) {\n\tfloat result;\n\n\tlua_pushvalue(TL, -1);\n\tlua_pushnumber(TL, x);\n\tlua_call(TL, 1, 1);\n\tresult = lua_tonumber(TL, -1);\n\tlua_pop(TL, 1);\n\treturn result;\n}\n\n/* apply function */\nstatic int applyx (lua_State *L) {\n\tluaL_checktype(L, 2, LUA_TFUNCTION);\n\tlua_settop(L, 2);\n\tTL = L;\n\treturn apply(L, _apply, 0);\n}\n\n/* invokes the GEMV subprogram (y <- alpha A x + b y) */\nstatic int gemv (lua_State *L) {\n\tstruct matrix *A;\n\tstruct vector *x, *y;\t\n\tfloat alpha, beta;\n\tCBLAS_TRANSPOSE ta;\n\tint m, n;\n\n\t/* check and process arguments */\n\tA = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tx = luaL_checkudata(L, 2, LUALINEAR_VECTOR_METATABLE);\n\ty = luaL_checkudata(L, 3, LUALINEAR_VECTOR_METATABLE);\n\talpha = luaL_optnumber(L, 4, 1.0);\n\tbeta = luaL_optnumber(L, 5, 0.0);\n\tta = checktranspose(L, 6);\n\tm = ta == CblasNoTrans ? A->rows : A->cols;\n\tn = ta == CblasNoTrans ? A->cols : A->rows;\n\tluaL_argcheck(L, x->size == n, 2, \"dimension mismatch\");\n\tluaL_argcheck(L, y->size == m, 3, \"dimension mismatch\");\n\n\t/* invoke subprogram */\n\tcblas_sgemv(A->order, ta, A->rows, A->cols, alpha, A->values, A->ld,\n\t\t\tx->values, x->inc, beta, y->values, y->inc);\n\treturn 0;\n}\n\n/* invokes the GER subprogram (A <- alpha x y' + A) */\nstatic int ger (lua_State *L) {\n\tstruct vector *x, *y;\t\n\tstruct matrix *A;\n\tfloat alpha;\n\n\t/* check and process arguments */\n\tx = luaL_checkudata(L, 1, LUALINEAR_VECTOR_METATABLE);\n\ty = luaL_checkudata(L, 2, LUALINEAR_VECTOR_METATABLE);\n\tA = luaL_checkudata(L, 3, LUALINEAR_MATRIX_METATABLE);\n\talpha = luaL_optnumber(L, 4, 1.0);\n\tluaL_argcheck(L, x->size == A->rows, 1, \"dimension mismatch\");\n\tluaL_argcheck(L, y->size == A->cols, 2, \"dimension mismatch\");\n\n\t/* invoke subprogram */\n\tcblas_sger(A->order, A->rows, A->cols, alpha, x->values, x->inc,\n\t\t\ty->values, y->inc, A->values, A->ld);\n\treturn 0;\n}\n\n/* invokes the GEMM subprogram (C <- alpha A B + beta C) */\nstatic int gemm (lua_State *L) {\n\tstruct matrix *A, *B, *C;\n\tfloat alpha, beta;\n\tCBLAS_TRANSPOSE ta, tb;\n\tint m, n, ka, kb;\n\n\t/* check and process arguments */\n\tA = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tB = luaL_checkudata(L, 2, LUALINEAR_MATRIX_METATABLE);\n\tluaL_argcheck(L, B->order == A->order, 2, \"order mismatch\");\n\tC = luaL_checkudata(L, 3, LUALINEAR_MATRIX_METATABLE);\n\tluaL_argcheck(L, C->order == A->order, 3, \"order mismatch\");\n\talpha = luaL_optnumber(L, 4, 1.0);\n\tbeta = luaL_optnumber(L, 5, 0.0);\n\tta = checktranspose(L, 6);\n\ttb = checktranspose(L, 7);\n\tm = ta == CblasNoTrans ? A->rows : A->cols;\n\tn = tb == CblasNoTrans ? B->cols : B->rows;\n\tka = ta == CblasNoTrans ? A->cols : A->rows;\n\tkb = tb == CblasNoTrans ? B->rows : B->cols;\n\tluaL_argcheck(L, ka == kb, 2, \"dimension mismatch\");\n\n\t/* invoke subprogramm */\n\tcblas_sgemm(A->order, ta, tb, m, n, ka, alpha, A->values, A->ld,\n\t\t\tB->values, B->ld, beta, C->values, C->ld);\n\treturn 0;\n}\n\n/* invokes the GESV subprogram */\nstatic int gesv (lua_State *L) {\n\tstruct matrix *A, *B;\n\tint *ipiv, result;\n\n\t/* check and process arguments */\n\tA = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tluaL_argcheck(L, A->rows == A->cols, 1, \"not square\");\n\tB = luaL_checkudata(L, 2, LUALINEAR_MATRIX_METATABLE);\n\tluaL_argcheck(L, B->order == A->order, 2, \"order mismatch\");\n\tluaL_argcheck(L, B->rows == A->rows, 2, \"dimension mismatch\");\n\n\t/* invoke subprogramm */\n\tipiv = calloc(A->rows, sizeof(lapack_int));\n\tif (ipiv == NULL) {\n\t\treturn luaL_error(L, \"cannot allocate indexes\");\n\t}\n\tresult = LAPACKE_sgesv(A->order, A->rows, B->cols, A->values, A->ld,\n\t\t\tipiv, B->values, B->ld);\n\tfree(ipiv);\n\tlua_pushinteger(L, result);\n\treturn 1;\n}\n\n/* invokes the GELS subprogram */\nstatic int gels (lua_State *L) {\n\tstruct matrix *A, *B;\n\tchar ta;\n\n\t/* check and process arguments */\n\tA = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tB = luaL_checkudata(L, 2, LUALINEAR_MATRIX_METATABLE);\n\tluaL_argcheck(L, B->order == A->order, 2, \"order mismatch\");\n\tta = lapacktranspose(checktranspose(L, 3));\n\tluaL_argcheck(L, B->rows == (A->rows >= A->cols ? A->rows : A->cols), 2,\n\t\t\t\"dimension mismatch\");\n\n\t/* invoke subprogramm */\n\tlua_pushinteger(L, LAPACKE_sgels(A->order, ta, A->rows, A->cols,\n\t\t\tB->cols, A->values, A->ld, B->values, B->ld));\n\treturn 1;\n}\n\n/* calculates the inverse of a matrix */\nstatic int inv (lua_State *L) {\n\tstruct matrix *A;\n\tint *ipiv, result;\n\n\t/* check and process arguments */\n\tA = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tluaL_argcheck(L, A->rows == A->cols, 1, \"not square\");\n\n\t/* invoke subprograms */\n\tipiv = calloc(A->rows, sizeof(lapack_int));\n\tif (ipiv == NULL) {\n\t\treturn luaL_error(L, \"cannot allocate indexes\");\n\t}\n\tresult = LAPACKE_sgetrf(A->order, A->rows, A->cols, A->values, A->ld,\n\t\t\tipiv);\n\tif (result != 0) {\n\t\tfree(ipiv);\n\t\tlua_pushinteger(L, result);\n\t\treturn 1;\n\t}\n\tresult = LAPACKE_sgetri(A->order, A->rows, A->values, A->ld, ipiv);\n\tfree(ipiv);\n\tlua_pushinteger(L, result);\n\treturn 1;\n}\n\n/* calculates the determinant of a matrix */\nstatic int det (lua_State *L) {\n\tstruct matrix *A;\n\tfloat *copy, *d, *s, det;\n\tint n, *ipiv, result, neg, i;\n\n\t/* check and process arguments */\n\tA = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tluaL_argcheck(L, A->rows == A->cols, 1, \"not square\");\n\tn = A->rows;\n\n\t/* copy matrix */\n\tcopy = calloc((size_t)n * n, sizeof(float));\n\tif (copy == NULL) {\n\t\treturn luaL_error(L, \"cannot allocate values\");\n\t}\n\td = copy;\n\ts = A->values;\n\tfor (i = 0; i < n; i++) {\n\t\tmemcpy(d, s, (size_t)n * sizeof(float));\n\t\td += n;\n\t\ts += A->ld;\n\t}\n\n\t/* invoke subprograms */\n\tipiv = calloc(n, sizeof(lapack_int));\n\tif (ipiv == NULL) {\n\t\tfree(copy);\n\t\treturn luaL_error(L, \"cannot allocate indexes\");\n\t}\n\tresult = LAPACKE_sgetrf(A->order, n, n, copy, n, ipiv);\n\tif (result != 0) {\n\t\tfree(copy);\n\t\tfree(ipiv);\n\t\tlua_pushnumber(L, 0.0);\n\t\treturn 1;\n\t}\n\n\t/* calculate determinant */\n\tdet = 1.0;\n\tneg = 0;\n\tfor (i = 0; i < n; i++) {\n\t\tdet *= copy[(size_t)i * n + i];\n\t\tif (ipiv[i] != i + 1) {\n\t\t\tneg = !neg;\n\t\t}\n\t}\n\tfree(copy);\n\tfree(ipiv);\n\tlua_pushnumber(L, neg ? -det : det);\n\treturn 1;\n}\n\n/* calculates the covariance of a matrix */\nstatic int cov (lua_State *L) {\n\tstruct matrix *A, *B;\n\tint ddof, i, j, k;\n\tfloat *means, *v, *vi, *vj, sum;\n\n\t/* check and process arguments */\n\tA = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tB = luaL_checkudata(L, 2, LUALINEAR_MATRIX_METATABLE);\n\tluaL_argcheck(L, A->cols == B->rows, 2, \"dimension mismatch\");\n\tluaL_argcheck(L, B->rows == B->cols, 2, \"not square\");\n\tddof = luaL_optinteger(L, 3, 0);\n\tluaL_argcheck(L, ddof >= 0 && ddof < A->rows, 3, \"bad ddof\");\n\n\t/* calculate means */\n\tmeans = calloc((size_t)A->cols, sizeof(float));\n\tif (means == NULL) {\n\t\treturn luaL_error(L, \"cannot allocate values\");\n\t}\n\tswitch (A->order) {\n\tcase CblasRowMajor:\n\t\t#pragma omp parallel for private(i, j, sum, v) schedule(auto) \\\n\t\t\t\tif(A->rows * A->cols >= LUALINEAR_OMP_MINSIZE)\n\t\tfor (i = 0; i < A->cols; i++) {\n\t\t\tsum = 0.0;\n\t\t\tv = &A->values[i];\n\t\t\tfor (j = 0; j < A->rows; j++) {\n\t\t\t\tsum += *v;\n\t\t\t\tv += A->ld;\n\t\t\t}\n\t\t\tmeans[i] = sum / A->rows;\n\t\t}\n\t\tbreak;\n\n\tcase CblasColMajor:\n\t\t#pragma omp parallel for private(i, j, sum, v) schedule(auto) \\\n\t\t\t\tif(A->rows * A->cols >= LUALINEAR_OMP_MINSIZE)\n\t\tfor (i = 0; i < A->cols; i++) {\n\t\t\tsum = 0.0;\n\t\t\tv = &A->values[(size_t)i * A->ld];\n\t\t\tfor (j = 0; j < A->rows; j++) {\n\t\t\t\tsum += *v;\n\t\t\t\tv++;\n\t\t\t}\n\t\t\tmeans[i] = sum / A->rows;\n\t\t}\n\t\tbreak;\n\t}\n\n\t/* calculate covariance */\n\tswitch (A->order) {\n\tcase CblasRowMajor:\n\t\tfor (i = 0; i < A->cols; i++) {\n\t\t\t#pragma omp parallel for private(j, k, sum, vi, vj) \\\n\t\t\t\t\tschedule(auto) if(A->rows * (A->cols \\\n\t\t\t\t\t- i) >= LUALINEAR_OMP_MINSIZE)\n\t\t\tfor (j = i; j < A->cols; j++) {\n\t\t\t\tsum = 0.0;\n\t\t\t\tvi = &A->values[i];\n\t\t\t\tvj = &A->values[j];\n\t\t\t\tfor (k = 0; k < A->rows; k++) {\n\t\t\t\t\tsum += (*vi - means[i])\n\t\t\t\t\t\t\t* (*vj - means[j]);\n\t\t\t\t\tvi += A->ld;\n\t\t\t\t\tvj += A->ld;\n\t\t\t\t}\n\t\t\t\tB->values[(size_t)i * B->ld + j] = B->values[\n\t\t\t\t\t\t(size_t)j * B->ld + i]\n\t\t\t\t\t\t= sum / (A->rows - ddof);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase CblasColMajor:\n\t\tfor (i = 0; i < A->cols; i++) {\n\t\t\t#pragma omp parallel for private(j, k, sum, vi, vj) \\\n\t\t\t\t\tschedule(auto) if(A->rows * (A->cols \\\n\t\t\t\t\t- i) >= LUALINEAR_OMP_MINSIZE)\n\t\t\tfor (j = i; j < A->cols; j++) {\n\t\t\t\tsum = 0.0;\n\t\t\t\tvi = &A->values[(size_t)i * A->ld];\n\t\t\t\tvj = &A->values[(size_t)j * A->ld];\n\t\t\t\tfor (k = 0; k < A->rows; k++) {\n\t\t\t\t\tsum += (*vi - means[i])\n\t\t\t\t\t\t\t* (*vj - means[j]);\n\t\t\t\t\tvi++;\n\t\t\t\t\tvj++;\n\t\t\t\t}\n\t\t\t\tB->values[(size_t)i * B->ld + j] = B->values[\n\t\t\t\t\t\t(size_t)j * B->ld + i]\n\t\t\t\t\t\t= sum / (A->rows - ddof);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tfree(means);\n\treturn 0;\n}\n\n/* calculates the correlation of a matrix */\nstatic int corr (lua_State *L) {\n\tstruct matrix *A, *B;\n\tint i, j, k;\n\tfloat *means, *stds, *v, *vi, *vj, sum;\n\n\t/* check and process arguments */\n\tA = luaL_checkudata(L, 1, LUALINEAR_MATRIX_METATABLE);\n\tB = luaL_checkudata(L, 2, LUALINEAR_MATRIX_METATABLE);\n\tluaL_argcheck(L, A->cols == B->rows, 2, \"dimension mismatch\");\n\tluaL_argcheck(L, B->rows == B->cols, 2, \"not square\");\n\n\t/* calculate means and stds */\n\tmeans = calloc((size_t)A->cols, sizeof(float));\n\tif (means == NULL) {\n\t\treturn luaL_error(L, \"cannot allocate values\");\n\t}\n\tstds = calloc((size_t)A->cols, sizeof(float));\n\tif (stds == NULL) {\n\t\tfree(means);\n\t\treturn luaL_error(L, \"cannot allocate values\");\n\t}\n\tswitch (A->order) {\n\tcase CblasRowMajor:\n\t\t#pragma omp parallel for private(i, j, sum, v) schedule(auto) \\\n\t\t\t\tif(A->rows * A->cols >= LUALINEAR_OMP_MINSIZE)\n\t\tfor (i = 0; i < A->cols; i++) {\n\t\t\tsum = 0.0;\n\t\t\tv = &A->values[i];\n\t\t\tfor (j = 0; j < A->rows; j++) {\n\t\t\t\tsum += *v;\n\t\t\t\tv += A->ld;\n\t\t\t}\n\t\t\tmeans[i] = sum / A->rows;\n\t\t\tsum = 0.0;\n\t\t\tv = &A->values[i];\n\t\t\tfor (j = 0; j < A->rows; j++) {\n\t\t\t\tsum += (*v - means[i]) * (*v - means[i]);\n\t\t\t\tv += A->ld;\n\t\t\t}\n\t\t\tstds[i] = sqrt(sum);\n\t\t}\n\t\tbreak;\n\n\tcase CblasColMajor:\n\t\t#pragma omp parallel for private(i, j, sum, v) schedule(auto) \\\n\t\t\t\tif(A->rows * A->cols >= LUALINEAR_OMP_MINSIZE)\n\t\tfor (i = 0; i < A->cols; i++) {\n\t\t\tsum = 0.0;\n\t\t\tv = &A->values[(size_t)i * A->ld];\n\t\t\tfor (j = 0; j < A->rows; j++) {\n\t\t\t\tsum += *v;\n\t\t\t\tv++;\n\t\t\t}\n\t\t\tmeans[i] = sum / A->rows;\n\t\t\tsum = 0.0;\n\t\t\tv = &A->values[(size_t)i * A->ld];\n\t\t\tfor (j = 0; j < A->rows; j++) {\n\t\t\t\tsum += (*v - means[i]) * (*v - means[i]);\n\t\t\t\tv++;\n\t\t\t}\n\t\t\tstds[i] = sqrt(sum);\n\t\t}\n\t\tbreak;\n\t}\n\n\t/* calculate correlation */\n\tswitch (A->order) {\n\tcase CblasRowMajor:\n\t\tfor (i = 0; i < A->cols; i++) {\n\t\t\t#pragma omp parallel for private(j, k, sum, vi, vj) \\\n\t\t\t\t\tschedule(auto) if(A->rows * (A->cols \\\n\t\t\t\t\t- i) >= LUALINEAR_OMP_MINSIZE)\n\t\t\tfor (j = i; j < A->cols; j++) {\n\t\t\t\tsum = 0.0;\n\t\t\t\tvi = &A->values[i];\n\t\t\t\tvj = &A->values[j];\n\t\t\t\tfor (k = 0; k < A->rows; k++) {\n\t\t\t\t\tsum += (*vi - means[i])\n\t\t\t\t\t\t\t* (*vj - means[j]);\n\t\t\t\t\tvi += A->ld;\n\t\t\t\t\tvj += A->ld;\n\t\t\t\t}\n\t\t\t\tB->values[(size_t)i * B->ld + j] = B->values[\n\t\t\t\t\t\t(size_t)j * B->ld + i]\n\t\t\t\t\t\t= sum / (stds[i] * stds[j]);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase CblasColMajor:\n\t\tfor (i = 0; i < A->cols; i++) {\n\t\t\t#pragma omp parallel for private(j, k, sum, vi, vj) \\\n\t\t\t\t\tschedule(auto) if(A->rows * (A->cols \\\n\t\t\t\t\t- i) >= LUALINEAR_OMP_MINSIZE)\n\t\t\tfor (j = i; j < A->cols; j++) {\n\t\t\t\tsum = 0.0;\n\t\t\t\tvi = &A->values[(size_t)i * A->ld];\n\t\t\t\tvj = &A->values[(size_t)j * A->ld];\n\t\t\t\tfor (k = 0; k < A->rows; k++) {\n\t\t\t\t\tsum += (*vi - means[i])\n\t\t\t\t\t\t\t* (*vj - means[j]);\n\t\t\t\t\tvi++;\n\t\t\t\t\tvj++;\n\t\t\t\t}\n\t\t\t\tB->values[(size_t)i * B->ld + j] = B->values[\n\t\t\t\t\t\t(size_t)j * B->ld + i]\n\t\t\t\t\t\t= sum / (stds[i] * stds[j]);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tfree(means);\n\tfree(stds);\n\treturn 0;\n}\n\n\n/*\n * Exported functions.\n */\n\nint luaopen_linear (lua_State *L) {\n\tstatic const luaL_Reg FUNCTIONS[] = {\n\t\t{ \"vector\", vector },\n\t\t{ \"matrix\", matrix },\n\t\t{ \"type\", type },\n\t\t{ \"size\", size },\n\t\t{ \"tvector\", tvector },\n\t\t{ \"sub\", sub },\n\t\t{ \"unwind\", unwind },\n\t\t{ \"reshape\", reshape },\n\t\t{ \"totable\", totable },\n\t\t{ \"tolinear\", tolinear },\n\t\t{ \"dot\", dot },\n\t\t{ \"nrm2\", nrm2 },\n\t\t{ \"asum\", asum },\n\t\t{ \"iamax\", iamax },\n\t\t{ \"sum\", sum },\n\t\t{ \"swap\", swap },\n\t\t{ \"copy\", copy },\n\t\t{ \"axpy\", axpy },\n\t\t{ \"scal\", scal },\n\t\t{ \"set\", set },\n\t\t{ \"uniform\", uniform },\n\t\t{ \"normal\", normal },\n\t\t{ \"inc\", inc },\n\t\t{ \"mul\", mul },\n\t\t{ \"pow\", powx },\n\t\t{ \"sign\", sign },\n\t\t{ \"abs\", absx },\n\t\t{ \"exp\", expx },\n\t\t{ \"log\", logx },\n\t\t{ \"logistic\", logistic },\n\t\t{ \"tanh\", tanhx },\n\t\t{ \"softplus\", softplus },\n\t\t{ \"rectifier\", rectifier },\n\t\t{ \"apply\", applyx },\n\t\t{ \"gemv\", gemv },\n\t\t{ \"ger\", ger },\n\t\t{ \"gemm\", gemm },\n\t\t{ \"gesv\", gesv },\n\t\t{ \"gels\", gels },\n\t\t{ \"inv\", inv },\n\t\t{ \"det\", det },\n\t\t{ \"cov\", cov },\n\t\t{ \"corr\", corr },\n\t\t{ NULL, NULL }\n\t};\n\n\t/* register functions */\n\t#if LUA_VERSION_NUM >= 502\n\tluaL_newlib(L, FUNCTIONS);\n\t#else\n\tluaL_register(L, luaL_checkstring(L, 1), FUNCTIONS);\n\t#endif\n\n\t/* vector metatable */\n\tluaL_newmetatable(L, LUALINEAR_VECTOR_METATABLE);\n\tlua_pushcfunction(L, vector_len);\n\tlua_setfield(L, -2, \"__len\");\n\tlua_pushcfunction(L, vector_index);\n\tlua_setfield(L, -2, \"__index\");\n\tlua_pushcfunction(L, vector_newindex);\n\tlua_setfield(L, -2, \"__newindex\");\n\tlua_pushcfunction(L, vector_ipairs);\n\tlua_setfield(L, -2, \"__ipairs\");\n\tlua_pushcfunction(L, vector_tostring);\n\tlua_setfield(L, -2, \"__tostring\");\n\tlua_pushcfunction(L, vector_free);\n\tlua_setfield(L, -2, \"__gc\");\n\tlua_pop(L, 1);\n\n\t/* matrix metatable */\n\tluaL_newmetatable(L, LUALINEAR_MATRIX_METATABLE);\n\tlua_pushcfunction(L, matrix_len);\n\tlua_setfield(L, -2, \"__len\");\n\tlua_pushcfunction(L, matrix_index);\n\tlua_setfield(L, -2, \"__index\");\n\tlua_pushcfunction(L, matrix_ipairs);\n\tlua_setfield(L, -2, \"__ipairs\");\n\tlua_pushcfunction(L, matrix_tostring);\n\tlua_setfield(L, -2, \"__tostring\");\n\tlua_pushcfunction(L, matrix_free);\n\tlua_setfield(L, -2, \"__gc\");\n\tlua_pop(L, 1);\n\n\treturn 1;\n}\n", "meta": {"hexsha": "e04cb06194fd86400dee21c3fae83e5be8cbd61e", "size": 46096, "ext": "c", "lang": "C", "max_stars_repo_path": "linear.c", "max_stars_repo_name": "anaef/lua-linear", "max_stars_repo_head_hexsha": "6bf65edd89ae89589f6d4ae76ddc7f2f934e5a79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-21T00:09:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:33:01.000Z", "max_issues_repo_path": "linear.c", "max_issues_repo_name": "anaef/lua-linear", "max_issues_repo_head_hexsha": "6bf65edd89ae89589f6d4ae76ddc7f2f934e5a79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear.c", "max_forks_repo_name": "anaef/lua-linear", "max_forks_repo_head_hexsha": "6bf65edd89ae89589f6d4ae76ddc7f2f934e5a79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-05T23:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T09:33:02.000Z", "avg_line_length": 23.8099173554, "max_line_length": 74, "alphanum_fraction": 0.5999652898, "num_tokens": 15951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.3730084114462643}}
{"text": "/**\n */\n#include <math.h>\n#include \"fitsio.h\"\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_interp.h>\n#include \"spc_cfg.h\"\n#include \"aXe_utils.h\"\n#include \"aXe_errors.h\"\n#include \"fringe_conf.h\"\n\n#define AXE_CONFIG_PATH \"AXE_CONFIG_PATH\"\n\n/**\n * Function: load_CCD_layer\n * The function creates and returns a structure for an optical\n * CCD layer. The input parameters are interpreted, and\n * the data which defines the CCD layer is loaded.\n *\n * Parameters:\n * @param refr_table - the name of the refractive index table\n * @param thickness  - the value for the thicknes keyword\n                       (number or image name)\n *\n * Returns:\n * @return opt_layer  - the optical layer created\n */\nccd_layer *\nload_CCD_layer(const char refr_table[], const char thickness[])\n{\n  ccd_layer *opt_layer;\n\n  float tvalue;\n\n  char **t_err=NULL;\n\n  char refr_table_path[MAXCHAR];\n  char thickness_path[MAXCHAR];\n\n  // build the full pathname to the refraction table\n  build_path (AXE_CONFIG_PATH, refr_table, refr_table_path);\n\n\n  // allocate an error array\n  t_err = (char **) malloc(sizeof(char *)*1);\n\n  // allocate space for the return structure;\n  // complain if this fails\n  opt_layer = (ccd_layer *)malloc(sizeof(ccd_layer));\n\n  // initialize both, the single value\n  // as well as the matrix to NULL;\n  opt_layer->thickness   = 0.0;\n  opt_layer->thickness2D = NULL;\n\n  // convert the keyvalue to a float\n  // tvalue = atof(thickness);\n  tvalue = strtod(thickness,t_err);\n\n  // in case the float value is NULL = 0.0\n  // the conversion failed, and it must be a string\n  //  if (tvalue)\n  if (strcmp(thickness, t_err[0]))\n    {\n#ifdef DEBUGFCONF\n      fprintf(stderr, \"Setting the layer thickness to value: %f mum\\n\",tvalue);\n#endif\n      // set the fixed thickness value\n      opt_layer->thickness = tvalue;\n    }\n  else\n    {\n#ifdef DEBUGFCONF\n      fprintf(stderr, \"Loading layer thickness image: %s\\n\", thickness);\n#endif\n\n      // build the full pathname to the thickness image\n      build_path (AXE_CONFIG_PATH, thickness, thickness_path);\n\n      // load the 2D image for the thickness\n      opt_layer->thickness2D = FITSimage_to_gsl(thickness_path, 1, 1);\n    }\n\n#ifdef DEBUGFCONF\n      fprintf(stderr, \"Loading refractive index table: %s\\n\", refr_table);\n#endif\n  // load the real part of the refraction index\n  opt_layer->re_refraction =\n    create_interp_ftable(refr_table_path, 2, \"WAVELENGTH\", \"N\",\n\t\t\t REFRAC_INTERP_TYPE);\n\n  // load the real part of the refraction index\n  opt_layer->im_refraction =\n    create_interp_ftable(refr_table_path, 2, \"WAVELENGTH\", \"K\",\n\t\t\t REFRAC_INTERP_TYPE);\n\n  // return the optical layer\n  return opt_layer;\n}\n\n\n/**\n * Function: free_CCD_layer\n * The function releases all the memory allocated\n * in a structure for a CCD layer.\n *\n * Parameters:\n * @param opt_layer - structure for CCD layer\n *\n * Returns:\n * @return -\n */\nvoid\nfree_CCD_layer(ccd_layer *opt_layer)\n{\n  // free the thickness matrix\n  if (opt_layer->thickness2D)\n    gsl_matrix_free(opt_layer->thickness2D);\n\n  // free both interpolators\n  free_interp(opt_layer->re_refraction);\n  free_interp(opt_layer->im_refraction);\n\n  // free the rest\n  free(opt_layer);\n\n  // set the structure to NULL\n  opt_layer = NULL;\n}\n\n\n/**\n * Function: load_CCD_layers\n * The function extracts from a fringe configuration file\n * all information on individual CCD layers. It creates\n * the appropriate structure for every CCD layer,\n * and creates and returns a structure which completely\n * describes all layers in a CCD.\n *\n * Parameters:\n * @param fring_conf_path - the name of a fringe configuration file\n *\n * Returns:\n * @return opt_layers - the structure for the optical layers created\n */\nccd_layers *\nload_CCD_layers(char fring_conf_path[])\n{\n  ccd_layers *opt_layers;\n\n  char layer[MAXCHAR];\n  char refr_table[MAXCHAR];\n\n  //int nlayers;\n  int i=0;\n\n  struct CfgStrings LayerConfig[] = {\n    {NULL, NULL},\n    {NULL, NULL}\n  };\n\n  LayerConfig[0].name = layer;\n\n  // allocate space for the return structure;\n  // complain if this fails\n  opt_layers = malloc (sizeof (ccd_layers));\n\n  // initialize the substrate\n  opt_layers->substrate = NULL;\n\n  // detemrine the number of layers\n  // which are described in the\n  //configuration file\n  opt_layers->num_layers = 0;\n  for (i = 0; i < MAX_BEAMS; i++)\n    {\n      sprintf (layer, \"REFR_INDEX_%c\", BEAM (i));\n      CfgRead (fring_conf_path, LayerConfig);\n      if (LayerConfig[0].data != NULL)\n\t{\n\t  opt_layers->num_layers += 1;\n\t  LayerConfig[0].data = NULL;\n\t}\n    }\n\n  //  if (opt_layers->num_layers < NLAYERS_MIN)\n  //    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n  //\t\t \"The number of layers in the configuration\\n file is %i. \"\n  //\t\t \"There must be at least: %i!\\n\",\n  //\t\t opt_layers->num_layers, NLAYERS_MIN);\n\n\n  // allocate space for the array to\n  // the layers described in the\n  // configuration file\n  opt_layers->opt_layer =\n    (ccd_layer **)malloc (opt_layers->num_layers*sizeof(ccd_layers));\n\n  // successively find the\n  // description and finally\n  // load all layers\n  for (i = 0; i < MAX_BEAMS; i++)\n    {\n      // chekc for the first relevant keyword\n      sprintf (layer, \"REFR_INDEX_%c\", BEAM (i));\n      CfgRead (fring_conf_path, LayerConfig);\n      if (LayerConfig[0].data != NULL)\n\t{\n\t  sprintf (refr_table, \"%s\", LayerConfig[0].data);\n\t  LayerConfig[0].data = NULL;\n\n\t  // check for the second relevant keyword\n\t  sprintf (layer, \"THICKNESS_%c\", BEAM (i));\n\t  CfgRead (fring_conf_path, LayerConfig);\n\t  if (LayerConfig[0].data != NULL)\n\t    {\n\t      // load the layer\n\t      opt_layers->opt_layer[i] =\n\t\tload_CCD_layer(refr_table, LayerConfig[0].data);\n\n\t      LayerConfig[0].data = NULL;\n\t    }\n\t  else\n\t    {\n\t      // complain that a keyword is missing\n\t      // for a layer\n\t      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t\t   \"Could load index table %s,\\n\"\n\t\t\t   \"but not thickness information \"\n\t\t\t   \"for beam %c\\n\", refr_table, BEAM (i));\n\t    }\n\t}\n    }\n\n  // return the whole structure\n  return opt_layers;\n}\n\n\n/**\n * Function: free_CCD_layers\n * The function releases all memory allocated in a\n * CCD layers structure.\n *\n * Parameters:\n * @param opt_layers - the CCD layers structure\n *\n * Returns:\n * @return -\n */\nvoid\nfree_CCD_layers(ccd_layers *opt_layers)\n{\n  int index=0;\n\n  // free each layer individually\n  for (index=0; index < opt_layers->num_layers; index++)\n      free_CCD_layer(opt_layers->opt_layer[index]);\n\n  // free the interpolator for the substrate\n  //  free_linint(opt_layers->substrate);\n  free_interp(opt_layers->substrate);\n\n  // free everything\n  free(opt_layers);\n\n  // set the structure to NULL\n  opt_layers = NULL;\n}\n\n\n/**\n * Function: load_fringe_conf\n * The function loads the fringe configuration file given as parameter.\n * All relevant data marked with keywords is extracted. A fringe\n * configuration structure is built up and returned from the\n * data given in the keyvalues.\n *\n * Parameters:\n * @param fring_conf_path - the complete path-name to a fringe configuration file\n *\n * Returns:\n * @return fconf - the fringe configuration structure created\n */\nfringe_conf *\nload_fringe_conf(char fring_conf_path[])\n{\n  char beam[MAXCHAR];\n\n  char ffile_name[MAXCHAR];\n  char ffile_name_path[MAXCHAR];\n\n  int index=0;\n\n  fringe_conf *fconf=NULL;\n\n  gsl_vector *v=NULL;\n\n  struct CfgStrings FringeConfig[] =\n    {\n      {\"FRINGE_AMPLITUDE\", NULL},\n      {\"FRINGE_PHASE\", NULL},\n      {\"FRINGE_RANGE\", NULL},\n      {\"MAX_DISPERSION\", NULL},\n      {\"FILTER_NAME\", NULL},\n      {\"FRINGE_STEP\",NULL},\n      {\"NUM_STEPS\",NULL},\n      {\"SUBSTR_TRANS\",NULL},\n\n      {NULL, NULL},\n      {NULL, NULL}\t\t/* array terminator. REQUIRED !!! */\n    };\n\n\n  FringeConfig[8].name = beam;\n\n  // allocate space for the return structure;\n  // complain if this fails\n  fconf = malloc (sizeof (fringe_conf));\n  if (fconf == NULL)\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"Could not allocate memory for fringe configuration\");\n    }\n\n  // load the optical layers directly from the file\n  fconf->opt_layers = load_CCD_layers(fring_conf_path);\n\n  // read in the file\n  CfgRead (fring_conf_path, FringeConfig);\n\n  // make some intitializations\n  fconf->fringe_amp     = 0.0;\n  fconf->fringe_phase   = 1.0e+32;\n  fconf->fringe_step    = 0.0;\n  fconf->num_steps      = 0;\n  fconf->fringe_range   = NULL;\n  fconf->max_dispersion = 0.0;\n  fconf->filter_through = NULL;\n\n\n  for (index = 0; index < 9; index++)\n    {\n\n      // read in the fringe amplitude\n      if (!strcmp (FringeConfig[index].name, \"FRINGE_AMPLITUDE\"))\n\t{\n\t  if (FringeConfig[index].data != NULL)\n\t    {\n\t      fconf->fringe_amp = atof(FringeConfig[index].data);\n\t    }\n\t}\n\n      // read in the fringe phase\n      if (!strcmp (FringeConfig[index].name, \"FRINGE_PHASE\"))\n\t{\n\t  if (FringeConfig[index].data != NULL)\n\t    {\n\t      fconf->fringe_phase = atof(FringeConfig[index].data);\n\t    }\n\t}\n\n\n      // read in the fringe step\n      if (!strcmp (FringeConfig[index].name, \"FRINGE_STEP\"))\n\t{\n\t  if (FringeConfig[index].data != NULL)\n\t    {\n\t      fconf->fringe_step = atof(FringeConfig[index].data);\n\t    }\n\t}\n\n      // read in the number of steps\n      if (!strcmp (FringeConfig[index].name, \"NUM_STEPS\"))\n\t{\n\t  if (FringeConfig[index].data != NULL)\n\t    {\n\t      fconf->num_steps = atoi(FringeConfig[index].data);\n\t    }\n\t}\n\n      // read in the fringe range\n      if (!strcmp (FringeConfig[index].name, \"FRINGE_RANGE\"))\n\t{\n\t  if (FringeConfig[index].data != NULL)\n\t    {\n\t      v = string_to_gsl_array (FringeConfig[index].data);\n\t      fconf->fringe_range = v;\n\t    }\n\t}\n\n      // read in the fringe amplitude\n      if (!strcmp (FringeConfig[index].name, \"MAX_DISPERSION\"))\n\t{\n\t  if (FringeConfig[index].data != NULL)\n\t    {\n\t      fconf->max_dispersion = atof(FringeConfig[index].data);\n\t    }\n\t}\n\n      // read in the filter name\n      if (!strcmp (FringeConfig[index].name, \"FILTER_NAME\"))\n\t{\n\t  if (FringeConfig[index].data != NULL)\n\t    {\n\t      sprintf (ffile_name, \"%s\", FringeConfig[index].data);\n\n\t      // build the full pathname to the refraction table\n\t      build_path (AXE_CONFIG_PATH, ffile_name, ffile_name_path);\n\n\t      fconf->filter_through =\n\t\tcreate_interp_ftable(ffile_name_path, 2, \"WAVELENGTH\",\n\t\t\t\t     \"THROUGHPUT\", FILTER_INTERP_TYPE);\n\t    }\n\t}\n\n      // read in the substrate transmission\n      if (!strcmp (FringeConfig[index].name, \"SUBSTR_TRANS\"))\n\t{\n\t  if (FringeConfig[index].data != NULL)\n\t    {\n\t      sprintf (ffile_name, \"%s\", FringeConfig[index].data);\n\n\t      // build the full pathname to the refraction table\n\t      build_path (AXE_CONFIG_PATH, ffile_name, ffile_name_path);\n\n\t      fconf->opt_layers->substrate =\n\t\tcreate_interp_ftable(ffile_name_path, 2, \"WAVELENGTH\",\n\t\t\t\t     \"TRANSMISSION\", REFRAC_INTERP_TYPE);\n\t    }\n\t}\n    }\n\n  return fconf;\n}\n\n/**\n * Function: check_fringe_conf\n *\n * Parameters:\n * @param fconf  - the fringe configuration structure\n *\n * Returns:\n * @return\n */\nvoid\ncheck_fringe_conf(fringe_conf *fconf)\n{\n  // make  sure the fringe amplitude is set\n  if (!fconf->fringe_amp)\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"fringe_conf: The fringing amplitude must\\n\"\n\t\t \"be set to be able determining pixel fringing!\\n\");\n\n  // make  sure the fringe phase is set\n  if (fconf->fringe_phase > 1.0e+31)\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"fringe_conf: The fringing phase must\\n\"\n\t\t \"be set to be able determining pixel fringing!\\n\");\n\n  // make  sure the transmission of the substrate\n  // layer is given\n  if (!fconf->opt_layers->substrate)\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"fringe_conf: The substrate transmission\\n\"\n\t\t \"must be given to be able determining pixel fringing!\\n\");\n\n  // make sure that there is a minimum\n  // number of layers.\n  if (fconf->opt_layers->num_layers < NLAYERS_MIN)\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"The number of layers in the configuration\\n file is %i. \"\n\t\t \"There must be at least: %i!\\n\",\n\t\t fconf->opt_layers->num_layers, NLAYERS_MIN);\n\n  // if not defined, give a meaningfull\n  // default for the fringing range\n   if (!fconf->fringe_range)\n    {\n      fconf->fringe_range = gsl_vector_alloc(2);\n      gsl_vector_set(fconf->fringe_range, 0, DEFAULT_MIN_LAMBDA);\n      gsl_vector_set(fconf->fringe_range, 1, DEFAULT_MAX_LAMBDA);\n      fprintf(stdout, \"Setting the fringing range to defaults: [ %f, %f].\\n\",\n\t      DEFAULT_MIN_LAMBDA, DEFAULT_MAX_LAMBDA);\n    }\n\n   // give reasonable default for\n   // the fringe step\n   if (!fconf->fringe_step)\n     {\n       fconf->fringe_step = DEFAULT_FRINGE_STEP;\n       fprintf(stdout, \"Setting the fringing step to default: %f.\\n\",\n\t       DEFAULT_FRINGE_STEP);\n     }\n\n   // give a reasonable default for the\n   // number of steps\n   if (!fconf->num_steps)\n     {\n       fconf->num_steps = DEFAULT_NUM_STEPS;\n       fprintf(stdout, \"Setting the number of steps to default: %i.\\n\",\n\t       DEFAULT_NUM_STEPS);\n     }\n\n   // give a reasonable default for the\n   // maximum dispersion to correct for\n   if (!fconf->max_dispersion)\n     {\n       fconf->max_dispersion = DEFAULT_MAX_DISPERSION;\n       fprintf(stdout, \"Setting the maximal dispersion to default: %f.\\n\",\n\t       DEFAULT_MAX_DISPERSION);\n     }\n}\n\n/**\n * Function: free_fringe_conf\n * The function deallocates all memory in a\n * fringe configuration structure.\n *\n * Parameters:\n * @param fconf  - the fringe configuration structure\n *\n * Returns:\n * @return -\n */\nvoid\nfree_fringe_conf(fringe_conf *fconf)\n{\n\n\n  // free the filter throughput\n  if (fconf->filter_through)\n    free_interp(fconf->filter_through);\n\n  // free the optical layers\n  free_CCD_layers(fconf->opt_layers);\n\n  // free the fringe range\n  gsl_vector_free(fconf->fringe_range);\n  fconf->fringe_range = NULL;\n\n  // free everything\n  free(fconf);\n}\n\n\n/**\n * Function: create_interp_ftable\n * This function cretaes an interpolator from data values stored\n * in a fits table. An interpolator is a structure to hold all\n * data to compute the interpolated data values for different\n * interpolation methods. Core of this structure is the interpolator\n * types offered in the gsl-library.\n * This function is a tool to extract the relevant data points from\n * a fits table and to set up and return the interpolator.\n *\n *\n * Parameters:\n * @param table_name  - the name of the fits table\n * @param hdunum      - the extension number with the data\n * @param xcol        - the column name with the indepenent values\n * @param ycol        - the column name with the dependent values\n * @param interp_type - the interpolation type\n *\n * Returns:\n * @return interp - the interpolation structure created\n */\ninterpolator *\ncreate_interp_ftable(const char table_name[], const int hdunum,\n\t\t     char xcol[], char ycol[],\n\t\t     const gsl_interp_type *interp_type)\n{\n\n  interpolator *interp;\n\n  double *x;\n  double *y;\n  int    f_status = 0;\n  int hdutype, anynul;\n  long nrows=0;\n  int colnum=0;\n\n  fitsfile *input;\n\n  // allocate space for the return structure;\n  // complain if this fails\n  //    interp = (interpolator *)malloc (sizeof (interpolator));\n  //   if (interp == NULL)\n  //     {\n  //        aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n  //  \t\t   \"Could not allocate memory for interpolator\");\n  //      }\n\n#ifdef DEBUGFCONF\n  fprintf(stderr, \"Loading columns %s and %s of fitstable: %s\\n\", xcol, ycol, table_name);\n#endif\n\n  //  Open the file for reading\n  fits_open_file (&input, table_name, READONLY, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"get_response_function_fromFITS: \"\n\t\t   \"Could not open\" \" file: %s\",\n\t\t   table_name);\n    }\n\n  /* Move to the correct hdu */\n  fits_movabs_hdu (input, hdunum, &hdutype, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"create_interp_ftable:\"\n\t\t   \"Could not read extention %d from file: %s\",\n\t\t   hdunum, table_name);\n    }\n\n  /* Get number of rows */\n  fits_get_num_rows (input, &nrows, &f_status);\n  if (f_status) {\n    ffrprt (stderr, f_status);\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"create_interp_ftable: \"\n\t\t \"Could not determine the number of rows in\"\n\t\t \" table %s\",table_name);\n  }\n\n  /* Allocate temporary memory space */\n  x = (double *) malloc(nrows*sizeof(double));\n  if (!x) {\n    aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t \"Memory allocation failed\");\n  }\n  y = (double *) malloc(nrows*sizeof(double));\n  if (!y) {\n    aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t \"Memory allocation failed\");\n  }\n\n  /**************************/\n  /* Read the X-column      */\n  /**************************/\n  /* Get column number */\n  fits_get_colnum (input, CASEINSEN, xcol, &colnum, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"create_interp_ftable: \"\n\t\t   \"Could not determine column %s in \"\n\t\t   \" table %s\", xcol, table_name);\n    }\n\n  /* Read the data */\n  fits_read_col (input, TDOUBLE, colnum, 1, 1, nrows, NULL, x,\n                    &anynul, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"create_interp_ftable: \"\n\t\t   \"Could not read content of WAVELENGTH column \"\n\t\t   \" from BINARY table %s\",table_name);\n    }\n\n  /**************************/\n  /* Read the y-column      */\n  /**************************/\n  /* Get column number */\n  fits_get_colnum (input, CASEINSEN, ycol, &colnum, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"create_interp_ftable: \"\n\t\t   \"Could not determine column %s in \"\n\t\t   \" table %s\", ycol, table_name);\n    }\n\n  /* Read the data */\n  fits_read_col (input, TDOUBLE, colnum, 1, 1, nrows, NULL, y,\n                    &anynul, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"create_interp_ftable: \"\n\t\t   \"Could not read column %s\"\n\t\t   \" from BINARY table %s\", ycol, table_name);\n    }\n\n  fits_close_file(input,&f_status);\n  if (f_status) {\n      aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t   \"Could not close %s\", table_name);\n  }\n\n  // create the interpolator\n  interp = create_interp(nrows, interp_type, x, y);\n\n  // return the interpolator\n  return interp;\n}\n\n\n/**\n * Function: create_interp\n * The function creates, and intializes and returns an interpolator\n * from the basic input, which is the data, the number of data\n * items and the interpolator type requested.\n *\n * Parameters:\n * @param nvals       - the number of data values in the arrays\n * @param interp_type - the interpolation type\n * @param xvals       - the array with the independent data values\n * @param yvals       - the array with the dependent data values\n *\n * Returns:\n * @return interp - the interpolation structure created\n */\ninterpolator *\ncreate_interp(const int nvals, const gsl_interp_type *interp_type,\n\t      double *xvals, double *yvals)\n{\n  interpolator *interp;\n\n  // allocate space for the return structure;\n  // complain if this fails\n  interp = (interpolator *)malloc (sizeof (interpolator));\n  if (interp == NULL)\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"Could not allocate memory for interpolator\");\n    }\n\n  // store the min and max values\n  interp->xmin    = xvals[0];\n  interp->xmax    = xvals[nvals-1];\n\n  // check for ascending order in the\n  // independent values\n  if (interp->xmax < interp->xmin)\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"The independent data values to be stored\\n\"\n\t\t \" in an interplator must be in INCREASING order!\\n\");\n\n  // store the number of data values\n  interp->nvals   = nvals;\n\n  // store the data arrays\n  interp->xvals   = xvals;\n  interp->yvals   = yvals;\n\n  // create and intitialize the gsl inteprolator\n  interp->acc     = gsl_interp_accel_alloc();\n  interp->interp  = gsl_interp_alloc(interp_type, interp->nvals);\n  gsl_interp_init(interp->interp, interp->xvals, interp->yvals, interp->nvals);\n\n  // return the new structure\n  return interp;\n}\n\n/**\n * Function: print_interp\n *\n * Parameters:\n * @param interp - the interpolator structure\n *\n * Returns:\n * @return -\n */\nvoid\nprint_interp(interpolator *interp)\n{\n  int index;\n  double x_typical;\n\n  x_typical = interp->xmin+(interp->xmax-interp->xmin)/2.0;\n\n  fprintf(stdout, \"xmin: %e, xmax: %e\\n\",interp->xmin, interp->xmax);\n  fprintf(stdout, \"number of data values: %i\\n\",interp->nvals);\n  fprintf(stdout, \"Interpolation type: %s\\n\", gsl_interp_name(interp->interp));\n  fprintf(stdout, \"Characteristic value pair: (x,y) = (%e, %e)\\n\",\n\t  x_typical, gsl_interp_eval(interp->interp, interp->xvals,\n\t\t\t\t     interp->yvals, x_typical, interp->acc));\n\n  fprintf(stdout, \"Alternative value pair: (x,y) = (%e, %e)\\n\",\n\t  x_typical, eval_interp(interp, x_typical));\n  for (index=0; index < interp->nvals; index++)\n    fprintf(stdout, \"xvalue: %e, yvalue: %e\\n\",interp->xvals[index], interp->yvals[index]);\n  fprintf(stdout, \"\\n\");\n}\n\n\n/**\n * Function: eval_interp\n * The function computes and returns the interpolated value\n * at a given position for an interpolater.\n *\n * Parameters:\n * @param interp - the interpolator\n * @param xval   - the position to evaluate the interpolator\n *\n * Returns:\n * @return (value) - the interpolated data value\n */\ndouble\neval_interp(interpolator *interp, const double xval)\n{\n  // check whether the x-value is within\n  // the range spanned by the data;\n  // complain if the x-value is outside\n  if (xval < interp->xmin || xval > interp->xmax)\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"independent interpolation value %f \"\n\t\t   \"is outside interval (%f, %f)\\n\", xval,\n\t\t   interp->xmin, interp->xmax);\n\n  // evaluate and return the interpolated value\n  // in on the spot\n  return  gsl_interp_eval(interp->interp, interp->xvals, interp->yvals,\n\t\t\t  xval, interp->acc);\n}\n\n\n/**\n * Function: free_interp\n * the function frees all memory allocated in\n * an interpolator structure.\n *\n * Parameters:\n * @param interp - the interpolator structure\n *\n * Returns:\n * @return -\n */\nvoid\nfree_interp(interpolator *interp)\n{\n  // free the data vectors\n  free(interp->xvals);\n  free(interp->yvals);\n\n  // free the two gsl structures\n  gsl_interp_accel_free(interp->acc);\n  gsl_interp_free (interp->interp);\n\n  // free the rest\n  free(interp);\n\n  // set it to NULL\n  interp = NULL;\n}\n\n\n/**\n * Function: create_linint_ftable\n * This function creates a linear interpolator from data values stored\n * in a fits table. An linear interpolator is a structure to hold all\n * data to compute the linear interpolated data values at any\n * point bracketed by the data.\n * This function is a tool to extract the relevant data points from\n * a fits table and to set up and return the linear interpolator.\n *\n * Parameters:\n * @param table_name  - the name of the fits table\n * @param hdunum      - the extension number with the data\n * @param xcol        - the column name with the indepenent values\n * @param ycol        - the column name with the dependent values\n * @param interp_type - the interpolation type\n *\n * Returns:\n * @return lin_int - the linear interplator structure created\n */\nlinear_interp *\ncreate_linint_ftable(const char table_name[], const int hdunum,\n\t\t     char xcol[], char ycol[])\n{\n\n  linear_interp *lin_int;\n\n  double *x;\n  double *y;\n  int    f_status = 0;\n  int hdutype, anynul;\n  long nrows=0;\n  int colnum;\n  int index=0;\n\n  gsl_vector *xvals;\n  gsl_vector *yvals;\n\n  fitsfile *input;\n\n  // allocate space for the return structure;\n  // complain if this fails\n  lin_int = (linear_interp *)malloc (sizeof (linear_interp));\n  if (lin_int == NULL)\n    {\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"Could not allocate memory for linear interpolator\");\n    }\n\n#ifdef DEBUGFCONF\n  fprintf(stderr, \"Loading columns %s and %s of fitstable: %s\\n\", xcol, ycol, table_name);\n#endif\n\n  //  Open the file for reading\n  fits_open_file (&input, table_name, READONLY, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"get_response_function_fromFITS: \"\n\t\t   \"Could not open\" \" file: %s\",\n\t\t   table_name);\n    }\n\n  /* Move to the correct hdu */\n  fits_movabs_hdu (input, hdunum, &hdutype, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"create_interp_ftable:\"\n\t\t   \"Could not read extention %d from file: %s\",\n\t\t   hdunum, table_name);\n    }\n\n  /* Get number of rows */\n  fits_get_num_rows (input, &nrows, &f_status);\n  if (f_status) {\n    ffrprt (stderr, f_status);\n    aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t \"create_interp_ftable: \"\n\t\t \"Could not determine the number of rows in\"\n\t\t \" table %s\",table_name);\n  }\n\n  /* Allocate temporary memory space */\n  x = (double *) malloc(nrows*sizeof(double));\n  if (!x) {\n    aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t \"Memory allocation failed\");\n  }\n  y = (double *) malloc(nrows*sizeof(double));\n  if (!y) {\n    aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t \"Memory allocation failed\");\n  }\n\n  /**************************/\n  /* Read the X-column      */\n  /**************************/\n  /* Get column number */\n  fits_get_colnum (input, CASEINSEN, xcol, &colnum, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"create_interp_ftable: \"\n\t\t   \"Could not determine column %s in \"\n\t\t   \" table %s\", xcol, table_name);\n    }\n\n  /* Read the data */\n  fits_read_col (input, TDOUBLE, colnum, 1, 1, nrows, NULL, x,\n                    &anynul, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"create_interp_ftable: \"\n\t\t   \"Could not read content of WAVELENGTH column \"\n\t\t   \" from BINARY table %s\",table_name);\n    }\n\n  /**************************/\n  /* Read the y-column      */\n  /**************************/\n  /* Get column number */\n  fits_get_colnum (input, CASEINSEN, ycol, &colnum, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"create_interp_ftable: \"\n\t\t   \"Could not determine column %s in \"\n\t\t   \" table %s\", ycol, table_name);\n    }\n\n  /* Read the data */\n  fits_read_col (input, TDOUBLE, colnum, 1, 1, nrows, NULL, y,\n                    &anynul, &f_status);\n  if (f_status)\n    {\n      ffrprt (stderr, f_status);\n      aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t   \"create_interp_ftable: \"\n\t\t   \"Could not read column %s\"\n\t\t   \" from BINARY table %s\", ycol, table_name);\n    }\n\n  fits_close_file(input,&f_status);\n  if (f_status) {\n      aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t   \"Could not close %s\", table_name);\n  }\n\n#ifdef DEBUGFCONF\n  fprintf(stderr, \"Number of rows: %i\\n\", nrows);\n#endif\n\n  // allocate space for the two vectors\n  xvals = gsl_vector_alloc(nrows);\n  yvals = gsl_vector_alloc(nrows);\n\n  // transport the values from the\n  // arrays to the gsl-arrays\n  for (index=0; index < nrows; index++)\n    {\n      gsl_vector_set(xvals, index, x[index]);\n      gsl_vector_set(yvals, index, y[index]);\n    }\n\n  // reverse both vectors if necessary\n  if (gsl_vector_get(xvals, 0) > gsl_vector_get(xvals, nrows-1))\n    {\n      gsl_vector_reverse(xvals);\n      gsl_vector_reverse(yvals);\n    }\n\n  // set the two helper elements\n  lin_int->act_index = 0;\n  lin_int->num_elem  = nrows;\n\n  // set the minimum and maximum\n  lin_int->xmin = gsl_vector_get(xvals, 0);\n  lin_int->xmax = gsl_vector_get(xvals, nrows-1);\n\n  // set the two vectors\n  lin_int->xvals = xvals;\n  lin_int->yvals = yvals;\n\n  // release memory in the temp variables\n  free(x);\n  free(y);\n\n  // return the new structure\n  return lin_int;\n}\n\n\n/**\n * Function: free_linint\n * The function frees all memory allocated\n * in a linear interpolator structure.\n *\n * Parameters:\n * @param lin_int - the linear inteprolator\n *\n * Returns:\n * @return -\n */\nvoid\nfree_linint(linear_interp *lin_int)\n{\n  // free the two gsl-vectors\n  gsl_vector_free(lin_int->xvals);\n  gsl_vector_free(lin_int->yvals);\n\n  // free the whole structure\n  free(lin_int);\n\n  // set the structure to NULL\n  lin_int = NULL;\n}\n", "meta": {"hexsha": "282f11717402dab6027a8f7a59b567f52478e01c", "size": 28344, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/fringe_conf.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/fringe_conf.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/fringe_conf.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-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.2201665125, "max_line_length": 91, "alphanum_fraction": 0.6598574654, "num_tokens": 7799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3727968183980298}}
{"text": "#pragma once\n#include \"GradUtil.h\"\n\n#ifndef _NOGSL\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#else\n#include \"CustomSolver.h\"\n#endif\n\n#include <limits>\n#include <math.h>\n#include <vector>\n#include \"BasicError.h\"\n#include \"Util.h\"\n\nusing namespace std;\n\nclass ValueGrad;\nclass DistanceGrad {\npublic:\n\tdouble dist;\n\tgsl_vector* grad;\n\tbool set; // TODO: this bit is not necessary if the default dist is 0\n\tDistanceGrad(double d, gsl_vector* g): dist(d), grad(g), set(true) {}\n\t~DistanceGrad(void) {\n\t\tgsl_vector_free(grad);\n\t}\n\tstring print() {\n\t\tstringstream str;\n\t\tif (set) {\n\t\t\tstr << \"Dist: \" << dist;\n\t\t} else {\n\t\t\tstr << \"Dist: NOT SET\";\n\t\t}\n\t\treturn str.str();\n\t}\n\tstring printFull() {\n\t\tstringstream str;\n\t\tif (set) {\n\t\t\tstr << \"Dist: \" << dist << endl;\n\t\t\tstr << \"DGrads: \";\n\t\t\tfor (int i = 0; i < grad->size; i++) {\n\t\t\t\tstr << gsl_vector_get(grad, i) << \", \";\n\t\t\t}\n            if (dist > 1e5 || gsl_blas_dnrm2(grad) > 1e5) {\n                str << \"LARGE VALUES\" << endl;\n            }\n\t\t} else {\n\t\t\tstr << \"Dist: NOT SET\";\n\t\t}\n\t\treturn str.str();\n\t}\n\n\tstatic void dg_and(DistanceGrad* m, DistanceGrad* f, DistanceGrad* d);\n\tstatic void dg_or(DistanceGrad* m, DistanceGrad* f, DistanceGrad* d);\n\tstatic void dg_not(DistanceGrad* m, DistanceGrad* d);\n\tstatic void dg_ite(DistanceGrad* b, DistanceGrad* m, DistanceGrad* f, DistanceGrad* d);\n\n\tstatic double dg_copy(DistanceGrad* m, gsl_vector* grad);\n\tstatic void dg_copy(DistanceGrad* m, DistanceGrad* o);\n\n\tstatic double dg_times(DistanceGrad* m, DistanceGrad* f, gsl_vector* grad);\n    \n    static void dg_ite(DistanceGrad* m, DistanceGrad* f, double dval, gsl_vector* dgrad, DistanceGrad* o);\n\n    static bool same(DistanceGrad* m, DistanceGrad* f);\n\n    static double dg_combine(DistanceGrad* m, DistanceGrad* f);\n    static void dg_combine(DistanceGrad* m, DistanceGrad* f, DistanceGrad* o);\n\n    static double dg_combine(DistanceGrad* m, DistanceGrad* f, double cval, gsl_vector* grad, int bv, gsl_vector* o);\n    static double dg_combine(DistanceGrad* m, DistanceGrad* f, double cval, int bv);\n\n    static void dg_combine(vector<DistanceGrad*>& cdists, DistanceGrad* vdist, vector<ValueGrad*>& cvals, int bv, DistanceGrad* o);\n};\n", "meta": {"hexsha": "2131e4d93b1087ca6b144e75f0a899393bf1fc1f", "size": 2205, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/DistanceGrad.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/DistanceGrad.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/DistanceGrad.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "avg_line_length": 28.6363636364, "max_line_length": 131, "alphanum_fraction": 0.6702947846, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3727945996510082}}
{"text": "/* matrices.c */\n\n// 8.4.13 Example programs for matrices of gsl-ref.pdf\n// GNU GSL GNU Scientific Library reference book\n\n#include <stdio.h>\n#include <gsl/gsl_matrix.h>\n\nint main (void) {\n  int i, j;\n  gsl_matrix * m = gsl_matrix_alloc (10, 3);\n\n  for (i = 0; i < 10; i++)\n    for (j = 0; j < 3; j++)\n      gsl_matrix_set (m, i, j, 0.23 + 100*i + j);\n\n  for (i = 0; i < 100; i++) /* OUT OF RANGE ERROR */\n    for (j = 0; j < 3; j++)\n      printf(\"m(%d,%d) = %g\\n\", i, j,\n\t     gsl_matrix_get (m, i, j));\n\n  gsl_matrix_free(m);\n\n  return 0;\n}\n\n\n", "meta": {"hexsha": "86a2ce1ad52507c38322fdd46118a909d4318b3b", "size": 545, "ext": "c", "lang": "C", "max_stars_repo_path": "gslExamples/matrices.c", "max_stars_repo_name": "ernestyalumni/CompPhys", "max_stars_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2017-07-24T04:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T16:00:41.000Z", "max_issues_repo_path": "gslExamples/matrices.c", "max_issues_repo_name": "ernestyalumni/CompPhys", "max_issues_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-01-16T22:34:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T22:37:10.000Z", "max_forks_repo_path": "gslExamples/matrices.c", "max_forks_repo_name": "ernestyalumni/CompPhys", "max_forks_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2017-01-24T19:18:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-01T07:13:35.000Z", "avg_line_length": 19.4642857143, "max_line_length": 54, "alphanum_fraction": 0.5449541284, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623216, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3727274611773016}}
{"text": "#pragma once\n#include \"BooleanNodes.h\"\n#include \"BooleanDAG.h\"\n#include \"NodeVisitor.h\"\n#include \"VarStore.h\"\n#include <map>\n#include \"FloatSupport.h\"\n#include <tuple>\n#include <iostream>\n#ifndef _NOGSL\n#include <gsl/gsl_vector.h>\n#else\n#include \"CustomSolver.h\"\n#endif\n#include \"Util.h\"\n#include \"Interface.h\"\n\nusing namespace std;\n\n\nclass SimpleEvaluator: NodeVisitor\n{\n    BooleanDAG& bdag;\n    map<string, int>& floatCtrls; // Maps float ctrl names to indices with grad vectors\n    gsl_vector* ctrls; // ctrl values\n    vector<double> distances; // Keeps track of distance metric for boolean nodes\n    double MIN_VALUE = 0.001;\n    Interface* inputValues;\n    int DEFAULT_INPUT = -32;\n    \npublic:\n    SimpleEvaluator(BooleanDAG& bdag_p, map<string, int>& floatCtrls_p);\n\tvirtual ~SimpleEvaluator();\n\n    virtual void visit( SRC_node& node );\n    virtual void visit( DST_node& node );\n    virtual void visit( CTRL_node& node );\n    virtual void visit( PLUS_node& node );\n    virtual void visit( TIMES_node& node );\n    virtual void visit( ARRACC_node& node );\n    virtual void visit( DIV_node& node );\n    virtual void visit( MOD_node& node );\n    virtual void visit( NEG_node& node );\n    virtual void visit( CONST_node& node );\n    virtual void visit( LT_node& node );\n    virtual void visit( EQ_node& node );\n    virtual void visit( AND_node& node );\n    virtual void visit( OR_node& node );\n    virtual void visit( NOT_node& node );\n    virtual void visit( ARRASS_node& node );\n    virtual void visit( UFUN_node& node );\n    virtual void visit( TUPLE_R_node& node );\n    virtual void visit( ASSERT_node& node );\n    \n    \n    void setInputs(Interface* inputValues_p);\n    void run(const gsl_vector* ctrls_p);\n    \n    \n    double getErrorOnConstraint(int nodeid);\n    double getSqrtError(bool_node* node);\n    double getAssertError(bool_node* node);\n    double getBoolCtrlError(bool_node* node);\n    double getBoolExprError(bool_node* node);\n\n\n    double dist(int nodeid) {\n        return d(bdag[nodeid]);\n    }\n        \n    void setvalue(bool_node& bn, double d) {\n        distances[bn.id] = d;\n    }\n    \n    double d(bool_node& bn) {\n        return distances[bn.id];\n    }\n    \n    double d(bool_node* bn) {\n        return d(*bn);\n    }\n    \n    void print() {\n        for (int i = 0; i < bdag.size(); i++) {\n            cout << bdag[i]->lprint() << endl;\n            cout << d(bdag[i]) << endl;\n        }\n    }\n    \n    bool isFloat(bool_node& bn) {\n        return (bn.getOtype() == OutType::FLOAT);\n    }\n    \n    bool isFloat(bool_node* bn) {\n        return (bn->getOtype() == OutType::FLOAT);\n    }\n    \n    int getInputValue(bool_node& bn) {\n        if (inputValues->hasValue(bn.id)) {\n            int val = inputValues->getValue(bn.id);\n            return val;\n        } else {\n            return DEFAULT_INPUT;\n        }\n    }\n    \n    int getInputValue(bool_node* bn) {\n        return getInputValue(*bn);\n    }\n\n    \n    \n};\n", "meta": {"hexsha": "26d51f76e7bea7304799c3d06e49d6ca928b72a9", "size": 2944, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/SimpleEvaluator.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/SimpleEvaluator.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/SimpleEvaluator.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "avg_line_length": 25.8245614035, "max_line_length": 87, "alphanum_fraction": 0.6219429348, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3726765168030598}}
{"text": "/* \n *            Copyright 2009-2017 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#ifndef _VOTCA_XTP_DIIS__H\n#define _VOTCA_XTP_DIIS__H\n\n\n\n   \n#include <gsl/gsl_multimin.h>\n#include <gsl/gsl_vector.h>\n\n\n#include <votca/tools/linalg.h>\n#include <votca/xtp/aomatrix.h>\n#include <votca/xtp/orbitals.h>\n#include <votca/ctp/logger.h>\n\n\nusing namespace votca::tools;\n\nnamespace votca { namespace xtp {\n namespace ub = boost::numeric::ublas;\n\n \n class Diis{\npublic:\n\n    Diis() {_maxerrorindex=0;\n                _maxerror=0.0; };\n   ~Diis() {\n     for (std::vector< ub::matrix<double>* >::iterator it = _mathist.begin() ; it !=_mathist.end(); ++it){\n         delete *it;\n     }\n     _mathist.clear();\n      for (std::vector< ub::matrix<double>* >::iterator it = _dmathist.begin() ; it !=_dmathist.end(); ++it){\n         delete *it;\n     }\n     _dmathist.clear();\n     for (std::vector< ub::matrix<double>* >::iterator it = _errormatrixhist.begin() ; it !=_errormatrixhist.end(); ++it){\n         delete *it;\n     }\n    _errormatrixhist.clear();\n    \n    for (std::vector< std::vector<double>* >::iterator it = _Diis_Bs.begin() ; it !=_Diis_Bs.end(); ++it){\n         delete *it;\n     }\n    _Diis_Bs.clear(); \n    \n   }\n   \n   void Configure(bool usediis,bool noisy, unsigned histlength, bool maxout, string diismethod, double adiis_start,double diis_start,double levelshift,double levelshiftend,unsigned nocclevels){\n       \n       _usediis=usediis;\n       _noisy=noisy;\n       _histlength=histlength;\n       _maxout=maxout;\n       _diismethod=diismethod;\n       _adiis_start=adiis_start;\n       _diis_start=diis_start;\n       _levelshift=levelshift;\n       _levelshiftend=levelshiftend;\n      \n       _nocclevels=nocclevels;\n  \n   }\n   \n   void setOverlap(ub::matrix<double>* _S){\n       S=_S;\n   }\n   void setSqrtOverlap(ub::matrix<double>* _Sminusahalf){\n       Sminusahalf=_Sminusahalf;\n   }\n    void setLogger(ctp::Logger *pLog){_pLog=pLog;}\n    double Evolve(const ub::matrix<double>& dmat,const ub::matrix<double>& H,ub::vector<double> &MOenergies,ub::matrix<double> &MOs, int this_iter,double totE);\n    void SolveFockmatrix(ub::vector<double>& MOenergies,ub::matrix<double>& MOs,ub::matrix<double>&H);\n    void Levelshift(ub::matrix<double>& H,const ub::matrix<double>&MOs);\n    unsigned gethistlength(){return _mathist.size();}\n    \n    \n    double get_E_adiis(const gsl_vector * x) const;\n\n    void get_dEdx_adiis(const gsl_vector * x, gsl_vector * dEdx) const;\n    void get_E_dEdx_adiis(const gsl_vector * x, double * Eval, gsl_vector * dEdx) const;\n   \n private:\n     \n    ctp::Logger *_pLog;\n    ub::matrix<double>* S;\n    ub::matrix<double>* Sminusahalf;\n    bool                              _usediis;\n    bool                              _noisy;\n    unsigned                          _histlength;\n    bool                              _maxout;\n    string                            _diismethod;\n    ub::matrix<double>                _Sminusonehalf;\n    double                              _maxerror;\n    double                              _adiis_start;  \n    double                              _diis_start;\n    double                              _levelshiftend;\n    unsigned                            _maxerrorindex;\n    std::vector< ub::matrix<double>* >   _mathist;\n    std::vector< ub::matrix<double>* >   _dmathist;\n    std::vector< ub::matrix<double>* >   _errormatrixhist;\n    std::vector< std::vector<double>* >  _Diis_Bs;\n   \n    std::vector<double>                 _totE;\n    ub::vector<double>                  _DiF;\n    ub::matrix<double>                  _DiFj;\n  \n    ub::vector<double> ADIIsCoeff();\n    \n    \n ub::vector<double> compute_c(const gsl_vector * x);\n /// Compute jacobian\n ub::matrix<double> compute_jac(const gsl_vector * x);\n /// Compute energy\n double min_f(const gsl_vector * x, void * params);\n /// Compute derivative\n void min_df(const gsl_vector * x, void * params, gsl_vector * g);\n /// Compute energy and derivative\nvoid min_fdf(const gsl_vector * x, void * params, double * f, gsl_vector * g);\n\nub::vector<double> DIIsCoeff();\n    \n    unsigned _nocclevels;\n    double _levelshift;\n    \n    \n  \n };\n \n \n namespace adiis {\n  /// Compute weights\n  ub::vector<double> compute_c(const gsl_vector * x);\n  /// Compute jacobian\n  ub::matrix<double> compute_jac(const gsl_vector * x);\n\n  /// Compute energy\n  double min_f(const gsl_vector * x, void * params);\n  /// Compute derivative\n  void min_df(const gsl_vector * x, void * params, gsl_vector * g);\n  /// Compute energy and derivative\n  void min_fdf(const gsl_vector * x, void * params, double * f, gsl_vector * g);\n};\n    \n}}\n\n#endif\t\n\n", "meta": {"hexsha": "918615cac9fe4f23236bba2e139a5aba283586f8", "size": 5247, "ext": "h", "lang": "C", "max_stars_repo_path": "include/votca/xtp/diis.h", "max_stars_repo_name": "choudarykvsp/xtp", "max_stars_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-05T17:36:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-05T17:36:53.000Z", "max_issues_repo_path": "include/votca/xtp/diis.h", "max_issues_repo_name": "choudarykvsp/xtp", "max_issues_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/votca/xtp/diis.h", "max_forks_repo_name": "choudarykvsp/xtp", "max_forks_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2321428571, "max_line_length": 193, "alphanum_fraction": 0.6136840099, "num_tokens": 1376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3723767732361381}}
{"text": "#ifndef __gslSpline_\n#define __gslSpline__\n\n#include \"include/stdinc.h\"\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_integration.h>\n\nclass gslSpline {\nprotected:\n  const gsl_interp_type *spline_type;\n  gsl_interp_accel *acc;\n  gsl_spline       *spl;\npublic:\n  \n  gslSpline(vector<double> &x, vector<double> &y) {\n    spline_type = gsl_interp_cspline;\n    spl = gsl_spline_alloc(spline_type, x.size());\n    acc = gsl_interp_accel_alloc();\n    gsl_spline_init(spl, &x[0], &y[0], x.size());\n  }\n  ~gslSpline() {\n    gsl_interp_accel_free(acc);\n    gsl_spline_free(spl);\n  }\n  void init(vector<double> &x, vector<double> &y) {\n    gsl_interp_accel_free(acc);\n    gsl_spline_free(spl);     \n    spl = gsl_spline_alloc(spline_type, x.size());\n    acc = gsl_interp_accel_alloc();\n    gsl_spline_init(spl, &x[0], &y[0], x.size());\n  }\n\n  inline real eval  (double xc)  {return gsl_spline_eval(spl, xc, acc);}\n  inline real deriv (double xc)  {return gsl_spline_eval_deriv(spl, xc, acc);}\n  inline real deriv2(double xc)  {return gsl_spline_eval_deriv2(spl, xc, acc);}\n  inline real integ (double x_lo, double x_up)  {\n    return gsl_spline_eval_integ(spl, x_lo, x_up, acc);\n  }\n};\n\n#endif // __gslSpline__\n", "meta": {"hexsha": "5bd73e083bb5f5243acd871f1390e1087ad9d58a", "size": 1254, "ext": "h", "lang": "C", "max_stars_repo_path": "src/amuse/community/mmams/src/mmas2/src/gsl/gslSpline.h", "max_stars_repo_name": "rknop/amuse", "max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z", "max_issues_repo_path": "src/amuse/community/mmams/src/mmas2/src/gsl/gslSpline.h", "max_issues_repo_name": "rknop/amuse", "max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 690.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z", "max_forks_repo_path": "src/amuse/community/mmams/src/mmas2/src/gsl/gslSpline.h", "max_forks_repo_name": "rieder/amuse", "max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 102.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z", "avg_line_length": 28.5, "max_line_length": 79, "alphanum_fraction": 0.6905901116, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3721721136589892}}
{"text": "/**\n * @file bblas_sutil.c\n *\n * @brief BBLAS testing utilities for float routines.\n *\n * BBLAS is a software package provided by Univ. of Manchester,\n * Univ. of Tennessee.\n *\n * @version 1.0.0\n * @author  Samuel  D. Relton\n * @author  Pedro   V. Lara\n * @author  Mawussi Zounon\n * @date    2016-02-20\n *\n * Contains routines used in the testing to modify randomly generated matrices\n * and compute the average error over an entire batch etc.\n *\n **/\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n/**\n * Code generation\n * @generated from bblas_zutil.c normal z -> s, Mon Jun  6 09:44:13 2016\n **/\n#endif\n\n#include \"bblas_common.h\"\n#if defined(BBLAS_WITH_MKL)\n#include <mkl_lapacke.h>\n#else\n#include <lapacke.h>\n#endif\n\n/** Include real functions since using float real precision **/\n#define REAL\n\n/** Quick access to the matrix elements **/\n#define A(i,j)  A[i + j*lda]\n\n/**\n * Make a matrix symmetric/symmetric.  Makes diagonal real.\n * Sets Aji = conj( Aij ) for j < i, that is, copy & conjugate\n * lower triangle to upper triangle.\n **/\n\nvoid bblas_smake_symmetric(int lda, int N, float* A)\n{\n    int i, j;\n    for( i=0; i < N; ++i ) {\n        A(i,i) = creal( A(i,i) );\n        for( j=0; j < i; ++j ) {\n            A(j,i) = conj( A(i,j) );\n        }\n    }\n}\n\n#ifdef COMPLEX\n\n/**\n * Make a matrix real-symmetric\n * Does NOT make diagonal real.\n * Sets Aji = Aij for j < i, that is,\n * copy lower triangle to upper triangle.\n **/\n\nvoid bblas_smake_symmetric(int lda, int N, float* A)\n{\n    int i, j;\n    for( i=0; i < N; ++i ) {\n        for( j=0; j < i; ++j ) {\n            A(j,i) =  A(i,j);\n        }\n    }\n}\n#endif\n\n\n/**\n * irandRange generates a random value (int)\n * in the range min_n and max_n\n **/\n\nint irandRange(int min_n, int max_n)\n{\n    return rand() % (max_n - min_n + 1) + min_n;\n}\n\n/**\n * bblas_srandRange generates a random value (float)\n * in the range [0,max_n]: TODO replace by generic\n */\n\nfloat bblas_srandRange( int max_n )\n{\n    return ( float )rand()/( float )( RAND_MAX/max_n );\n}\n\n/**\n * Computes statistics of the relative errors to summarise them for the user.\n **/\n\nvoid bblas_sstatistic(bblas_stest_t *test)\n{\n\n    enum BBLAS_ROUTINE routine  = test->routine;\n\n    /*Compute avg(M), avg(N), avg(K) */\n    if(test->batch_opts == BBLAS_VARIABLE)\n    {\n\tif ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t    (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) ||\n\t    (routine == BBLAS_TRSM))\n\t{\n\t    test->avgM = bblas_avgarrayI(test->M, test->batch_count);\n\t}\n\n\tif ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK)  ||\n\t    (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) ||\n\t    (routine == BBLAS_HER2K))\n\t{\n\t    test->avgK = bblas_avgarrayI(test->K, test->batch_count);\n\t}\n\n\ttest->avgN = bblas_avgarrayI(test->N, test->batch_count);\n\n    } else if (test->batch_opts == BBLAS_FIXED)\n    {\n\n\tif ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t    (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) ||\n\t    (routine == BBLAS_TRSM))\n\t{\n\t    test->avgM = test->M[0];\n\t}\n\n\tif ((routine == BBLAS_GEMM) || (routine == BBLAS_SYRK)  ||\n\t    (routine == BBLAS_HERK) || (routine == BBLAS_SYR2K) ||\n\t    (routine == BBLAS_HER2K))\n\t{\n\t    test->avgK = test->K[0];\n\t}\n\ttest->avgN = test->N[0];\n\n    } else\n    {\n\tbblas_error(\"testing_sgemm_batch.c\", \"wrong batch_opts value\");\n    }\n\n    /*Statistics on the error */\n    switch(test->target)\n    {\n    case BBLAS_MKL:\n      test->mkl_min_error = bblas_sminarrayD(test->mkl_error, test->batch_count);\n      test->mkl_avg_error = bblas_savgarrayD(test->mkl_error, test->batch_count);\n      test->mkl_max_error = bblas_smaxarrayD(test->mkl_error, test->batch_count);\n      test->mkl_std_error = bblas_sstdarrayD(test->mkl_error, test->batch_count);\n      break;\n\n    case BBLAS_CUBLAS:\n    case BBLAS_MAGMA:\n      test->device_min_error = bblas_sminarrayD(test->device_error, test->batch_count);\n      test->device_avg_error = bblas_savgarrayD(test->device_error, test->batch_count);\n      test->device_max_error = bblas_smaxarrayD(test->device_error, test->batch_count);\n      test->device_std_error = bblas_sstdarrayD(test->device_error, test->batch_count);\n      break;\n\n    case BBLAS_OTHER:\n      test->other_min_error = bblas_sminarrayD(test->other_error, test->batch_count);\n      test->other_avg_error = bblas_savgarrayD(test->other_error, test->batch_count);\n      test->other_max_error = bblas_smaxarrayD(test->other_error, test->batch_count);\n      test->other_std_error = bblas_sstdarrayD(test->other_error, test->batch_count);\n      break;\n\n    default:\n      printf(\"In bblas_sstatistic(): Target no defined\\n\");\n      exit(EXIT_FAILURE);\n    }\n}\n\n\n/**\n * Print a matrix.\n **/\nvoid bblas_sprintmatrix(float *matrix, int row, int col)\n{\n    /*Local variables */\n    int i, j;\n\n    for (i=0; i < row; i++)\n    {\n\tprintf(\"\\n\\n\");\n\tfor (j=0; j < col; j++)\n\t{\n#ifdef COMPLEX\n\t    printf(\"%1.2f + %1.2f\\t\", creal(matrix[i*col+j]), cimag(matrix[i*col+j]));\n#else\n\t    printf(\"%1.2f\",matrix[i*col+j]);\n#endif\n\t}\n    }\n    printf(\"\\n\");\n}\n\n/**\n * Decide whether a batch is fixed or variable.\n **/\n\nchar* bblas_getoption(enum BBLAS_OPTS opts)\n{\n   /*Local variable */\n    char funcname[] = \"bblas_getoption\";\n\n    switch(opts)\n    {\n\tcase BBLAS_VARIABLE:\n\t    return \"BATCH OPTION: VARIABLE\";\n\t    break;\n\n\tcase BBLAS_FIXED:\n\t    return \"BATCH OPTION: FIXED\";\n\t    break;\n\n\tdefault:\n\t    printf(\"ERROR in %s, undefined bblas routine name\\n\",funcname);\n\t    exit(EXIT_FAILURE);\n    }\n\n}\n\n/**\n * Get the name of the current test routine.\n **/\n\nchar* bblas_getroutine(enum BBLAS_ROUTINE routine)\n{\n    /*Local variable */\n    char funcname[] = \"bblas_getroutine\";\n\n    switch(routine)\n    {\n\tcase BBLAS_GEMM:\n\t    return \"SGEMM\";\n\t    break;\n\n\tcase BBLAS_HEMM:\n\t    return \"SSYMM\";\n\t    break;\n\n\tcase BBLAS_HER2K:\n\t    return \"SSYR2K\";\n\t    break;\n\n\tcase BBLAS_HERK:\n\t    return \"SSYRK\";\n\t    break;\n\n\tcase BBLAS_SYMM:\n\t    return \"SSYMM\";\n\t    break;\n\n\tcase BBLAS_SYR2K:\n\t    return \"SSYR2K\";\n\t    break;\n\n\tcase BBLAS_SYRK:\n\t    return \"SSYRK\";\n\t    break;\n\n\tcase BBLAS_TRMM:\n\t    return \"STRMM\";\n\t    break;\n\n\tcase BBLAS_TRSM:\n\t    return \"STRSM\";\n\t    break;\n\n\tdefault:\n\t    printf(\"ERROR in %s, undefined bblas routine name\\n\",funcname);\n\t    exit(EXIT_FAILURE);\n    }\n}\n\n\n\n/**\n * Computes the maximum value of an array of real floats.\n **/\n\nfloat bblas_smaxarrayD(float *myArray, int size)\n{\n    int iter;\n    float maxValue = myArray[0];\n\n    for (iter = 0; iter < size; ++iter)\n    {\n        if ( myArray[iter] > maxValue )\n\t{\n            maxValue = myArray[iter];\n        }\n    }\n    return maxValue;\n}\n\n\n/**\n * Computes the minimum value of an array of real floats.\n **/\n\nfloat bblas_sminarrayD(float *myArray, int size)\n{\n    int iter;\n    float minValue = myArray[0];\n\n    for (iter = 0; iter < size; ++iter)\n    {\n        if ( myArray[iter] < minValue )\n\t{\n            minValue = myArray[iter];\n        }\n    }\n    return minValue;\n}\n\n/**\n * Computes the mean value of an array of real floats.\n **/\n\nfloat bblas_savgarrayD(float *myArray, int size)\n{\n    int iter;\n    float avg = 0.;\n\n    for (iter = 0; iter < size; ++iter)\n    {\n\tavg += myArray[iter];\n    }\n    return avg/size;\n}\n\n/**\n * Computes the standard deviation of an array of real floats.\n **/\n\nfloat bblas_sstdarrayD(float *myArray, int size)\n{\n    int iter;\n    float avg, sd=0.;\n\n    avg =  bblas_savgarrayD(myArray, size);\n\n    for (iter = 0; iter < size; ++iter)\n    {\n\tsd += (myArray[iter] -avg)*(myArray[iter] -avg);\n    }\n    return sd/size;\n}\n\n/**\n * Computes the minimum value of an array of integers.\n **/\n\nint bblas_minarrayI(int *myArray, int size)\n{\n    int iter;\n    int minValue = myArray[0];\n\n    for (iter = 0; iter < size; ++iter)\n    {\n        if ( myArray[iter] < minValue )\n\t{\n            minValue = myArray[iter];\n        }\n    }\n    return minValue;\n}\n\n/**\n * Computes the mean of an array of integers.\n **/\n\nint bblas_avgarrayI(int *myArray, int size)\n{\n    int iter;\n    int avg = 0;\n\n    for (iter = 0; iter < size; ++iter)\n    {\n\tavg += myArray[iter];\n    }\n    return avg/size;\n}\n\n\n/**\n * Transform BBLAS enum values for <tt>trans</tt>, <tt>uplo</tt> etc. to human-readable strings.\n **/\n\nchar* bblas_op2char(unsigned int op)\n{\n    char *opname = (char*)malloc(30*sizeof(char));\n    switch(op)\n    {\n        case BblasNoTrans:\n            strcpy(opname,\"CblasNoTrans\");\n            break;\n\n        case BblasTrans:\n\t    strcpy(opname,\"CblasTrans\");\n            break;\n\n        case BblasConjTrans:\n            strcpy(opname,\"CblasConjTrans\");\n            break;\n\n        case BblasLower:\n            strcpy(opname,\"CblasLower\");\n            break;\n\n        case BblasUpper:\n\t    strcpy(opname,\"CblasUpper\");\n            break;\n\n        case BblasNonUnit:\n\t    strcpy(opname,\"CblasNonUnit\");\n            break;\n\n        case BblasUnit:\n\t   strcpy(opname,\"CblasUnit\");\n            break;\n\n        case BblasLeft:\n\t   strcpy(opname,\"CblasLeft\");\n            break;\n\n        case BblasRight:\n\t    strcpy(opname,\"CblasRight\");\n            break;\n\n        default:\n            return 0;\n            exit(EXIT_FAILURE);\n    }\n    return opname;\n}\n\n/**\n * Get the amount of data needed.\n **/\n\nint bblas_snbdata(bblas_stest_t *test)\n{\n    enum BBLAS_OPTS batch_opts        = test->batch_opts;\n    int nb_data;\n    char function_name[NAME_LENGTH]   =\"bblas_getdatacount\";\n\n    switch(batch_opts)\n    {\n\tcase BBLAS_VARIABLE:\n\t    nb_data =  test->batch_count;\n\t    break;\n\n\tcase BBLAS_FIXED:\n\t    nb_data = 1;\n\t    break;\n\n\tdefault:\n\t    bblas_fatal_error(function_name, \"wrong batch_opts value\");\n    }\n\n    return nb_data;\n}\n\n\n/**\n * Inject an error into the computation if this is set in the input file.\n **/\n\nvoid bblas_sset_error(bblas_stest_t *test)\n{\n    int   nb_data =  bblas_snbdata(test);\n    int   routine = test->routine;\n    int   error_index = irandRange(0, nb_data);\n\n    if (test->global_error){\n\ttest->batch_count = -1;\n\treturn;\n    }\n\n\n    if (test->batch_opts == BBLAS_FIXED)\n    {\n\terror_index = 0;\n    }\n\n    if (test->set_error)\n    {\n\tif ((routine == BBLAS_GEMM) || (routine == BBLAS_SYMM) ||\n\t    (routine == BBLAS_HEMM) || (routine == BBLAS_TRMM) ||\n\t    (routine == BBLAS_TRSM))\n\t{\n\t    test->M[error_index] = -1;\n\t}else if ((routine == BBLAS_SYRK) || (routine == BBLAS_HERK) ||\n\t\t  (routine == BBLAS_SYR2K)|| (routine == BBLAS_HER2K))\n\t{\n\t    test->K[error_index] = -1;\n\t}\n    }\n}\n\n/**\n * Check whether a computation has passed or failed our accuracy test.\n * When new_accuracy=1 in the input file this uses an appropriate\n * forward/backward error bound,\n * otherwise this looks at the relative error.\n **/\n\nvoid bblas_spassed_failed(bblas_stest_t  *test, float error, char *result, int info)\n{\n    float eps = LAPACKE_slamch_work('e');\n\n\t/* Use our new accuracy test based on forward/backward error analysis*/\n    if (test->new_accuracy)\n    {\n\tif( (error > 1) || (info))\n\t{\n\t    strcpy(result, \"FAILED\");\n\n\t}else\n\t{\n\t    strcpy(result, \"PASSED\");\n\t}\n    }else\n    {\n\t\t/* Use old accuracy test based on the relative error */\n\tif((error > eps*test->tolerance) || (info))\n\t{\n\t    strcpy(result, \"FAILED\");\n\n\t}else\n\t{\n\t    strcpy(result, \"PASSED\");\n\t}\n    }\n}\n\n/**\n * Set the batch_count.\n **/\n\nvoid bblas_sset_batch_count(bblas_stest_t *test)\n{\n\n  test->batch_count = test->minbatch_count* (test->current_iter+1);\n}\n\n\n#undef REAL\n", "meta": {"hexsha": "928f5a0f4292c85e34f474d48901370af93ff7ca", "size": 11328, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/bblas_sutil.c", "max_stars_repo_name": "NLAFET/BBLAS-ref", "max_stars_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "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": "testing/bblas_sutil.c", "max_issues_repo_name": "NLAFET/BBLAS-ref", "max_issues_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/bblas_sutil.c", "max_forks_repo_name": "NLAFET/BBLAS-ref", "max_forks_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d", "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.3010752688, "max_line_length": 96, "alphanum_fraction": 0.6092867232, "num_tokens": 3324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.37203702102157044}}
{"text": "\n\n#include <inttypes.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <assert.h>\n#include <cblas.h>\n#include <string.h> // memcpy\n#include <math.h>\n\n#include \"cgraph.h\"\n#include \"cg_operation.h\"\n#include \"cg_types.h\"\n#include \"cg_variables.h\"\n#include \"cg_errors.h\"\n#include \"cg_constants.h\"\n#include \"cg_enums.h\"\n#include \"cg_factory.h\"\n#include \"cg_math.h\"\n\n\n\n\nvoid freeDoubleValue(CGDouble* v){\n}\n\nvoid freeVectorValue(CGVector* data){\n\tfree(data->data);\n}\n\nvoid freeMatrixValue(CGMatrix* data){\n\tfree(data->data);\n}\n\nvoid freeNode(CGraph* graph, CGNode* node){\n\t//printf(\"freeing node %d\\n\", node->type);\n\tif(node->result != NULL){\n\t\tfreeResultNode(node->result);\n\t\tfree(node->result);\n\t\tnode->result = NULL;\n\t}\n\t\n\tif(node->diff != NULL){\n\t\tfreeNode(graph, node->diff);\n\t\tfree(node->diff);\n\t}\n\t\n\tswitch(node->type){\n\t\tcase CGNT_CONSTANT:{\n\t\t\tswitch(node->constant->type){\n\t\t\t\tcase CGVT_DOUBLE:\n\t\t\t\t{\n\t\t\t\t\tfree(node->constant->value);\n\t\t\t\t\tfree(node->constant);\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase CGVT_VECTOR:{\n\t\t\t\t\tCGVector* vec = (CGVector*)node->constant->value;\n\t\t\t\t\tfreeVectorValue(vec);\n\t\t\t\t\tfree(node->constant->value);\n\t\t\t\t\tfree(node->constant);\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase CGVT_MATRIX:{\n\t\t\t\t\tCGMatrix* mat = (CGMatrix*)node->constant->value;\n\t\t\t\t\tfreeMatrixValue(mat);\n\t\t\t\t\tfree(node->constant->value);\n\t\t\t\t\tfree(node->constant);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase CGNT_VARIABLE:{\n\t\t\tfree(node->var);\n\t\t\tbreak;\n\t\t}\n\t\tcase CGNT_BINARY_OPERATION:\n\t\t\tfree(node->bop);\n\t\t\tbreak;\n\t\tcase CGNT_UNARY_OPERATION:\n\t\t\tfree(node->uop);\n\t\t\tbreak;\n\t\tcase CGNT_AXIS_BOUND_OPERATION:\n\t\t\tfree(node->axop);\n\t\t\tbreak;\n\t\tcase CGNT_GRAPH:\n\t\t\tfree(node->graph);\n\t\t\tbreak;\n\t\tcase CGNT_CROSS_ENTROPY_LOSS_FUNC:\n\t\t\tfree(node->crossEntropyLoss);\n\t\t\tbreak;\n\t}\n\t\n}\n\nvoid freeResultNode(CGResultNode* node){\n\tif(node->error){\n\t\tfree(node->error);\n\t\tfree(node);\n\t\treturn;\n\t}\n\t\n\tswitch(node->type){\n\t\tcase CGVT_DOUBLE:\n\t\t\tfreeDoubleValue(node->value);\n\t\t\tbreak;\n\t\tcase CGVT_VECTOR:\n\t\t\tfreeVectorValue(node->value);\n\t\t\tbreak;\n\t\tcase CGVT_MATRIX:\n\t\t\tfreeMatrixValue(node->value);\n\t\t\tbreak;\n\t}\n\t\n\tfree(node->value);\n}\n\nvoid freeGraph(CGraph* graph){\n\tif(graph == NULL)\n\t\treturn;\n\t\n\tconst char *key;\n\t\n\tmap_iter_t iter = map_iter(&graph->vars);\n\n\twhile ((key = map_next(&graph->vars, &iter))) {\n\t\tCGNode* node = *map_get(&graph->vars, key);\n\t\tif(node != NULL){\n\t\t\tfreeNode(graph, node);\n\t\t\tfree(node);\n\t\t}\n\t}\n\t\n\tmap_deinit(&graph->vars);\n\t\n\tint i = 0;\n\tCGNode* node;\n\t\n\tvec_foreach(&graph->nodes, node, i) {\n\t\tfreeNode(graph, node);\n\t\tfree(node);\n\t}\n\t\n\tvec_deinit(&graph->nodes);\n\t// graph pointer must be freed elsewhere. in lua API we create a copy so we cannot free the parameter of this function.\n}\n\n/*\n * Lua lightuser data are automatically freed within the lua VM,\n * this version is lua friendly.\n */\nvoid freeGraph_lua(CGraph* graph){\n\tif(graph == NULL)\n\t\treturn;\n\t\n\tconst char *key;\n\t\n\tmap_deinit(&graph->vars);\n\t\n\tint i = 0;\n\tCGNode* node;\n\n\t\n\tvec_deinit(&graph->nodes);\n\t// graph pointer must be freed elsewhere. in lua API we create a copy so we cannot free the parameter of this function.\n}\n\n\nvoid freeNode_lua(CGraph* graph, CGNode* node){\n\t//printf(\"freeing node %d\\n\", node->type);\n\n\tif(node->result != NULL){\n\t\tfreeResultNode(node->result);\n\t\tfree(node->result);\n\t\tnode->result = NULL;\n\t}\n\t\n\tif(node->diff != NULL){\n\t\tfreeNode(graph, node->diff);\n\t\tfree(node->diff);\n\t}\n\n\tswitch(node->type){\n\t\tcase CGNT_CONSTANT:{\n\t\t\tswitch(node->constant->type){\n\t\t\t\tcase CGVT_DOUBLE:\n\t\t\t\t{\n\t\t\t\t\tfree(node->constant->value);\n\t\t\t\t\tfree(node->constant);\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase CGVT_VECTOR:{\n\t\t\t\t\tCGVector* vec = (CGVector*)node->constant->value;\n\t\t\t\t\tfreeVectorValue(vec);\n\t\t\t\t\tfree(node->constant->value);\n\t\t\t\t\tfree(node->constant);\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase CGVT_MATRIX:{\n\t\t\t\t\tCGMatrix* mat = (CGMatrix*)node->constant->value;\n\t\t\t\t\tfreeMatrixValue(mat);\n\t\t\t\t\tfree(node->constant->value);\n\t\t\t\t\tfree(node->constant);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase CGNT_VARIABLE:{\n\t\t\tfree(node->var);\n\t\t\tbreak;\n\t\t}\n\t\tcase CGNT_BINARY_OPERATION:\n\t\t\tfree(node->bop);\n\t\t\tbreak;\n\t\tcase CGNT_UNARY_OPERATION:\n\t\t\tfree(node->uop);\n\t\t\tbreak;\n\t\tcase CGNT_AXIS_BOUND_OPERATION:\n\t\t\tfree(node->axop);\n\t\t\tbreak;\n\t\tcase CGNT_GRAPH:\n\t\t\tfree(node->graph);\n\t\t\tbreak;\n\t\tcase CGNT_CROSS_ENTROPY_LOSS_FUNC:\n\t\t\tfree(node->crossEntropyLoss);\n\t\t\tbreak;\n\t}\n\t\n}\n", "meta": {"hexsha": "ae1bf6efff5838ecbd351a663927f011f1be08f2", "size": 4362, "ext": "c", "lang": "C", "max_stars_repo_path": "source/libcgraph/source/cg_free.c", "max_stars_repo_name": "Enehcruon/cgraph", "max_stars_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-29T17:55:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T03:25:53.000Z", "max_issues_repo_path": "source/libcgraph/source/cg_free.c", "max_issues_repo_name": "Enehcruon/cgraph", "max_issues_repo_head_hexsha": "cc12d6e195d0d260584e1d4bc822bcc34d24a9af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-01-22T18:39:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-08T12:27:17.000Z", "max_forks_repo_path": "source/libcgraph/source/cg_free.c", "max_forks_repo_name": "praisethemoon/ccgraph", "max_forks_repo_head_hexsha": "ff5ff885dcddc19cfe1c6a21550a39c19684680f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-26T13:55:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-21T05:16:24.000Z", "avg_line_length": 18.175, "max_line_length": 120, "alphanum_fraction": 0.6398441082, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863695, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3720370131322144}}
{"text": "#include <cblas.h>\n#include <lapacke.h>\n#include <malloc.h>\n#include <math.h>\n#include <phobos.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\n#define min(x, y)       (((x) < (y)) ? (x) : (y))\n#define max(x, y)       (((x) > (y)) ? (x) : (y))\n#define KRONDELTA(i, j) (((i) == (j)) ? (1.0) : (0.0))\n\nvoid\ncopyPointer(double *initial, double *destination, int elements)\n{\n  int i;\n  for (i = 0; i < elements; ++i)\n    destination[i] = initial[i];\n}\n\ndouble\nsecondNorm(double *vec, int elements)\n{\n  int i;\n  double mag = .0;\n  for (i = 0; i < elements; ++i)\n    mag += (vec[i] * vec[i]);\n  return sqrt(mag);\n}\n\ndouble\ninfiniteNorm(double *vec, int elements)\n{\n  int i;\n  double res = 0;\n  for (i = 0; i < elements; ++i)\n    res = max(res, fabs(vec[i]));\n  return res;\n}\n\ndouble *\nallocateWork(int worksize)\n{\n  int i;\n  double *work = (double *) malloc((worksize) * sizeof(double));\n  for (i = 0; i < (worksize); ++i)\n    work[i] = .0;\n  return work;\n}\n\ndouble\ncomputeRho(\n    void (*func)(double *parVec, double *meaVec, int par, int mea, void *data),\n    double *parNew,\n    double *delta,\n    double *g,\n    double *epsilon,\n    double *epsilonNew,\n    double *meaVec,\n    double mu,\n    int par,\n    int mea,\n    void *data)\n{\n  int i;\n  double rho = .0, eMag, eNewMag, denom;\n  func(parNew, epsilonNew, par, mea, data);\n  for (i = 0; i < mea; ++i)\n    epsilonNew[i] = (meaVec[i] - epsilonNew[i]);\n  eMag    = secondNorm(epsilon, par);\n  eNewMag = secondNorm(epsilonNew, par);\n  denom   = .0;\n  for (i = 0; i < par; ++i)\n    denom += (delta[i] * (mu * delta[i] + g[i]));\n  rho = (eMag * eMag - eNewMag * eNewMag) / denom;\n  return rho;\n}\n\nvoid\nnumericalGradient(\n    void (*func)(double *parVec, double *meaVec, int par, int mea, void *data),\n    double *parVec,\n    double *jac,\n    double *work,\n    int par,\n    int mea,\n    void *data)\n{\n  int i, j;\n  double h;\n  h = 1e-4;\n  func(parVec, work, par, mea, data);\n  double *tmp_mea = work + mea;\n  for (i = 0; i < par; ++i)\n  {\n    parVec[i] += h;\n    func(parVec, tmp_mea, par, mea, data);\n    for (j = 0; j < mea; ++j)\n      jac[j * mea + i] = ((tmp_mea[j] - work[j]) / h);\n    parVec[i] -= h;\n  }\n  tmp_mea = NULL;\n}\n\nextern int\nphobos(\n    void (*func)(double *parVec, double *meaVec, int par, int mea, void *data),\n    void (*jac)(double *parVec, double *jacobi, int par, int mea, void *data),\n    double *parVec,\n    double *meaVec,\n    int par,\n    int mea,\n    int itmax,\n    double *opts,\n    double *info,\n    double *work,\n    double *covar,\n    void *data)\n{\n  int i, j, index, freeWork, freeCovar, freeInfo, measXpar, parSq, meaSq,\n      worksize, iter, incx, stop, numGrad;\n  int *ipiv = (int *) malloc(par * sizeof(int));\n\n  double alpha, beta, mu, muNew, nu, rho, tau, e1, e2, e3, maxHess,\n      oneOverThree, compVal;\n  double *jacobi, *hessian, *nMatrix, *currMeasure, *epsilon, *tmpMeasure, *g,\n      *delta, *pNew, *numWork;\n\n  numWork = NULL;\n  if (jac == NULL)\n  {\n    numGrad = 1;\n    numWork = (double *) malloc(2 * mea * sizeof(double));\n  }\n  else\n    numGrad = 0;\n\n  if (opts)\n  {\n    tau = opts[0];\n    e1  = opts[1];\n    e2  = opts[2];\n    e3  = opts[3];\n  }\n  else\n  {\n    tau = STAN_TAU;\n    e1  = STAN_EPSILON;\n    e2  = STAN_EPSILON;\n    e3  = STAN_EPSILON;\n  }\n\n  if (info)\n    freeInfo = 0;\n  else\n  {\n    info     = (double *) malloc(PHOBOS_INFOSIZE * sizeof(double));\n    freeInfo = 1;\n  }\n  for (i = 0; i < PHOBOS_INFOSIZE; ++i)\n    info[i] = .0;\n\n  freeWork  = 0;\n  freeCovar = 0;\n  stop      = 0;\n  iter      = 0;\n  incx      = 1;\n\n  measXpar = mea * par;\n  parSq    = par * par;\n  meaSq    = mea * mea;\n  worksize = PHOBOS_WORKSIZE(par, mea);\n\n  // cblas_dgemm implementation: C = alpha*A*B + beta*C\n  alpha        = 1.0;\n  beta         = .0;\n  rho          = .0;\n  nu           = 2.0;\n  maxHess      = .0;\n  oneOverThree = 1.0 / 3.0;\n  compVal      = .0;\n\n  // Handle the workspace\n  if (work == NULL && covar == NULL)\n  {\n    work     = allocateWork((worksize + parSq));\n    covar    = work + worksize;\n    freeWork = 1;\n  }\n  else if (work == NULL || covar == NULL)\n  {\n    if (work == NULL)\n    {\n      work     = allocateWork(worksize);\n      freeWork = 1;\n    }\n    else\n    {\n      covar     = allocateWork(parSq);\n      freeCovar = 1;\n    }\n  }\n  // Clean memory\n  // Care with worksize: covar matrix is included\n  // in standard implementation of PHOBOS_WORKSIZE.\n  // This means we might run in trouble when just\n  // running i < workspace ans user defined\n  // workspace and covar seperatly.\n  for (i = 0; i < (worksize - parSq); ++i)\n    work[i] = .0;\n  for (i = 0; i < parSq; ++i)\n    covar[i] = .0;\n  for (i = 0; i < mea; ++i)\n    meaVec[i] = .0;\n\n  // manage memory\n  // for more information see phobos.h\n  jacobi      = work;\n  hessian     = (work + measXpar);\n  nMatrix     = hessian + parSq;\n  currMeasure = (nMatrix + parSq);\n  epsilon     = currMeasure + mea;\n  tmpMeasure  = epsilon + mea;\n  g           = tmpMeasure + mea;\n  delta       = g + par;\n  pNew        = delta + par;\n\n  // Calculate initial jacobi matrix\n  if (numGrad)\n    numericalGradient(func, parVec, jacobi, numWork, par, mea, data);\n  else\n    jac(parVec, jacobi, par, mea, data);\n\n  // Calculate estimate for hessian matrix\n  cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, par, par, mea, alpha,\n              jacobi, par, jacobi, par, beta, hessian, par);\n\n  // find maxHess\n  for (i = 0; i < meaSq; i += (mea + 1))\n    maxHess = max(maxHess, hessian[i]);\n\n  // calculate mu = tau * maxHess\n  mu = tau * maxHess;\n\n  // Calculate current measurement vector\n  func(parVec, currMeasure, par, mea, data);\n\n  // Shift the arrays to fit the cblas implementation\n  copyPointer(meaVec, epsilon, mea);\n  copyPointer(currMeasure, tmpMeasure, mea);\n\n  // calculate epsilon\n  cblas_daxpy(mea, -alpha, tmpMeasure, incx, epsilon, incx);\n  info[1] = secondNorm(epsilon, mea);\n\n  // Calculate g = J(t) * epsilon\n  cblas_dgemv(CblasRowMajor, CblasTrans, mea, par, alpha, jacobi, par, epsilon,\n              incx, beta, g, incx);\n\n  info[2] = infiniteNorm(g, par);\n  if (info[2] <= e1)\n  {\n    info[7] = 5.0;\n    info[8] = e1;\n    stop    = 1;\n  }\n  while (!stop && (iter < itmax))\n  {\n    ++iter;\n    info[0] += 1.0;\n    do\n    {\n      //         printf(\"%d\", ++it );\n      for (i = 0; i < par; ++i)\n      {\n        for (j = 0; j < par; ++j)\n        {\n          index          = i * par + j;\n          nMatrix[index] = hessian[index] + KRONDELTA(i, j) * mu;\n        }\n        delta[i] = g[i];\n      }\n\n      LAPACKE_dgesv(LAPACK_ROW_MAJOR, par, 1, nMatrix, par, ipiv, delta, 1);\n      info[5] = secondNorm(delta, par);\n      compVal = (e2 * secondNorm(parVec, par));\n      if (info[5] <= compVal)\n      {\n        info[7] = 1.0;\n        info[8] = compVal;\n        stop    = 1;\n      }\n      else\n      {\n        for (j = 0; j < par; ++j)\n          pNew[j] = parVec[j] + delta[j];\n        rho = computeRho(func, pNew, delta, g, epsilon, tmpMeasure, meaVec, mu,\n                         par, mea, data);\n        //            printf( \"  %f\", rho);\n        if (rho > .0)\n        {\n          copyPointer(pNew, parVec, par);\n\n          if (numGrad)\n            numericalGradient(func, parVec, jacobi, numWork, par, mea, data);\n          else\n            jac(parVec, jacobi, par, mea, data);\n\n          cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, par, par, mea,\n                      alpha, jacobi, par, jacobi, par, beta, hessian, par);\n\n          // Calculate current measurement vector\n          func(parVec, currMeasure, par, mea, data);\n          copyPointer(meaVec, epsilon, par);\n          copyPointer(currMeasure, tmpMeasure, par);\n\n          // calculate epsilon\n          cblas_daxpy(par, -alpha, tmpMeasure, incx, epsilon, incx);\n\n          // Calculate g = J(t) * epsilon\n          cblas_dgemv(CblasRowMajor, CblasTrans, mea, par, alpha, jacobi, par,\n                      epsilon, incx, beta, g, incx);\n\n          // calculate mu = tau * maxHess\n          muNew = (1.0 - pow((2.0 * rho - 1), 3.0));\n          mu *= (max(oneOverThree, muNew));\n          nu      = 2.0;\n          info[3] = secondNorm(epsilon, mea);\n          muNew *= info[3];\n          info[4] = infiniteNorm(g, par);\n          if (((info[4]) <= e1))\n          {\n            stop    = 1;\n            info[7] = 2.0;\n            info[8] = e1;\n          }\n          else if ((info[3] * info[3] < e3))\n          {\n            stop    = 1;\n            info[7] = 3.0;\n            info[8] = e3;\n          }\n        }\n        else\n        {\n          mu *= nu;\n          nu *= 2.0;\n        }\n      }\n    } while (!(rho < 0 || stop));\n  }\n  if (iter == itmax && info[7] == .0)\n  {\n    info[7] = 4.0;\n    info[8] = (double) itmax;\n  }\n  for (i = 0; i < meaSq; i += (mea + 1))\n    info[6] = max(info[6], hessian[i]);\n  /*   info[1] = mu;\n     info[2] = nu;\n     info[3] = infiniteNorm(g, par);\n     info[4] = rho;\n  */\n  // Clean the workspace\n  free(ipiv);\n  if (freeWork)\n    free(work);\n  if (freeCovar)\n    free(covar);\n  if (numGrad)\n    free(numWork);\n  if (freeInfo)\n    free(info);\n  return iter;\n}\n", "meta": {"hexsha": "0eb7fb17ad22daba4e6da5e90f3da74889bc451d", "size": 9047, "ext": "c", "lang": "C", "max_stars_repo_path": "plugins/phobos/src/phobos.c", "max_stars_repo_name": "volkerschmidts/titania", "max_stars_repo_head_hexsha": "1ad441a7f9481392e21216a2be86b20b1d090a97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plugins/phobos/src/phobos.c", "max_issues_repo_name": "volkerschmidts/titania", "max_issues_repo_head_hexsha": "1ad441a7f9481392e21216a2be86b20b1d090a97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-24T03:54:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:32:09.000Z", "max_forks_repo_path": "plugins/phobos/src/phobos.c", "max_forks_repo_name": "volkerschmidts/titania", "max_forks_repo_head_hexsha": "1ad441a7f9481392e21216a2be86b20b1d090a97", "max_forks_repo_licenses": ["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.9973474801, "max_line_length": 79, "alphanum_fraction": 0.5252569913, "num_tokens": 3088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.371617544161784}}
{"text": "#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_interp2d.h>\n#include <gsl/gsl_spline2d.h>\n\nconst gsl_interp_type   *types[7];\nconst gsl_interp2d_type *types2d[2];\n\nvoid init(void)\n{\n  types[0]   = gsl_interp_linear;\n  types[1]   = gsl_interp_polynomial;\n  types[2]   = gsl_interp_cspline;\n  types[3]   = gsl_interp_cspline_periodic;\n  types[4]   = gsl_interp_akima;\n  types[5]   = gsl_interp_akima_periodic;\n  types[6]   = gsl_interp_steffen;\n  types2d[0] = gsl_interp2d_bilinear;\n  types2d[1] = gsl_interp2d_bicubic;\n}\n\n/* 1D */\ngsl_interp *mgsl_interp_alloc(int type, size_t size)\n{\n  if(types[0] == NULL) init();\n  return gsl_interp_alloc(types[type], size);\n}\n\nunsigned int mgsl_interp_type_min_size(int type)\n{\n  if(types[0] == NULL) init();\n  return gsl_interp_type_min_size(types[type]);\n}\n\ngsl_spline *mgsl_spline_alloc(int type, size_t size)\n{\n  if(types[0] == NULL) init();\n  return gsl_spline_alloc(types[type], size);\n}\n\n/* 2D */\ngsl_interp2d *mgsl_interp2d_alloc(int type, size_t xsize, size_t ysize)\n{\n  if(types[0] == NULL) init();\n  return gsl_interp2d_alloc(types2d[type], xsize, ysize);\n}\n\nunsigned int mgsl_interp2d_type_min_size(int type)\n{\n  if(types[0] == NULL) init();\n  return gsl_interp2d_type_min_size(types2d[type]);\n}\n\ngsl_spline2d *mgsl_spline2d_alloc(int type, size_t xsize, size_t ysize)\n{\n  if(types[0] == NULL) init();\n  return gsl_spline2d_alloc(types2d[type], xsize, ysize);\n}\n", "meta": {"hexsha": "56e90900cdc1528fd23ae8563fea18e6a6f51d47", "size": 1438, "ext": "c", "lang": "C", "max_stars_repo_path": "src/interpolation.c", "max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Interpolation", "max_stars_repo_head_hexsha": "c38f16cde531bd811e8d01cb5e3f6b7a5582587c", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/interpolation.c", "max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Interpolation", "max_issues_repo_head_hexsha": "c38f16cde531bd811e8d01cb5e3f6b7a5582587c", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interpolation.c", "max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Interpolation", "max_forks_repo_head_hexsha": "c38f16cde531bd811e8d01cb5e3f6b7a5582587c", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3728813559, "max_line_length": 71, "alphanum_fraction": 0.7197496523, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5, "lm_q1q2_score": 0.37158400430624056}}
{"text": "/***********************************************************\n *\tProgram Name: conv.\n *\n *\tA program used to process the data from mcml -\n *\tA Monte Carlo simulation of photon distribution in\n *\tmulti-layered turbid media in ANSI Standard C.\n ****\n *\tCreation Date:\t11/1991.\n *\tCurrent Date:\t6/1992.\n *\n *\tLihong Wang, Ph. D.\n *\tSteven L. Jacques, Ph. D.\n *\tLaser Biology Research Laboratory - 17\n *\tM.D. Anderson Cancer Center\n *\tUniversity of Texas\n *\t1515 Holcombe Blvd.\n *\tHouston, TX 77030\n *\tUSA\n *\n ****\n *\tGeneral Naming Conventions:\n *\tPreprocessor names: all capital letters,\n *\t\te.g. #define PREPROCESSORS\n *\tGlobals: first letter of each word is capital, no\n *\t\tunderscores,\n *\t\te.g. short GlobalVar;\n *\tDummy variables:  first letter of each word is capital,\n *\t\tand words are connected by underscores,\n *\t\te.g. void NiceFunction(char Dummy_Var);\n *\tLocal variables:  all lower cases, words are connected\n *\t\tby underscores,\n *\t\te.g. short local_var;\n *\tFunction names or data types:  same as Globals.\n *\n ****\n *\tDimension of length: cm.\n *\n ****/\n\n#ifndef __MCML_CONV_H__\n#define __MCML_CONV_H__\n\n#include <math.h>\n#include <new>\n#include <string>\n#include <algorithm>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_sf_bessel.h>\n#include \"mcml_model.h\"\n\n#define GAUSSLIMIT 4\n#define PI 3.1415926\n\n#define SIGN(x) ((x)>=0 ? 1:-1)\n\n/****************** Classes *****************************/\n\nclass Beam {\n/* Beam class - incident light beam class\n        Parameters to describe a photon beam.\n        Pencil: infinitely narrow beam. This is default for the\n            beam from the mcml output.\n        Flat:\tFlat beam with radius R.\n        Gaussian:\tGaussian with 1/e2 radius R.\n        Others: general beam described by points with interpolation.\n        Class instance variables:\n            type - incident beam type, FLAT or GAUSSIAN\n            P - total beam power/energy [W or J]\n            R - beam radius, defined as 1/e^2 for Gaussian beam [cm]\n        Methods:\n            \n*/\n  public:\n    enum BeamType {\n        FLAT,\n        GAUSSIAN\n    };\n    BeamType type;\t\t\t// beam type\n    double P;       // total power. [J or W]\n    double R;       // radius. [cm]\n\n};\n\n\n\n\nclass Node {\n/* Node class - node link list binary tree class\n        Data structures for the binary tree used to store part of\n        the integrand evaluation.\n        \n        Class instance variables:\n            x - x grid node position\n            y - y grid node position\n            left - left node pointer\n            right - right node pointer          \n        Methods:            \n*/\n\n  public:\n    double x;\n    double y;\n    Node * left;\n    Node * right;\n\n    Node () : left (nullptr), right (nullptr) {};\n    static Node * FillNode(double x, double y);\n    static Node * SearchNode(Node * tree, double x);\n    static void InsertNode(Node * tree, double x, double y);\n    static void FreeTree(Node * tree);\n};\n\n\n\nclass ConvVar {\n/* ConvVar class - convoluation variables class\n        A global structure to pass the current coordinate of the\n        physical quantities being evaluated and the pointers of the\n        input and output parameters to the integration function.\n        \n        Class instance variables:\n            r - r position\n            iz - iz index\n            ia - ia index\n            tree - A tree to store ITheta() & ExpBessI0().           \n        Methods:\n            \n*/\n    \n  public:\n    double r;\n    short iz;\n    short ia;\n    Node * tree;      // A tree to store ITheta() & ExpBessI0().\n\n    ConvVar () : tree (nullptr) {};\n};\n\n\n\nclass ConvInput {\n/* ConvInput class - beam convolution input class\n        Input parameters for each independent run.\n        z and r are for the cylindrical coordinate system. [cm]\n        a is for the angle alpha between the photon exiting\n        direction and the surface normal. [radian]\n        The grid line separations in z, r, and alpha\n        directions are dz, dr, and da respectively.  The numbers\n        of grid lines in z, r, and alpha directions are\n        nz, nr, and na respectively.\n        The member layerspecs will point to an array of\n        structures which store parameters of each layer.\n        This array has (number_layers + 2) elements. One\n        element is for a layer.\n        The layers 0 and (num_layers + 1) are for top ambient\n        medium and the bottom ambient medium respectively.\n        For convolution, the grid line separations in z, and alpha\n        directions are still dz, and da respectively.  The numbers\n        of grid lines in z, and alpha directions are still\n        nz, and na respectively. However, the grid line separation\n        and the number of grid lines in r direction are drc and\n        nrc respectively.\n        Class instance variables:\n            beam - incident beam class instance object\n            drc - convolution r grid separation.[cm]\n            nrc - convolution array range 0..nrc-1.\n            eps - relative error in convolution           \n        Methods:\n            \n*/\n\n  public:\n    Beam beam;    // incident beam of finite size\n    double drc;\n    short nrc;\n    MCMLModel mcmlModel;\n    ConvVar convVar;\n    \n    void SelectConvInput (MCMLModel mcmlModelSet, \n          Beam::BeamType beamType = Beam::FLAT, double P = 1.0, double R = 0);\n    void FreeConvInput();       \n};     \n\n\n\nclass MCMLConv : public ConvInput {\n/* MCMLConv class - multi-layered photon scattering model beam convolution\n        inherits from ConvInput beam setup\n        Structures for scored physical quantities\n        from mcml and to be convolved for photon\n        beams of finite size.  Therefore, \"Out\"\n        here means the output of both mcml and conv.\n        The member allocated is used to keep the status\n        of the arrays.  It is set to 1 if all the arrays\n        are allocated and assigned values.  It is set to\n        0 otherwise.\n        z and r represent z and r coordinates of the\n        cylindrical coordinate system. [cm]\n        a is the angle alpha between the photon exiting\n        direction and the normal to the surfaces. [radian]\n        See comments of the InputStruct.\n        See manual for the physcial quantities.\n        Class instance variables:\n            Rd_rac - convolved data. [J/(cm2 sr)]\n            Rd_rc - 1D radial distribution of diffuse reflectance [J/cm2]\n            A_rzc - 2D probability density in turbid media over r & z [J/cm3]\n            Tt_rac - 2D distribution of total transmittance [J/(cm2 sr)]\n            Tt_rc - 1D radial distribution of transmittance [J/cm2]\n        Methods:\n            \n*/\n  private:\n    void ConvRd_ra ();\n    void ConvRd_r ();\n    void ConvA_rz ();\n    void ConvTt_ra ();\n    void ConvTt_r ();\n    void ConvA2F();    \n  \n  public:\n    double ** Rd_rac;\n    double * Rd_rc;\n    double ** A_rzc;\n    double ** Tt_rac;\n    double * Tt_rc;\n    double ** F_rzc;\n\n    MCMLConv () : Rd_rac (nullptr), Rd_rc (nullptr), A_rzc (nullptr), \n      Tt_rac (nullptr), Tt_rc (nullptr), F_rzc (nullptr) {};\n    void SelectMCMLConv (MCMLModel mcmlModelSet, std::string beamType,\n          double P, double R);\n    void FreeMCMLConv ();\n    void RunConv ();\n    double CenterHalfMaxDepth ();\n    double SurfaceHalfMaxWidth ();      \n};\n\n\n\n#endif    //__MCML_CONV_H__\n\n", "meta": {"hexsha": "0da282e58b1de27e7f2a244ffa40bb4a3b1210a7", "size": 7295, "ext": "h", "lang": "C", "max_stars_repo_path": "mcml_conv.h", "max_stars_repo_name": "harveyiliu/mcml-photon-scattering-cpp", "max_stars_repo_head_hexsha": "a60c399beced68778bc96ed5527666f7ce5bed7d", "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": "mcml_conv.h", "max_issues_repo_name": "harveyiliu/mcml-photon-scattering-cpp", "max_issues_repo_head_hexsha": "a60c399beced68778bc96ed5527666f7ce5bed7d", "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": "mcml_conv.h", "max_forks_repo_name": "harveyiliu/mcml-photon-scattering-cpp", "max_forks_repo_head_hexsha": "a60c399beced68778bc96ed5527666f7ce5bed7d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-02T16:54:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T16:54:12.000Z", "avg_line_length": 30.1446280992, "max_line_length": 78, "alphanum_fraction": 0.6167237834, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.371524154492938}}
{"text": "/**\n *\n * @file testing_zposv.c\n *\n *  PLASMA testing routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Bilel Hadri, Hatem Ltaief\n * @date 2010-11-15\n * @precisions normal z -> c d s\n *\n **/\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#include <plasma.h>\n#include <cblas.h>\n#include <lapacke.h>\n#include <core_blas.h>\n#include \"testing_zmain.h\"\n\nenum blas_order_type {\n            blas_rowmajor = 101,\n            blas_colmajor = 102 };\n\nenum blas_cmach_type {\n            blas_base      = 151,\n            blas_t         = 152,\n            blas_rnd       = 153,\n            blas_ieee      = 154,\n            blas_emin      = 155,\n            blas_emax      = 156,\n            blas_eps       = 157,\n            blas_prec      = 158,\n            blas_underflow = 159,\n            blas_overflow  = 160,\n            blas_sfmin     = 161};\n\nenum blas_norm_type {\n            blas_one_norm       = 171,\n            blas_real_one_norm  = 172,\n            blas_two_norm       = 173,\n            blas_frobenius_norm = 174,\n            blas_inf_norm       = 175,\n            blas_real_inf_norm  = 176,\n            blas_max_norm       = 177,\n            blas_real_max_norm  = 178 };\n\nstatic void\nBLAS_error(char *rname, int err, int val, int x) {\n  fprintf( stderr, \"%s %d %d %d\\n\", rname, err, val, x );\n  abort();\n}\n\nstatic\nvoid\nBLAS_zge_norm(enum blas_order_type order, enum blas_norm_type norm,\n  int m, int n, const PLASMA_Complex64_t *a, int lda, double *res) {\n  int i, j; float anorm, v;\n  char rname[] = \"BLAS_zge_norm\";\n\n  if (order != blas_colmajor) BLAS_error( rname, -1, order, 0 );\n\n  if (norm == blas_frobenius_norm) {\n    anorm = 0.0f;\n    for (j = n; j; --j) {\n      for (i = m; i; --i) {\n        v = a[0];\n        anorm += v * v;\n        a++;\n      }\n      a += lda - m;\n    }\n    anorm = sqrt( anorm );\n  } else if (norm == blas_inf_norm) {\n    anorm = 0.0f;\n    for (i = 0; i < m; ++i) {\n      v = 0.0f;\n      for (j = 0; j < n; ++j) {\n        v += cabs( a[i + j * lda] );\n      }\n      if (v > anorm)\n        anorm = v;\n    }\n  } else {\n    BLAS_error( rname, -2, norm, 0 );\n    return;\n  }\n\n  if (res) *res = anorm;\n}\n\nstatic\ndouble\nBLAS_dpow_di(double x, int n) {\n  double rv = 1.0;\n\n  if (n < 0) {\n    n = -n;\n    x = 1.0 / x;\n  }\n\n  for (; n; n >>= 1, x *= x) {\n    if (n & 1)\n      rv *= x;\n  }\n\n  return rv;\n}\n\nstatic\ndouble\nBLAS_dfpinfo(enum blas_cmach_type cmach) {\n  double eps = 1.0, r = 1.0, o = 1.0, b = 2.0;\n  int t = 53, l = 1024, m = -1021;\n  char rname[] = \"BLAS_dfpinfo\";\n\n  if ((sizeof eps) == sizeof(float)) {\n    t = 24;\n    l = 128;\n    m = -125;\n  } else {\n    t = 53;\n    l = 1024;\n    m = -1021;\n  }\n\n  /* for (i = 0; i < t; ++i) eps *= half; */\n  eps = BLAS_dpow_di( b, -t );\n  /* for (i = 0; i >= m; --i) r *= half; */\n  r = BLAS_dpow_di( b, m-1 );\n\n  o -= eps;\n  /* for (i = 0; i < l; ++i) o *= b; */\n  o = (o * BLAS_dpow_di( b, l-1 )) * b;\n\n  switch (cmach) {\n    case blas_eps: return eps;\n    case blas_sfmin: return r;\n    default:\n      BLAS_error( rname, -1, cmach, 0 );\n      break;\n  }\n  return 0.0;\n}\n\nstatic int check_factorization(int, PLASMA_Complex64_t*, PLASMA_Complex64_t*, int, int , double);\nstatic int check_solution(int, int, PLASMA_Complex64_t*, int, PLASMA_Complex64_t*, PLASMA_Complex64_t*, int, double);\nstatic int check_estimator(PLASMA_enum, int, PLASMA_Complex64_t *, int,\n                           PLASMA_Complex64_t *, double, double,\n                           double);\n\nint testing_zposv(int argc, char **argv)\n{\n\n    /* Check for number of arguments*/\n    if (argc != 4){\n        USAGE(\"POSV\", \"N LDA NRHS LDB\",\n              \"   - N    : the size of the matrix\\n\"\n              \"   - LDA  : leading dimension of the matrix A\\n\"\n              \"   - NRHS : number of RHS\\n\"\n              \"   - LDB  : leading dimension of the RHS B\\n\");\n        return -1;\n    }\n\n    int N     = atoi(argv[0]);\n    int LDA   = atoi(argv[1]);\n    int NRHS  = atoi(argv[2]);\n    int LDB   = atoi(argv[3]);\n    double eps;\n    int info_solution, info_factorization;\n    int u, trans1, trans2;\n\n    PLASMA_Complex64_t *A1   = (PLASMA_Complex64_t *)malloc(LDA*N*sizeof(PLASMA_Complex64_t));\n    PLASMA_Complex64_t *A2   = (PLASMA_Complex64_t *)malloc(LDA*N*sizeof(PLASMA_Complex64_t));\n    PLASMA_Complex64_t *B1   = (PLASMA_Complex64_t *)malloc(LDB*NRHS*sizeof(PLASMA_Complex64_t));\n    PLASMA_Complex64_t *B2   = (PLASMA_Complex64_t *)malloc(LDB*NRHS*sizeof(PLASMA_Complex64_t));\n\n    /* Check if unable to allocate memory */\n    if ((!A1)||(!A2)||(!B1)||(!B2)){\n        printf(\"Out of Memory \\n \");\n        return -2;\n    }\n\n    eps = BLAS_dfpinfo( blas_eps );\n\n    for(u=0; u<2; u++) {\n\n        trans1 = uplo[u] == PlasmaUpper ? PlasmaConjTrans : PlasmaNoTrans;\n        trans2 = uplo[u] == PlasmaUpper ? PlasmaNoTrans : PlasmaConjTrans;\n\n        /*-------------------------------------------------------------\n         *  TESTING ZPOSV\n         */\n\n        /* Initialize A1 and A2 for Symmetric Positif Matrix */\n        PLASMA_zplghe( (double)N, N, A1, LDA, 51 );\n        PLASMA_zlacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA );\n\n        /* Initialize B1 and B2 */\n        PLASMA_zplrnt( N, NRHS, B1, LDB, 371 );\n        PLASMA_zlacpy( PlasmaUpperLower, N, NRHS, B1, LDB, B2, LDB );\n\n        printf(\"\\n\");\n        printf(\"------ TESTS FOR PLASMA ZPOSV ROUTINE -------  \\n\");\n        printf(\"            Size of the Matrix %d by %d\\n\", N, N);\n        printf(\"\\n\");\n        printf(\" The matrix A is randomly generated for each test.\\n\");\n        printf(\"============\\n\");\n        printf(\" The relative machine precision (eps) is to be %e \\n\", eps);\n        printf(\" Computational tests pass if scaled residuals are less than 60.\\n\");\n\n        /* PLASMA ZPOSV */\n        PLASMA_zposv(uplo[u], N, NRHS, A2, LDA, B2, LDB);\n\n        /* Check the factorization and the solution */\n        info_factorization = check_factorization( N, A1, A2, LDA, uplo[u], eps);\n        info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB, eps);\n\n        if ( (info_solution == 0) && (info_factorization == 0) ) {\n            printf(\"***************************************************\\n\");\n            printf(\" ---- TESTING ZPOSV(%s) ...................... PASSED !\\n\", uplostr[u]);\n            printf(\"***************************************************\\n\");\n        }\n        else {\n            printf(\"***************************************************\\n\");\n            printf(\" - TESTING ZPOSV(%s) ... FAILED !\\n\", uplostr[u]);\n            printf(\"***************************************************\\n\");\n        }\n\n        /*-------------------------------------------------------------\n         *  TESTING ZPOTRF + ZPOTRS\n         */\n\n        /* Initialize A1 and A2 for Symmetric Positif Matrix */\n        PLASMA_zplghe( (double)N, N, A1, LDA, 51 );\n        PLASMA_zlacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA );\n\n        /* Initialize B1 and B2 */\n        PLASMA_zplrnt( N, NRHS, B1, LDB, 371 );\n        PLASMA_zlacpy( PlasmaUpperLower, N, NRHS, B1, LDB, B2, LDB );\n\n        /* Plasma routines */\n        PLASMA_zpotrf(uplo[u], N, A2, LDA);\n        PLASMA_zpotrs(uplo[u], N, NRHS, A2, LDA, B2, LDB);\n\n        printf(\"\\n\");\n        printf(\"------ TESTS FOR PLASMA ZPOTRF + ZPOTRS ROUTINE -------  \\n\");\n        printf(\"            Size of the Matrix %d by %d\\n\", N, N);\n        printf(\"\\n\");\n        printf(\" The matrix A is randomly generated for each test.\\n\");\n        printf(\"============\\n\");\n        printf(\" The relative machine precision (eps) is to be %e \\n\", eps);\n        printf(\" Computational tests pass if scaled residuals are less than 60.\\n\");\n\n        /* Check the factorization and the solution */\n        info_factorization = check_factorization( N, A1, A2, LDA, uplo[u], eps);\n        info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB, eps);\n\n        if ((info_solution == 0)&(info_factorization == 0)){\n            printf(\"***************************************************\\n\");\n            printf(\" ---- TESTING ZPOTRF + ZPOTRS (%s)............ PASSED !\\n\", uplostr[u]);\n            printf(\"***************************************************\\n\");\n        }\n        else{\n            printf(\"****************************************************\\n\");\n            printf(\" - TESTING ZPOTRF + ZPOTRS (%s)... FAILED !\\n\", uplostr[u]);\n            printf(\"****************************************************\\n\");\n        }\n\n        /*-------------------------------------------------------------\n         *  TESTING ZPOTRF + ZPTRSM + ZTRSM\n         */\n\n        /* Initialize A1 and A2 for Symmetric Positif Matrix */\n        PLASMA_zplghe( (double)N, N, A1, LDA, 51 );\n        PLASMA_zlacpy( PlasmaUpperLower, N, N, A1, LDA, A2, LDA );\n\n        /* Initialize B1 and B2 */\n        PLASMA_zplrnt( N, NRHS, B1, LDB, 371 );\n        PLASMA_zlacpy( PlasmaUpperLower, N, NRHS, B1, LDB, B2, LDB );\n\n        /* PLASMA routines */\n        PLASMA_zpotrf(uplo[u], N, A2, LDA);\n        PLASMA_ztrsm(PlasmaLeft, uplo[u], trans1, PlasmaNonUnit,\n                     N, NRHS, 1.0, A2, LDA, B2, LDB);\n        PLASMA_ztrsm(PlasmaLeft, uplo[u], trans2, PlasmaNonUnit,\n                     N, NRHS, 1.0, A2, LDA, B2, LDB);\n\n        printf(\"\\n\");\n        printf(\"------ TESTS FOR PLASMA ZPOTRF + ZTRSM + ZTRSM  ROUTINE -------  \\n\");\n        printf(\"            Size of the Matrix %d by %d\\n\", N, N);\n        printf(\"\\n\");\n        printf(\" The matrix A is randomly generated for each test.\\n\");\n        printf(\"============\\n\");\n        printf(\" The relative machine precision (eps) is to be %e \\n\", eps);\n        printf(\" Computational tests pass if scaled residuals are less than 60.\\n\");\n\n        /* Check the factorization and the solution */\n        info_factorization = check_factorization( N, A1, A2, LDA, uplo[u], eps);\n        info_solution = check_solution(N, NRHS, A1, LDA, B1, B2, LDB, eps);\n\n        if ((info_solution == 0)&(info_factorization == 0)){\n            printf(\"***************************************************\\n\");\n            printf(\" ---- TESTING ZPOTRF + ZTRSM + ZTRSM (%s)..... PASSED !\\n\", uplostr[u]);\n            printf(\"***************************************************\\n\");\n        }\n        else{\n            printf(\"***************************************************\\n\");\n            printf(\" - TESTING ZPOTRF + ZTRSM + ZTRSM (%s)... FAILED !\\n\", uplostr[u]);\n            printf(\"***************************************************\\n\");\n        }\n\n        /*-------------------------------------------------------------\n         *  TESTING ZPOCON on the last call\n         */\n        {\n            double Anorm = PLASMA_zlanhe( PlasmaOneNorm, uplo[u], N, A1, LDA );\n            double Acond;\n\n            info_solution = PLASMA_zpocon(uplo[u], N, A2, LDA, Anorm, &Acond);\n            if ( info_solution == 0 ) {\n                info_solution = check_estimator(uplo[u], N, A1, LDA, A2, Anorm, Acond, eps);\n            } else {\n                printf(\" PLASMA_zpocon returned info = %d\\n\", info_solution );\n            }\n            if ((info_solution == 0)){\n                printf(\"***************************************************\\n\");\n                printf(\" ---- TESTING ZPOTRF + ZPOCON (%s) ........... PASSED !\\n\", uplostr[u]);\n                printf(\"***************************************************\\n\");\n            }\n            else{\n                printf(\"**************************************************\\n\");\n                printf(\" - TESTING ZPOTRF + ZPOCON (%s) ... FAILED !\\n\", uplostr[u]);\n                printf(\"**************************************************\\n\");\n            }\n        }\n    }\n\n    free(A1); free(A2); free(B1); free(B2);\n\n    return 0;\n}\n\n\n/*------------------------------------------------------------------------\n *  Check the factorization of the matrix A2\n */\nstatic int check_factorization(int N, PLASMA_Complex64_t *A1, PLASMA_Complex64_t *A2, int LDA, int uplo, double eps)\n{\n    double Anorm, Rnorm;\n    PLASMA_Complex64_t alpha;\n    int info_factorization;\n    int i,j;\n\n    PLASMA_Complex64_t *Residual = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t));\n    PLASMA_Complex64_t *L1       = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t));\n    PLASMA_Complex64_t *L2       = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t));\n    double *work              = (double *)malloc(N*sizeof(double));\n\n    memset((void*)L1, 0, N*N*sizeof(PLASMA_Complex64_t));\n    memset((void*)L2, 0, N*N*sizeof(PLASMA_Complex64_t));\n\n    alpha= 1.0;\n\n    LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N);\n\n    /* Dealing with L'L or U'U  */\n    if (uplo == PlasmaUpper){\n        LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N);\n        LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N);\n        cblas_ztrmm(CblasColMajor, CblasLeft, CblasUpper, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N);\n    }\n    else{\n        LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N);\n        LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N);\n        cblas_ztrmm(CblasColMajor, CblasRight, CblasLower, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N);\n    }\n\n    /* Compute the Residual || A -L'L|| */\n    for (i = 0; i < N; i++)\n        for (j = 0; j < N; j++)\n           Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i];\n\n    BLAS_zge_norm( blas_colmajor, blas_inf_norm, N, N, Residual, N, &Rnorm );\n    BLAS_zge_norm( blas_colmajor, blas_inf_norm, N, N, A1, LDA, &Anorm );\n\n    printf(\"============\\n\");\n    printf(\"Checking the Cholesky Factorization \\n\");\n    printf(\"-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \\n\",Rnorm/(Anorm*N*eps));\n\n    if ( isnan(Rnorm/(Anorm*N*eps)) || isinf(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 60.0) ){\n        printf(\"-- Factorization is suspicious ! \\n\");\n        info_factorization = 1;\n    }\n    else{\n        printf(\"-- Factorization is CORRECT ! \\n\");\n        info_factorization = 0;\n    }\n\n    free(Residual); free(L1); free(L2); free(work);\n\n    return info_factorization;\n}\n\n\n/*------------------------------------------------------------------------\n *  Check the accuracy of the solution of the linear system\n */\n\nstatic int check_solution(int N, int NRHS, PLASMA_Complex64_t *A1, int LDA, PLASMA_Complex64_t *B1, PLASMA_Complex64_t *B2, int LDB, double eps )\n{\n    int info_solution;\n    double Rnorm, Anorm, Xnorm, Bnorm, result;\n    PLASMA_Complex64_t alpha, beta;\n    double *work = (double *)malloc(N*sizeof(double));\n\n    alpha = 1.0;\n    beta  = -1.0;\n\n    BLAS_zge_norm( blas_colmajor, blas_inf_norm, N, NRHS, B2, LDB, &Xnorm );\n    BLAS_zge_norm( blas_colmajor, blas_inf_norm, N, N,    A1, LDA, &Anorm );\n    BLAS_zge_norm( blas_colmajor, blas_inf_norm, N, NRHS, B1, LDB, &Bnorm );\n\n    cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, N, NRHS, N, CBLAS_SADDR(alpha), A1, LDA, B2, LDB, CBLAS_SADDR(beta), B1, LDB);\n    BLAS_zge_norm( blas_colmajor, blas_inf_norm, N, NRHS, B1, LDB, &Rnorm );\n\n    if (getenv(\"PLASMA_TESTING_VERBOSE\"))\n      printf( \"||A||_oo=%f\\n||X||_oo=%f\\n||B||_oo=%f\\n||A X - B||_oo=%e\\n\", Anorm, Xnorm, Bnorm, Rnorm );\n\n    result = Rnorm / ( (Anorm*Xnorm+Bnorm)*N*eps ) ;\n    printf(\"============\\n\");\n    printf(\"Checking the Residual of the solution \\n\");\n    printf(\"-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \\n\", result);\n\n    if (  isnan(Xnorm) || isinf(Xnorm) || isnan(result) || isinf(result) || (result > 60.0) ) {\n        printf(\"-- The solution is suspicious ! \\n\");\n        info_solution = 1;\n     }\n    else{\n        printf(\"-- The solution is CORRECT ! \\n\");\n        info_solution = 0;\n    }\n\n    free(work);\n\n    return info_solution;\n}\n\n\n/*------------------------------------------------------------------------\n *  Check the accuracy of the condition estimator\n */\nstatic int check_estimator(PLASMA_enum uplo, int N, PLASMA_Complex64_t *A1, int LDA,\n                           PLASMA_Complex64_t *A2, double Anorm, double Acond,\n                           double eps)\n{\n    int info_solution;\n    double result, Acond_lapack;\n    double invcond, invcond_lapack;\n\n    info_solution = LAPACKE_zpocon(LAPACK_COL_MAJOR, lapack_const(uplo), N, A2, LDA, Anorm, &Acond_lapack);\n\n    if ( info_solution != 0 ) {\n        printf(\" PLASMA_zgecon returned info = %d\\n\", info_solution );\n        return info_solution;\n    }\n\n    invcond_lapack = 1. / ( Acond_lapack );\n    invcond        = 1. / ( Acond );\n\n    printf(\"============\\n\");\n    printf(\"Checking the condition number \\n\");\n    printf(\"-- Acond_plasma = %e, Acond_lapack = %e \\n\"\n           \"-- Ainvcond_plasma = %e, Ainvcond_lapack = %e \\n\",\n           Acond, Acond_lapack, invcond, invcond_lapack );\n\n    result = fabs( Acond_lapack - Acond ) / eps;\n    if ( result > 60. ) {\n        printf(\"-- The solution is suspicious ! \\n\");\n        info_solution = 1;\n     }\n    else{\n        printf(\"-- The solution is CORRECT ! \\n\");\n        info_solution = 0;\n    }\n    return info_solution;\n}\n\n", "meta": {"hexsha": "f65cdc5d921fa8fd2dde9c81c3efd9cb07f46b28", "size": 17184, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/testing_zposv.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/testing_zposv.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/testing_zposv.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.7854251012, "max_line_length": 145, "alphanum_fraction": 0.5071578212, "num_tokens": 5189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3715143078706121}}
{"text": "#ifndef __GSLPRINT_H__\n#define __GSLPRINT_H__\n\n#include <stdio.h>\n#include <iostream>\n#include <math.h>\n#include <fstream>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_poly.h>\n#include <gsl/gsl_integration.h>\n\n#endif\n\nvoid gsl_matrix_fprint(FILE * stream, gsl_matrix * target,int rows,int columns, char const * format);\nvoid gsl_vector_fprint(FILE * stream, gsl_vector * target,int length, char const * format);\nvoid gsl_matrix_printf(gsl_matrix * m, int rows, int columns, char const * format);\nvoid gsl_vector_printf(gsl_vector * m,int length, char const * format);\nvoid gsl_vector_complex_fprint(FILE * stream, gsl_vector_complex * target, int length, char const * format);\nvoid gsl_matrix_complex_fprint(FILE * stream, gsl_matrix_complex * target, int rows, int columns, char const * format);\nvoid gsl_matrix_complex_printf(gsl_matrix_complex * target, int rows, int columns, char const * format);\nvoid gsl_vector_complex_fprint(gsl_vector_complex * target, int length, char const * format);\n", "meta": {"hexsha": "18984b08e3465fed4f2185ca72a8f888da4ac24c", "size": 1141, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslprint.h", "max_stars_repo_name": "Walter-Feng/Hartree-Fock", "max_stars_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-08-23T21:27:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T18:50:05.000Z", "max_issues_repo_path": "gslprint.h", "max_issues_repo_name": "Walter-Feng/HomebrewLib", "max_issues_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gslprint.h", "max_forks_repo_name": "Walter-Feng/HomebrewLib", "max_forks_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T13:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T03:11:07.000Z", "avg_line_length": 42.2592592593, "max_line_length": 119, "alphanum_fraction": 0.7782646801, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.3715142991827137}}
{"text": "/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.\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#pragma once\n#ifdef PADDLE_USE_MKLML\n#include <mkl_cblas.h>\n#include <mkl_lapacke.h>\n#include <mkl_vml_functions.h>\n#endif\n\n#ifdef PADDLE_USE_MKL\n#include <mkl.h>\n#include <mkl_lapacke.h>\n#endif\n\n#ifdef PADDLE_USE_ATLAS\nextern \"C\" {\n#include <cblas.h>\n#include <clapack.h>\n}\n#endif\n\n#ifdef PADDLE_USE_OPENBLAS\n#include <cblas.h>\n#include <lapacke.h>\n#endif\n\n#ifndef LAPACK_FOUND\nextern \"C\" {\n#include <cblas.h>\nint LAPACKE_sgetrf(int matrix_layout, int m, int n, float* a, int lda,\n                   int* ipiv);\nint LAPACKE_dgetrf(int matrix_layout, int m, int n, double* a, int lda,\n                   int* ipiv);\nint LAPACKE_sgetri(int matrix_layout, int n, float* a, int lda,\n                   const int* ipiv);\nint LAPACKE_dgetri(int matrix_layout, int n, double* a, int lda,\n                   const int* ipiv);\n}\n#endif\n\n#include <cmath>\n\n#include \"paddle/framework/tensor.h\"\n#include \"paddle/platform/device_context.h\"\n#include \"paddle/platform/enforce.h\"\n\nnamespace paddle {\nnamespace operators {\nnamespace math {\n\n// Support continuous memory now\n// If transA = N, and transB = N\n// Then matrixA: M * K, matrixB: K * N matrixC : M * N\n// For more detailed info, please refer to\n// http://www.netlib.org/lapack/explore-html/d4/de2/sgemm_8f.html\ntemplate <typename Place, typename T>\nvoid gemm(const platform::DeviceContext& context, const CBLAS_TRANSPOSE transA,\n          const CBLAS_TRANSPOSE transB, const int M, const int N, const int K,\n          const T alpha, const T* A, const T* B, const T beta, T* C);\n\n// matrix multiply with continuous memory\ntemplate <typename Place, typename T>\nvoid matmul(const platform::DeviceContext& context,\n            const framework::Tensor& matrix_a, bool trans_a,\n            const framework::Tensor& matrix_b, bool trans_b, T alpha,\n            framework::Tensor* matrix_out, T beta);\n\n}  // namespace math\n}  // namespace operators\n}  // namespace paddle\n", "meta": {"hexsha": "d8518e77fa7b4abdbcf08b7983013c24806e14ca", "size": 2502, "ext": "h", "lang": "C", "max_stars_repo_path": "paddle/operators/math/math_function.h", "max_stars_repo_name": "AI-books/Paddle", "max_stars_repo_head_hexsha": "5b5f4f514047975ac09ec42b31e46dabf235e7dd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paddle/operators/math/math_function.h", "max_issues_repo_name": "AI-books/Paddle", "max_issues_repo_head_hexsha": "5b5f4f514047975ac09ec42b31e46dabf235e7dd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paddle/operators/math/math_function.h", "max_forks_repo_name": "AI-books/Paddle", "max_forks_repo_head_hexsha": "5b5f4f514047975ac09ec42b31e46dabf235e7dd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T04:27:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-04T04:27:15.000Z", "avg_line_length": 30.1445783133, "max_line_length": 79, "alphanum_fraction": 0.7134292566, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.37145854098498254}}
{"text": "/**\n *\n * @file core_zsyssq.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.8.0\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @precisions normal z -> c d s\n *\n **/\n#include <math.h>\n#include <lapacke.h>\n#include \"common.h\"\n\n#define COMPLEX\n\n#define UPDATE( __nb, __value )                                         \\\n    if (__value != 0. ){                                                \\\n        if ( *scale < __value ) {                                       \\\n            *sumsq = __nb + (*sumsq) * ( *scale / __value ) * ( *scale / __value ); \\\n            *scale = __value;                                           \\\n        } else {                                                        \\\n            *sumsq = *sumsq + __nb * ( __value / *scale ) *  ( __value / *scale ); \\\n        }                                                               \\\n    }\n\n/*****************************************************************************\n *\n * @ingroup dplasma_cores_complex64\n *\n *  CORE_zsyssq returns the values scl and ssq such that\n *\n *    ( scl**2 )*ssq = sum( A( i, j )**2 ) + ( scale**2 )*sumsq,\n *                     i,j\n *\n * with i from 0 to N-1 and j form 0 to N-1. The value of sumsq is\n * assumed to be at least unity and the value of ssq will then satisfy\n *\n *    1.0 .le. ssq .le. ( sumsq + 2*n*n ).\n *\n * scale is assumed to be non-negative and scl returns the value\n *\n *    scl = max( scale, abs( real( A( i, j ) ) ), abs( aimag( A( i, j ) ) ) ),\n *          i,j\n *\n * scale and sumsq must be supplied in SCALE and SUMSQ respectively.\n * SCALE and SUMSQ are overwritten by scl and ssq respectively.\n *\n * The routine makes only one pass through the tile triangular part of the\n * symmetric tile A defined by uplo.\n * See also LAPACK zlassq.f\n *\n *******************************************************************************\n *\n *  @param[in] uplo\n *          Specifies whether the upper or lower triangular part of\n *          the symmetric matrix A is to be referenced as follows:\n *          = PlasmaLower:     Only the lower triangular part of the\n *                             symmetric matrix A is to be referenced.\n *          = PlasmaUpper:     Only the upper triangular part of the\n *                             symmetric matrix A is to be referenced.\n *\n *  @param[in] N\n *          The number of columns and rows in the tile A.\n *\n *  @param[in] A\n *          The N-by-N matrix on which to compute the norm.\n *\n *  @param[in] LDA\n *          The leading dimension of the tile A. LDA >= max(1,N).\n *\n *  @param[in,out] scale\n *          On entry, the value  scale  in the equation above.\n *          On exit, scale is overwritten with the value scl.\n *\n *  @param[in,out] sumsq\n *          On entry, the value  sumsq  in the equation above.\n *          On exit, SUMSQ is overwritten with the value ssq.\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *          \\retval -k, the k-th argument had an illegal value\n *\n */\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zsyssq = PCORE_zsyssq\n#define CORE_zsyssq PCORE_zsyssq\n#endif\nint CORE_zsyssq(PLASMA_enum uplo, int N,\n                const PLASMA_Complex64_t *A, int LDA,\n                double *scale, double *sumsq)\n{\n    int i, j;\n    double tmp;\n    double *ptr;\n\n    if ( uplo == PlasmaUpper ) {\n        for(j=0; j<N; j++) {\n            ptr = (double*) ( A + j * LDA );\n\n            for(i=0; i<j; i++, ptr++) {\n\n                tmp = fabs(*ptr);\n                UPDATE( 2., tmp );\n\n#ifdef COMPLEX\n                ptr++;\n                tmp = fabs(*ptr);\n                UPDATE( 2., tmp );\n#endif\n            }\n\n            /* Diagonal */\n            tmp = fabs(*ptr);\n            UPDATE( 1., tmp );\n\n#ifdef COMPLEX\n            ptr++;\n            tmp = fabs(*ptr);\n            UPDATE( 1., tmp );\n#endif\n        }\n    } else {\n\n        for(j=0; j<N; j++) {\n            ptr = (double*) ( A + j * LDA + j);\n\n            /* Diagonal */\n            tmp = fabs(*ptr);\n            UPDATE( 1., tmp );\n            ptr++;\n\n#ifdef COMPLEX\n            tmp = fabs(*ptr);\n            UPDATE( 1., tmp );\n            ptr++;\n#endif\n\n            for(i=j+1; i<N; i++, ptr++) {\n\n                tmp = fabs(*ptr);\n                UPDATE( 2., tmp );\n\n#ifdef COMPLEX\n                ptr++;\n                tmp = fabs(*ptr);\n                UPDATE( 2., tmp );\n#endif\n            }\n        }\n    }\n    return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "82843a2b6f46b905d5a53047411efd51c12dc275", "size": 4633, "ext": "c", "lang": "C", "max_stars_repo_path": "src/cores/core_zsyssq.c", "max_stars_repo_name": "therault/dplasma", "max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z", "max_issues_repo_path": "src/cores/core_zsyssq.c", "max_issues_repo_name": "therault/dplasma", "max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z", "max_forks_repo_path": "src/cores/core_zsyssq.c", "max_forks_repo_name": "therault/dplasma", "max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z", "avg_line_length": 28.95625, "max_line_length": 85, "alphanum_fraction": 0.4558601338, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3714505028394518}}
{"text": "#ifndef PAHEMISSIONMODEL_H_\n#define PAHEMISSIONMODEL_H_\n\n#include \"Exception.h\"\n\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <utility>\n#include <vector>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_roots.h>\n\nclass PAHEmissionModel {\n\npublic:\n  static double _energy;\n\n  static double _frequency;\n\n  static double solveInitialTemperatureFunc(double temperature,\n                                            void *transitions);\n\n  static double integralOverHeatCapacity(double temperature, void *transitions);\n\n  static double heatCapacity(double temperature, void *transitions);\n\n  static double featureStrength(double temperature, void *transitions);\n\n  static void convertFromFrequencyToWavelength(std::vector<double> &grid);\n\n  static void convertFromFrequencyToWavelength(std::array<double, 2> &grid);\n\n  static void convertFromWavelengthToFrequency(std::vector<double> &grid);\n\n  static void convertFromFrequencyToWavelength(\n      std::vector<std::vector<std::pair<double, double>>> &transitions);\n\n  static void convertFromWavelengthToFrequency(\n      std::vector<std::vector<std::pair<double, double>>> &transitions);\n\n  PAHEmissionModel();\n\n  PAHEmissionModel(\n      const std::vector<std::vector<std::pair<double, double>>> &transitions);\n\n  void setTransitions(\n      const std::vector<std::vector<std::pair<double, double>>> &transitions);\n\n  void getTransitions(\n      std::vector<std::vector<std::pair<double, double>>> &transitions);\n\n  void shiftTransitions(double shift);\n\n  void setGrid(const std::vector<double> &grid);\n\n  void makeGrid(const std::vector<double> &frange, double step);\n\n  void makeGrid(double fmin, double fmax, double step);\n\n  std::vector<double> const &getGrid() const;\n\n  void printTransitions();\n\n  void applyCascadeWithEnergy(double energy, std::vector<double> &temperatures);\n\n  void applyTemperatureWithEnergy(double energy,\n                                  std::vector<double> &temperatures);\n\n  void applyBlackbodyWithTemperature(double temperature);\n\n  void\n  applyBlackbodyWithTemperatureForEach(const std::vector<double> &temperatures);\n\n  void getSpectraAndConvolveWithLorentianOfFHWM(\n      std::vector<std::vector<double>> &vector, double fwhm = 15);\n\n  void getSpectraAndConvolveWithGaussianOfFHWM(\n      std::vector<std::vector<double>> &vector, double fwhm = 15);\n\n  void\n  getSpectraAndConvolveWithDrudeOfFHWM(std::vector<std::vector<double>> &vector,\n                                       double fwhm = 15);\n\nprivate:\n  static constexpr double TemperatureMin = 2.73;\n\n  static constexpr double TemperatureMax = 5000.0;\n\n  static constexpr double RootAccuracy = 1e-4;\n\n  static constexpr double IntegrationAccuracy = 1e-4;\n\n  static constexpr int MaxIterations = 150;\n\n  static constexpr int MaxSteps = 100;\n\n  static constexpr double PlanckConstant = 6.6260693000000018e-27;\n\n  static constexpr double SpeedOfLight = 29979245800.0;\n\n  static constexpr double BoltzmannConstant = 1.3806504e-16;\n\n  std::vector<std::vector<std::pair<double, double>>> _transitions;\n\n  std::vector<double> _grid;\n\n  double _fmin;\n\n  double _fmax;\n\n  double\n  solveInitialTemperature(double energy,\n                          std::vector<std::pair<double, double>> &transitions);\n\n  double Lorentzian(double frequency, double centroid, double hwhm);\n\n  double Gaussian(double frequency, double centroid, double sigma);\n\n  double Drude(double frequency, double centroid, double fwhm);\n\n  double Blackbody(double frequency, double temperature);\n};\n\ninline void PAHEmissionModel::makeGrid(const std::vector<double> &frange,\n                                       double step) {\n  makeGrid(frange[0], frange[1], step);\n}\n\ninline std::vector<double> const &PAHEmissionModel::getGrid() const {\n  return (_grid);\n}\n\ninline double PAHEmissionModel::Lorentzian(double frequency, double centroid,\n                                           double hwhm) {\n  return ((1.0 / M_PI) * hwhm / (pow(frequency - centroid, 2) + pow(hwhm, 2)));\n}\n\ninline double PAHEmissionModel::Gaussian(double frequency, double centroid,\n                                         double sigma) {\n  return ((1.0 / (sigma * sqrt(2.0 * M_PI))) *\n          exp(-pow(frequency - centroid, 2) / (2.0 * pow(sigma, 2))));\n}\n\ninline double PAHEmissionModel::Drude(double frequency, double centroid,\n                                      double fwhm) {\n  return ((2.0 / (fwhm * M_PI)) * pow(fwhm / centroid, 2) /\n          (pow(centroid / frequency - frequency / centroid, 2) +\n           pow(fwhm / centroid, 2)));\n}\n\ninline double PAHEmissionModel::Blackbody(double frequency,\n                                          double temperature) {\n  return (\n      (2.0 * PlanckConstant * SpeedOfLight * SpeedOfLight * pow(frequency, 3)) /\n      (exp(PlanckConstant * SpeedOfLight * frequency /\n           (BoltzmannConstant * temperature)) -\n       1.0));\n}\n\n#endif /* PAHEMISSIONMODEL_H_ */\n", "meta": {"hexsha": "68357558af6090cc35b6d0e7e026250556e86f38", "size": 5016, "ext": "h", "lang": "C", "max_stars_repo_path": "include/PAHEmissionModel.h", "max_stars_repo_name": "PAHdb/CPP-Backend", "max_stars_repo_head_hexsha": "3bd9dc62360c8b97239b4922db32c70c83eb6822", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/PAHEmissionModel.h", "max_issues_repo_name": "PAHdb/CPP-Backend", "max_issues_repo_head_hexsha": "3bd9dc62360c8b97239b4922db32c70c83eb6822", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/PAHEmissionModel.h", "max_forks_repo_name": "PAHdb/CPP-Backend", "max_forks_repo_head_hexsha": "3bd9dc62360c8b97239b4922db32c70c83eb6822", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-23T18:00:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T18:00:50.000Z", "avg_line_length": 29.8571428571, "max_line_length": 80, "alphanum_fraction": 0.6846092504, "num_tokens": 1204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.37141308332325906}}
{"text": "#include <assert.h>\n#include <time.h>\n#include <stdlib.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n#include \"utils/utils.h\"\n#include \"utils/compress.h\"\n#include \"rule.h\"\n\n#define DIRICHLET 1\n#define D_CONST .4\n\n\nvoid populate_buf(uint64_t grule_size, uint8_t* rule_array, char* rule_buf)\n{\n  /* Populate buffer with newly created rule */\n  for (uint64_t v = 0; v < grule_size; v++) {\n    sprintf(&rule_buf[v], \"%\"PRIu8, rule_array[v]);\n  }\n  rule_buf[grule_size] = '\\0';\n}\n\n/**\n * Symmetrize the rule by setting all the states and their symmetries to having\n * the same output.\n */\nvoid symmetrize_rule(uint64_t grule_size,\n                     uint8_t rule_array[grule_size],\n                     int states, int horizon)\n{\n  int side = 2 * horizon + 1;\n  int neigh_size = side * side - 1;\n\n  uint32_t position_180;\n  uint32_t position_90;\n  uint32_t position_270;\n  uint32_t position_vflip;\n  uint32_t position_hflip;\n  uint32_t position_dflip;\n  uint32_t position_aflip;\n\n  /* grule_size can be very big, this array is better on the heap */\n  /* Keep track of already seen positions with book-keeping */\n  uint8_t* book_keep = calloc(grule_size, sizeof(uint8_t));\n\n  int pos;\n\n  for (uint64_t i = 0; i < grule_size; ++i) {\n    /* Skip already seen positions when looping through the rule */\n    if (book_keep[i] == 1) {\n      continue;\n    }\n\n    position_180 = 0;\n    position_90 = 0;\n    position_270 = 0;\n    position_vflip = 0;\n    position_hflip = 0;\n    position_dflip = 0;\n    position_aflip = 0;\n\n    /* Create the representation of the symmetrized position by swapping the\n       states in its number representation. */\n    for (int p = 0; p < neigh_size + 1; ++p) {\n      /* 180\u00b0 rotation */\n      position_180 += (uint32_t)ipow(states, p) *\n        ((i / (uint32_t)ipow(states, neigh_size  - p)) % states);\n\n      /* 90\u00b0 rotation */\n      pos = (neigh_size - side + 1 - (side * (p%side)) + p/side);\n      position_90 += (uint32_t)ipow(states, p) *\n        ((i / (uint32_t)ipow(states, pos)) % states);\n\n      /* 270\u00b0 rotation */\n      position_270 += (uint32_t)ipow(states, p) *\n        ((i / (uint32_t)ipow(states, neigh_size  - pos)) % states);\n\n      /* Vertical flip */\n      pos = (side * (p / side)) + (side - 1 - (p % 3));\n      position_vflip += (uint32_t)ipow(states, p) *\n        ((i / (uint32_t)ipow(states, pos)) % states);\n\n      /* Horizontal flip */\n      if (p/side < side/2) {\n        pos = (p - side + neigh_size + 1)%(neigh_size + 1);\n      } else if (p/side > side/2) {\n        pos = (p + side)%(neigh_size + 1);\n      } else {\n        pos = p;\n      }\n      position_hflip += (uint32_t)ipow(states, p) *\n        ((i / (uint32_t)ipow(states, pos)) % states);\n\n      /* Diagonal flip */\n      pos = neigh_size - ((p % side) * side  + (p / side));\n      position_dflip += (uint32_t)ipow(states, p) *\n        ((i / (uint32_t)ipow(states, pos)) % states);\n\n      /* Antidiagonal flip */\n      pos = ((p % side) * side  + (p / side));\n      position_aflip += (uint32_t)ipow(states, p) *\n        ((i / (uint32_t)ipow(states, pos)) % states);\n\n    }\n\n    /* Add all seen positions to the book to not process them again */\n    book_keep[i] = 1;\n    book_keep[position_180] = 1;\n    book_keep[position_90] = 1;\n    book_keep[position_270] = 1;\n    book_keep[position_vflip] = 1;\n    book_keep[position_hflip] = 1;\n    book_keep[position_dflip] = 1;\n    book_keep[position_aflip] = 1;\n\n    rule_array[position_180] = rule_array[i];\n    rule_array[position_90] = rule_array[i];\n    rule_array[position_270] = rule_array[i];\n    rule_array[position_vflip] = rule_array[i];\n    rule_array[position_hflip] = rule_array[i];\n    rule_array[position_dflip] = rule_array[i];\n    rule_array[position_aflip] = rule_array[i];\n  }\n  free(book_keep);\n}\n\n/**\n * @brief Build a rule from the provided command-line arguments.\n * @param grule_size The size of the rule.\n * @param rule_array The array holding the rule.\n * @param rule_buf A mirror buffer containing a string representation of the\n *                 rule.\n * @param rule_arg The string from which the rule is read.\n * @param states Number of expected states in the rule.\n */\nvoid build_rule_from_args(uint64_t grule_size,\n                          uint8_t rule_array[grule_size],\n                          char rule_buf[grule_size + 1],\n                          char* rule_arg, int states)\n{\n  /* Rule is given in base-(states - 1) format */\n  for (uint64_t s = 0 ; s < grule_size; ++s) {\n    rule_array[s] = rule_arg[s] - '0';\n    rule_buf[s] = rule_arg[s];\n    assert(rule_array[s] < states);\n  }\n  rule_buf[grule_size] = '\\0';\n}\n\n/**\n * Simple double comparison function used for sorting in the rule generation\n * function.\n */\nint comp (const void * elem1, const void * elem2)\n{\n  float f = *((float*)elem1);\n  float s = *((float*)elem2);\n  return (f > s) - (f < s);\n}\n\n/**\n * Generate a random general rule. The rule is written to rule_array and a\n * string  representation is also saved in rule_buf.\n */\nvoid generate_general_rule(uint64_t grule_size,\n                           uint8_t rule_array[grule_size],\n                           char rule_buf[grule_size + 1],\n                           int states, int horizon)\n{\n  int inc;\n\n  /* Choose lambda parameter at random as well as the proportion of\n     transitions to other states */\n  double alphas[states];\n  double theta[states], lambda[states - 1], rand_num;\n\n  /* This method samples the transition probability simplex according to a\n     Dirichlet distribution with parameter D_CONST */\n  if (DIRICHLET == 1) {\n    const gsl_rng_type * T;\n\n    gsl_rng * r;\n    gsl_rng_env_setup();\n\n    T = gsl_rng_default;\n    r = gsl_rng_alloc(T);\n    time_t t;\n    gsl_rng_set(r, (unsigned long)time(&t));\n\n    for (int i = 0; i < states; ++i) {\n      alphas[i] = D_CONST;\n    }\n    gsl_ran_dirichlet(r, states, alphas, theta);\n    lambda[0] = theta[0];\n    for (int i = 1; i < states - 1; ++i) {\n      lambda[i] = theta[i] + lambda[i - 1];\n    }\n\n    gsl_rng_free(r);\n  }\n  /* Second method that samples the simplex uniformly */\n  else {\n    for (int i = 0; i < states - 1; ++i) {\n      lambda[i] = ((double)rand() / (double)((unsigned)RAND_MAX + 1));\n    }\n    qsort(lambda, sizeof(lambda)/sizeof(*lambda), sizeof(*lambda), comp);\n  }\n\n  for (uint64_t v = 0; v < grule_size; v++) {\n    /* Assign the rule to the first state that passes the test */\n    rand_num = (double)rand() / (double)((unsigned)RAND_MAX + 1);\n    inc = 0;\n    while (lambda[inc] < rand_num && inc < states - 1) {\n      ++inc;\n    }\n    rule_array[v] = (uint8_t)inc;\n  }\n\n  symmetrize_rule(grule_size, rule_array, states, horizon);\n\n  populate_buf(grule_size, rule_array, rule_buf);\n}\n\n\nvoid cross_breed(uint64_t grule_size, uint8_t* parent_rule_A,\n                 uint8_t* parent_rule_B, uint8_t* child,\n                 char rule_buf[grule_size], double rate,\n                 int horizon, int states)\n{\n  for (uint64_t i = 0; i < grule_size; ++i) {\n    double rand_num = (double)rand() / (double)((unsigned)RAND_MAX + 1);\n    child[i] = (rate > rand_num) ? parent_rule_A[i]: parent_rule_B[i];\n  }\n\n  perturb_rule(grule_size, child, rule_buf, states, horizon, 0.05);\n}\n\n\nvoid perturb_rule(uint64_t grule_size,\n                  uint8_t rule_array[grule_size],\n                  char rule_buf[grule_size + 1],\n                  int states, int horizon, double rate)\n{\n  for (uint64_t v = 0; v < grule_size; ++v) {\n    /* Perturb transisition outcome with probability rate */\n    double rand_num = (double)rand() / (double)((unsigned)RAND_MAX + 1);\n    if (rand_num < rate) {\n      rule_array[v] += (1 + rand() % (states - 1));\n      rule_array[v] %= states;\n    }\n  }\n\n  symmetrize_rule(grule_size, rule_array, states, horizon);\n  populate_buf(grule_size, rule_array, rule_buf);\n}\n\nvoid make_map(struct Options2D* opts, char* rule_buf, int step)\n{\n  FILE* dic_file;\n  char* fname;\n\n  asprintf(&fname, \"%s/map/%lu.map\", opts->data_dir_name, hash(rule_buf));\n  dic_file = fopen(fname, \"w+\");\n\n  if (dic_file == NULL) {\n    fprintf(stderr, \"Error while opening map file %s.\", fname);\n    exit(1);\n  }\n\n  fprintf(dic_file, \"%s\", rule_buf);\n  fclose(dic_file);\n  free(fname);\n\n  sprintf(rule_buf, \"%lu\", hash(rule_buf));\n  printf(\"%i: Rule %s\\n\", step, rule_buf);\n}\n\nvoid generate_totalistic_rule(uint64_t rule_size, uint8_t rule_array[rule_size],\n                              char rule_buf[rule_size + 1], int states)\n{\n  unsigned long rule_number = 0UL;\n\n  for (uint64_t s = 0 ; s < rule_size; ++s) {\n    rule_array[s] = rand() % states;\n    rule_number += rule_array[s] * ipow(states, s);\n    if (states >= 3) {\n      rule_buf[s] = '0' + rule_array[s];\n    }\n  }\n\n  if (states == 2) {\n    sprintf(rule_buf, \"%lu\", rule_number);\n  }\n}\n", "meta": {"hexsha": "4b351d9d246395d6c0abaf1c20d27cc7b1b8045b", "size": 8747, "ext": "c", "lang": "C", "max_stars_repo_path": "src/automaton/rule.c", "max_stars_repo_name": "smearle/evolving-structures-in-complex-systems", "max_stars_repo_head_hexsha": "7e877c917f83bdd5032959205564ca06928b1a6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T05:38:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T05:38:21.000Z", "max_issues_repo_path": "src/automaton/rule.c", "max_issues_repo_name": "smearle/evolving-structures-in-complex-systems", "max_issues_repo_head_hexsha": "7e877c917f83bdd5032959205564ca06928b1a6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/automaton/rule.c", "max_forks_repo_name": "smearle/evolving-structures-in-complex-systems", "max_forks_repo_head_hexsha": "7e877c917f83bdd5032959205564ca06928b1a6c", "max_forks_repo_licenses": ["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.6508474576, "max_line_length": 80, "alphanum_fraction": 0.6104950269, "num_tokens": 2538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.37125537733049674}}
{"text": "/***************************************************************************\n * data_cf.h is part of Math Graphic Library\n * Copyright (C) 2007-2016 Alexey Balakin <mathgl.abalakin@gmail.ru>       *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU Library General Public License as       *\n *   published by the Free Software Foundation; either version 3 of the    *\n *   License, or (at your option) any later version.                       *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU Library General Public     *\n *   License along with this program; if not, write to the                 *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************/\n#ifndef _MGL_DATAC_CF_H_\n#define _MGL_DATAC_CF_H_\n//-----------------------------------------------------------------------------\n#include \"mgl2/abstract.h\"\n//-----------------------------------------------------------------------------\n#if MGL_HAVE_GSL\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#else\nstruct gsl_vector;\nstruct gsl_matrix;\n#endif\n//-----------------------------------------------------------------------------\n#ifdef __cplusplus\nclass mglDataC;\ntypedef mglDataC* HADT;\nextern \"C\" {\n#else\ntypedef void *HADT;\n#endif\n/// Get integer power of x\ncmdual MGL_EXPORT_CONST mgl_ipowc(mdual x,int n);\ncmdual MGL_EXPORT mgl_ipowc_(mdual *x,int *n);\n/// Get complex number from string. Parse (%g,%g), {%g,%g} and [%g,%g] if adv!=0.\ncmdual MGL_EXPORT mgl_atoc(const char *s, int adv);\n/// Get exp(i*a)\ncmdual MGL_EXPORT_CONST mgl_expi(mdual a);\n\n/// Create HMDT object\nHADT MGL_EXPORT mgl_create_datac();\nuintptr_t MGL_EXPORT mgl_create_datac_();\n/// Create HMDT object with specified sizes\nHADT MGL_EXPORT mgl_create_datac_size(long nx, long ny, long nz);\nuintptr_t MGL_EXPORT mgl_create_datac_size_(int *nx, int *ny, int *nz);\n/// Create HMDT object with data from file\nHADT MGL_EXPORT mgl_create_datac_file(const char *fname);\nuintptr_t MGL_EXPORT mgl_create_datac_file_(const char *fname, int len);\n/// Delete HMDT object\nvoid MGL_EXPORT mgl_delete_datac(HADT dat);\nvoid MGL_EXPORT mgl_delete_datac_(uintptr_t *dat);\n\n/// Rearange data dimensions\nvoid MGL_EXPORT mgl_datac_rearrange(HADT dat, long mx,long my,long mz);\nvoid MGL_EXPORT mgl_datac_rearrange_(uintptr_t *dat, int *mx, int *my, int *mz);\n/// Link external data array (don't delete it at exit)\nvoid MGL_EXPORT mgl_datac_link(HADT dat, mdual *A,long mx,long my,long mz);\nvoid MGL_EXPORT mgl_datac_link_(uintptr_t *d, mdual *A, int *nx,int *ny,int *nz);\n/// Allocate memory and copy the data from the (float *) array\nvoid MGL_EXPORT mgl_datac_set_float(HADT dat, const float *A,long mx,long my,long mz);\nvoid MGL_EXPORT mgl_datac_set_float_(uintptr_t *dat, const float *A,int *NX,int *NY,int *NZ);\n/// Allocate memory and copy the data from the (double *) array\nvoid MGL_EXPORT mgl_datac_set_double(HADT dat, const double *A,long mx,long my,long mz);\nvoid MGL_EXPORT mgl_datac_set_double_(uintptr_t *dat, const double *A,int *NX,int *NY,int *NZ);\n/// Allocate memory and copy the data from the (dual *) array\nvoid MGL_EXPORT mgl_datac_set_complex(HADT dat, const mdual *A,long mx,long my,long mz);\nvoid MGL_EXPORT mgl_datac_set_complex_(uintptr_t *d, const mdual *A,int *NX,int *NY,int *NZ);\n/// Import data from abstract type\nvoid MGL_EXPORT mgl_datac_set(HADT dat, HCDT a);\nvoid MGL_EXPORT mgl_datac_set_(uintptr_t *dat, uintptr_t *a);\n/// Allocate memory and copy the data from the gsl_vector\nvoid MGL_EXPORT mgl_datac_set_vector(HADT dat, gsl_vector *v);\n/// Allocate memory and copy the data from the gsl_matrix\nvoid MGL_EXPORT mgl_datac_set_matrix(HADT dat, gsl_matrix *m);\n/// Set value of data element [i,j,k]\nvoid MGL_EXPORT mgl_datac_set_value(HADT dat, mdual v, long i, long j, long k);\nvoid MGL_EXPORT mgl_datac_set_value_(uintptr_t *d, mdual *v, int *i, int *j, int *k);\n/// Get value of data element [i,j,k]\ncmdual MGL_EXPORT mgl_datac_get_value(HCDT dat, long i, long j, long k);\ncmdual MGL_EXPORT mgl_datac_get_value_(uintptr_t *d, int *i, int *j, int *k);\n/// Allocate memory and scanf the data from the string\nvoid MGL_EXPORT mgl_datac_set_values(HADT dat, const char *val, long nx, long ny, long nz);\nvoid MGL_EXPORT mgl_datac_set_values_(uintptr_t *d, const char *val, int *nx, int *ny, int *nz, int l);\n\n/// Get array as solution of tridiagonal matrix solution a[i]*x[i-1]+b[i]*x[i]+c[i]*x[i+1]=d[i]\n/** String \\a how may contain:\n * 'x', 'y', 'z' for solving along x-,y-,z-directions, or\n * 'h' for solving along hexagonal direction at x-y plain (need nx=ny),\n * 'c' for using periodical boundary conditions,\n * 'd' for diffraction/diffuse calculation.\n * NOTE: It work for flat data model only (i.e. for a[i,j]==a[i+nx*j]) */\nHADT MGL_EXPORT mgl_datac_tridmat(HCDT A, HCDT B, HCDT C, HCDT D, const char *how);\nuintptr_t MGL_EXPORT mgl_datac_tridmat_(uintptr_t *A, uintptr_t *B, uintptr_t *C, uintptr_t *D, const char *how, int);\n\n/// Returns pointer to internal data array\nMGL_EXPORT mdual *mgl_datac_data(HADT dat);\n/// Returns pointer to data element [i,j,k]\nMGL_EXPORT mdual *mgl_datac_value(HADT dat, long i,long j,long k);\n\n/// Set the data from HCDT objects for real and imaginary parts\nvoid MGL_EXPORT mgl_datac_set_ri(HADT dat, HCDT re, HCDT im);\nvoid MGL_EXPORT mgl_datac_set_ri_(uintptr_t *dat, uintptr_t *re, uintptr_t *im);\n/// Set the data from HCDT objects as amplitude and phase of complex data\nvoid MGL_EXPORT mgl_datac_set_ap(HADT dat, HCDT abs, HCDT phi);\nvoid MGL_EXPORT mgl_datac_set_ap_(uintptr_t *dat, uintptr_t *abs, uintptr_t *phi);\n\n/// Read data from tab-separated text file with auto determining size\nint MGL_EXPORT mgl_datac_read(HADT dat, const char *fname);\nint MGL_EXPORT mgl_datac_read_(uintptr_t *d, const char *fname,int l);\n/// Read data from text file with size specified at beginning of the file\nint MGL_EXPORT mgl_datac_read_mat(HADT dat, const char *fname, long dim);\nint MGL_EXPORT mgl_datac_read_mat_(uintptr_t *dat, const char *fname, int *dim, int);\n/// Read data from text file with specifeid size\nint MGL_EXPORT mgl_datac_read_dim(HADT dat, const char *fname,long mx,long my,long mz);\nint MGL_EXPORT mgl_datac_read_dim_(uintptr_t *dat, const char *fname,int *mx,int *my,int *mz,int);\n/// Read data from tab-separated text files with auto determining size which filenames are result of sprintf(fname,templ,t) where t=from:step:to\nint MGL_EXPORT mgl_datac_read_range(HADT d, const char *templ, double from, double to, double step, int as_slice);\nint MGL_EXPORT mgl_datac_read_range_(uintptr_t *d, const char *fname, mreal *from, mreal *to, mreal *step, int *as_slice,int l);\n/// Read data from tab-separated text files with auto determining size which filenames are satisfied to template (like \"t_*.dat\")\nint MGL_EXPORT mgl_datac_read_all(HADT dat, const char *templ, int as_slice);\nint MGL_EXPORT mgl_datac_read_all_(uintptr_t *d, const char *fname, int *as_slice,int l);\n/// Save whole data array (for ns=-1) or only ns-th slice to text file\nvoid MGL_EXPORT mgl_datac_save(HCDT dat, const char *fname,long ns);\nvoid MGL_EXPORT mgl_datac_save_(uintptr_t *dat, const char *fname,int *ns,int);\n\n/// Read data array from HDF file (parse HDF4 and HDF5 files)\nint MGL_EXPORT mgl_datac_read_hdf(HADT d,const char *fname,const char *data);\nint MGL_EXPORT mgl_datac_read_hdf_(uintptr_t *d, const char *fname, const char *data,int l,int n);\n/// Save data to HDF file\nvoid MGL_EXPORT mgl_datac_save_hdf(HCDT d,const char *fname,const char *data,int rewrite);\nvoid MGL_EXPORT mgl_datac_save_hdf_(uintptr_t *d, const char *fname, const char *data, int *rewrite,int l,int n);\n\n/// Create or recreate the array with specified size and fill it by zero\nvoid MGL_EXPORT mgl_datac_create(HADT dat, long nx,long ny,long nz);\nvoid MGL_EXPORT mgl_datac_create_(uintptr_t *dat, int *nx,int *ny,int *nz);\n/// Transpose dimensions of the data (generalization of Transpose)\nvoid MGL_EXPORT mgl_datac_transpose(HADT dat, const char *dim);\nvoid MGL_EXPORT mgl_datac_transpose_(uintptr_t *dat, const char *dim,int);\n\n/// Get sub-array of the data with given fixed indexes\nHADT MGL_EXPORT mgl_datac_subdata(HCDT dat, long xx,long yy,long zz);\nuintptr_t MGL_EXPORT mgl_datac_subdata_(uintptr_t *dat, int *xx,int *yy,int *zz);\n/// Get sub-array of the data with given fixed indexes (like indirect access)\nHADT MGL_EXPORT mgl_datac_subdata_ext(HCDT dat, HCDT xx, HCDT yy, HCDT zz);\nuintptr_t MGL_EXPORT mgl_datac_subdata_ext_(uintptr_t *dat, uintptr_t *xx,uintptr_t *yy,uintptr_t *zz);\n/// Get column (or slice) of the data filled by formulas of named columns\nHADT MGL_EXPORT mgl_datac_column(HCDT dat, const char *eq);\nuintptr_t MGL_EXPORT mgl_datac_column_(uintptr_t *dat, const char *eq,int l);\n/// Get trace of the data array\nHADT MGL_EXPORT mgl_datac_trace(HCDT d);\nuintptr_t MGL_EXPORT mgl_datac_trace_(uintptr_t *d);\n/// Resize the data to new sizes\nHADT MGL_EXPORT mgl_datac_resize(HCDT dat, long mx,long my,long mz);\nuintptr_t MGL_EXPORT mgl_datac_resize_(uintptr_t *dat, int *mx,int *my,int *mz);\n/// Resize the data to new sizes of box [x1,x2]*[y1,y2]*[z1,z2]\nHADT MGL_EXPORT mgl_datac_resize_box(HCDT dat, long mx,long my,long mz,mreal x1,mreal x2,mreal y1,mreal y2,mreal z1,mreal z2);\nuintptr_t MGL_EXPORT mgl_datac_resize_box_(uintptr_t *dat, int *mx,int *my,int *mz,mreal *x1,mreal *x2,mreal *y1,mreal *y2,mreal *z1,mreal *z2);\n/// Get momentum (1D-array) of data along direction 'dir'. String looks like \"x1\" for median in x-direction, \"x2\" for width in x-dir and so on.\nHADT MGL_EXPORT mgl_datac_momentum(HCDT dat, char dir, const char *how);\nuintptr_t MGL_EXPORT mgl_datac_momentum_(uintptr_t *dat, char *dir, const char *how, int,int);\n/// Get array which values is result of interpolation this for coordinates from other arrays\nHADT MGL_EXPORT mgl_datac_evaluate(HCDT dat, HCDT idat, HCDT jdat, HCDT kdat, int norm);\nuintptr_t MGL_EXPORT mgl_datac_evaluate_(uintptr_t *dat, uintptr_t *idat, uintptr_t *jdat, uintptr_t *kdat, int *norm);\n/// Get array which is result of summation in given direction or directions\nHADT MGL_EXPORT mgl_datac_sum(HCDT dat, const char *dir);\nuintptr_t MGL_EXPORT mgl_datac_sum_(uintptr_t *dat, const char *dir,int);\n/// Get the data which is direct multiplication (like, d[i,j] = this[i]*a[j] and so on)\nHADT MGL_EXPORT mgl_datac_combine(HCDT dat1, HCDT dat2);\nuintptr_t MGL_EXPORT mgl_datac_combine_(uintptr_t *dat1, uintptr_t *dat2);\n/// Get data from sections ids, separated by value val along specified direction.\n/** If section id is negative then reverse order is used (i.e. -1 give last section). */\nHADT MGL_EXPORT mgl_datac_section(HCDT dat, HCDT ids, char dir, mreal val);\nuintptr_t MGL_EXPORT mgl_datac_section_(uintptr_t *d, uintptr_t *ids, const char *dir, mreal *val,int);\n/// Get data from section id, separated by value val along specified direction.\n/** If section id is negative then reverse order is used (i.e. -1 give last section). */\nHADT MGL_EXPORT mgl_datac_section_val(HCDT dat, long id, char dir, mreal val);\nuintptr_t MGL_EXPORT mgl_datac_section_val_(uintptr_t *d, int *id, const char *dir, mreal *val,int);\n\n/// Equidistantly fill the data to range [x1,x2] in direction dir\nvoid MGL_EXPORT mgl_datac_fill(HADT dat, mdual x1,mdual x2,char dir);\nvoid MGL_EXPORT mgl_datac_fill_(uintptr_t *dat, mdual *x1,mdual *x2,const char *dir,int);\n/// Modify the data by specified formula assuming x,y,z in range [r1,r2]\nvoid MGL_EXPORT mgl_datac_fill_eq(HMGL gr, HADT dat, const char *eq, HCDT vdat, HCDT wdat,const char *opt);\nvoid MGL_EXPORT mgl_datac_fill_eq_(uintptr_t *gr, uintptr_t *dat, const char *eq, uintptr_t *vdat, uintptr_t *wdat,const char *opt, int, int);\n/// Fill dat by interpolated values of vdat parametrically depended on xdat for x in range [x1,x2] using global spline\nvoid MGL_EXPORT mgl_datac_refill_gs(HADT dat, HCDT xdat, HCDT vdat, mreal x1, mreal x2, long sl);\nvoid MGL_EXPORT mgl_datac_refill_gs_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *vdat, mreal *x1, mreal *x2, long *sl);\n/// Fill dat by interpolated values of vdat parametrically depended on xdat for x in range [x1,x2]\nvoid MGL_EXPORT mgl_datac_refill_x(HADT dat, HCDT xdat, HCDT vdat, mreal x1, mreal x2, long sl);\nvoid MGL_EXPORT mgl_datac_refill_x_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *vdat, mreal *x1, mreal *x2, long *sl);\n/// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat for x,y in range [x1,x2]*[y1,y2]\nvoid MGL_EXPORT mgl_datac_refill_xy(HADT dat, HCDT xdat, HCDT ydat, HCDT vdat, mreal x1, mreal x2, mreal y1, mreal y2, long sl);\nvoid MGL_EXPORT mgl_datac_refill_xy_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *vdat, mreal *x1, mreal *x2, mreal *y1, mreal *y2, long *sl);\n/// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in range [x1,x2]*[y1,y2]*[z1,z2]\nvoid MGL_EXPORT mgl_datac_refill_xyz(HADT dat, HCDT xdat, HCDT ydat, HCDT zdat, HCDT vdat, mreal x1, mreal x2, mreal y1, mreal y2, mreal z1, mreal z2);\nvoid MGL_EXPORT mgl_datac_refill_xyz_(uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, uintptr_t *vdat, mreal *x1, mreal *x2, mreal *y1, mreal *y2, mreal *z1, mreal *z2);\n/// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in axis range\nvoid MGL_EXPORT mgl_datac_refill_gr(HMGL gr, HADT dat, HCDT xdat, HCDT ydat, HCDT zdat, HCDT vdat, long sl, const char *opt);\nvoid MGL_EXPORT mgl_datac_refill_gr_(uintptr_t *gr, uintptr_t *dat, uintptr_t *xdat, uintptr_t *ydat, uintptr_t *zdat, uintptr_t *vdat, long *sl, const char *opt,int);\n\n/// Modify the data by specified formula\nvoid MGL_EXPORT mgl_datac_modify(HADT dat, const char *eq,long dim);\nvoid MGL_EXPORT mgl_datac_modify_(uintptr_t *dat, const char *eq,int *dim,int);\n/// Modify the data by specified formula\nvoid MGL_EXPORT mgl_datac_modify_vw(HADT dat, const char *eq,HCDT vdat,HCDT wdat);\nvoid MGL_EXPORT mgl_datac_modify_vw_(uintptr_t *dat, const char *eq, uintptr_t *vdat, uintptr_t *wdat,int);\n\n/// Limit the data to be inside [-v,v], keeping the original sign\nvoid MGL_EXPORT mgl_datac_limit(HADT dat, mreal v);\nvoid MGL_EXPORT mgl_datac_limit_(uintptr_t *dat, mreal *v);\n\n/// Put value to data element(s)\nvoid MGL_EXPORT mgl_datac_put_val(HADT dat, mdual val, long i, long j, long k);\nvoid MGL_EXPORT mgl_datac_put_val_(uintptr_t *dat, mdual *val, int *i, int *j, int *k);\n/// Put array to data element(s)\nvoid MGL_EXPORT mgl_datac_put_dat(HADT dat, HCDT val, long i, long j, long k);\nvoid MGL_EXPORT mgl_datac_put_dat_(uintptr_t *dat, uintptr_t *val, int *i, int *j, int *k);\n\n/// Reduce size of the data\nvoid MGL_EXPORT mgl_datac_squeeze(HADT dat, long rx,long ry,long rz,long smooth);\nvoid MGL_EXPORT mgl_datac_squeeze_(uintptr_t *dat, int *rx,int *ry,int *rz,int *smooth);\n/// Extend data dimensions\nvoid MGL_EXPORT mgl_datac_extend(HADT dat, long n1, long n2);\nvoid MGL_EXPORT mgl_datac_extend_(uintptr_t *dat, int *n1, int *n2);\n/// Insert data rows/columns/slices\nvoid MGL_EXPORT mgl_datac_insert(HADT dat, char dir, long at, long num);\nvoid MGL_EXPORT mgl_datac_insert_(uintptr_t *dat, const char *dir, int *at, int *num, int);\n/// Delete data rows/columns/slices\nvoid MGL_EXPORT mgl_datac_delete(HADT dat, char dir, long at, long num);\nvoid MGL_EXPORT mgl_datac_delete_(uintptr_t *dat, const char *dir, int *at, int *num, int);\n/// Joind another data array\nvoid MGL_EXPORT mgl_datac_join(HADT dat, HCDT d);\nvoid MGL_EXPORT mgl_datac_join_(uintptr_t *dat, uintptr_t *d);\n\n/// Smooth the data on specified direction or directions\n/** String \\a dir may contain:\n *  \u2018x\u2019, \u2018y\u2019, \u2018z\u2019 for 1st, 2nd or 3d dimension;\n *  \u2018dN\u2019 for linear averaging over N points;\n *  \u20183\u2019 for linear averaging over 3 points;\n *  \u20185\u2019 for linear averaging over 5 points.\n *  By default quadratic averaging over 5 points is used. */\nvoid MGL_EXPORT mgl_datac_smooth(HADT d, const char *dirs, mreal delta);\nvoid MGL_EXPORT mgl_datac_smooth_(uintptr_t *dat, const char *dirs, mreal *delta,int);\n/// Cumulative summation the data in given direction or directions\nvoid MGL_EXPORT mgl_datac_cumsum(HADT dat, const char *dir);\nvoid MGL_EXPORT mgl_datac_cumsum_(uintptr_t *dat, const char *dir,int);\n/// Integrate (cumulative summation) the data in given direction or directions\nvoid MGL_EXPORT mgl_datac_integral(HADT dat, const char *dir);\nvoid MGL_EXPORT mgl_datac_integral_(uintptr_t *dat, const char *dir,int);\n/// Differentiate the data in given direction or directions\nvoid MGL_EXPORT mgl_datac_diff(HADT dat, const char *dir);\nvoid MGL_EXPORT mgl_datac_diff_(uintptr_t *dat, const char *dir,int);\n/// Differentiate the parametrically specified data along direction v1 with v2,v3=const (v3 can be NULL)\nvoid MGL_EXPORT mgl_datac_diff_par(HADT dat, HCDT v1, HCDT v2, HCDT v3);\nvoid MGL_EXPORT mgl_datac_diff_par_(uintptr_t *dat, uintptr_t *v1, uintptr_t *v2, uintptr_t *v3);\n/// Double-differentiate (like Laplace operator) the data in given direction\nvoid MGL_EXPORT mgl_datac_diff2(HADT dat, const char *dir);\nvoid MGL_EXPORT mgl_datac_diff2_(uintptr_t *dat, const char *dir,int);\n/// Swap left and right part of the data in given direction (useful for Fourier spectrum)\nvoid MGL_EXPORT mgl_datac_swap(HADT dat, const char *dir);\nvoid MGL_EXPORT mgl_datac_swap_(uintptr_t *dat, const char *dir,int);\n/// Roll data along direction dir by num slices\nvoid MGL_EXPORT mgl_datac_roll(HADT dat, char dir, long num);\nvoid MGL_EXPORT mgl_datac_roll_(uintptr_t *dat, const char *dir, int *num, int);\n/// Mirror the data in given direction (useful for Fourier spectrum)\nvoid MGL_EXPORT mgl_datac_mirror(HADT dat, const char *dir);\nvoid MGL_EXPORT mgl_datac_mirror_(uintptr_t *dat, const char *dir,int);\n/// Crop the data\nvoid MGL_EXPORT mgl_datac_crop(HADT dat, long n1, long n2, char dir);\nvoid MGL_EXPORT mgl_datac_crop_(uintptr_t *dat, int *n1, int *n2, const char *dir,int);\n/// Crop the data to be most optimal for FFT (i.e. to closest value of 2^n*3^m*5^l)\nvoid MGL_EXPORT mgl_datac_crop_opt(HADT dat, const char *how);\nvoid MGL_EXPORT mgl_datac_crop_opt_(uintptr_t *dat, const char *how,int);\n\n/// Multiply the data by other one for each element\nvoid MGL_EXPORT mgl_datac_mul_dat(HADT dat, HCDT d);\nvoid MGL_EXPORT mgl_datac_mul_dat_(uintptr_t *dat, uintptr_t *d);\n/// Divide the data by other one for each element\nvoid MGL_EXPORT mgl_datac_div_dat(HADT dat, HCDT d);\nvoid MGL_EXPORT mgl_datac_div_dat_(uintptr_t *dat, uintptr_t *d);\n/// Add the other data\nvoid MGL_EXPORT mgl_datac_add_dat(HADT dat, HCDT d);\nvoid MGL_EXPORT mgl_datac_add_dat_(uintptr_t *dat, uintptr_t *d);\n/// Subtract the other data\nvoid MGL_EXPORT mgl_datac_sub_dat(HADT dat, HCDT d);\nvoid MGL_EXPORT mgl_datac_sub_dat_(uintptr_t *dat, uintptr_t *d);\n/// Multiply each element by the number\nvoid MGL_EXPORT mgl_datac_mul_num(HADT dat, mdual d);\nvoid MGL_EXPORT mgl_datac_mul_num_(uintptr_t *dat, mdual *d);\n/// Divide each element by the number\nvoid MGL_EXPORT mgl_datac_div_num(HADT dat, mdual d);\nvoid MGL_EXPORT mgl_datac_div_num_(uintptr_t *dat, mdual *d);\n/// Add the number\nvoid MGL_EXPORT mgl_datac_add_num(HADT dat, mdual d);\nvoid MGL_EXPORT mgl_datac_add_num_(uintptr_t *dat, mdual *d);\n/// Subtract the number\nvoid MGL_EXPORT mgl_datac_sub_num(HADT dat, mdual d);\nvoid MGL_EXPORT mgl_datac_sub_num_(uintptr_t *dat, mdual *d);\n\n/// Apply Hankel transform\nvoid MGL_EXPORT mgl_datac_hankel(HADT dat, const char *dir);\nvoid MGL_EXPORT mgl_datac_hankel_(uintptr_t *dat, const char *dir,int);\n/// Apply Sin-Fourier transform\nvoid MGL_EXPORT mgl_datac_sinfft(HADT dat, const char *dir);\nvoid MGL_EXPORT mgl_datac_sinfft_(uintptr_t *dat, const char *dir,int);\n/// Apply Cos-Fourier transform\nvoid MGL_EXPORT mgl_datac_cosfft(HADT dat, const char *dir);\nvoid MGL_EXPORT mgl_datac_cosfft_(uintptr_t *dat, const char *dir,int);\n/// Apply Fourier transform\nvoid MGL_EXPORT mgl_datac_fft(HADT dat, const char *dir);\nvoid MGL_EXPORT mgl_datac_fft_(uintptr_t *dat, const char *dir,int);\n/// Find correlation between 2 data arrays\nHADT MGL_EXPORT mgl_datac_correl(HCDT dat1, HCDT dat2, const char *dir);\nuintptr_t MGL_EXPORT mgl_datac_correl_(uintptr_t *dat1, uintptr_t *dat2, const char *dir,int);\n/// Calculate one step of diffraction by finite-difference method with parameter q\nvoid MGL_EXPORT mgl_datac_diffr(HADT dat, const char *how, mreal q);\nvoid MGL_EXPORT mgl_datac_diffr_(uintptr_t *d, const char *how, double q,int l);\n/// Apply wavelet transform\n/** Parameter \\a dir may contain:\n * \u2018x\u2018,\u2018y\u2018,\u2018z\u2018 for directions,\n * \u2018d\u2018 for daubechies, \u2018D\u2018 for centered daubechies,\n * \u2018h\u2018 for haar, \u2018H\u2018 for centered haar,\n * \u2018b\u2018 for bspline, \u2018B\u2018 for centered bspline,\n * \u2018i\u2018 for applying inverse transform. */\nvoid MGL_EXPORT mgl_datac_wavelet(HADT dat, const char *how, int k);\nvoid MGL_EXPORT mgl_datac_wavelet_(uintptr_t *d, const char *dir, int *k,int);\n/// Set as the data envelop\nvoid MGL_EXPORT mgl_datac_envelop(HADT dat, char dir);\nvoid MGL_EXPORT mgl_datac_envelop_(uintptr_t *dat, const char *dir, int);\n\n/// Get real part of data values\nHMDT MGL_EXPORT mgl_datac_real(HCDT dat);\nuintptr_t MGL_EXPORT mgl_datac_real_(uintptr_t *dat);\n/// Get imaginary part of data values\nHMDT MGL_EXPORT mgl_datac_imag(HCDT dat);\nuintptr_t MGL_EXPORT mgl_datac_imag_(uintptr_t *dat);\n/// Get absolute value of data values, i.e. |u|\nHMDT MGL_EXPORT mgl_datac_abs(HCDT dat);\nuintptr_t MGL_EXPORT mgl_datac_abs_(uintptr_t *dat);\n/// Get argument of data values\nHMDT MGL_EXPORT mgl_datac_arg(HCDT dat);\nuintptr_t MGL_EXPORT mgl_datac_arg_(uintptr_t *dat);\n/// Get square of absolute value of data values, i.e. |u|^2\nHMDT MGL_EXPORT mgl_datac_norm(HCDT dat);\nuintptr_t MGL_EXPORT mgl_datac_norm_(uintptr_t *dat);\n\n/// Interpolate by linear function the data to given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1]\ncmdual MGL_EXPORT mgl_datac_linear(HCDT d, mreal x,mreal y,mreal z);\ncmdual MGL_EXPORT mgl_datac_linear_(uintptr_t *d, mreal *x,mreal *y,mreal *z);\n/// Interpolate by linear function the data and return its derivatives at given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1]\ncmdual MGL_EXPORT mgl_datac_linear_ext(HCDT d, mreal x,mreal y,mreal z, mdual *dx,mdual *dy,mdual *dz);\ncmdual MGL_EXPORT mgl_datac_linear_ext_(uintptr_t *d, mreal *x,mreal *y,mreal *z, mdual *dx,mdual *dy,mdual *dz);\n/// Interpolate by cubic spline the data to given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1]\ncmdual MGL_EXPORT mgl_datac_spline(HCDT dat, mreal x,mreal y,mreal z);\ncmdual MGL_EXPORT mgl_datac_spline_(uintptr_t *dat, mreal *x,mreal *y,mreal *z);\n/// Interpolate by cubic spline the data and return its derivatives at given point x=[0...nx-1], y=[0...ny-1], z=[0...nz-1]\ncmdual MGL_EXPORT mgl_datac_spline_ext(HCDT dat, mreal x,mreal y,mreal z, mdual *dx,mdual *dy,mdual *dz);\ncmdual MGL_EXPORT mgl_datac_spline_ext_(uintptr_t *dat, mreal *x,mreal *y,mreal *z, mdual *dx,mdual *dy,mdual *dz);\n/// Prepare coefficients for global spline interpolation\nHADT MGL_EXPORT mgl_gsplinec_init(HCDT x, HCDT v);\nuintptr_t MGL_EXPORT mgl_gspline_init_(uintptr_t *x, uintptr_t *v);\n/// Evaluate global spline (and its derivatives d1, d2 if not NULL) using prepared coefficients \\a coef\ncmdual MGL_EXPORT mgl_gsplinec(HCDT coef, mreal dx, mdual *d1, mdual *d2);\ncmdual MGL_EXPORT mgl_gsplinec_(uintptr_t *c, mreal *dx, mdual *d1, mdual *d2);\n\n/// Find roots for set of nonlinear equations defined by textual formulas\nHADT MGL_EXPORT mgl_find_roots_txt_c(const char *func, const char *vars, HCDT ini);\nuintptr_t MGL_EXPORT mgl_find_roots_txt_c_(const char *func, const char *vars, uintptr_t *ini,int,int);\n\n#ifdef __cplusplus\n}\n#endif\n//-----------------------------------------------------------------------------\n#endif\n", "meta": {"hexsha": "17b1cf6fc8f4ed9b75484406cdbede91decf43c4", "size": 24386, "ext": "h", "lang": "C", "max_stars_repo_path": "mathgl-2.4.3/include/mgl2/datac_cf.h", "max_stars_repo_name": "angelamsj/cruise-control", "max_stars_repo_head_hexsha": "0fb94e86217afee2e637de694b0148b99b052ccf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mathgl-2.4.3/include/mgl2/datac_cf.h", "max_issues_repo_name": "angelamsj/cruise-control", "max_issues_repo_head_hexsha": "0fb94e86217afee2e637de694b0148b99b052ccf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mathgl-2.4.3/include/mgl2/datac_cf.h", "max_forks_repo_name": "angelamsj/cruise-control", "max_forks_repo_head_hexsha": "0fb94e86217afee2e637de694b0148b99b052ccf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 63.6710182768, "max_line_length": 188, "alphanum_fraction": 0.7380054129, "num_tokens": 7366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.37087435629044263}}
{"text": "#ifndef _RICO_\n#define _RICO_\n\n#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <ctype.h>\n#include <math.h>\n#include <unistd.h>\n#include \"../Parameter_files/COSMOLOGY.H\"\n#include \"../Parameter_files/INIT_PARAMS.H\"\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_spline.h>\n#include \"cosmo_progs.c\"\n#include \"misc.c\"\n#include \"ps.c\"\n\n#define A_NPTS (int) (60) /*Warning: the calculation of the MHR model parameters is valid only from redshift 2 to A_NPTS+2*/\nstatic double A_table[A_NPTS], A_params[A_NPTS];\nstatic gsl_interp_accel *A_acc;\nstatic gsl_spline *A_spline;\n\n#define C_NPTS (int) (12)\nstatic double C_table[C_NPTS], C_params[C_NPTS];\nstatic gsl_interp_accel *C_acc;\nstatic gsl_spline *C_spline;\n\n#define beta_NPTS (int) (5)\nstatic double beta_table[beta_NPTS], beta_params[beta_NPTS];\nstatic gsl_interp_accel *beta_acc;\nstatic gsl_spline *beta_spline;\n\n#define RR_Z_NPTS (int) (300) // number of points in redshift axis;  we will only interpolate over gamma, and just index sample in redshift\n#define RR_DEL_Z (float) (0.2)\n#define RR_lnGamma_NPTS (int) (150) // number of samples of gamma for the interpolation tables\n#define RR_lnGamma_min (double) (-10) // min ln gamma12 used\n#define RR_DEL_lnGamma (float) (0.1)\nstatic double RR_table[RR_Z_NPTS][RR_lnGamma_NPTS], lnGamma_values[RR_lnGamma_NPTS];\nstatic gsl_interp_accel *RR_acc[RR_Z_NPTS];\nstatic gsl_spline *RR_spline[RR_Z_NPTS];\n\n\n/***  FUNCTION PROTOTYPES ***/\ndouble splined_recombination_rate(double z_eff, double gamma12_bg); // assumes T=1e4 and case B\n\ndouble recombination_rate(double z_eff, double gamma12_bg, double T4, int usecaseB);\nvoid init_MHR(); /*initializes the lookup table for the PDF density integral in MHR00 model at redshift z*/\nvoid free_MHR(); /* deallocates the gsl structures from init_MHR */\ndouble Gamma_SS(double Gamma_bg, double Delta, double T_4, double z);//ionization rate w. self shielding\ndouble MHR_rr (double D, void *params);\ndouble A_MHR(double z); /*returns the A parameter in MHR00model*/\ndouble C_MHR(double z); /*returns the C parameter in MHR00model*/\ndouble beta_MHR(double z); /*returns the beta parameter in MHR00model*/\ndouble splined_A_MHR(double z); /*returns the splined A parameter in MHR00model*/\ndouble splined_C_MHR(double z); /*returns the splined C parameter in MHR00model*/\ndouble splined_beta_MHR(double z);/*returns the splined beta parameter in MHR00*/\nvoid free_A_MHR(); /* deallocates the gsl structures from init_A */\nvoid free_C_MHR(); /* deallocates the gsl structures from init_C */\nvoid free_beta_MHR(); /* deallocates the gsl structures from init_beta */\nvoid init_A_MHR(); /*initializes the lookup table for the A paremeter in MHR00 model*/\nvoid init_C_MHR(); /*initializes the lookup table for the C paremeter in MHR00 model*/\nvoid init_beta_MHR(); /*initializes the lookup table for the beta paremeter in MHR00 model*/\n\n\ndouble splined_recombination_rate(double z_eff, double gamma12_bg){\n  int z_ct = (int) (z_eff / RR_DEL_Z + 0.5); // round to nearest int\n  double lnGamma = log(gamma12_bg);\n\n  // check out of bounds\n  if ( z_ct < 0 ){ // out of array bounds\n//    fprintf(stderr, \"WARNING: splined_recombination_rate: effective redshift %g is outside of array bouds\\n\", z_eff);\n    z_ct = 0;\n  }\n  else if (z_ct  >= RR_Z_NPTS){\n//    fprintf(stderr, \"WARNING: splined_recombination_rate: effective redshift %g is outside of array bouds\\n\", z_eff);\n    z_ct = RR_Z_NPTS-1;\n  }\n\n  if (lnGamma < RR_lnGamma_min){\n    return 0;\n  }\n  else if (lnGamma >= (RR_lnGamma_min + RR_DEL_lnGamma * RR_lnGamma_NPTS) ){\n//    fprintf(stderr, \"WARNING: splined_recombination_rate: Gamma12 of %g is outside of interpolation array\\n\", gamma12_bg);\n    lnGamma =  RR_lnGamma_min + RR_DEL_lnGamma * RR_lnGamma_NPTS - FRACT_FLOAT_ERR;\n  }\n\n  return gsl_spline_eval(RR_spline[z_ct], lnGamma, RR_acc[z_ct]);\n}\n\nvoid init_MHR(){\n  int z_ct, gamma_ct;\n  float z, gamma;\n\n  // first initialize the MHR parameter look up tables\n  init_C_MHR(); /*initializes the lookup table for the C paremeter in MHR00 model*/\n  init_beta_MHR(); /*initializes the lookup table for the beta paremeter in MHR00 model*/\n  init_A_MHR(); /*initializes the lookup table for the A paremeter in MHR00 model*/\n\n  // now the recombination rate look up tables\n  for (z_ct=0; z_ct < RR_Z_NPTS; z_ct++){\n\n    z = z_ct * RR_DEL_Z; // redshift corresponding to index z_ct of the array\n\n    // Intialize the Gamma values\n    for (gamma_ct=0; gamma_ct < RR_lnGamma_NPTS; gamma_ct++){\n      lnGamma_values[gamma_ct] = RR_lnGamma_min  + gamma_ct*RR_DEL_lnGamma;  // ln of Gamma12    \n      gamma = exp(lnGamma_values[gamma_ct]);\n      RR_table[z_ct][gamma_ct] = recombination_rate(z, gamma, 1, 1); // CHANGE THIS TO INCLUDE TEMPERATURE\n    }\n\n    // set up the spline in gamma\n    RR_acc[z_ct] = gsl_interp_accel_alloc();\n    RR_spline[z_ct] = gsl_spline_alloc (gsl_interp_cspline, RR_lnGamma_NPTS);\n    gsl_spline_init(RR_spline[z_ct], lnGamma_values, RR_table[z_ct], RR_lnGamma_NPTS);\n\n  } // go to next redshift\n\n  return;\n}\n\nvoid free_MHR(){\n  int z_ct;\n\n  free_A_MHR(); \n  free_C_MHR(); \n  free_beta_MHR();\n\n  // now the recombination rate look up tables\n  for (z_ct=0; z_ct < RR_Z_NPTS; z_ct++){\n    gsl_spline_free (RR_spline[z_ct]);\n    gsl_interp_accel_free(RR_acc[z_ct]);\n  }\n\n  return;\n}\n\n//calculates the attenuated photoionization rate due to self-shielding (in units of 1e-12 s^-1)\n// input parameters are the background ionization rate, overdensity, temperature (in 10^4k), redshift, respectively\n//  Uses the fitting formula from Rahmati et al, assuming a UVB power law index of alpha=5\ndouble Gamma_SS(double Gamma_bg, double D, double T_4, double z){\n  double D_ss = 26.7*pow(T_4, 0.17) * pow( (1+z)/10.0, -3) * pow(Gamma_bg, 2.0/3.0);\n  return Gamma_bg * (0.98 * pow( (1.0+pow(D/D_ss, 1.64)), -2.28) + 0.02*pow( 1.0+D/D_ss, -0.84));\n}\n\n\ntypedef struct {double z, gamma12_bg, T4, A, C_0, beta, avenH; int usecaseB;} RR_par;\n\ndouble MHR_rr (double lnD, void *params){\n  double D=exp(lnD);\n  double alpha;\n  RR_par p = *(RR_par *) params;\n  double z = p.z;\n  double gamma = Gamma_SS(p.gamma12_bg, D, p.T4, z);\n  double n_H = p.avenH*D;\n  double x_e = 1.0 - neutral_fraction(n_H, p.T4, gamma, p.usecaseB);\n  double PDelta;\n\n  PDelta = p.A * exp( - 0.5*pow((pow(D,-2.0/3.0)- p.C_0 ) / ((2.0*7.61/(3.0*(1.0+z)))), 2)) * pow(D, p.beta);\n    \n  if (p.usecaseB)\n    alpha = alpha_B(p.T4*1e4);\n  else\n    alpha = alpha_A(p.T4*1e4);\n\n  //  fprintf(stderr, \"%g\\t%g\\t%g\\t%g\\t%g\\n\", n_H, PDelta, alpha, x_e, D);\n  \n  return n_H * PDelta * alpha * x_e * x_e * D * D;//note extra D since we are integrating over lnD\n}\n\n\n// returns the recombination rate per baryon (1/s), integrated over the MHR density PDF,\n// given an ionizing background of gamma12_bg\n// temeperature T4 (in 1e4 K), and usecaseB rate coefficient\n// Assumes self-shielding according to Rahmati+ 2013\ndouble recombination_rate(double z, double gamma12_bg, double T4, int usecaseB){\n  double result, error, lower_limit, upper_limit, A, C_0, beta, avenH;\n  gsl_function F;\n  double rel_tol  = 0.01; //<- relative tolerance\n  gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);\n  RR_par p = {z, gamma12_bg, T4, A_MHR(z), C_MHR(z), beta_MHR(z), No*pow( 1+z, 3), usecaseB};\n\n  F.function = &MHR_rr;\n  F.params=&p;\n  lower_limit = log(0.01);\n  upper_limit = log(200);\n\t\t\t   \n  gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,\n\t\t       1000, GSL_INTEG_GAUSS61, w, &result, &error); \n  gsl_integration_workspace_free (w);\n\n  return result;\n}\n\ndouble aux_function(double D, void *params){\n  double result;\n  double z = *(double *) params;\n  \n  result = exp(-(pow(D,-2.0/3.0)-C_MHR(z))*(pow(D,-2.0/3.0)-C_MHR(z))/(2.0*(2.0*7.61/(3.0*(1.0+z)))*(2.0*7.61/(3.0*(1.0+z)))))*pow(D, beta_MHR(z));\n\n  return result;\n}\n\ndouble A_aux_integral(double z){\n  double result, error, lower_limit, upper_limit;\n  gsl_function F;\n  double rel_tol  = 0.001; //<- relative tolerance\n  gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);\n\n  F.function = &aux_function;\n  F.params = &z;\n  lower_limit = 1e-25;\n  upper_limit = 1e25;\n\t\t\t   \n  gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,\n\t\t       1000, GSL_INTEG_GAUSS61, w, &result, &error); \n  gsl_integration_workspace_free (w);\n\n  return result;\n}\n\ndouble A_MHR(double z){\n  double result;\n  if(z>=2.0+(float)A_NPTS)\n    result = splined_A_MHR(2.0+(float)A_NPTS);\n  else\n    if(z<=2.0)\n      result = splined_A_MHR(2.0);\n    else\n      result = splined_A_MHR(z);\n  return result;\n}\n\nvoid init_A_MHR(){\n/* initialize the lookup table for the parameter A in the MHR00 model */\n   int i;\n   \n   for (i=0; i<A_NPTS; i++){\n     A_params[i] = 2.0+(float)i;\n     A_table[i] = 1.0/A_aux_integral(2.0+(float)i);\n   }\n \n  // Set up spline table\n  A_acc   = gsl_interp_accel_alloc();\n  A_spline  = gsl_spline_alloc (gsl_interp_cspline, A_NPTS);\n  gsl_spline_init(A_spline, A_params, A_table, A_NPTS);\n\n  return;\n }\n\n \ndouble splined_A_MHR(double x){\n  return gsl_spline_eval(A_spline, x, A_acc);\n}\n\nvoid free_A_MHR(){\n\n  gsl_spline_free (A_spline);\n  gsl_interp_accel_free(A_acc);\n  \n  return;\n}\n\n\n\ndouble C_MHR(double z){\n  double result;\n  if(z>=13.0)\n    result = 1.0;\n  else\n    if(z<=2.0)\n      result = 0.558;\n    else\n      result = splined_C_MHR(z);\n  return result;\n}\n\nvoid init_C_MHR(){\n/* initialize the lookup table for the parameter C in the MHR00 model */\n   int i;\n   \n  for (i=0; i<C_NPTS; i++)\n    C_params[i] = (float)i+2.0;\n\n  C_table[0] = 0.558;\n  C_table[1] = 0.599;\n  C_table[2] = 0.611;\n  C_table[3] = 0.769;\n  C_table[4] = 0.868;\n  C_table[5] = 0.930;\n  C_table[6] = 0.964;\n  C_table[7] = 0.983;\n  C_table[8] = 0.993;\n  C_table[9] = 0.998;\n  C_table[10] = 0.999;\n  C_table[11] = 1.00;\n   \n  // Set up spline table\n  C_acc   = gsl_interp_accel_alloc ();\n  C_spline  = gsl_spline_alloc (gsl_interp_cspline, C_NPTS);\n  gsl_spline_init(C_spline, C_params, C_table, C_NPTS);\n\n  return;\n }\n\n \ndouble splined_C_MHR(double x){\n  return gsl_spline_eval(C_spline, x, C_acc);\n}\n\nvoid free_C_MHR(){\n\n  gsl_spline_free (C_spline);\n  gsl_interp_accel_free(C_acc);\n  \n  return;\n}\n\n\n\ndouble beta_MHR(double z){\n  double result;\n  if(z>=6.0)\n    result = -2.50;\n  else\n    if(z<=2.0)\n      result = -2.23;\n    else\n      result = splined_beta_MHR(z);\n  return result;\n}\n\nvoid init_beta_MHR(){\n/* initialize the lookup table for the parameter C in the MHR00 model */\n   int i;\n   \n  for (i=0; i<beta_NPTS; i++)\n    beta_params[i] = (float)i+2.0;\n\n  beta_table[0] = -2.23;\n  beta_table[1] = -2.35;\n  beta_table[2] = -2.48;\n  beta_table[3] = -2.49;\n  beta_table[4] = -2.50;\n   \n  // Set up spline table\n  beta_acc   = gsl_interp_accel_alloc ();\n  beta_spline  = gsl_spline_alloc (gsl_interp_cspline, beta_NPTS);\n  gsl_spline_init(beta_spline, beta_params, beta_table, beta_NPTS);\n\n  return;\n }\n\n\ndouble splined_beta_MHR(double x){\n  return gsl_spline_eval(beta_spline, x, beta_acc);\n}\n\nvoid free_beta_MHR(){\n\n  gsl_spline_free(beta_spline);\n  gsl_interp_accel_free(beta_acc);\n  \n  return;\n}\n\n\n#endif\n", "meta": {"hexsha": "8d6e9d1dc391b1cca083b923aac6c09a22a04381", "size": 11057, "ext": "c", "lang": "C", "max_stars_repo_path": "public_21CMvFAST_MC/Cosmo_c_files/recombinations.c", "max_stars_repo_name": "NNSSA/21cmvFAST", "max_stars_repo_head_hexsha": "8f015427f3609a3051b4fa185bdbe55b379c930f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-04-18T11:31:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-15T03:29:14.000Z", "max_issues_repo_path": "public_21CMvFAST_MC/Cosmo_c_files/recombinations.c", "max_issues_repo_name": "NNSSA/21cmvFAST", "max_issues_repo_head_hexsha": "8f015427f3609a3051b4fa185bdbe55b379c930f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-17T05:27:25.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T19:59:55.000Z", "max_forks_repo_path": "public_21CMvFAST_MC/Cosmo_c_files/recombinations.c", "max_forks_repo_name": "NNSSA/21cmvFAST", "max_forks_repo_head_hexsha": "8f015427f3609a3051b4fa185bdbe55b379c930f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-14T13:54:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T17:16:53.000Z", "avg_line_length": 30.0461956522, "max_line_length": 147, "alphanum_fraction": 0.6963914262, "num_tokens": 3506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3708543435015912}}
{"text": "/**\n * @file batch_zdotu_sub.c\n *\n * Part of API test for Batched BLAS routines.\n *\n * @author  Samuel  D. Relton\n * @author  Pedro   V. Lara\n * @author  Mawussi Zounon\n * @date \n *\n * @precisions normal z -> c d s\n *\n **/\n\n#include <cblas.h>\n#include \"bblas.h\"\n\n#define COMPLEX\n\nvoid batch_zdotu_sub(\n\t\t  const int *n,\n\t\t  BBLAS_Complex64_t const * const *x,\n\t\t  const int *incx,\n\t\t  BBLAS_Complex64_t const * const *y,\n\t\t  const int *incy,\n\t\t  BBLAS_Complex64_t *dotu,\n\t\t  const int batch_count, const enum BBLAS_OPTS batch_opts,\n\t\t  int* info)\n{\n\t/* Local variables */\n\tint first_index = 0;\n\tchar func_name[15] = \"batch_zdotu\";\n\n\t/*initialize the result */\n\tfor (int batch_iter = 0; batch_iter < batch_count; batch_iter++)\n\t  {\n\t    dotu[batch_iter] = (BBLAS_Complex64_t)0.0;\n\t  }\n\t\n\t/* Check input arguments */\n\tif (batch_count < 0)\n\t{\n\t\txerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1);\n\t}\n\n\tif (batch_opts == BBLAS_FIXED)\n\t  {\n\t    /* Call fixed size code */\n\t    batchf_zdotu_sub(\n\t\t\t     n[first_index],\n\t\t\t     x,\n\t\t\t     incx[first_index],\n\t\t\t     y,\n\t\t\t     incy[first_index],\n\t\t\t     dotu,\n\t\t\t     batch_count, info);\n\t  }\n\telse if (batch_opts == BBLAS_VARIABLE)\n\t  {\n\t    /* Call variable size code */\n\t    batchv_zdotu_sub(\n\t\t\t     n,\n\t\t\t     x,\n\t\t\t     incx,\n\t\t\t     y,\n\t\t\t     incy,\n\t\t\t     dotu,\n\t\t\t     batch_count, info);\n\t    \n\t  }\n\telse\n\t  {\n\t    xerbla_batch(func_name, BBLAS_ERR_BATCH_OPTS, -1);\n\t  }\n}\n#undef COMPLEX\n", "meta": {"hexsha": "52c2b9161a61afa3a7adb78c1848c5923d4a4d25", "size": 1443, "ext": "c", "lang": "C", "max_stars_repo_path": "src/batch_zdotu.c", "max_stars_repo_name": "mawussi/BBLAS-group", "max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z", "max_issues_repo_path": "src/batch_zdotu.c", "max_issues_repo_name": "sdrelton/bblas_api_test", "max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/batch_zdotu.c", "max_forks_repo_name": "sdrelton/bblas_api_test", "max_forks_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7402597403, "max_line_length": 65, "alphanum_fraction": 0.595980596, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3706316367762173}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <QuEST.h>\n#include \"QuEST_debug.h\"\n#include \"QuEST_tn.h\"\n#include <cblas.h>\n\n#define DEBUG 0\n\n#if DEBUG\n# define DEBUG_PRINT(x) printf x\n#else\n# define DEBUG_PRINT(x) do {} while (0)\n#endif\n\nint* getTensorIndexPermutation(int* contractionIndices, int numContractions,\n        int* freeIndices, int numFreeIndices, int tensor){\n\n    int *perm = (int*) malloc((numContractions+numFreeIndices)*sizeof(int));\n\n    int firstSize, secondSize;\n    int *firstArray, *secondArray;\n    if (tensor==1){\n        firstSize=numFreeIndices;\n        firstArray=freeIndices;\n        secondSize=numContractions;\n        secondArray=contractionIndices;\n    } else {\n        secondSize=numFreeIndices;\n        secondArray=freeIndices;\n        firstSize=numContractions;\n        firstArray=contractionIndices;\n    }\n\n    for (int i=0; i<firstSize; i++){\n        perm[i]=firstArray[i];\n    }\n    for (int i=0; i<secondSize; i++){\n        perm[i+firstSize]=secondArray[i];\n    }\n    return perm;\n}\n\n/*\n * All indices are of size 2\n */\nint* getTensorSizes(int numQubits){\n    int *sizes = (int*) malloc(numQubits*sizeof(int));\n    for (int i=0; i<numQubits; i++) sizes[i]=2;\n    return sizes;\n}\n\n\nTensor createTensor(int numPq, int numVq, QuESTEnv env){\n    Tensor tensor;\n\n    //! Probably don't need to store these any more\n    tensor.numPq = numPq;\n    tensor.numVq = numVq;\n\n    tensor.qureg = createQureg(tensor.numPq + tensor.numVq, env);\n    //! might need to store next available vq\n\n    return tensor;\n}\n\n/*\n * Swap corresponding qubit IDs in perm and return new index\n */\nint swapBits(long long int b, int *perm, int nQubits) {\n  long long int out = 0;\n  for(int j=0;j<nQubits; j++) {\n    out += (b >> j & 1) * (1 << perm[j]);\n  }\n  return out;\n}\n\nqreal* permuteArray(Qureg qureg, int *perm) {\n  qreal* outArr = (qreal *) malloc(sizeof(qreal)*2*qureg.numAmpsPerChunk);\n  for (long long int i = 0; i < qureg.numAmpsPerChunk; i++) {\n    long long int newIndex = 2*swapBits(i, perm, qureg.numQubitsRepresented);\n    outArr[newIndex] = qureg.stateVec.real[i];\n    outArr[newIndex+1] = qureg.stateVec.imag[i];\n  }\n  return outArr;\n}\n\n/*\n * Expects tensor1Contractions to be in order from smallest to largest.\n * Expects tensor2Contractions to be ordered to match indices in tensor1.\n * Ie if tensor1 and tensor2 each have 3 indices and (tensor1, index 1) is\n * contracted with (tensor2, index 2) and (tensor1, index 2) is contracted with\n * (tensor2, index 0), use:\n * tensor1Contractions = [1, 2]\n * tensor2Contractions = [2, 0]\n */\nTensor contractIndices(Tensor tensor1, Tensor tensor2,\n        int *tensor1Contractions, int *tensor2Contractions, int numContractions,\n        int *tensor1FreeIndices, int numTensor1FreeIndices,\n        int *tensor2FreeIndices, int numTensor2FreeIndices,\n        QuESTEnv env){\n\n    printf(\"Begin contracting\\n\");\n    int numTensor1Qubits, numTensor2Qubits;\n    numTensor1Qubits = tensor1.qureg.numQubitsRepresented;\n    numTensor2Qubits = tensor2.qureg.numQubitsRepresented;\n    int totalNumQ = numTensor1FreeIndices + numTensor2FreeIndices;\n\n    printf(\"Permute indices to transform tensor contraction into the form of a matrix matrix multiply\\n\");\n    int *tensor1Perm = getTensorIndexPermutation(tensor1Contractions, numContractions,\n\t\t\t\t\t\t tensor1FreeIndices, numTensor1FreeIndices, 1);\n    int *tensor2Perm = getTensorIndexPermutation(tensor2Contractions, numContractions,\n\t\t\t\t\t\t tensor2FreeIndices, numTensor2FreeIndices, 2);\n\n    qreal* tensor1StateVecPermuted = permuteArray(tensor1.qureg, tensor1Perm);\n    qreal* tensor2StateVecPermuted = permuteArray(tensor2.qureg, tensor2Perm);\n\n    // Working output array for BLAS routine. This needs to be separate to contractedQureg as \n    // that represents complex numbers as a struct of arrays where BLAS will output an array of complex types\n    qreal* outputQureg = (qreal *) malloc(sizeof(qreal)*(1LL << (totalNumQ+1LL)));\n\n    // Dimensions of MM multiply\n    int M, N, K;\n    M = 1 << numTensor2FreeIndices;\n    N = 1 << numTensor1FreeIndices;\n    K = 1 << numContractions;\n    qreal alpha[2] = {1.0, 0.0};\n    qreal beta[2] = {0.0, 0.0};\n\n    printf(\"MM multiply dimensions: M:%d N:%d K:%d\\n\", M, N, K);\n\n    printf(\"Do MM multiply\\n\");\n    // tensor2 x tensor1.\n    cblas_zgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans, M, N, K, alpha,\n    \t\ttensor2StateVecPermuted, K, tensor1StateVecPermuted, N, beta, outputQureg, N);\n\n    // Copy output into qureg object\n    Qureg contractedQureg = createQureg(totalNumQ, env);\n    for(long long int index = 0; index < contractedQureg.numAmpsPerChunk; index++) {\n      contractedQureg.stateVec.real[index] = outputQureg[2*index];\n      contractedQureg.stateVec.imag[index] = outputQureg[2*index+1];\n    }\n\n    printf(\"Free memory\\n\");\n    free(tensor1StateVecPermuted);\n    free(tensor2StateVecPermuted);\n    free(outputQureg);\n\n    free(tensor1Perm);\n    free(tensor2Perm);\n\n    // Free old quregs\n    destroyQureg(tensor1.qureg, env);\n    destroyQureg(tensor2.qureg, env);\n\n    // Create output tensor\n    Tensor outputTensor;\n    outputTensor.qureg = contractedQureg;\n    //! TODO: We may need to set total number of qubits here\n    //outputTensor.numPq = totalNumPq;\n    //outputTensor.numVq = totalNumVq;\n\n    outputTensor.qureg = contractedQureg;\n    return outputTensor;\n}\n\n// ----- operations ------------------------------------------------------------\n\n\n/** Place target virtual qubit in the zero state\n * @param[in,out] tensor the tensor object\n */\nvoid initVirtualTarget(Tensor tensor, int virtualTargetIndex){\n         int vqIndex = virtualTargetIndex + tensor.numPq;\n     printf(\"vqIndex: %d\\n\", vqIndex);\n\n    Qureg qureg = tensor.qureg;\n\n    long long int stateVecSize;\n    long long int index;\n\n    // dimension of the state vector\n    // TODO: This won't work in parallel\n    stateVecSize = 1LL << vqIndex;\n\n    qreal *stateVecReal = qureg.stateVec.real;\n    qreal *stateVecImag = qureg.stateVec.imag;\n\n# ifdef _OPENMP\n# pragma omp parallel \\\n    default  (none) \\\n    shared   (stateVecSize, stateVecReal, stateVecImag) \\\n    private  (index)\n# endif\n    {\n# ifdef _OPENMP\n# pragma omp for schedule (static)\n# endif\n        for (index=0; index<stateVecSize; index++) {\n            stateVecReal[index+stateVecSize] = 0;\n            stateVecImag[index+stateVecSize] = 0;\n        }\n    }\n}\n\n/** Initialize virtual qubit to |0> + |1>\n * NOTE: not (1/sqrt(2))(|0> + |1>)\n * @param[in,out] tensor the tensor object\n * @param[in] virtual qubit to initialize. Index is local to a tensor but includes all physical qubits in the tensor\n */\nvoid initVirtualControl(Tensor tensor, int virtualControlIndex){\n    int vqIndex = virtualControlIndex + tensor.numPq;\n    Qureg qureg = tensor.qureg;\n\n    long long int stateVecSize;\n    long long int index;\n\n    // dimension of the state vector\n    // TODO: This won't work in parallel\n    stateVecSize = 1LL << vqIndex;\n\n    qreal *stateVecReal = qureg.stateVec.real;\n    qreal *stateVecImag = qureg.stateVec.imag;\n\n# ifdef _OPENMP\n# pragma omp parallel \\\n    default  (none) \\\n    shared   (stateVecSize, stateVecReal, stateVecImag) \\\n    private  (index)\n# endif\n    {\n# ifdef _OPENMP\n# pragma omp for schedule (static)\n# endif\n        for (index=0; index<stateVecSize; index++) {\n            stateVecReal[index+stateVecSize] = stateVecReal[index];\n            stateVecImag[index+stateVecSize] = stateVecImag[index];\n        }\n    }\n}\n\n\n", "meta": {"hexsha": "9c04570e25d0df05e260ec31f1e8ec3fe6cca076", "size": 7454, "ext": "c", "lang": "C", "max_stars_repo_path": "TN/QuEST_tn.c", "max_stars_repo_name": "aniabrown/QuEST-TN", "max_stars_repo_head_hexsha": "8e0c8686859531d670d537af5eec03b7232f6b26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TN/QuEST_tn.c", "max_issues_repo_name": "aniabrown/QuEST-TN", "max_issues_repo_head_hexsha": "8e0c8686859531d670d537af5eec03b7232f6b26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-02-06T07:02:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-01T14:44:40.000Z", "max_forks_repo_path": "TN/QuEST_tn.c", "max_forks_repo_name": "aniabrown/QuEST-TN", "max_forks_repo_head_hexsha": "8e0c8686859531d670d537af5eec03b7232f6b26", "max_forks_repo_licenses": ["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.6748971193, "max_line_length": 116, "alphanum_fraction": 0.6773544406, "num_tokens": 2099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.3705442184703919}}
{"text": "/* filter/rmedian.c\n *\n * Copyright (C) 2018 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/*\n * This module contains routines related to the recursive median filter. The\n * algorithm is based on this paper,\n *\n * [1] S-J Ko, Y. H. Lee, and A. T. Fam, Efficient Implementation of One-Dimensional\n * Recursive Median Filters, IEEE Transactions on Circuits and Systems, Vol 37,\n * No 11, 1990.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_filter.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_statistics.h>\n#include <gsl/gsl_movstat.h>\n\ntypedef struct\n{\n  const gsl_movstat_accum * minmax_acc; /* minimum/maximum accumulator */\n  void *minmax_state;                   /* minimum/maximum accumulator workspace */\n} rmedian_state_t;\n\nstatic size_t rmedian_size(const size_t n);\nstatic int rmedian_init(const size_t n, void * vstate);\nstatic int rmedian_insert(const double x, void * vstate);\nstatic int rmedian_delete(void * vstate);\nstatic int rmedian_get(void * params, double * result, const void * vstate);\n\nstatic const gsl_movstat_accum rmedian_accum_type;\n\ngsl_filter_rmedian_workspace *\ngsl_filter_rmedian_alloc(const size_t K)\n{\n  gsl_filter_rmedian_workspace *w;\n  size_t state_size;\n\n  w = calloc(1, sizeof(gsl_filter_rmedian_workspace));\n  if (w == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for workspace\", GSL_ENOMEM);\n    }\n\n  w->H = K / 2;\n  w->K = 2*w->H + 1;\n  w->minmaxacc = gsl_movstat_accum_minmax;\n\n  w->window = malloc(w->K * sizeof(double));\n  if (w->window == NULL)\n    {\n      gsl_filter_rmedian_free(w);\n      GSL_ERROR_NULL (\"failed to allocate space for window\", GSL_ENOMEM);\n    }\n\n  state_size = rmedian_size(w->H + 1);\n\n  w->state = malloc(state_size);\n  if (w->state == NULL)\n    {\n      gsl_filter_rmedian_free(w);\n      GSL_ERROR_NULL (\"failed to allocate space for min/max state\", GSL_ENOMEM);\n    }\n\n  w->movstat_workspace_p = gsl_movstat_alloc_with_size(state_size, 0, w->H);\n  if (!w->movstat_workspace_p)\n    {\n      gsl_filter_rmedian_free(w);\n      GSL_ERROR_NULL (\"failed to allocate space for movstat workspace\", GSL_ENOMEM);\n    }\n\n  return w;\n}\n\nvoid\ngsl_filter_rmedian_free(gsl_filter_rmedian_workspace * w)\n{\n  if (w->state)\n    free(w->state);\n\n  if (w->window)\n    free(w->window);\n\n  if (w->movstat_workspace_p)\n    gsl_movstat_free(w->movstat_workspace_p);\n\n  free(w);\n}\n\n/*\ngsl_filter_rmedian()\n  Recursive median filter\n\nInputs: endtype - end point handling\n        x       - input vector\n        y       - output vector\n        w       - workspace\n*/\n\nint\ngsl_filter_rmedian(const gsl_filter_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_filter_rmedian_workspace * w)\n{\n  if (x->size != y->size)\n    {\n      GSL_ERROR(\"input and output vectors must have same length\", GSL_EBADLEN);\n    }\n  else\n    {\n      int status = GSL_SUCCESS;\n      const size_t n = x->size;\n      const int H = (int) w->H;\n      double yprev;\n      int wsize;\n\n      /* find median of first window to initialize filter */\n      wsize = gsl_movstat_fill(endtype, x, 0, H, H, w->window);\n      yprev = gsl_stats_median(w->window, 1, wsize);\n      gsl_vector_set(y, 0, yprev);\n\n      if (x->size > 1)\n        {\n          gsl_vector_const_view xv = gsl_vector_const_subvector(x, 1, n - 1);\n          gsl_vector_view yv = gsl_vector_subvector(y, 1, n - 1);\n\n          /* apply recursive median filter to x[2:end] */\n          status = gsl_movstat_apply_accum(endtype, &xv.vector, &rmedian_accum_type, (void *) &yprev, &yv.vector,\n                                           NULL, w->movstat_workspace_p);\n        }\n\n      return status;\n    }\n}\n\nstatic size_t\nrmedian_size(const size_t n)\n{\n  size_t size = 0;\n  const gsl_movstat_accum * acc = gsl_movstat_accum_minmax;\n\n  size += sizeof(rmedian_state_t);\n  size += (acc->size)(n);\n\n  return size;\n}\n\nstatic int\nrmedian_init(const size_t n, void * vstate)\n{\n  rmedian_state_t * state = (rmedian_state_t *) vstate;\n\n  state->minmax_acc = gsl_movstat_accum_minmax;\n  state->minmax_state = (void *) ((unsigned char *) vstate + sizeof(rmedian_state_t));\n\n  (state->minmax_acc->init)(n, state->minmax_state);\n\n  return GSL_SUCCESS;\n}\n\nstatic int\nrmedian_insert(const double x, void * vstate)\n{\n  rmedian_state_t * state = (rmedian_state_t *) vstate;\n  return (state->minmax_acc->insert)(x, state->minmax_state);\n}\n\nstatic int\nrmedian_delete(void * vstate)\n{\n  rmedian_state_t * state = (rmedian_state_t *) vstate;\n  return (state->minmax_acc->delete_oldest)(state->minmax_state);\n}\n\nstatic int\nrmedian_get(void * params, double * result, const void * vstate)\n{\n  const rmedian_state_t * state = (const rmedian_state_t *) vstate;\n  double *yprev = (double *) params; /* previous filter output */\n  double y;                          /* new filter output */\n  double xminmax[2];\n\n  /* get minimum/maximum values of {x_i,...,x_{i+H}} */\n  (state->minmax_acc->get)(NULL, xminmax, state->minmax_state);\n\n  /* y = median [ yprev, xmin, xmax ] */\n  if (*yprev <= xminmax[0])\n    y = xminmax[0];\n  else if (*yprev <= xminmax[1])\n    y = *yprev;\n  else\n    y = xminmax[1];\n\n  *result = y;\n  *yprev = y;\n\n  return GSL_SUCCESS;\n}\n\nstatic const gsl_movstat_accum rmedian_accum_type =\n{\n  rmedian_size,\n  rmedian_init,\n  rmedian_insert,\n  rmedian_delete,\n  rmedian_get\n};\n", "meta": {"hexsha": "e57169a3ac5f1e3ae2a056a98ce2be7ff32c8cd7", "size": 6037, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/filter/rmedian.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/filter/rmedian.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/filter/rmedian.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 26.5947136564, "max_line_length": 122, "alphanum_fraction": 0.6746728508, "num_tokens": 1656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979746, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.37054421145966565}}
{"text": "#include \"ccv.h\"\n#include \"ccv_internal.h\"\n#if defined(HAVE_SSE2)\n#include <xmmintrin.h>\n#elif defined(HAVE_NEON)\n#include <arm_neon.h>\n#endif\n#ifdef HAVE_GSL\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#endif\n#ifdef USE_DISPATCH\n#include <dispatch/dispatch.h>\n#endif\n#ifdef HAVE_CUDA\n#include \"cuda/cwc.h\"\n#endif\n#include \"3rdparty/sqlite3/sqlite3.h\"\n#include \"inl/ccv_convnet_inl.h\"\n\n#ifndef CASE_TESTS\n\nccv_convnet_t* ccv_convnet_new(int use_cwc_accel, ccv_size_t input, ccv_convnet_layer_param_t params[], int count)\n{\n\tccv_convnet_t* convnet = (ccv_convnet_t*)ccmalloc(sizeof(ccv_convnet_t) + sizeof(ccv_convnet_layer_t) * count + sizeof(ccv_dense_matrix_t*) * count * 2);\n\tconvnet->use_cwc_accel = use_cwc_accel;\n#ifdef HAVE_GSL\n\tgsl_rng_env_setup();\n\tgsl_rng* rng = gsl_rng_alloc(gsl_rng_default);\n\tgsl_rng_set(rng, (unsigned long int)convnet);\n#endif\n\tconvnet->reserved = 0;\n\tconvnet->layers = (ccv_convnet_layer_t*)(convnet + 1);\n\tconvnet->acts = (ccv_dense_matrix_t**)(convnet->layers + count);\n\tmemset(convnet->acts, 0, sizeof(ccv_dense_matrix_t*) * count);\n\tconvnet->denoms = (ccv_dense_matrix_t**)(convnet->acts + count);\n\tmemset(convnet->denoms, 0, sizeof(ccv_dense_matrix_t*) * count);\n\tconvnet->count = count;\n\tconvnet->input = input;\n\tconvnet->rows = params[0].input.matrix.rows;\n\tconvnet->cols = params[0].input.matrix.cols;\n\tconvnet->channels = params[0].input.matrix.channels;\n\tconvnet->mean_activity = ccv_dense_matrix_new(convnet->input.height, convnet->input.width, convnet->channels | CCV_32F, 0, 0);\n\tccv_zero(convnet->mean_activity);\n\tccv_convnet_layer_t* layers = convnet->layers;\n\tint i, j;\n\tfor (i = 0; i < count; i++)\n\t{\n\t\tlayers[i].type = params[i].type;\n\t\tlayers[i].input = params[i].input;\n\t\tlayers[i].net = params[i].output;\n\t\tlayers[i].reserved = 0;\n\t\tswitch (params[i].type)\n\t\t{\n\t\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t\tassert(params[i].input.matrix.channels % params[i].input.matrix.partition == 0);\n\t\t\t\tassert(params[i].output.convolutional.count % params[i].output.convolutional.partition == 0);\n\t\t\t\tassert(params[i].output.convolutional.partition % params[i].input.matrix.partition == 0);\n\t\t\t\tassert(params[i].output.convolutional.partition >= params[i].input.matrix.partition);\n\t\t\t\tlayers[i].wnum = params[i].output.convolutional.rows * params[i].output.convolutional.cols * params[i].output.convolutional.channels / params[i].input.matrix.partition * params[i].output.convolutional.count;\n\t\t\t\tlayers[i].w = (float*)ccmalloc(sizeof(float) * (layers[i].wnum + params[i].output.convolutional.count));\n\t\t\t\tlayers[i].bias = layers[i].w + layers[i].wnum;\n#ifdef HAVE_GSL\n\t\t\t\tfor (j = 0; j < layers[i].wnum; j++)\n\t\t\t\t\tlayers[i].w[j] = (gsl_rng_uniform_pos(rng) * 2 - 1) * params[i].glorot / sqrtf(params[i].output.convolutional.rows * params[i].output.convolutional.cols * params[i].output.convolutional.channels / params[i].input.matrix.partition + params[i].output.convolutional.count);\n#else\n\t\t\t\tfor (j = 0; j < layers[i].wnum; j++)\n\t\t\t\t\tlayers[i].w[j] = 0;\n#endif\n\t\t\t\tfor (j = 0; j < params[i].output.convolutional.count; j++)\n\t\t\t\t\tlayers[i].bias[j] = params[i].bias;\n\t\t\t\tbreak;\n\t\t\tcase CCV_CONVNET_FULL_CONNECT:\n\t\t\t\tlayers[i].wnum = params[i].input.node.count * params[i].output.full_connect.count;\n\t\t\t\tlayers[i].w = (float*)ccmalloc(sizeof(float) * (layers[i].wnum + params[i].output.full_connect.count));\n\t\t\t\tlayers[i].bias = layers[i].w + layers[i].wnum;\n#ifdef HAVE_GSL\n\t\t\t\tfor (j = 0; j < layers[i].wnum; j++)\n\t\t\t\t\tlayers[i].w[j] = (gsl_rng_uniform_pos(rng) * 2 - 1) * params[i].glorot / sqrtf(params[i].input.node.count + params[i].output.full_connect.count);\n#else\n\t\t\t\tfor (j = 0; j < layers[i].wnum; j++)\n\t\t\t\t\tlayers[i].w[j] = 0;\n#endif\n\t\t\t\tfor (j = 0; j < params[i].output.full_connect.count; j++)\n\t\t\t\t\tlayers[i].bias[j] = params[i].bias;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tlayers[i].wnum = 0;\n\t\t\t\tlayers[i].w = 0;\n\t\t\t\tlayers[i].bias = 0;\n\t\t\t\tbreak;\n\t\t}\n\t}\n#ifdef HAVE_GSL\n\tgsl_rng_free(rng);\n#endif\n\treturn convnet;\n}\n\nint ccv_convnet_verify(ccv_convnet_t* convnet, int output)\n{\n\tint i, out_rows, out_cols, out_partition;\n\tif (convnet->count < 1)\n\t\treturn -1;\n\t// the last layer has to be full connect\n\tif (convnet->layers[convnet->count - 1].type != CCV_CONVNET_FULL_CONNECT)\n\t\treturn -1;\n\t// you cannot enable relu on the last layer\n\tif (convnet->layers[convnet->count - 1].net.full_connect.relu)\n\t\treturn -1;\n\tfor (i = 0; i < convnet->count; i++)\n\t{\n\t\tccv_convnet_layer_t* layer = convnet->layers + i;\n\t\tif (i > 0 && (out_rows != layer->input.matrix.rows || out_cols != layer->input.matrix.cols))\n\t\t\treturn -1;\n\t\tccv_convnet_make_output(layer, layer->input.matrix.rows, layer->input.matrix.cols, &out_rows, &out_cols, &out_partition);\n\t}\n\tif (out_rows * out_cols != output)\n\t\treturn -1;\n\tint count = 0;\n\tfor (i = 0; i < convnet->count; i++)\n\t{\n\t\tccv_convnet_layer_t* layer = convnet->layers + i;\n\t\tif (layer->type == CCV_CONVNET_FULL_CONNECT)\n\t\t{\n\t\t\tcount = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\t// all the layers after the first full connect layer should only be full connect layer\n\tfor (i = count; i < convnet->count; i++)\n\t\tif (convnet->layers[i].type != CCV_CONVNET_FULL_CONNECT ||\n\t\t\tconvnet->layers[i].input.matrix.rows * convnet->layers[i].input.matrix.cols * convnet->layers[i].input.matrix.channels != convnet->layers[i].input.node.count)\n\t\t\treturn -1;\n\treturn 0;\n}\n\n#endif\n\n#if defined(HAVE_SSE2) || defined(HAVE_NEON)\n\nstatic void _ccv_convnet_layer_simd_alloc_reserved(ccv_convnet_layer_t* layer)\n{\n\tif (layer->reserved)\n\t\treturn;\n\tint partition = layer->input.matrix.partition;\n\tint ch = layer->net.convolutional.channels;\n\tint count = layer->net.convolutional.count;\n\tint kernel_rows = layer->net.convolutional.rows;\n\tint kernel_cols = layer->net.convolutional.cols;\n\tint ch_per_partition = ch / partition;\n\tint count_per_4 = count / 4;\n\tfloat* simd_w = (float*)ccmalloc(sizeof(float) * layer->wnum);\n\tint i, j, k, c;\n\tfor (k = 0; k < count_per_4; k++)\n\t\tfor (i = 0; i < kernel_rows * kernel_cols; i++)\n\t\t\tfor (j = 0; j < ch_per_partition; j++)\n\t\t\t\tfor (c = 0; c < 4; c++)\n\t\t\t\t\tsimd_w[(k * kernel_rows * kernel_cols * ch_per_partition + i * ch_per_partition + j) * 4 + c] = layer->w[(k * 4 + c) * kernel_rows * kernel_cols * ch_per_partition + i * ch_per_partition + j];\n\tlayer->reserved = simd_w;\n}\n\n#endif\n\n#define SIMD(x) ((float*)((x)->reserved))\n\n#if defined(HAVE_SSE2)\nstatic inline void _ccv_convnet_convolutional_forward_propagate_sse2(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* db, int rows, int cols, int ch, int count, int strides, int border, int kernel_rows, int kernel_cols, int ch_per_partition, int count_per_partition)\n{\n\tassert(SIMD(layer));\n#define main_for(block) \\\n\tparallel_for(k, (count >> 2)) { \\\n\t\tint i, j, x, y, c; \\\n\t\tint p = k * 4 / count_per_partition; \\\n\t\tfloat* ap = a->data.f32 + p * ch_per_partition; \\\n\t\tfloat* bp = db->data.f32 + k * 4; \\\n\t\tfloat* layer_w = SIMD(layer) + k * 4 * kernel_rows * kernel_cols * ch_per_partition; \\\n\t\tfloat bias[4] __attribute__ ((__aligned__(16))); \\\n\t\tmemcpy(bias, layer->bias + k * 4, sizeof(float) * 4); \\\n\t\t/* 4 accumulators */ \\\n\t\t__m128 z4 = _mm_setzero_ps(); \\\n\t\tfor (i = 0; i < db->rows; i++) \\\n\t\t{ \\\n\t\t\tint comy = ccv_max(i * strides - border, 0) - (i * strides - border); \\\n\t\t\tint maxy = kernel_rows - comy - (i * strides + kernel_rows - ccv_min(a->rows + border, i * strides + kernel_rows)); \\\n\t\t\tcomy *= ch_per_partition * kernel_cols; \\\n\t\t\tfor (j = 0; j < db->cols; j++) \\\n\t\t\t{ \\\n\t\t\t\t__m128 v40 = _mm_load_ps(bias); \\\n\t\t\t\t__m128 v41 = _mm_setzero_ps(); \\\n\t\t\t\t__m128 v42 = _mm_setzero_ps(); \\\n\t\t\t\t__m128 v43 = _mm_setzero_ps(); \\\n\t\t\t\tint comx = ccv_max(j * strides - border, 0) - (j * strides - border); \\\n\t\t\t\tint maxx = kernel_cols - comx - (j * strides + kernel_cols - ccv_min(a->cols + border, j * strides + kernel_cols)); \\\n\t\t\t\tfloat* w = layer_w + (comx * ch_per_partition + comy) * 4; \\\n\t\t\t\tfloat* apz = ap + ccv_max(j * strides - border, 0) * ch; \\\n\t\t\t\t/* when we have border, we simply do zero padding */ \\\n\t\t\t\tfor (y = 0; y < maxy; y++) \\\n\t\t\t\t{ \\\n\t\t\t\t\t/* special casing for these cases to speed up SIMD computation */ \\\n\t\t\t\t\tfor (x = 0; x < maxx; x++) \\\n\t\t\t\t\t{ \\\n\t\t\t\t\t\tc = 0; \\\n\t\t\t\t\t\tfor (; c < ch_per_partition - 3; c += 4) \\\n\t\t\t\t\t\t{ \\\n\t\t\t\t\t\t\t__m128 apz4 = _mm_loadu_ps(apz + x * ch + c); \\\n\t\t\t\t\t\t\t__m128 w40 = _mm_loadu_ps(w + (x * ch_per_partition + c) * 4); \\\n\t\t\t\t\t\t\t__m128 w41 = _mm_loadu_ps(w + (x * ch_per_partition + c + 1) * 4); \\\n\t\t\t\t\t\t\t__m128 w42 = _mm_loadu_ps(w + (x * ch_per_partition + c + 2) * 4); \\\n\t\t\t\t\t\t\t__m128 w43 = _mm_loadu_ps(w + (x * ch_per_partition + c + 3) * 4); \\\n\t\t\t\t\t\t\t__m128 apz40 = _mm_shuffle_ps(apz4, apz4, 0x00); \\\n\t\t\t\t\t\t\t__m128 apz41 = _mm_shuffle_ps(apz4, apz4, 0x55); \\\n\t\t\t\t\t\t\t__m128 apz42 = _mm_shuffle_ps(apz4, apz4, 0xAA); \\\n\t\t\t\t\t\t\t__m128 apz43 = _mm_shuffle_ps(apz4, apz4, 0xFF); \\\n\t\t\t\t\t\t\tv40 =_mm_add_ps(_mm_mul_ps(w40, apz40), v40); \\\n\t\t\t\t\t\t\tv41 =_mm_add_ps(_mm_mul_ps(w41, apz41), v41); \\\n\t\t\t\t\t\t\tv42 =_mm_add_ps(_mm_mul_ps(w42, apz42), v42); \\\n\t\t\t\t\t\t\tv43 =_mm_add_ps(_mm_mul_ps(w43, apz43), v43); \\\n\t\t\t\t\t\t} \\\n\t\t\t\t\t\tblock /* insert executions for tail partition */ \\\n\t\t\t\t\t} \\\n\t\t\t\t\tw += kernel_cols * ch_per_partition * 4; \\\n\t\t\t\t\tapz += a->cols * ch; \\\n\t\t\t\t} \\\n\t\t\t\t__m128 v4 = _mm_max_ps(z4, _mm_add_ps(_mm_add_ps(v40, v41), _mm_add_ps(v42, v43))); \\\n\t\t\t\t_mm_storeu_ps(bp + j * count, v4); /* ReLU */ \\\n\t\t\t} \\\n\t\t\tbp += db->cols * count; \\\n\t\t\tap += a->cols * ch * (ccv_max((i + 1) * strides - border, 0) - ccv_max(i * strides - border, 0)); \\\n\t\t} \\\n\t} parallel_endfor\n\tif (ch_per_partition % 4 == 0)\n\t{\n\t\tmain_for();\n\t} else if (ch_per_partition % 4 == 3) { // unroll the last for-loops\n#define block \\\n\t\t__m128 apz40 = _mm_load1_ps(apz + x * ch + c); \\\n\t\t__m128 apz41 = _mm_load1_ps(apz + x * ch + c + 1); \\\n\t\t__m128 apz42 = _mm_load1_ps(apz + x * ch + c + 2); \\\n\t\t__m128 w40 = _mm_loadu_ps(w + (x * ch_per_partition + c) * 4); \\\n\t\t__m128 w41 = _mm_loadu_ps(w + (x * ch_per_partition + c + 1) * 4); \\\n\t\t__m128 w42 = _mm_loadu_ps(w + (x * ch_per_partition + c + 2) * 4); \\\n\t\tv40 = _mm_add_ps(_mm_mul_ps(w40, apz40), v40); \\\n\t\tv41 = _mm_add_ps(_mm_mul_ps(w41, apz41), v41); \\\n\t\tv42 = _mm_add_ps(_mm_mul_ps(w42, apz42), v42);\n\t\tmain_for(block);\n#undef block\n\t} else if (ch_per_partition % 4 == 2) { // unroll the last for-loops\n#define block \\\n\t\t__m128 apz40 = _mm_load1_ps(apz + x * ch + c); \\\n\t\t__m128 apz41 = _mm_load1_ps(apz + x * ch + c + 1); \\\n\t\t__m128 w40 = _mm_loadu_ps(w + (x * ch_per_partition + c) * 4); \\\n\t\t__m128 w41 = _mm_loadu_ps(w + (x * ch_per_partition + c + 1) * 4); \\\n\t\tv40 = _mm_add_ps(_mm_mul_ps(w40, apz40), v40); \\\n\t\tv41 = _mm_add_ps(_mm_mul_ps(w41, apz41), v41);\n\t\tmain_for(block);\n#undef block\n\t} else {\n#define block \\\n\t\t__m128 apz4 = _mm_load1_ps(apz + x * ch + c); \\\n\t\t__m128 w4 = _mm_loadu_ps(w + (x * ch_per_partition + c) * 4); \\\n\t\tv40 = _mm_add_ps(_mm_mul_ps(w4, apz4), v40);\n\t\tmain_for(block);\n#undef block\n\t}\n#undef main_for\n}\n#elif defined(HAVE_NEON)\nstatic inline void _ccv_convnet_convolutional_forward_propagate_neon(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* db, int rows, int cols, int ch, int count, int strides, int border, int kernel_rows, int kernel_cols, int ch_per_partition, int count_per_partition)\n{\n\tassert(SIMD(layer));\n#define main_for(block) \\\n\tparallel_for(k, (count >> 2)) { \\\n\t\tint i, j, x, y, c; \\\n\t\tint p = k * 4 / count_per_partition; \\\n\t\tfloat* ap = a->data.f32 + p * ch_per_partition; \\\n\t\tfloat* bp = db->data.f32 + k * 4; \\\n\t\tfloat* layer_w = SIMD(layer) + k * 4 * kernel_rows * kernel_cols * ch_per_partition; \\\n\t\tfloat bias[4] __attribute__ ((__aligned__(16))); \\\n\t\tmemcpy(bias, layer->bias + k * 4, sizeof(float) * 4); \\\n\t\tfloat32x4_t z4 = vmovq_n_f32(0); \\\n\t\tfor (i = 0; i < db->rows; i++) \\\n\t\t{ \\\n\t\t\tint comy = ccv_max(i * strides - border, 0) - (i * strides - border); \\\n\t\t\tint maxy = kernel_rows - comy - (i * strides + kernel_rows - ccv_min(a->rows + border, i * strides + kernel_rows)); \\\n\t\t\tcomy *= ch_per_partition * kernel_cols; \\\n\t\t\tfor (j = 0; j < db->cols; j++) \\\n\t\t\t{ \\\n\t\t\t\tfloat32x4_t v40 = vld1q_f32(bias); \\\n\t\t\t\tfloat32x4_t v41 = vmovq_n_f32(0); \\\n\t\t\t\tint comx = ccv_max(j * strides - border, 0) - (j * strides - border); \\\n\t\t\t\tint maxx = kernel_cols - comx - (j * strides + kernel_cols - ccv_min(a->cols + border, j * strides + kernel_cols)); \\\n\t\t\t\tfloat* w = layer_w + (comx * ch_per_partition + comy) * 4; \\\n\t\t\t\tfloat* apz = ap + ccv_max(j * strides - border, 0) * ch; \\\n\t\t\t\t/* when we have border, we simply do zero padding */ \\\n\t\t\t\tfor (y = 0; y < maxy; y++) \\\n\t\t\t\t{ \\\n\t\t\t\t\tfor (x = 0; x < maxx; x++) \\\n\t\t\t\t\t{ \\\n\t\t\t\t\t\tc = 0; \\\n\t\t\t\t\t\tfor (; c < ch_per_partition - 1; c += 2) \\\n\t\t\t\t\t\t{ \\\n\t\t\t\t\t\t\tfloat32x2_t apz4 = vld1_f32(apz + x * ch + c); \\\n\t\t\t\t\t\t\tfloat32x4_t apz40 = vdupq_lane_f32(apz4, 0); \\\n\t\t\t\t\t\t\tfloat32x4_t apz41 = vdupq_lane_f32(apz4, 1); \\\n\t\t\t\t\t\t\tfloat32x4_t w40 = vld1q_f32(w + (x * ch_per_partition + c) * 4); \\\n\t\t\t\t\t\t\tfloat32x4_t w41 = vld1q_f32(w + (x * ch_per_partition + c + 1) * 4); \\\n\t\t\t\t\t\t\tv40 = vmlaq_f32(v40, w40, apz40); \\\n\t\t\t\t\t\t\tv41 = vmlaq_f32(v41, w41, apz41); \\\n\t\t\t\t\t\t} \\\n\t\t\t\t\t\tblock /* insert executions for tail partition */ \\\n\t\t\t\t\t} \\\n\t\t\t\t\tw += kernel_cols * ch_per_partition * 4; \\\n\t\t\t\t\tapz += a->cols * ch; \\\n\t\t\t\t} \\\n\t\t\t\tfloat32x4_t v4 = vmaxq_f32(z4, vaddq_f32(v40, v41)); \\\n\t\t\t\tvst1q_f32(bp + j * count, v4); /* ReLU */ \\\n\t\t\t} \\\n\t\t\tbp += db->cols * count; \\\n\t\t\tap += a->cols * ch * (ccv_max((i + 1) * strides - border, 0) - ccv_max(i * strides - border, 0)); \\\n\t\t} \\\n\t} parallel_endfor\n\tif (ch_per_partition % 2 == 0)\n\t{\n\t\tmain_for();\n\t} else { // unroll the last for-loops\n#define block \\\n\t\tfloat32x4_t apz4 = vmovq_n_f32(apz[x * ch + c]); \\\n\t\tfloat32x4_t w4 = vld1q_f32(w + (x * ch_per_partition + c) * 4); \\\n\t\tv40 = vmlaq_f32(v40, w4, apz4);\n\t\tmain_for(block);\n#undef block\n\t}\n#undef main_for\n}\n#else\nstatic inline void _ccv_convnet_convolutional_forward_propagate_fallback(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* db, int rows, int cols, int ch, int count, int strides, int border, int kernel_rows, int kernel_cols, int ch_per_partition, int count_per_partition)\n{\n\tparallel_for(k, count) {\n\t\tint i, j, x, y, c;\n\t\tint p = k / count_per_partition;\n\t\tfloat* ap = a->data.f32 + p * ch_per_partition;\n\t\tfloat* bp = db->data.f32 + k;\n\t\tfloat* layer_w = layer->w + k * kernel_rows * kernel_cols * ch_per_partition;\n\t\tfloat bias = layer->bias[k];\n\t\tfor (i = 0; i < db->rows; i++)\n\t\t{\n\t\t\tint comy = ccv_max(i * strides - border, 0) - (i * strides - border);\n\t\t\tint maxy = kernel_rows - comy - (i * strides + kernel_rows - ccv_min(a->rows + border, i * strides + kernel_rows));\n\t\t\tcomy *= ch_per_partition * kernel_cols;\n\t\t\tfor (j = 0; j < db->cols; j++)\n\t\t\t{\n\t\t\t\tfloat v = bias;\n\t\t\t\tint comx = ccv_max(j * strides - border, 0) - (j * strides - border);\n\t\t\t\tint maxx = kernel_cols - comx - (j * strides + kernel_cols - ccv_min(a->cols + border, j * strides + kernel_cols));\n\t\t\t\tfloat* w = layer_w + comx * ch_per_partition + comy;\n\t\t\t\tfloat* apz = ap + ccv_max(j * strides - border, 0) * ch;\n\t\t\t\t// when we have border, we simply do zero padding\n\t\t\t\tfor (y = 0; y < maxy; y++)\n\t\t\t\t{\n\t\t\t\t\tfor (x = 0; x < maxx; x++)\n\t\t\t\t\t\tfor (c = 0; c < ch_per_partition; c++)\n\t\t\t\t\t\t\tv += w[x * ch_per_partition + c] * apz[x * ch + c];\n\t\t\t\t\tw += kernel_cols * ch_per_partition;\n\t\t\t\t\tapz += a->cols * ch;\n\t\t\t\t}\n\t\t\t\tbp[j * count] = ccv_max(0, v); // ReLU\n\t\t\t}\n\t\t\tbp += db->cols * count;\n\t\t\tap += a->cols * ch * (ccv_max((i + 1) * strides - border, 0) - ccv_max(i * strides - border, 0));\n\t\t}\n\t} parallel_endfor\n}\n#endif\n\nstatic void _ccv_convnet_convolutional_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b)\n{\n\tint rows, cols, partition;\n\tccv_convnet_make_output(layer, a->rows, a->cols, &rows, &cols, &partition);\n\tint ch = layer->net.convolutional.channels;\n\tint count = layer->net.convolutional.count;\n\tint strides = layer->net.convolutional.strides;\n\tint border = layer->net.convolutional.border;\n\tint kernel_rows = layer->net.convolutional.rows;\n\tint kernel_cols = layer->net.convolutional.cols;\n\tint type = CCV_32F | count;\n\tassert(CCV_GET_CHANNEL(a->type) == ch);\n\tassert(CCV_GET_DATA_TYPE(a->type) == CCV_32F);\n\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, rows, cols, type, type, 0);\n\tint ch_per_partition = ch / partition;\n\tint count_per_partition = count / partition;\n\tassert(count_per_partition % 4 == 0);\n#if defined(HAVE_SSE2) || defined(HAVE_NEON)\n\t_ccv_convnet_layer_simd_alloc_reserved(layer);\n#endif\n#if defined(HAVE_SSE2)\n\t_ccv_convnet_convolutional_forward_propagate_sse2(layer, a, db, rows, cols, ch, count, strides, border, kernel_rows, kernel_cols, ch_per_partition, count_per_partition);\n#elif defined(HAVE_NEON)\n\t_ccv_convnet_convolutional_forward_propagate_neon(layer, a, db, rows, cols, ch, count, strides, border, kernel_rows, kernel_cols, ch_per_partition, count_per_partition);\n#else\n\t_ccv_convnet_convolutional_forward_propagate_fallback(layer, a, db, rows, cols, ch, count, strides, border, kernel_rows, kernel_cols, ch_per_partition, count_per_partition);\n#endif\n}\n\nstatic void _ccv_convnet_full_connect_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b)\n{\n\tassert(CCV_GET_DATA_TYPE(a->type) == CCV_32F);\n\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, layer->net.full_connect.count, 1, CCV_32F | CCV_C1, CCV_32F | CCV_C1, 0);\n\tint ch = CCV_GET_CHANNEL(a->type);\n\tint rows = a->rows, cols = a->cols;\n\t// reshape a for gemm\n\tassert(a->step == a->cols * CCV_GET_DATA_TYPE_SIZE(a->type) * ch);\n\ta->rows = rows * cols * ch, a->cols = 1, a->type = (a->type - ch) | CCV_C1;\n\tassert(a->rows * db->rows == layer->wnum);\n\ta->step = a->cols * CCV_GET_DATA_TYPE_SIZE(a->type);\n\tint i;\n\tfloat* bptr = db->data.f32;\n\tfor (i = 0; i < db->rows; i++)\n\t\tbptr[i] = layer->bias[i];\n\tccv_dense_matrix_t dw = ccv_dense_matrix(db->rows, a->rows, CCV_32F | CCV_C1, layer->w, 0);\n\tccv_gemm(&dw, a, 1, db, 1, 0, (ccv_matrix_t**)&db, 0); // supply db as matrix C is allowed\n\tif (layer->net.full_connect.relu)\n\t\tfor (i = 0; i < db->rows; i++)\n\t\t\tbptr[i] = ccv_max(0, bptr[i]); // relu\n\ta->rows = rows, a->cols = cols, a->type = (a->type - CCV_GET_CHANNEL(a->type)) | ch;\n\ta->step = a->cols * CCV_GET_DATA_TYPE_SIZE(a->type) * CCV_GET_CHANNEL(a->type);\n}\n\nstatic void _ccv_convnet_rnorm_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, ccv_dense_matrix_t** denoms)\n{\n\tint rows, cols, partition;\n\tccv_convnet_make_output(layer, a->rows, a->cols, &rows, &cols, &partition);\n\tint size = layer->net.rnorm.size;\n\tfloat kappa = layer->net.rnorm.kappa;\n\tfloat alpha = layer->net.rnorm.alpha;\n\tfloat beta = layer->net.rnorm.beta;\n\tint way = size / 2;\n\tassert(CCV_GET_DATA_TYPE(a->type) == CCV_32F);\n\tint ch = CCV_GET_CHANNEL(a->type);\n\tint type = CCV_32F | ch;\n\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, rows, cols, type, type, 0);\n\tint i, j, k, x, p;\n\tfloat* ap = a->data.f32;\n\tfloat* bp = db->data.f32;\n\tint ch_per_partition = ch / partition;\n\tif (denoms)\n\t{\n\t\tccv_dense_matrix_t* ddenoms = *denoms = ccv_dense_matrix_renew(*denoms, rows, cols, type, type, 0);\n\t\tfloat* dp = ddenoms->data.f32;\n\t\tfor (i = 0; i < db->rows; i++)\n\t\t{\n\t\t\tfor (j = 0; j < db->cols; j++)\n\t\t\t\tfor (p = 0; p < partition; p++)\n\t\t\t\t\tfor (k = 0; k < ch_per_partition; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat v = ap[j * ch + p * ch_per_partition + k];\n\t\t\t\t\t\tfloat denom = 0;\n\t\t\t\t\t\tfor (x = ccv_max(k - way, 0); x <= ccv_min(k + way, ch_per_partition - 1); x++)\n\t\t\t\t\t\t\tdenom += ap[j * ch + p * ch_per_partition + x] * ap[j * ch + p * ch_per_partition + x];\n\t\t\t\t\t\tdenom = kappa + alpha * denom;\n\t\t\t\t\t\tdp[j * ch + p * ch_per_partition + k] = denom;\n\t\t\t\t\t\tbp[j * ch + p * ch_per_partition + k] = v * powf(denom, -beta);\n\t\t\t\t\t}\n\t\t\tap += a->cols * ch;\n\t\t\tdp += ddenoms->cols * ch;\n\t\t\tbp += db->cols * ch;\n\t\t}\n\t} else {\n\t\tfor (i = 0; i < db->rows; i++)\n\t\t{\n\t\t\tfor (j = 0; j < db->cols; j++)\n\t\t\t\tfor (p = 0; p < partition; p++)\n\t\t\t\t\tfor (k = 0; k < ch_per_partition; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat v = ap[j * ch + p * ch_per_partition + k];\n\t\t\t\t\t\tfloat denom = 0;\n\t\t\t\t\t\tfor (x = ccv_max(k - way, 0); x <= ccv_min(k + way, ch_per_partition - 1); x++)\n\t\t\t\t\t\t\tdenom += ap[j * ch + p * ch_per_partition + x] * ap[j * ch + p * ch_per_partition + x];\n\t\t\t\t\t\tdenom = kappa + alpha * denom;\n\t\t\t\t\t\tbp[j * ch + p * ch_per_partition + k] = v * powf(denom, -beta);\n\t\t\t\t\t}\n\t\t\tap += a->cols * ch;\n\t\t\tbp += db->cols * ch;\n\t\t}\n\t}\n}\n\nstatic void _ccv_convnet_max_pool_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b)\n{\n\tint rows, cols, partition;\n\tccv_convnet_make_output(layer, a->rows, a->cols, &rows, &cols, &partition);\n\tint size = layer->net.pool.size;\n\tint strides = layer->net.pool.strides;\n\tint border = layer->net.pool.border;\n\tassert(CCV_GET_DATA_TYPE(a->type) == CCV_32F);\n\tint ch = CCV_GET_CHANNEL(a->type);\n\tint type = CCV_32F | ch;\n\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, rows, cols, type, type, 0);\n\tint i, j, k, x, y;\n\tfloat* ap = a->data.f32;\n\tfloat* bp = db->data.f32;\n\tfor (i = 0; i < db->rows; i++)\n\t{\n\t\tconst int start_y = ccv_max(i * strides - border, 0) - (i * strides - border);\n\t\tconst int end_y = size + ccv_min(i * strides + size - border, a->rows) - (i * strides + size - border);\n\t\tfor (j = 0; j < db->cols; j++)\n\t\t{\n\t\t\tconst int start_x = ccv_max(j * strides - border, 0) - (j * strides - border);\n\t\t\tconst int end_x = size + ccv_min(j * strides + size - border, a->cols) - (j * strides + size - border);\n\t\t\tfor (k = 0; k < ch; k++)\n\t\t\t{\n\t\t\t\tfloat v = 0;\n\t\t\t\tfor (y = start_y; y < end_y; y++)\n\t\t\t\t\tfor (x = start_x; x < end_x; x++)\n\t\t\t\t\t\tif (x == start_x && y == start_y)\n\t\t\t\t\t\t\tv = ap[(j * strides - border + x + (y - border) * a->cols) * ch + k];\n\t\t\t\t\t\telse if (ap[(j * strides - border + x + (y - border) * a->cols) * ch + k] > v)\n\t\t\t\t\t\t\tv = ap[(j * strides - border + x + (y - border) * a->cols) * ch + k];\n\t\t\t\tbp[j * ch + k] = v;\n\t\t\t}\n\t\t}\n\t\tap += a->cols * ch * strides;\n\t\tbp += db->cols * ch;\n\t}\n}\n\nstatic void _ccv_convnet_average_pool_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b)\n{\n\tint rows, cols, partition;\n\tccv_convnet_make_output(layer, a->rows, a->cols, &rows, &cols, &partition);\n\tint size = layer->net.pool.size;\n\tint strides = layer->net.pool.strides;\n\tint border = layer->net.pool.border;\n\tassert(CCV_GET_DATA_TYPE(a->type) == CCV_32F);\n\tint ch = CCV_GET_CHANNEL(a->type);\n\tint type = CCV_32F | ch;\n\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, rows, cols, type, type, 0);\n\tint i, j, k, x, y;\n\tfloat* ap = a->data.f32;\n\tfloat* bp = db->data.f32;\n\tfor (i = 0; i < db->rows; i++)\n\t{\n\t\tconst int start_y = ccv_max(i * strides - border, 0) - (i * strides - border);\n\t\tconst int end_y = size + ccv_min(i * strides + size - border, a->rows) - (i * strides + size - border);\n\t\tfor (j = 0; j < db->cols; j++)\n\t\t{\n\t\t\tconst int start_x = ccv_max(j * strides - border, 0) - (j * strides - border);\n\t\t\tconst int end_x = size + ccv_min(j * strides + size - border, a->cols) - (j * strides + size - border);\n\t\t\tfor (k = 0; k < ch; k++)\n\t\t\t{\n\t\t\t\tfloat v = 0;\n\t\t\t\tfor (y = start_y; y < end_y; y++)\n\t\t\t\t\tfor (x = start_x; x < end_x; x++)\n\t\t\t\t\t\tv += ap[(j * strides - border + x + (y - border) * a->cols) * ch + k];\n\t\t\t\tbp[j * ch + k] = v / ((end_x - start_x) * (end_y - start_y));\n\t\t\t}\n\t\t}\n\t\tap += a->cols * ch * strides;\n\t\tbp += db->cols * ch;\n\t}\n}\n\nstatic void _ccv_convnet_layer_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, ccv_dense_matrix_t** denoms)\n{\n\tswitch(layer->type)\n\t{\n\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t_ccv_convnet_convolutional_forward_propagate(layer, a, b);\n\t\t\tbreak;\n\t\tcase CCV_CONVNET_FULL_CONNECT:\n\t\t\t_ccv_convnet_full_connect_forward_propagate(layer, a, b);\n\t\t\tbreak;\n\t\tcase CCV_CONVNET_LOCAL_RESPONSE_NORM:\n\t\t\t_ccv_convnet_rnorm_forward_propagate(layer, a, b, denoms);\n\t\t\tbreak;\n\t\tcase CCV_CONVNET_MAX_POOL:\n\t\t\t_ccv_convnet_max_pool_forward_propagate(layer, a, b);\n\t\t\tbreak;\n\t\tcase CCV_CONVNET_AVERAGE_POOL:\n\t\t\t_ccv_convnet_average_pool_forward_propagate(layer, a, b);\n\t\t\tbreak;\n\t}\n}\n\nstatic void _ccv_convnet_full_connect_forward_propagate_parallel(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b)\n{\n\tassert(CCV_GET_DATA_TYPE(a->type) == CCV_32F);\n\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, a->rows, layer->net.full_connect.count, CCV_32F | CCV_C1, CCV_32F | CCV_C1, 0);\n\t// reshape a for gemm\n\tint i, j;\n\tfloat* bptr = db->data.f32;\n\tfor (i = 0; i < db->rows; i++)\n\t{\n\t\tfor (j = 0; j < db->cols; j++)\n\t\t\tbptr[j] = layer->bias[j];\n\t\tbptr += db->cols;\n\t}\n\tccv_dense_matrix_t dw = ccv_dense_matrix(db->cols, a->cols, CCV_32F | CCV_C1, layer->w, 0);\n\tccv_gemm(a, &dw, 1, db, 1, CCV_B_TRANSPOSE, (ccv_matrix_t**)&db, 0); // supply db as matrix C is allowed\n\tbptr = db->data.f32;\n\tif (layer->net.full_connect.relu)\n\t\tfor (i = 0; i < db->rows; i++)\n\t\t{\n\t\t\tfor (j = 0; j < db->cols; j++)\n\t\t\t\tbptr[j] = ccv_max(0, bptr[j]); // relu\n\t\t\tbptr += db->cols;\n\t\t}\n}\n\nstatic void _ccv_convnet_compute_softmax_parallel(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type)\n{\n\tassert(CCV_GET_CHANNEL(a->type) == CCV_C1);\n\tassert(CCV_GET_DATA_TYPE(a->type) == CCV_32F);\n\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, 1, a->cols, CCV_32F | CCV_C1, CCV_32F | CCV_C1, 0);\n\tccv_zero(db);\n\tint i, j;\n\tfloat* aptr = a->data.f32;\n\tfloat* bptr = db->data.f32;\n\tfloat* cptr = (float*)ccmalloc(sizeof(float) * a->cols);\n\tfor (i = 0; i < a->rows; i++)\n\t{\n\t\tdouble max = aptr[0];\n\t\tfor (j = 1; j < a->cols; j++)\n\t\t\tif (aptr[j] > max)\n\t\t\t\tmax = aptr[j];\n\t\tdouble tt = 0;\n\t\tfor (j = 0; j < a->cols; j++)\n\t\t\ttt += (cptr[j] = expf(aptr[j] - max));\n\t\ttt = 1.0 / tt;\n\t\tfor (j = 0; j < a->cols; j++)\n\t\t\tbptr[j] += cptr[j] * tt;\n\t\taptr += a->cols;\n\t}\n\tccfree(cptr);\n}\n\n#ifndef CASE_TESTS\n\nvoid ccv_convnet_encode(ccv_convnet_t* convnet, ccv_dense_matrix_t** a, ccv_dense_matrix_t** b, int batch)\n{\n#ifdef HAVE_CUDA\n\tif (convnet->use_cwc_accel)\n\t\tcwc_convnet_encode(convnet, a, b, batch);\n\telse {\n#endif\n\tassert(batch == 1);\n\tassert(CCV_GET_CHANNEL((*a)->type) == convnet->channels);\n\tassert((*a)->rows == convnet->rows);\n\tassert((*a)->cols == convnet->cols);\n\tint i;\n\t// save the last layer of neuron cache in case that we encode to a different matrix\n\tccv_dense_matrix_t* out_neuron = convnet->acts[convnet->count - 1];\n\tconvnet->acts[convnet->count - 1] = *b;\n\t_ccv_convnet_layer_forward_propagate(convnet->layers, *a, convnet->acts, convnet->denoms);\n\tfor (i = 1; i < convnet->count; i++)\n\t\t_ccv_convnet_layer_forward_propagate(convnet->layers + i, convnet->acts[i - 1], convnet->acts + i, convnet->denoms + i);\n\tif (convnet->acts + convnet->count - 1 != b)\n\t{\n\t\t*b = convnet->acts[convnet->count - 1];\n\t\t// restore the last layer of neuron cache\n\t\tconvnet->acts[convnet->count - 1] = out_neuron;\n\t}\n#ifdef HAVE_CUDA\n\t}\n#endif\n}\n\n// find the layer for scanning (it is the last convolutional layer)\nstatic int _ccv_convnet_find_scan(ccv_convnet_t* convnet)\n{\n\tint i;\n\tccv_convnet_layer_t* layers = convnet->layers;\n\tfor (i = convnet->count - 1; i >= 0; i--)\n\t\tif (layers[i].type == CCV_CONVNET_CONVOLUTIONAL)\n\t\t\treturn i;\n\treturn -1;\n}\n\nstatic int _ccv_convnet_derive_scale(ccv_convnet_t* convnet, int scan)\n{\n\tint i, scale = 1;\n\tfor (i = scan; i >= 0; i--)\n\t{\n\t\tccv_convnet_layer_t* layer = convnet->layers + i;\n\t\tswitch (layer->type)\n\t\t{\n\t\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t\tscale *= layer->net.convolutional.strides;\n\t\t\t\tbreak;\n\t\t\tcase CCV_CONVNET_MAX_POOL:\n\t\t\tcase CCV_CONVNET_AVERAGE_POOL:\n\t\t\t\tscale *= layer->net.pool.strides;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn scale;\n}\n\nstatic int _ccv_convnet_find_full_connect(ccv_convnet_t* convnet)\n{\n\tint i;\n\tfor (i = 0; i < convnet->count; i++)\n\t\tif (convnet->layers[i].type == CCV_CONVNET_FULL_CONNECT)\n\t\t\treturn i;\n\treturn -1;\n}\n\nvoid ccv_convnet_classify(ccv_convnet_t* convnet, ccv_dense_matrix_t** a, int symmetric, ccv_array_t** ranks, int tops, int batch)\n{\n#ifdef HAVE_CUDA\n\tif (convnet->use_cwc_accel)\n\t\tcwc_convnet_classify(convnet, a, symmetric, ranks, tops, batch);\n\telse {\n#endif\n\tint i, j, k, t;\n\tccv_dense_matrix_t** b = (ccv_dense_matrix_t**)alloca(sizeof(ccv_dense_matrix_t*) * (convnet->count + 1));\n\tint scan = _ccv_convnet_find_scan(convnet);\n\tint scale = _ccv_convnet_derive_scale(convnet, scan);\n\tint full_connect = _ccv_convnet_find_full_connect(convnet);\n\tassert(scan >= 0 && scan < convnet->count);\n\tassert(full_connect >= 0 && full_connect < convnet->count);\n\tmemset(b, 0, sizeof(ccv_dense_matrix_t*) * (convnet->count + 1));\n\tfor (i = 0; i < batch; i++)\n\t{\n\t\tassert(CCV_GET_CHANNEL(a[i]->type) == convnet->channels);\n\t\tassert(a[i]->rows == convnet->input.height || a[i]->cols == convnet->input.width);\n\t\tassert(a[i]->rows >= convnet->input.height && a[i]->cols >= convnet->input.width);\n\t\t// find optimal rows and cols to slice to\n\t\tint rows = convnet->rows + ((a[i]->rows - convnet->rows) / scale) * scale;\n\t\tint cols = convnet->cols + ((a[i]->cols - convnet->cols) / scale) * scale;\n\t\tassert(rows == convnet->input.height || cols == convnet->input.width);\n\t\tassert(rows <= a[i]->rows && cols <= a[i]->cols);\n\t\tccv_dense_matrix_t* slice = 0;\n\t\tccv_slice(a[i], (ccv_matrix_t**)&slice, CCV_32F, (a[i]->rows - rows) / 2, (a[i]->cols - cols) / 2, rows, cols);\n\t\tccv_dense_matrix_t* mean_activity = 0;\n\t\t// scale mean activity up to be substractable (from this one, the CPU implementation is an approximation of GPU implementation)\n\t\tccv_resample(convnet->mean_activity, &mean_activity, 0, rows, cols, CCV_INTER_CUBIC);\n\t\tccv_subtract(slice, mean_activity, (ccv_matrix_t**)b, CCV_32F);\n\t\tccv_matrix_free(mean_activity);\n\t\tccv_matrix_free(slice);\n\t\t// doing the first few layers until the first scan layer\n\t\tint out_rows, out_cols, out_partition;\n\t\tccv_dense_matrix_t* c = ccv_dense_matrix_new(5 * (!!symmetric + 1), convnet->layers[full_connect].input.node.count, CCV_32F | CCV_C1, 0, 0);\n\t\tfor (t = 0; t <= !!symmetric; t++)\n\t\t{\n\t\t\trows = b[0]->rows, cols = b[0]->cols;\n\t\t\tfor (j = 0; j < scan + 1; j++)\n\t\t\t{\n\t\t\t\tccv_convnet_layer_t* layer = convnet->layers + j;\n\t\t\t\tccv_convnet_make_output(layer, rows, cols, &out_rows, &out_cols, &out_partition);\n\t\t\t\t_ccv_convnet_layer_forward_propagate(layer, b[j], b + j + 1, 0);\n\t\t\t\tassert(b[j + 1]->rows == out_rows && b[j + 1]->cols == out_cols);\n\t\t\t\tif (j > 0)\n\t\t\t\t\tccv_matrix_free(b[j]);\n\t\t\t\trows = out_rows, cols = out_cols;\n\t\t\t}\n\t\t\tint offsets[5][2] = {\n\t\t\t\t{0, 0},\n\t\t\t\t{cols - convnet->layers[scan + 1].input.matrix.cols, 0},\n\t\t\t\t{(cols - convnet->layers[scan + 1].input.matrix.cols) / 2, (rows - convnet->layers[scan + 1].input.matrix.rows) / 2},\n\t\t\t\t{0, rows - convnet->layers[scan + 1].input.matrix.rows},\n\t\t\t\t{cols - convnet->layers[scan + 1].input.matrix.cols, rows - convnet->layers[scan + 1].input.matrix.rows},\n\t\t\t};\n\t\t\tfor (k = 0; k < 5; k++)\n\t\t\t{\n\t\t\t\tccv_dense_matrix_t* input = 0;\n\t\t\t\tccv_convnet_layer_t* layer = convnet->layers + scan + 1;\n\t\t\t\tccv_slice(b[scan + 1], (ccv_matrix_t**)&input, CCV_32F, offsets[k][1], offsets[k][0], layer->input.matrix.rows, layer->input.matrix.cols);\n\t\t\t\t// copy the last layer for full connect compute\n\t\t\t\tb[full_connect] = ccv_dense_matrix_new(convnet->layers[full_connect].input.matrix.rows, convnet->layers[full_connect].input.matrix.cols, CCV_NO_DATA_ALLOC | CCV_32F | convnet->layers[full_connect].input.matrix.channels, c->data.f32 + (t * 5 + k) * convnet->layers[full_connect].input.node.count, 0);\n\t\t\t\tfor (j = scan + 1; j < full_connect; j++)\n\t\t\t\t{\n\t\t\t\t\tlayer = convnet->layers + j;\n\t\t\t\t\t_ccv_convnet_layer_forward_propagate(layer, j > scan + 1 ? b[j] : input, b + j + 1, 0);\n\t\t\t\t\tif (j > scan + 1)\n\t\t\t\t\t\tccv_matrix_free(b[j]);\n\t\t\t\t\telse\n\t\t\t\t\t\tccv_matrix_free(input);\n\t\t\t\t}\n\t\t\t\tccv_matrix_free(b[full_connect]);\n\t\t\t\t// set it to 0\n\t\t\t\tmemset(b + scan + 2, 0, sizeof(ccv_dense_matrix_t*) * (full_connect - scan - 1));\n\t\t\t}\n\t\t\tccv_matrix_free(b[scan + 1]);\n\t\t\tmemset(b + 1, 0, sizeof(ccv_dense_matrix_t*) * (scan + 1));\n\t\t\tccv_flip(b[0], &b[0], 0, CCV_FLIP_X);\n\t\t}\n\t\tccv_matrix_free(b[0]);\n\t\t// now have everything in c, do the last full connect propagate\n\t\tb[full_connect] = c;\n\t\tfor (j = full_connect; j < convnet->count; j++)\n\t\t{\n\t\t\tccv_convnet_layer_t* layer = convnet->layers + j;\n\t\t\tassert(layer->type == CCV_CONVNET_FULL_CONNECT);\n\t\t\t_ccv_convnet_full_connect_forward_propagate_parallel(layer, b[j], b + j + 1);\n\t\t\tccv_matrix_free(b[j]);\n\t\t}\n\t\tccv_dense_matrix_t* softmax = 0;\n\t\t_ccv_convnet_compute_softmax_parallel(b[convnet->count], &softmax, 0);\n\t\tccv_matrix_free(b[convnet->count]);\n\t\tranks[i] = ccv_array_new(sizeof(ccv_classification_t), tops, 0);\n\t\tfloat* r = softmax->data.f32;\n\t\tassert(tops <= softmax->cols);\n\t\tfor (j = 0; j < tops; j++)\n\t\t{\n\t\t\tfloat max_val = -1;\n\t\t\tint max_idx = -1;\n\t\t\tfor (k = 0; k < softmax->cols; k++)\n\t\t\t\tif (r[k] >= 0 && r[k] > max_val)\n\t\t\t\t\tmax_val = r[k], max_idx = k;\n\t\t\tassert(max_idx >= 0);\n\t\t\tr[max_idx] = -1;\n\t\t\tccv_classification_t classification = {\n\t\t\t\t.id = max_idx,\n\t\t\t\t.confidence = max_val / ((!!symmetric + 1) * 5),\n\t\t\t};\n\t\t\tccv_array_push(ranks[i], &classification);\n\t\t}\n\t\tccv_matrix_free(softmax);\n\t\tmemset(b, 0, sizeof(ccv_dense_matrix_t*) * (convnet->count + 1));\n\t}\n#ifdef HAVE_CUDA\n\t}\n#endif\n}\n\n#endif\n\n#ifdef HAVE_GSL\n\n// compute back propagated gradient & weight update delta\nstatic void _ccv_convnet_convolutional_backward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* n, ccv_dense_matrix_t* m, ccv_dense_matrix_t** b, ccv_convnet_layer_t* update_params)\n{\n\t// a is the input gradient (for back prop).\n\t// x is the input (for forward prop), b is the output gradient (gradient, or known as propagated error)\n\t// note that y (the output from forward prop) is not included because the full connect net is simple enough that we don't need it\n\tint rows, cols, partition;\n\tccv_convnet_make_output(layer, layer->input.matrix.rows, layer->input.matrix.cols, &rows, &cols, &partition);\n\tint ch = layer->net.convolutional.channels;\n\tint count = layer->net.convolutional.count;\n\tint strides = layer->net.convolutional.strides;\n\tint border = layer->net.convolutional.border;\n\tint kernel_rows = layer->net.convolutional.rows;\n\tint kernel_cols = layer->net.convolutional.cols;\n\tassert(a->rows == rows);\n\tassert(a->cols == cols);\n\tassert(CCV_GET_CHANNEL(a->type) == count);\n\tint a_rows = a->rows, a_cols = a->cols, a_ch = CCV_GET_CHANNEL(a->type);\n\ta->rows = rows, a->cols = cols, a->type = (a->type - a_ch) | count;\n\tassert(CCV_GET_CHANNEL(m->type) == ch);\n\tassert(CCV_GET_DATA_TYPE(m->type) == CCV_32F);\n\tint count_per_partition = count / partition;\n\tint ch_per_partition = ch / partition;\n\t// update weight gradient\n\tparallel_for(k, count) {\n\t\tint i, j, x, y, c;\n\t\tint p = k / count_per_partition;\n\t\tfloat* mp = m->data.f32 + p * ch_per_partition;\n\t\tfloat* ap = a->data.f32 + k;\n\t\tfloat* np = n->data.f32 + k;\n\t\tfloat* update_w = update_params->w + k * kernel_rows * kernel_cols * ch_per_partition;\n\t\tfloat bias = 0;\n\t\tfor (i = 0; i < rows; i++)\n\t\t{\n\t\t\tint comy = ccv_max(i * strides - border, 0) - (i * strides - border);\n\t\t\tint maxy = kernel_rows - comy - (i * strides + kernel_rows - ccv_min(m->rows + border, i * strides + kernel_rows));\n\t\t\tcomy *= ch_per_partition * kernel_cols;\n\t\t\tfor (j = 0; j < cols; j++)\n\t\t\t{\n\t\t\t\tif (np[j * count] > 0)\n\t\t\t\t{ /* when np is bigger than 0, relu continues to update the weight, otherwise it stops */\n\t\t\t\t\tfloat v = ap[j * count];\n\t\t\t\t\tbias += v;\n\t\t\t\t\tint comx = ccv_max(j * strides - border, 0) - (j * strides - border);\n\t\t\t\t\tint maxx = kernel_cols - comx - (j * strides + kernel_cols - ccv_min(m->cols + border, j * strides + kernel_cols));\n\t\t\t\t\tfloat* w = update_w + comx * ch_per_partition + comy;\n\t\t\t\t\tfloat* mpz = mp + ccv_max(j * strides - border, 0) * ch;\n\t\t\t\t\t/* when we have border, we simply do zero padding */\n\t\t\t\t\tfor (y = 0; y < maxy; y++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (x = 0; x < maxx; x++)\n\t\t\t\t\t\t\tfor (c = 0; c < ch_per_partition; c++)\n\t\t\t\t\t\t\t\tw[x * ch_per_partition + c] += v * mpz[x * ch + c];\n\t\t\t\t\t\tw += kernel_cols * ch_per_partition;\n\t\t\t\t\t\tmpz += m->cols * ch;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tap += a->cols * count;\n\t\t\tnp += n->cols * count;\n\t\t\tmp += m->cols * ch * (ccv_max((i + 1) * strides - border, 0) - ccv_max(i * strides - border, 0));\n\t\t}\n\t\tupdate_params->bias[k] += bias;\n\t} parallel_endfor\n\tif (b)\n\t{\n\t\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, m->rows, m->cols, CCV_32F | CCV_GET_CHANNEL(m->type), CCV_32F | CCV_GET_CHANNEL(m->type), 0);\n\t\t// clear it up before propagate result\n\t\tccv_zero(db);\n\t\tint k;\n\t\tfor (k = 0; k < count; k++)\n\t\t{\n\t\t\tint i, j, x, y, c;\n\t\t\tint p = k / count_per_partition;\n\t\t\tfloat* bp = db->data.f32 + p * ch_per_partition;\n\t\t\tfloat* ap = a->data.f32 + k;\n\t\t\tfloat* np = n->data.f32 + k;\n\t\t\tfloat* layer_w = layer->w + k * kernel_rows * kernel_cols * ch_per_partition;\n\t\t\tfor (i = 0; i < rows; i++)\n\t\t\t{\n\t\t\t\tint comy = ccv_max(i * strides - border, 0) - (i * strides - border);\n\t\t\t\tint maxy = kernel_rows - comy - (i * strides + kernel_rows - ccv_min(db->rows + border, i * strides + kernel_rows));\n\t\t\t\tcomy *= ch_per_partition * kernel_cols;\n\t\t\t\tfor (j = 0; j < cols; j++)\n\t\t\t\t{\n\t\t\t\t\tif (np[j * count] > 0)\n\t\t\t\t\t{ /* when np is bigger than 0, relu continues to update the weight, otherwise it stops */\n\t\t\t\t\t\tfloat v = ap[j * count];\n\t\t\t\t\t\tint comx = ccv_max(j * strides - border, 0) - (j * strides - border);\n\t\t\t\t\t\tint maxx = kernel_cols - comx - (j * strides + kernel_cols - ccv_min(db->cols + border, j * strides + kernel_cols));\n\t\t\t\t\t\tfloat* w = layer_w + comx * ch_per_partition + comy;\n\t\t\t\t\t\tfloat* bpz = bp + ccv_max(j * strides - border, 0) * ch;\n\t\t\t\t\t\t/* when we have border, we simply do zero padding */\n\t\t\t\t\t\tfor (y = 0; y < maxy; y++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (x = 0; x < maxx; x++)\n\t\t\t\t\t\t\t\tfor (c = 0; c < ch_per_partition; c++)\n\t\t\t\t\t\t\t\t\tbpz[x * ch + c] += v * w[x * ch_per_partition + c];\n\t\t\t\t\t\t\tw += kernel_cols * ch_per_partition;\n\t\t\t\t\t\t\tbpz += db->cols * ch;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tap += a->cols * count;\n\t\t\t\tnp += n->cols * count;\n\t\t\t\tbp += db->cols * ch * (ccv_max((i + 1) * strides - border, 0) - ccv_max(i * strides - border, 0));\n\t\t\t}\n\t\t}\n\t}\n\ta->rows = a_rows, a->cols = a_cols, a->type = (a->type - CCV_GET_CHANNEL(a->type)) | a_ch;\n}\n\nstatic void _ccv_convnet_full_connect_backward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* y, ccv_dense_matrix_t* x, ccv_dense_matrix_t** b, ccv_convnet_layer_t* update_params)\n{\n\t// a is the input gradient (for back prop), y is the output (for forward prop)\n\t// x is the input (for forward prop), b is the output gradient (gradient, or known as propagated error)\n\tccv_dense_matrix_t* db = 0;\n\tif (b)\n\t\tdb = *b = ccv_dense_matrix_renew(*b, x->rows, x->cols, CCV_32F | CCV_GET_CHANNEL(x->type), CCV_32F | CCV_GET_CHANNEL(x->type), 0);\n\tint x_rows = x->rows, x_cols = x->cols, x_ch = CCV_GET_CHANNEL(x->type);\n\tx->rows = x_rows * x_cols * x_ch, x->cols = 1, x->type = (x->type - x_ch) | CCV_C1;\n\tx->step = x->cols * CCV_GET_DATA_TYPE_SIZE(x->type);\n\tint i;\n\tif (layer->net.full_connect.relu)\n\t\tfor (i = 0; i < y->rows; i++)\n\t\t\tif (y->data.f32[i] <= 0)\n\t\t\t\ta->data.f32[i] = 0;\n\tccv_dense_matrix_t w = ccv_dense_matrix(a->rows, x->rows, CCV_32F | CCV_C1, update_params->w, 0);\n\tccv_dense_matrix_t* dw = &w;\n\t// compute bias gradient\n\tccv_dense_matrix_t bias = ccv_dense_matrix(a->rows, 1, CCV_32F | CCV_C1, update_params->bias, 0);\n\tccv_dense_matrix_t* dbias = &bias;\n\tccv_add(a, dbias, (ccv_matrix_t**)&dbias, 0);\n\t// compute weight gradient\n\tccv_gemm(a, x, 1, dw, 1, CCV_B_TRANSPOSE, (ccv_matrix_t**)&dw, 0);\n\tw = ccv_dense_matrix(a->rows, x->rows, CCV_32F | CCV_C1, layer->w, 0);\n\t// propagate error\n\tif (db)\n\t{\n\t\tdb->rows = x->rows, db->cols = x->cols, db->type = (db->type - x_ch) | CCV_C1;\n\t\tdb->step = db->cols * CCV_GET_DATA_TYPE_SIZE(db->type);\n\t\tccv_gemm(&w, a, 1, 0, 0, CCV_A_TRANSPOSE, (ccv_matrix_t**)&db, 0);\n\t\tdb->rows = x_rows, db->cols = x_cols, db->type = (db->type - CCV_GET_CHANNEL(db->type)) | x_ch;\n\t\tdb->step = db->cols * CCV_GET_DATA_TYPE_SIZE(db->type) * CCV_GET_CHANNEL(db->type);\n\t}\n\tx->rows = x_rows, x->cols = x_cols, x->type = (x->type - CCV_GET_CHANNEL(x->type)) | x_ch;\n\tx->step = x->cols * CCV_GET_DATA_TYPE_SIZE(x->type) * CCV_GET_CHANNEL(x->type);\n}\n\nstatic void _ccv_convnet_rnorm_backward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* n, ccv_dense_matrix_t* m, ccv_dense_matrix_t* denoms, ccv_dense_matrix_t** b)\n{\n\tint rows, cols, partition;\n\tccv_convnet_make_output(layer, layer->input.matrix.rows, layer->input.matrix.cols, &rows, &cols, &partition);\n\tint size = layer->net.rnorm.size;\n\tfloat alpha = layer->net.rnorm.alpha;\n\tfloat beta = layer->net.rnorm.beta;\n\tint way = size / 2;\n\tassert(CCV_GET_DATA_TYPE(a->type) == CCV_32F);\n\tint ch = CCV_GET_CHANNEL(a->type);\n\tint type = CCV_32F | ch;\n\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, rows, cols, type, type, 0);\n\tint i, j, k, x, p;\n\tfloat* ap = a->data.f32;\n\tfloat* np = n->data.f32;\n\tfloat* mp = m->data.f32;\n\tfloat* dp = denoms->data.f32;\n\tfloat* bp = db->data.f32;\n\tint ch_per_partition = ch / partition;\n\tfor (i = 0; i < db->rows; i++)\n\t{\n\t\tfor (j = 0; j < db->cols; j++)\n\t\t\tfor (p = 0; p < partition; p++)\n\t\t\t\tfor (k = 0; k < ch_per_partition; k++)\n\t\t\t\t{\n\t\t\t\t\tfloat nom = 0;\n\t\t\t\t\tfor (x = ccv_max(k - way, 0); x <= ccv_min(k + way, ch_per_partition - 1); x++)\n\t\t\t\t\t\tnom += -2 * alpha * beta * ap[j * ch + x + p * ch_per_partition] * np[j * ch + x + p * ch_per_partition] / dp[j * ch + x + p * ch_per_partition];\n\t\t\t\t\tbp[j * ch + k + p * ch_per_partition] = mp[j * ch + k + p * ch_per_partition] * nom + ap[j * ch + k + p * ch_per_partition] * powf(dp[j * ch + k + p * ch_per_partition], -beta);\n\t\t\t\t}\n\t\tap += a->cols * ch;\n\t\tnp += n->cols * ch;\n\t\tmp += m->cols * ch;\n\t\tdp += denoms->cols * ch;\n\t\tbp += db->cols * ch;\n\t}\n}\n\nstatic void _ccv_convnet_max_pool_backward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* n, ccv_dense_matrix_t* m, ccv_dense_matrix_t** b)\n{\n\t// a is the input gradient (for back prop), y is the output (from forward prop),\n\t// x is the input (for forward prop), b is the output gradient (gradient, or known as propagated error)\n\t// pooling layer doesn't need the dropout\n\tif (b)\n\t{\n\t\tassert(CCV_GET_CHANNEL(a->type) == CCV_GET_CHANNEL(n->type));\n\t\tassert(CCV_GET_CHANNEL(a->type) == CCV_GET_CHANNEL(m->type));\n\t\tint ch = CCV_GET_CHANNEL(a->type);\n\t\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, m->rows, m->cols, CCV_32F | ch, CCV_32F | ch, 0);\n\t\tccv_zero(db);\n\t\tint size = layer->net.pool.size;\n\t\tint strides = layer->net.pool.strides;\n\t\tint border = layer->net.pool.border;\n\t\tint i, j, k, x, y;\n\t\tfloat* ap = a->data.f32;\n\t\tfloat* bp = db->data.f32;\n\t\tfloat* np = n->data.f32;\n\t\tfloat* mp = m->data.f32;\n\t\tfor (i = 0; i < a->rows; i++)\n\t\t{\n\t\t\tconst int start_y = ccv_max(i * strides - border, 0) - (i * strides - border);\n\t\t\tconst int end_y = size + ccv_min(i * strides + size - border, db->rows) - (i * strides + size - border);\n\t\t\tfor (j = 0; j < a->cols; j++)\n\t\t\t{\n\t\t\t\tconst int start_x = ccv_max(j * strides - border, 0) - (j * strides - border);\n\t\t\t\tconst int end_x = size + ccv_min(j * strides + size - border, db->cols) - (j * strides + size - border);\n\t\t\t\tfor (k = 0; k < ch; k++)\n\t\t\t\t{\n\t\t\t\t\tfloat v = np[j * ch + k];\n\t\t\t\t\tfloat u = ap[j * ch + k];\n\t\t\t\t\tfor (y = start_y; y < end_y; y++)\n\t\t\t\t\t\tfor (x = start_x; x < end_x; x++)\n\t\t\t\t\t\t\t// we have to do direct comparison otherwise it will contribute to too many cells\n\t\t\t\t\t\t\t// and the propagation won't work. But CPU will have different result comparing with GPU\n\t\t\t\t\t\t\tif (mp[(j * strides - border + x + (y - border) * m->cols) * ch + k] == v)\n\t\t\t\t\t\t\t\tbp[(j * strides - border + x + (y - border) * db->cols) * ch + k] += u;\n\t\t\t\t}\n\t\t\t}\n\t\t\tap += a->cols * ch;\n\t\t\tnp += n->cols * ch;\n\t\t\tbp += db->cols * ch * strides;\n\t\t\tmp += m->cols * ch * strides;\n\t\t}\n\t}\n}\n\nstatic void _ccv_convnet_average_pool_backward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* m, ccv_dense_matrix_t** b)\n{\n\t// a is the input gradient (for back prop), y is the output (from forward prop),\n\t// x is the input (for forward prop), b is the output gradient (gradient, or known as propagated error)\n\t// pooling layer doesn't need the dropout\n\tif (b)\n\t{\n\t\tassert(CCV_GET_CHANNEL(a->type) == CCV_GET_CHANNEL(m->type));\n\t\tint ch = CCV_GET_CHANNEL(a->type);\n\t\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, m->rows, m->cols, CCV_32F | ch, CCV_32F | ch, 0);\n\t\tccv_zero(db);\n\t\tint size = layer->net.pool.size;\n\t\tint strides = layer->net.pool.strides;\n\t\tint border = layer->net.pool.border;\n\t\tint i, j, k, x, y;\n\t\tfloat* ap = a->data.f32;\n\t\tfloat* bp = db->data.f32;\n\t\tfor (i = 0; i < a->rows; i++)\n\t\t{\n\t\t\tconst int start_y = ccv_max(i * strides - border, 0) - (i * strides - border);\n\t\t\tconst int end_y = size + ccv_min(i * strides + size - border, db->rows) - (i * strides + size - border);\n\t\t\tfor (j = 0; j < a->cols; j++)\n\t\t\t{\n\t\t\t\tconst int start_x = ccv_max(j * strides - border, 0) - (j * strides - border);\n\t\t\t\tconst int end_x = size + ccv_min(j * strides + size - border, db->cols) - (j * strides + size - border);\n\t\t\t\tfor (k = 0; k < ch; k++)\n\t\t\t\t{\n\t\t\t\t\tfloat u = ap[j * ch + k] / ((end_x - start_x) * (end_y - start_y));\n\t\t\t\t\tfor (y = start_y; y < end_y; y++)\n\t\t\t\t\t\tfor (x = start_x; x < end_x; x++)\n\t\t\t\t\t\t\tbp[(j * strides - border + x + (y - border) * db->cols) * ch + k] += u;\n\t\t\t\t}\n\t\t\t}\n\t\t\tap += a->cols * ch;\n\t\t\tbp += db->cols * ch * strides;\n\t\t}\n\t}\n}\n\nstatic void _ccv_convnet_propagate_loss(ccv_convnet_t* convnet, ccv_dense_matrix_t* a, ccv_dense_matrix_t* dloss, ccv_convnet_t* update_params)\n{\n\tint i;\n\tccv_convnet_layer_t* layer = convnet->layers + convnet->count - 1;\n\tassert(layer->type == CCV_CONVNET_FULL_CONNECT); // the last layer has too be a full connect one to generate softmax result\n\t_ccv_convnet_full_connect_backward_propagate(layer, dloss, convnet->acts[convnet->count - 1], convnet->acts[convnet->count - 2], convnet->count - 1 > 0 ? update_params->acts + convnet->count - 2 : 0, update_params->layers + convnet->count - 1);\n\tfor (i = convnet->count - 2; i >= 0; i--)\n\t{\n\t\tlayer = convnet->layers + i;\n\t\tswitch (layer->type)\n\t\t{\n\t\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t\t_ccv_convnet_convolutional_backward_propagate(layer, update_params->acts[i], convnet->acts[i], i > 0 ? convnet->acts[i - 1] : a, i > 0 ? update_params->acts + i - 1 : 0, update_params->layers + i);\n\t\t\t\tbreak;\n\t\t\tcase CCV_CONVNET_FULL_CONNECT:\n\t\t\t\t_ccv_convnet_full_connect_backward_propagate(layer, update_params->acts[i], convnet->acts[i], i > 0 ? convnet->acts[i - 1] : a, i > 0 ? update_params->acts + i - 1 : 0, update_params->layers + i);\n\t\t\t\tbreak;\n\t\t\tcase CCV_CONVNET_LOCAL_RESPONSE_NORM:\n\t\t\t\t_ccv_convnet_rnorm_backward_propagate(layer, update_params->acts[i], convnet->acts[i], i > 0 ? convnet->acts[i - 1] : a, convnet->denoms[i], i > 0 ? update_params->acts + i - 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase CCV_CONVNET_MAX_POOL:\n\t\t\t\t_ccv_convnet_max_pool_backward_propagate(layer, update_params->acts[i], convnet->acts[i], i > 0 ? convnet->acts[i - 1] : a, i > 0 ? update_params->acts + i - 1 : 0);\n\t\t\t\tbreak;\n\t\t\tcase CCV_CONVNET_AVERAGE_POOL:\n\t\t\t\t_ccv_convnet_average_pool_backward_propagate(layer, update_params->acts[i], i > 0 ? convnet->acts[i - 1] : a, i > 0 ? update_params->acts + i - 1 : 0);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\nstatic void _ccv_convnet_update(ccv_convnet_t* convnet, int batch, ccv_convnet_t* momentum, ccv_convnet_t* update_params, ccv_convnet_layer_train_param_t* layer_params)\n{\n\tint i, j;\n\tfloat learn_rate;\n\tfor (i = 0; i < convnet->count; i++)\n\t\tswitch (update_params->layers[i].type)\n\t\t{\n\t\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t{\n\t\t\t\tfloat* w = convnet->layers[i].w;\n\t\t\t\tfloat* vw = momentum->layers[i].w;\n\t\t\t\tfloat* dw = update_params->layers[i].w;\n\t\t\t\tlearn_rate = layer_params[i].w.learn_rate / batch;\n\t\t\t\tfor (j = 0; j < convnet->layers[i].wnum; j++)\n\t\t\t\t{\n\t\t\t\t\tvw[j] = layer_params[i].w.momentum * vw[j] - layer_params[i].w.decay * layer_params[i].w.learn_rate * w[j] + learn_rate * dw[j];\n\t\t\t\t\tw[j] += vw[j];\n\t\t\t\t}\n\t\t\t\tfloat* bias = convnet->layers[i].bias;\n\t\t\t\tfloat* vbias = momentum->layers[i].bias;\n\t\t\t\tfloat* dbias = update_params->layers[i].bias;\n\t\t\t\tlearn_rate = layer_params[i].bias.learn_rate / batch;\n\t\t\t\tfor (j = 0; j < convnet->layers[i].net.convolutional.count; j++)\n\t\t\t\t{\n\t\t\t\t\tvbias[j] = layer_params[i].bias.momentum * vbias[j] - layer_params[i].bias.decay * layer_params[i].bias.learn_rate * bias[j] + learn_rate * dbias[j];\n\t\t\t\t\tbias[j] += vbias[j];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase CCV_CONVNET_FULL_CONNECT:\n\t\t\t{\n\t\t\t\tfloat* w = convnet->layers[i].w;\n\t\t\t\tfloat* vw = momentum->layers[i].w;\n\t\t\t\tfloat* dw = update_params->layers[i].w;\n\t\t\t\tlearn_rate = layer_params[i].w.learn_rate / batch;\n\t\t\t\tfor (j = 0; j < convnet->layers[i].wnum; j++)\n\t\t\t\t{\n\t\t\t\t\tvw[j] = layer_params[i].w.momentum * vw[j] - layer_params[i].w.decay * layer_params[i].w.learn_rate * w[j] + learn_rate * dw[j];\n\t\t\t\t\tw[j] += vw[j];\n\t\t\t\t}\n\t\t\t\tfloat* bias = convnet->layers[i].bias;\n\t\t\t\tfloat* vbias = momentum->layers[i].bias;\n\t\t\t\tfloat* dbias = update_params->layers[i].bias;\n\t\t\t\tlearn_rate = layer_params[i].bias.learn_rate / batch;\n\t\t\t\tfor (j = 0; j < convnet->layers[i].net.full_connect.count; j++)\n\t\t\t\t{\n\t\t\t\t\tvbias[j] = layer_params[i].bias.momentum * vbias[j] - layer_params[i].bias.decay * layer_params[i].bias.learn_rate * bias[j] + learn_rate * dbias[j];\n\t\t\t\t\tbias[j] += vbias[j];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n}\n\nstatic void _ccv_convnet_update_zero(ccv_convnet_t* update_params)\n{\n\tint i;\n\tfor (i = 0; i < update_params->count; i++)\n\t\tswitch (update_params->layers[i].type)\n\t\t{\n\t\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t\tmemset(update_params->layers[i].w, 0, sizeof(float) * update_params->layers[i].wnum);\n\t\t\t\tmemset(update_params->layers[i].bias, 0, sizeof(float) * update_params->layers[i].net.convolutional.count);\n\t\t\t\tbreak;\n\t\t\tcase CCV_CONVNET_FULL_CONNECT:\n\t\t\t\tassert(update_params->layers[i].wnum % update_params->layers[i].net.full_connect.count == 0);\n\t\t\t\tmemset(update_params->layers[i].w, 0, sizeof(float) * update_params->layers[i].wnum);\n\t\t\t\tmemset(update_params->layers[i].bias, 0, sizeof(float) * update_params->layers[i].net.full_connect.count);\n\t\t\t\tbreak;\n\t\t}\n}\n\nstatic ccv_convnet_t* _ccv_convnet_update_new(ccv_convnet_t* convnet)\n{\n\tccv_convnet_t* update_params = (ccv_convnet_t*)ccmalloc(sizeof(ccv_convnet_t) + sizeof(ccv_convnet_layer_t) * convnet->count + sizeof(ccv_dense_matrix_t*) * convnet->count);\n\tupdate_params->reserved = 0;\n\tupdate_params->layers = (ccv_convnet_layer_t*)(update_params + 1);\n\tupdate_params->acts = (ccv_dense_matrix_t**)(update_params->layers + convnet->count);\n\tmemset(update_params->acts, 0, sizeof(ccv_dense_matrix_t*) * convnet->count);\n\tupdate_params->denoms = 0;\n\tupdate_params->input = convnet->input;\n\tupdate_params->rows = convnet->rows;\n\tupdate_params->cols = convnet->cols;\n\tupdate_params->count = convnet->count;\n\tupdate_params->channels = convnet->channels;\n\tupdate_params->mean_activity = 0;\n\tint i;\n\tfor (i = 0; i < convnet->count; i++)\n\t{\n\t\tupdate_params->layers[i].type = convnet->layers[i].type;\n\t\tupdate_params->layers[i].input = convnet->layers[i].input;\n\t\tupdate_params->layers[i].net = convnet->layers[i].net;\n\t\tupdate_params->layers[i].wnum = convnet->layers[i].wnum;\n\t\tupdate_params->layers[i].reserved = 0;\n\t\tswitch (update_params->layers[i].type)\n\t\t{\n\t\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t\tupdate_params->layers[i].w = (float*)cccalloc(update_params->layers[i].wnum + update_params->layers[i].net.convolutional.count, sizeof(float));\n\t\t\t\tupdate_params->layers[i].bias = update_params->layers[i].w + update_params->layers[i].wnum;\n\t\t\t\tbreak;\n\t\t\tcase CCV_CONVNET_FULL_CONNECT:\n\t\t\t\tassert(update_params->layers[i].wnum % update_params->layers[i].net.full_connect.count == 0);\n\t\t\t\tupdate_params->layers[i].w = (float*)cccalloc(update_params->layers[i].wnum + update_params->layers[i].net.full_connect.count, sizeof(float));\n\t\t\t\tupdate_params->layers[i].bias = update_params->layers[i].w + update_params->layers[i].wnum;\n\t\t\t\tbreak;\n\t\t\tcase CCV_CONVNET_LOCAL_RESPONSE_NORM:\n\t\t\tcase CCV_CONVNET_MAX_POOL:\n\t\t\tcase CCV_CONVNET_AVERAGE_POOL:\n\t\t\t\tupdate_params->layers[i].w = 0;\n\t\t\t\tupdate_params->layers[i].bias = 0;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn update_params;\n}\n\nstatic void _ccv_convnet_compute_softmax(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type)\n{\n\tint ch = CCV_GET_CHANNEL(a->type);\n\tassert(CCV_GET_DATA_TYPE(a->type) == CCV_32F);\n\tccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, a->rows, a->cols, CCV_32F | ch, CCV_32F | ch, 0);\n\tint i;\n\tfloat* aptr = a->data.f32;\n\tfloat* bptr = db->data.f32;\n\tdouble max = aptr[0];\n\tfor (i = 1; i < a->rows * a->cols * ch; i++)\n\t\tif (aptr[i] > max)\n\t\t\tmax = aptr[i];\n\tdouble tt = 0;\n\tfor (i = 0; i < a->rows * a->cols * ch; i++)\n\t\ttt += (bptr[i] = expf(aptr[i] - max));\n\ttt = 1.0 / tt;\n\tfor (i = 0; i < a->rows * a->cols * ch; i++)\n\t\tbptr[i] *= tt;\n}\n\nstatic void _ccv_convnet_classify(ccv_convnet_t* convnet, ccv_dense_matrix_t** a, int* labels, int batch)\n{\n\tassert(batch == 1);\n\tccv_convnet_encode(convnet, a, convnet->acts + convnet->count - 1, 1);\n\tint i, c = 0;\n\tccv_dense_matrix_t* b = convnet->acts[convnet->count - 1];\n\tfloat maxc = b->data.f32[0];\n\tfor (i = 1; i < b->rows; i++)\n\t\tif (b->data.f32[i] > maxc)\n\t\t\tmaxc = b->data.f32[i], c = i;\n\tlabels[0] = c;\n}\n\n#endif\n\n#ifndef CASE_TESTS\n\nvoid ccv_convnet_supervised_train(ccv_convnet_t* convnet, ccv_array_t* categorizeds, ccv_array_t* tests, const char* filename, ccv_convnet_train_param_t params)\n{\n#ifdef HAVE_GSL\n#ifdef HAVE_CUDA\n\tif (convnet->use_cwc_accel)\n\t\tcwc_convnet_supervised_train(convnet, categorizeds, tests, filename, params);\n\telse {\n#endif\n\tint i, j, t;\n\tgsl_rng_env_setup();\n\tgsl_rng* rng = gsl_rng_alloc(gsl_rng_default);\n\tint aligned_padding = categorizeds->rnum % params.mini_batch;\n\tint aligned_rnum = categorizeds->rnum - aligned_padding;\n\tint* idx = (int*)ccmalloc(sizeof(int) * (categorizeds->rnum + aligned_padding));\n\tfor (i = 0; i < categorizeds->rnum; i++)\n\t\tidx[i] = i;\n\tgsl_ran_shuffle(rng, idx, categorizeds->rnum, sizeof(int));\n\t// the last layer has to be full connect, thus we can use it as softmax layer\n\tassert(convnet->layers[convnet->count - 1].type == CCV_CONVNET_FULL_CONNECT);\n\tint category_count = convnet->layers[convnet->count - 1].net.full_connect.count;\n\tccv_convnet_t* update_params = _ccv_convnet_update_new(convnet);\n\tccv_convnet_t* momentum = _ccv_convnet_update_new(convnet);\n\tfor (t = 0; t < params.max_epoch; t++)\n\t{\n\t\tfor (i = 0; i < aligned_rnum; i++)\n\t\t{\n\t\t\t// dropout the first hidden layer\n\t\t\tccv_categorized_t* categorized = (ccv_categorized_t*)ccv_array_get(categorizeds, idx[i]);\n\t\t\tccv_convnet_encode(convnet, &categorized->matrix, convnet->acts + convnet->count - 1, 1);\n\t\t\tccv_dense_matrix_t* softmax = convnet->acts[convnet->count - 1];\n\t\t\tfloat* dloss = softmax->data.f32;\n\t\t\t_ccv_convnet_compute_softmax(softmax, &softmax, 0);\n\t\t\tassert(softmax->rows == category_count && softmax->cols == 1);\n\t\t\t// this mashes softmax and logistic regression together\n\t\t\t// also, it gives you -D[loss w.r.t. to x_i] (note the negative sign)\n\t\t\tfor (j = 0; j < category_count; j++)\n\t\t\t\tdloss[j] = (j == categorized->c) - dloss[j];\n\t\t\t_ccv_convnet_propagate_loss(convnet, categorized->matrix, softmax, update_params);\n\t\t\tif ((i + 1) % params.mini_batch == 0)\n\t\t\t{\n\t\t\t\tFLUSH(CCV_CLI_INFO, \" - at epoch %03d / %d => stochastic gradient descent at %d / %d\", t + 1, params.max_epoch, (i + 1) / params.mini_batch, aligned_rnum / params.mini_batch);\n\t\t\t\t// update weights\n\t\t\t\t_ccv_convnet_update(convnet, params.mini_batch, momentum, update_params, params.layer_params);\n\t\t\t\t_ccv_convnet_update_zero(update_params);\n\t\t\t\t// compact the convnet to avoid any staled temporary resource\n\t\t\t\tccv_convnet_compact(convnet);\n\t\t\t}\n\t\t}\n\t\tint miss = 0;\n\t\tfor (i = 0; i < tests->rnum; i++)\n\t\t{\n\t\t\tFLUSH(CCV_CLI_INFO, \" - at epoch %03d / %d => going through %d / %d for tests\", t + 1, params.max_epoch, i + 1, tests->rnum);\n\t\t\tccv_categorized_t* test = (ccv_categorized_t*)ccv_array_get(tests, i);\n\t\t\tint c = 0;\n\t\t\t_ccv_convnet_classify(convnet, &test->matrix, &c, 1);\n\t\t\tif (c != test->c)\n\t\t\t\t++miss;\n\t\t}\n\t\tFLUSH(CCV_CLI_INFO, \" - at epoch %03d / %d => with miss rate %.2f%%\\n\", t + 1, params.max_epoch, miss * 100.0f / tests->rnum);\n\t\tif (t + 1 < params.max_epoch)\n\t\t{\n\t\t\t// reshuffle the parts we visited and move the rest to the beginning\n\t\t\tmemcpy(idx + categorizeds->rnum, idx + aligned_rnum, sizeof(int) * aligned_padding);\n\t\t\tmemmove(idx + aligned_padding, idx, sizeof(int) * aligned_rnum);\n\t\t\tmemcpy(idx, idx + categorizeds->rnum, sizeof(int) * aligned_padding);\n\t\t\tgsl_ran_shuffle(rng, idx + aligned_padding, aligned_rnum, sizeof(int));\n\t\t}\n\t}\n\tccfree(idx);\n\tccv_convnet_free(momentum);\n\tccv_convnet_free(update_params);\n\tgsl_rng_free(rng);\n#ifdef HAVE_CUDA\n\t}\n#endif\n#else\n\tassert(0 && \"ccv_convnet_supervised_train requires GSL library support\");\n#endif\n}\n\nvoid ccv_convnet_compact(ccv_convnet_t* convnet)\n{\n#ifdef HAVE_CUDA\n\tcwc_convnet_compact(convnet);\n#endif\n\tint i;\n\tfor (i = 0; i < convnet->count; i++)\n\t{\n\t\tif (convnet->acts[i])\n\t\t\tccv_matrix_free(convnet->acts[i]);\n\t\tconvnet->acts[i] = 0;\n\t\tif (convnet->denoms)\n\t\t{\n\t\t\tif (convnet->denoms[i])\n\t\t\t\tccv_matrix_free(convnet->denoms[i]);\n\t\t\tconvnet->denoms[i] = 0;\n\t\t}\n\t\tif (SIMD(convnet->layers + i))\n\t\t{\n\t\t\tccfree(convnet->layers[i].reserved);\n\t\t\tconvnet->layers[i].reserved = 0;\n\t\t}\n\t}\n}\n\nvoid ccv_convnet_write(ccv_convnet_t* convnet, const char* filename, ccv_convnet_write_param_t params)\n{\n\tsqlite3* db = 0;\n\tif (SQLITE_OK == sqlite3_open(filename, &db))\n\t{\n\t\tconst char layer_create_table_qs[] =\n\t\t\t\"CREATE TABLE IF NOT EXISTS layer_params \"\n\t\t\t\"(layer INTEGER PRIMARY KEY ASC, type INTEGER, \"\n\t\t\t\"input_matrix_rows INTEGER, input_matrix_cols INTEGER, input_matrix_channels INTEGER, input_matrix_partition INTEGER, input_node_count INTEGER, \"\n\t\t\t\"output_rows INTEGER, output_cols INTEGER, output_channels INTEGER, output_partition INTEGER, output_count INTEGER, output_strides INTEGER, output_border INTEGER, \"\n\t\t\t\"output_size INTEGER, output_kappa REAL, output_alpha REAL, output_beta REAL, output_relu INTEGER);\"\n\t\t\t\"CREATE TABLE IF NOT EXISTS convnet_params \"\n\t\t\t\"(convnet INTEGER PRIMARY KEY ASC, input_height INTEGER, input_width INTEGER, mean_activity BLOB);\"\n\t\t\t\"CREATE TABLE IF NOT EXISTS layer_data \"\n\t\t\t\"(layer INTEGER PRIMARY KEY ASC, weight BLOB, bias BLOB, half_precision INTEGER);\";\n\t\tassert(SQLITE_OK == sqlite3_exec(db, layer_create_table_qs, 0, 0, 0));\n\t\tconst char layer_params_insert_qs[] = \n\t\t\t\"REPLACE INTO layer_params \"\n\t\t\t\"(layer, type, \"\n\t\t\t\"input_matrix_rows, input_matrix_cols, input_matrix_channels, input_matrix_partition, input_node_count, \"\n\t\t\t\"output_rows, output_cols, output_channels, output_partition, output_count, output_strides, output_border, \"\n\t\t\t\"output_size, output_kappa, output_alpha, output_beta, output_relu) VALUES \"\n\t\t\t\"($layer, $type, \" // 1\n\t\t\t\"$input_matrix_rows, $input_matrix_cols, $input_matrix_channels, $input_matrix_partition, $input_node_count, \" // 6\n\t\t\t\"$output_rows, $output_cols, $output_channels, $output_partition, $output_count, $output_strides, $output_border, \" // 13\n\t\t\t\"$output_size, $output_kappa, $output_alpha, $output_beta, $output_relu);\"; // 18\n\t\tsqlite3_stmt* layer_params_insert_stmt = 0;\n\t\tassert(SQLITE_OK == sqlite3_prepare_v2(db, layer_params_insert_qs, sizeof(layer_params_insert_qs), &layer_params_insert_stmt, 0));\n\t\tconst char layer_data_insert_qs[] =\n\t\t\t\"REPLACE INTO layer_data \"\n\t\t\t\"(layer, weight, bias, half_precision) VALUES ($layer, $weight, $bias, $half_precision);\";\n\t\tsqlite3_stmt* layer_data_insert_stmt = 0;\n\t\tassert(SQLITE_OK == sqlite3_prepare_v2(db, layer_data_insert_qs, sizeof(layer_data_insert_qs), &layer_data_insert_stmt, 0));\n\t\tint i;\n\t\tfor (i = 0; i < convnet->count; i++)\n\t\t{\n\t\t\tccv_convnet_layer_t* layer = convnet->layers + i;\n\t\t\t// insert layer params\n\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 1, i);\n\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 2, layer->type);\n\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 3, layer->input.matrix.rows);\n\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 4, layer->input.matrix.cols);\n\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 5, layer->input.matrix.channels);\n\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 6, layer->input.matrix.partition);\n\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 7, layer->input.node.count);\n\t\t\tswitch (layer->type)\n\t\t\t{\n\t\t\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 8, layer->net.convolutional.rows);\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 9, layer->net.convolutional.cols);\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 10, layer->net.convolutional.channels);\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 11, layer->net.convolutional.partition);\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 12, layer->net.convolutional.count);\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 13, layer->net.convolutional.strides);\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 14, layer->net.convolutional.border);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CCV_CONVNET_FULL_CONNECT:\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 12, layer->net.full_connect.count);\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 19, layer->net.full_connect.relu);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CCV_CONVNET_MAX_POOL:\n\t\t\t\tcase CCV_CONVNET_AVERAGE_POOL:\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 13, layer->net.pool.strides);\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 14, layer->net.pool.border);\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 15, layer->net.pool.size);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CCV_CONVNET_LOCAL_RESPONSE_NORM:\n\t\t\t\t\tsqlite3_bind_int(layer_params_insert_stmt, 15, layer->net.rnorm.size);\n\t\t\t\t\tsqlite3_bind_double(layer_params_insert_stmt, 16, layer->net.rnorm.kappa);\n\t\t\t\t\tsqlite3_bind_double(layer_params_insert_stmt, 17, layer->net.rnorm.alpha);\n\t\t\t\t\tsqlite3_bind_double(layer_params_insert_stmt, 18, layer->net.rnorm.beta);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tassert(SQLITE_DONE == sqlite3_step(layer_params_insert_stmt));\n\t\t\tsqlite3_reset(layer_params_insert_stmt);\n\t\t\tsqlite3_clear_bindings(layer_params_insert_stmt);\n\t\t\t// insert layer data\n\t\t\tif (layer->type == CCV_CONVNET_CONVOLUTIONAL || layer->type == CCV_CONVNET_FULL_CONNECT)\n\t\t\t{\n\t\t\t\tsqlite3_bind_int(layer_data_insert_stmt, 1, i);\n\t\t\t\tif (params.half_precision)\n\t\t\t\t{\n\t\t\t\t\tuint16_t* w = (uint16_t*)ccmalloc(sizeof(uint16_t) * layer->wnum);\n\t\t\t\t\tccv_float_to_half_precision(layer->w, w, layer->wnum);\n\t\t\t\t\tuint16_t* bias = (uint16_t*)ccmalloc(sizeof(uint16_t) * (layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count));\n\t\t\t\t\tccv_float_to_half_precision(layer->bias, bias, layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count);\n\t\t\t\t\tsqlite3_bind_blob(layer_data_insert_stmt, 2, w, sizeof(uint16_t) * layer->wnum, ccfree);\n\t\t\t\t\tsqlite3_bind_blob(layer_data_insert_stmt, 3, bias, sizeof(uint16_t) * (layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count), ccfree);\n\t\t\t\t} else {\n\t\t\t\t\tsqlite3_bind_blob(layer_data_insert_stmt, 2, layer->w, sizeof(float) * layer->wnum, SQLITE_STATIC);\n\t\t\t\t\tsqlite3_bind_blob(layer_data_insert_stmt, 3, layer->bias, sizeof(float) * (layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count), SQLITE_STATIC);\n\t\t\t\t}\n\t\t\t\tsqlite3_bind_int(layer_data_insert_stmt, 4, params.half_precision);\n\t\t\t\tassert(SQLITE_DONE == sqlite3_step(layer_data_insert_stmt));\n\t\t\t\tsqlite3_reset(layer_data_insert_stmt);\n\t\t\t\tsqlite3_clear_bindings(layer_data_insert_stmt);\n\t\t\t}\n\t\t}\n\t\t// insert convnet related params\n\t\tconst char convnet_params_insert_qs[] =\n\t\t\t\"REPLACE INTO convnet_params \"\n\t\t\t\"(convnet, mean_activity, input_height, input_width) VALUES (0, $mean_activity, $input_height, $input_width);\";\n\t\tsqlite3_stmt* convnet_params_insert_stmt = 0;\n\t\tassert(SQLITE_OK == sqlite3_prepare_v2(db, convnet_params_insert_qs, sizeof(convnet_params_insert_qs), &convnet_params_insert_stmt, 0));\n\t\tassert(convnet->mean_activity->rows == convnet->input.height);\n\t\tassert(convnet->mean_activity->cols == convnet->input.width);\n\t\tassert(CCV_GET_CHANNEL(convnet->mean_activity->type) == convnet->channels);\n\t\tassert(CCV_GET_DATA_TYPE(convnet->mean_activity->type) == CCV_32F);\n\t\tsqlite3_bind_blob(convnet_params_insert_stmt, 1, convnet->mean_activity->data.f32, sizeof(float) * convnet->input.height * convnet->input.width * convnet->channels, SQLITE_STATIC);\n\t\tsqlite3_bind_int(convnet_params_insert_stmt, 2, convnet->input.height);\n\t\tsqlite3_bind_int(convnet_params_insert_stmt, 3, convnet->input.width);\n\t\tassert(SQLITE_DONE == sqlite3_step(convnet_params_insert_stmt));\n\t\tsqlite3_reset(convnet_params_insert_stmt);\n\t\tsqlite3_clear_bindings(convnet_params_insert_stmt);\n\n\t\tsqlite3_finalize(layer_params_insert_stmt);\n\t\tsqlite3_finalize(layer_data_insert_stmt);\n\t\tsqlite3_finalize(convnet_params_insert_stmt);\n\t\tsqlite3_close(db);\n\t}\n}\n\nccv_convnet_t* ccv_convnet_read(int use_cwc_accel, const char* filename)\n{\n\tsqlite3* db = 0;\n\tif (SQLITE_OK == sqlite3_open(filename, &db))\n\t{\n\t\tccv_convnet_t* convnet = 0;\n\t\tsqlite3_stmt* layer_params_stmt = 0;\n\t\t// load layer params\n\t\tconst char layer_params_qs[] =\n\t\t\t\"SELECT type, \" // 1\n\t\t\t\"input_matrix_rows, input_matrix_cols, input_matrix_channels, input_matrix_partition, input_node_count, \" // 6\n\t\t\t\"output_rows, output_cols, output_channels, output_partition, output_count, output_strides, output_border, \" // 13\n\t\t\t\"output_size, output_kappa, output_alpha, output_beta, output_relu FROM layer_params ORDER BY layer ASC;\"; // 18\n\t\tif (SQLITE_OK == sqlite3_prepare_v2(db, layer_params_qs, sizeof(layer_params_qs), &layer_params_stmt, 0))\n\t\t{\n\t\t\tccv_array_t* layer_params = ccv_array_new(sizeof(ccv_convnet_layer_param_t), 3, 0);\n\t\t\twhile (sqlite3_step(layer_params_stmt) == SQLITE_ROW)\n\t\t\t{\n\t\t\t\tccv_convnet_layer_param_t layer_param;\n\t\t\t\tlayer_param.type = sqlite3_column_int(layer_params_stmt, 0);\n\t\t\t\tlayer_param.input.matrix.rows = sqlite3_column_int(layer_params_stmt, 1);\n\t\t\t\tlayer_param.input.matrix.cols = sqlite3_column_int(layer_params_stmt, 2);\n\t\t\t\tlayer_param.input.matrix.channels = sqlite3_column_int(layer_params_stmt, 3);\n\t\t\t\tlayer_param.input.matrix.partition = sqlite3_column_int(layer_params_stmt, 4);\n\t\t\t\tlayer_param.input.node.count = sqlite3_column_int(layer_params_stmt, 5);\n\t\t\t\tlayer_param.bias = layer_param.glorot = 0; // this is irrelevant to read convnet\n\t\t\t\tswitch (layer_param.type)\n\t\t\t\t{\n\t\t\t\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t\t\t\tlayer_param.output.convolutional.rows = sqlite3_column_int(layer_params_stmt, 6);\n\t\t\t\t\t\tlayer_param.output.convolutional.cols = sqlite3_column_int(layer_params_stmt, 7);\n\t\t\t\t\t\tlayer_param.output.convolutional.channels = sqlite3_column_int(layer_params_stmt, 8);\n\t\t\t\t\t\tlayer_param.output.convolutional.partition = sqlite3_column_int(layer_params_stmt, 9);\n\t\t\t\t\t\tlayer_param.output.convolutional.count = sqlite3_column_int(layer_params_stmt, 10);\n\t\t\t\t\t\tlayer_param.output.convolutional.strides = sqlite3_column_int(layer_params_stmt, 11);\n\t\t\t\t\t\tlayer_param.output.convolutional.border = sqlite3_column_int(layer_params_stmt, 12);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase CCV_CONVNET_FULL_CONNECT:\n\t\t\t\t\t\tlayer_param.output.full_connect.count = sqlite3_column_int(layer_params_stmt, 10);\n\t\t\t\t\t\tlayer_param.output.full_connect.relu = sqlite3_column_int(layer_params_stmt, 17);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase CCV_CONVNET_MAX_POOL:\n\t\t\t\t\tcase CCV_CONVNET_AVERAGE_POOL:\n\t\t\t\t\t\tlayer_param.output.pool.strides = sqlite3_column_int(layer_params_stmt, 11);\n\t\t\t\t\t\tlayer_param.output.pool.border = sqlite3_column_int(layer_params_stmt, 12);\n\t\t\t\t\t\tlayer_param.output.pool.size = sqlite3_column_int(layer_params_stmt, 13);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase CCV_CONVNET_LOCAL_RESPONSE_NORM:\n\t\t\t\t\t\tlayer_param.output.rnorm.size = sqlite3_column_int(layer_params_stmt, 13);\n\t\t\t\t\t\tlayer_param.output.rnorm.kappa = sqlite3_column_double(layer_params_stmt, 14);\n\t\t\t\t\t\tlayer_param.output.rnorm.alpha = sqlite3_column_double(layer_params_stmt, 15);\n\t\t\t\t\t\tlayer_param.output.rnorm.beta = sqlite3_column_double(layer_params_stmt, 16);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tccv_array_push(layer_params, &layer_param);\n\t\t\t}\n\t\t\tsqlite3_finalize(layer_params_stmt);\n\t\t\tsqlite3_stmt* convnet_params_input_stmt = 0;\n\t\t\t// load convnet params for input\n\t\t\tconst char convnet_params_input_qs[] =\n\t\t\t\t\"SELECT input_height, input_width FROM convnet_params WHERE convnet = 0;\";\n\t\t\tccv_size_t input = ccv_size(0, 0);\n\t\t\tif (SQLITE_OK == sqlite3_prepare_v2(db, convnet_params_input_qs, sizeof(convnet_params_input_qs), &convnet_params_input_stmt, 0))\n\t\t\t{\n\t\t\t\tif (sqlite3_step(convnet_params_input_stmt) == SQLITE_ROW)\n\t\t\t\t{\n\t\t\t\t\tinput.height = sqlite3_column_int(convnet_params_input_stmt, 0);\n\t\t\t\t\tinput.width = sqlite3_column_int(convnet_params_input_stmt, 1);\n\t\t\t\t}\n\t\t\t\tsqlite3_finalize(convnet_params_input_stmt);\n\t\t\t}\n\t\t\tassert(input.height != 0 && input.width != 0);\n\t\t\tconvnet = ccv_convnet_new(use_cwc_accel, input, (ccv_convnet_layer_param_t*)ccv_array_get(layer_params, 0), layer_params->rnum);\n\t\t\tccv_array_free(layer_params);\n\t\t\t// load layer data\n\t\t\tsqlite3_stmt* layer_data_stmt = 0;\n\t\t\tconst char layer_data_qs[] =\n\t\t\t\t\"SELECT layer, weight, bias, half_precision FROM layer_data;\";\n\t\t\tif (SQLITE_OK == sqlite3_prepare_v2(db, layer_data_qs, sizeof(layer_data_qs), &layer_data_stmt, 0))\n\t\t\t{\n\t\t\t\twhile (sqlite3_step(layer_data_stmt) == SQLITE_ROW)\n\t\t\t\t{\n\t\t\t\t\tccv_convnet_layer_t* layer = convnet->layers + sqlite3_column_int(layer_data_stmt, 0);\n\t\t\t\t\tint half_precision = sqlite3_column_int(layer_data_stmt, 3);\n\t\t\t\t\tint wnum = sqlite3_column_bytes(layer_data_stmt, 1) / (half_precision ? sizeof(uint16_t) : sizeof(float));\n\t\t\t\t\t// if weights available, load weights\n\t\t\t\t\tif (wnum == layer->wnum)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst void* w = sqlite3_column_blob(layer_data_stmt, 1);\n\t\t\t\t\t\tif (half_precision)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat* f = (float*)ccmalloc(sizeof(float) * layer->wnum);\n\t\t\t\t\t\t\tccv_half_precision_to_float((uint16_t*)w, f, layer->wnum);\n\t\t\t\t\t\t\tw = f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tswitch (layer->type)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t\t\t\t\t\tmemcpy(layer->w, w, sizeof(float) * layer->wnum);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase CCV_CONVNET_FULL_CONNECT:\n\t\t\t\t\t\t\t\tmemcpy(layer->w, w, sizeof(float) * layer->wnum);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (half_precision)\n\t\t\t\t\t\t\tccfree((void*)w);\n\t\t\t\t\t}\n\t\t\t\t\tint bnum = sqlite3_column_bytes(layer_data_stmt, 2) / (half_precision ? sizeof(uint16_t) : sizeof(float));\n\t\t\t\t\t// if bias available, load bias\n\t\t\t\t\tif (bnum == (layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count))\n\t\t\t\t\t{\n\t\t\t\t\t\tconst void* bias = sqlite3_column_blob(layer_data_stmt, 2);\n\t\t\t\t\t\tif (half_precision)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat* f = (float*)ccmalloc(sizeof(float) * (layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count));\n\t\t\t\t\t\t\tccv_half_precision_to_float((uint16_t*)bias, f, layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count);\n\t\t\t\t\t\t\tbias = f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tswitch (layer->type)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase CCV_CONVNET_CONVOLUTIONAL:\n\t\t\t\t\t\t\t\tmemcpy(layer->bias, bias, sizeof(float) * layer->net.convolutional.count);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase CCV_CONVNET_FULL_CONNECT:\n\t\t\t\t\t\t\t\tmemcpy(layer->bias, bias, sizeof(float) * layer->net.full_connect.count);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (half_precision)\n\t\t\t\t\t\t\tccfree((void*)bias);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsqlite3_finalize(layer_data_stmt);\n\t\t\t}\n\t\t\tsqlite3_stmt* convnet_params_mean_activity_stmt = 0;\n\t\t\t// load convnet params for mean activity\n\t\t\tconst char convnet_params_mean_activity_qs[] =\n\t\t\t\t\"SELECT mean_activity FROM convnet_params WHERE convnet = 0;\";\n\t\t\tif (SQLITE_OK == sqlite3_prepare_v2(db, convnet_params_mean_activity_qs, sizeof(convnet_params_mean_activity_qs), &convnet_params_mean_activity_stmt, 0))\n\t\t\t{\n\t\t\t\tif (sqlite3_step(convnet_params_mean_activity_stmt) == SQLITE_ROW)\n\t\t\t\t{\n\t\t\t\t\tint elems = sqlite3_column_bytes(convnet_params_mean_activity_stmt, 0) / sizeof(float);\n\t\t\t\t\tif (elems == convnet->input.height * convnet->input.width * convnet->channels)\n\t\t\t\t\t\tmemcpy(convnet->mean_activity->data.f32, sqlite3_column_blob(convnet_params_mean_activity_stmt, 0), sizeof(float) * elems);\n\t\t\t\t}\n\t\t\t\tsqlite3_finalize(convnet_params_mean_activity_stmt);\n\t\t\t}\n\t\t}\n\t\tsqlite3_close(db);\n\t\treturn convnet;\n\t}\n\treturn 0;\n}\n\nvoid ccv_convnet_input_formation(ccv_size_t input, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b)\n{\n\tif (a->rows > input.height && a->cols > input.width)\n\t\tccv_resample(a, b, CCV_32F, ccv_max(input.height, (int)(a->rows * (float)input.height / a->cols + 0.5)), ccv_max(input.width, (int)(a->cols * (float)input.width / a->rows + 0.5)), CCV_INTER_AREA);\n\telse if (a->rows < input.height || a->cols < input.width)\n\t\tccv_resample(a, b, CCV_32F, ccv_max(input.height, (int)(a->rows * (float)input.height / a->cols + 0.5)), ccv_max(input.width, (int)(a->cols * (float)input.width / a->rows + 0.5)), CCV_INTER_CUBIC);\n\telse\n\t\tccv_shift(a, (ccv_matrix_t**)b, CCV_32F, 0, 0); // converting to 32f\n}\n\nvoid ccv_convnet_free(ccv_convnet_t* convnet)\n{\n\tccv_convnet_compact(convnet);\n\tint i;\n\tfor (i = 0; i < convnet->count; i++)\n\t\tif (convnet->layers[i].w)\n\t\t\tccfree(convnet->layers[i].w);\n\tif (convnet->mean_activity)\n\t\tccv_matrix_free(convnet->mean_activity);\n\tccfree(convnet);\n}\n\n#endif\n", "meta": {"hexsha": "ca79e27857d1050327c25552812aebb906134c0c", "size": 73282, "ext": "c", "lang": "C", "max_stars_repo_path": "lib/ccv_convnet.c", "max_stars_repo_name": "sunkaianna/ccv", "max_stars_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2016-06-08T19:47:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T15:14:13.000Z", "max_issues_repo_path": "lib/ccv_convnet.c", "max_issues_repo_name": "sunkaianna/ccv", "max_issues_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-07-24T03:41:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-23T16:48:05.000Z", "max_forks_repo_path": "lib/ccv_convnet.c", "max_forks_repo_name": "sunkaianna/ccv", "max_forks_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2016-02-18T08:34:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T17:57:28.000Z", "avg_line_length": 43.3108747045, "max_line_length": 303, "alphanum_fraction": 0.6704238421, "num_tokens": 23542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.370455700866889}}
{"text": "#define MAXLOCI 1000000\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n\n/* data definition- holds sample size of each species, segsites in each species, D, length of locus */\nstruct hkaData{\n  int na, nb, length, lArray[30], sArray[30];\n  double d, sa, sb;\n  char name[81];\n};\n\nstruct hkaParams{\n  int *lengths;\n};\n\ndouble harmSum(int n);\ndouble harmSumSquare(int n);\nvoid getData(int argc, char *argv[]);\nvoid usage();\ndouble calculateHKA(gsl_vector *params,gsl_vector *chiSquares, gsl_vector *expSA, gsl_vector *expD);\nint chopByWhite(char *in, char *outArray[], int outSize);\nint setHKAFunction(const gsl_vector *x, void *p, gsl_vector *f);\nint solveSystem(gsl_vector *params);\n", "meta": {"hexsha": "c6d6a41b29d63b0538deeecd00fbca9c81d9b55e", "size": 718, "ext": "h", "lang": "C", "max_stars_repo_path": "hka.h", "max_stars_repo_name": "kern-lab/hka", "max_stars_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-06T02:12:05.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-06T02:12:05.000Z", "max_issues_repo_path": "hka.h", "max_issues_repo_name": "kern-lab/hka", "max_issues_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hka.h", "max_forks_repo_name": "kern-lab/hka", "max_forks_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_forks_repo_licenses": ["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.72, "max_line_length": 102, "alphanum_fraction": 0.7339832869, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.5, "lm_q1q2_score": 0.37008718675097974}}
{"text": "/* sys/test.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_test.h>\n\n#include <gsl/gsl_ieee_utils.h>\n\nint\nmain (void)\n{\n  double y, y_expected;\n\n  gsl_ieee_env_setup ();\n\n  /* Test for expm1 */\n\n  y = gsl_expm1 (0.0); y_expected = 0.0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_expm1(0.0)\");\n\n  y = gsl_expm1 (1e-10); y_expected = 1.000000000050000000002e-10;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_expm1(1e-10)\");\n\n  y = gsl_expm1 (-1e-10); y_expected = -9.999999999500000000017e-11;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_expm1(-1e-10)\");\n\n  y = gsl_expm1 (0.1); y_expected = 0.1051709180756476248117078264902;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_expm1(0.1)\");\n\n  y = gsl_expm1 (-0.1); y_expected = -0.09516258196404042683575094055356;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_expm1(-0.1)\");\n\n  y = gsl_expm1 (10.0); y_expected = 22025.465794806716516957900645284;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_expm1(10.0)\");\n\n  y = gsl_expm1 (-10.0); y_expected = -0.99995460007023751514846440848444;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_expm1(-10.0)\");\n   \n  /* Test for log1p */\n\n  y = gsl_log1p (0.0); y_expected = 0.0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_log1p(0.0)\");\n\n  y = gsl_log1p (1e-10); y_expected = 9.9999999995000000000333333333308e-11;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_log1p(1e-10)\");\n\n  y = gsl_log1p (0.1); y_expected = 0.095310179804324860043952123280765;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_log1p(0.1)\");\n\n  y = gsl_log1p (10.0); y_expected = 2.3978952727983705440619435779651;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_log1p(10.0)\");\n\n  /* Test for gsl_hypot */\n\n  y = gsl_hypot (0.0, 0.0) ; y_expected = 0.0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_hypot(0.0, 0.0)\");\n\n  y = gsl_hypot (1e-10, 1e-10) ; y_expected = 1.414213562373095048801688e-10;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_hypot(1e-10, 1e-10)\");\n\n  y = gsl_hypot (1e-38, 1e-38) ; y_expected = 1.414213562373095048801688e-38;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_hypot(1e-38, 1e-38)\");\n\n  y = gsl_hypot (1e-10, -1.0) ; y_expected = 1.000000000000000000005;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_hypot(1e-10, -1)\");\n\n  y = gsl_hypot (-1.0, 1e-10) ; y_expected = 1.000000000000000000005;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_hypot(-1, 1e-10)\");\n\n  y = gsl_hypot (1e307, 1e301) ; y_expected = 1.000000000000499999999999e307;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_hypot(1e307, 1e301)\");\n\n  y = gsl_hypot (1e301, 1e307) ; y_expected = 1.000000000000499999999999e307;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_hypot(1e301, 1e307)\");\n\n  y = gsl_hypot (1e307, 1e307) ; y_expected = 1.414213562373095048801688e307;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_hypot(1e307, 1e307)\");\n\n\n  /* Test for acosh */\n\n  y = gsl_acosh (1.0); y_expected = 0.0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_acosh(1.0)\");\n\n  y = gsl_acosh (1.1); y_expected = 4.435682543851151891329110663525e-1;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_acosh(1.1)\");\n\n  y = gsl_acosh (10.0); y_expected = 2.9932228461263808979126677137742e0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_acosh(10.0)\");\n\n  y = gsl_acosh (1e10); y_expected = 2.3718998110500402149594646668302e1;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_acosh(1e10)\");\n\n  /* Test for asinh */\n\n  y = gsl_asinh (0.0); y_expected = 0.0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(0.0)\");\n\n  y = gsl_asinh (1e-10); y_expected = 9.9999999999999999999833333333346e-11;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(1e-10)\");\n\n  y = gsl_asinh (-1e-10); y_expected = -9.9999999999999999999833333333346e-11;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(1e-10)\");\n\n  y = gsl_asinh (0.1); y_expected = 9.983407889920756332730312470477e-2;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(0.1)\");\n\n  y = gsl_asinh (-0.1); y_expected = -9.983407889920756332730312470477e-2;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(-0.1)\");\n\n  y = gsl_asinh (1.0); y_expected = 8.8137358701954302523260932497979e-1;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(1.0)\");\n\n  y = gsl_asinh (-1.0); y_expected = -8.8137358701954302523260932497979e-1;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(-1.0)\");\n\n  y = gsl_asinh (10.0); y_expected = 2.9982229502979697388465955375965e0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(10)\");\n\n  y = gsl_asinh (-10.0); y_expected = -2.9982229502979697388465955375965e0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(-10)\");\n\n  y = gsl_asinh (1e10); y_expected = 2.3718998110500402149599646668302e1;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(1e10)\");\n\n  y = gsl_asinh (-1e10); y_expected = -2.3718998110500402149599646668302e1;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_asinh(-1e10)\");\n\n  /* Test for atanh */\n\n  y = gsl_atanh (0.0); y_expected = 0.0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_atanh(0.0)\");\n\n  y = gsl_atanh (1e-20); y_expected = 1e-20;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_atanh(1e-20)\");\n\n  y = gsl_atanh (-1e-20); y_expected = -1e-20;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_atanh(-1e-20)\");\n\n  y = gsl_atanh (0.1); y_expected = 1.0033534773107558063572655206004e-1;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_atanh(0.1)\");\n\n  y = gsl_atanh (-0.1); y_expected = -1.0033534773107558063572655206004e-1;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_atanh(-0.1)\");\n\n  y = gsl_atanh (0.9); y_expected = 1.4722194895832202300045137159439e0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_atanh(0.9)\");\n\n  y = gsl_atanh (-0.9); y_expected = -1.4722194895832202300045137159439e0;\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_atanh(0.9)\");\n\n  /* Test for pow_int */\n\n  y = gsl_pow_2 (-3.14); y_expected = pow(-3.14, 2.0);\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_pow_2(-3.14)\");\n\n  y = gsl_pow_3 (-3.14); y_expected = pow(-3.14, 3.0);\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_pow_3(-3.14)\");\n\n  y = gsl_pow_4 (-3.14); y_expected = pow(-3.14, 4.0);\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_pow_4(-3.14)\");\n\n  y = gsl_pow_5 (-3.14); y_expected = pow(-3.14, 5.0);\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_pow_5(-3.14)\");\n\n  y = gsl_pow_6 (-3.14); y_expected = pow(-3.14, 6.0);\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_pow_6(-3.14)\");\n\n  y = gsl_pow_7 (-3.14); y_expected = pow(-3.14, 7.0);\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_pow_7(-3.14)\");\n\n  y = gsl_pow_8 (-3.14); y_expected = pow(-3.14, 8.0);\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_pow_8(-3.14)\");\n\n  y = gsl_pow_9 (-3.14); y_expected = pow(-3.14, 9.0);\n  gsl_test_rel (y, y_expected, 1e-15, \"gsl_pow_9(-3.14)\");\n\n  { \n    int n;\n    for (n = -9; n < 10; n++) {\n      y = gsl_pow_int (-3.14, n); y_expected = pow(-3.14, n);\n      gsl_test_rel (y, y_expected, 1e-15, \"gsl_pow_n(-3.14,%d)\", n);\n    }\n  }\n\n  /* Test for isinf, isnan, finite*/\n\n  {\n    double zero, one, inf, nan;\n    int s;\n\n    zero = 0.0;\n    one = 1.0;\n    inf = exp(1.0e10);\n    nan = inf / inf;\n    \n    s = gsl_isinf(zero);\n    gsl_test_int (s, 0, \"gsl_isinf(0)\");\n    \n    s = gsl_isinf(one);\n    gsl_test_int (s, 0, \"gsl_isinf(1)\");\n    \n    s = gsl_isinf(inf);\n    gsl_test_int (s, 1, \"gsl_isinf(inf)\");\n\n    s = gsl_isinf(-inf);\n    gsl_test_int (s, -1, \"gsl_isinf(-inf)\");\n    \n    s = gsl_isinf(nan);\n    gsl_test_int (s, 0, \"gsl_isinf(nan)\");\n\n\n    s = gsl_isnan(zero);\n    gsl_test_int (s, 0, \"gsl_isnan(0)\");\n    \n    s = gsl_isnan(one);\n    gsl_test_int (s, 0, \"gsl_isnan(1)\");\n    \n    s = gsl_isnan(inf);\n    gsl_test_int (s, 0, \"gsl_isnan(inf)\");\n    \n    s = gsl_isnan(nan);\n    gsl_test_int (s, 1, \"gsl_isnan(nan)\");\n\n\n    s = gsl_finite(zero);\n    gsl_test_int (s, 1, \"gsl_finite(0)\");\n    \n    s = gsl_finite(one);\n    gsl_test_int (s, 1, \"gsl_finite(1)\");\n    \n    s = gsl_finite(inf);\n    gsl_test_int (s, 0, \"gsl_finite(inf)\");\n    \n    s = gsl_finite(nan);\n    gsl_test_int (s, 0, \"gsl_finite(nan)\");\n  }\n\n  {\n    double x = gsl_fdiv (2.0, 3.0);\n    gsl_test_rel (x, 2.0/3.0, 4*GSL_DBL_EPSILON, \"gsl_fdiv(2,3)\");\n  }\n\n  exit (gsl_test_summary ());\n}\n\n\n", "meta": {"hexsha": "df30fe4ea48d93efcc2bef0a3035cd458f245651", "size": 8791, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/sys/test.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/sys/test.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/sys/test.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 32.925093633, "max_line_length": 78, "alphanum_fraction": 0.6587418951, "num_tokens": 3661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3700198058926444}}
{"text": "#ifndef Single_Pin_Subchannel_h\n#define Single_Pin_Subchannel_h\n\n#include <vector>\n\n// Trilinos includes\n#include \"Teuchos_ParameterList.hpp\"\n#include \"Teuchos_RCP.hpp\"\n\n// SCALE includes\n#include \"Nemesis/harness/DBC.hh\"\n\n// vendored includes\n#include <gsl/gsl>\n\nnamespace enrico {\n\n//===========================================================================//\n/*!\n * \\class Single_Pin_Subchannel\n * \\brief Solve subchannel flow in single channel.\n *\n * This class implements a two-equation subchannel model involving\n * conservation of energy and axial momentum.  No lateral flow is accounted\n * for.  The model excludes friction momentum losses and any spacer grid\n * effects.  It is useful for giving qualitatively-correct behavior but\n * should not be used for actual analysis.\n */\n//===========================================================================//\nclass Single_Pin_Subchannel {\npublic:\n  //@{\n  //! Typedefs\n  using RCP_PL = Teuchos::RCP<Teuchos::ParameterList>;\n  //@}\n\n  enum Verbosity { NONE, LOW, HIGH };\n\nprivate:\n  // >>> DATA\n\n  // Solve parameters\n  double d_tol;\n  int d_max_iters;\n  Verbosity d_verbosity;\n\n  // Axial grid\n  std::vector<double> d_delta_z;\n\n  // Channel geometry\n  double d_area;\n\n  // Flow conditions\n  double d_mdot;\n  double d_T_inlet;\n  double d_p_exit;\n\npublic:\n  // Constructor\n  Single_Pin_Subchannel(RCP_PL& parameters, const std::vector<double>& delta_z);\n\n  // Set channel area (cm^2)\n  void set_channel_area(double area)\n  {\n    // Channel area internally is needed in m^2\n    Expects(area > 0.0);\n    d_area = 1e-4 * area;\n  }\n\n  // Set mass flow rate (kg/s)\n  void set_mass_flow_rate(double mdot)\n  {\n    Expects(mdot > 0.0);\n    Expects(mdot < 2.0);\n    d_mdot = mdot;\n  }\n\n  // Set inlet temperature (K)\n  void set_inlet_temperature(double T)\n  {\n    Expects(T > 0);\n    Expects(T < 1000);\n    d_T_inlet = T;\n  }\n\n  // Set exit pressure (Pa)\n  void set_exit_pressure(double p)\n  {\n    Expects(p > 0);\n    Expects(p < 2.2e7);\n    d_p_exit = p;\n  }\n\n  // Solve for single subchannel given power distribution\n  void solve(const std::vector<double>& power,\n             std::vector<double>& temperature,\n             std::vector<double>& density);\n};\n\n//---------------------------------------------------------------------------//\n} // end namespace enrico\n\n//---------------------------------------------------------------------------//\n#endif // Single_Pin_Subchannel_h\n\n//---------------------------------------------------------------------------//\n// end of Single_Pin_Subchannel.h\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "53808424cb2845baccc7ebffeef57eafd9ed10b1", "size": 2626, "ext": "h", "lang": "C", "max_stars_repo_path": "include/smrt/Single_Pin_Subchannel.h", "max_stars_repo_name": "sphamil/enrico", "max_stars_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smrt/Single_Pin_Subchannel.h", "max_issues_repo_name": "sphamil/enrico", "max_issues_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smrt/Single_Pin_Subchannel.h", "max_forks_repo_name": "sphamil/enrico", "max_forks_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb", "max_forks_repo_licenses": ["BSD-3-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.0917431193, "max_line_length": 80, "alphanum_fraction": 0.5601675552, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.36992735951089156}}
{"text": "#pragma once\n\n#include <gsl/gsl>\n#include <memory>\n#include <tuple>\n\n#include \"../math/Constants.h\"\n#include \"../math/Exponentials.h\"\n#include \"../math/General.h\"\n#include \"../math/Point2.h\"\n#include \"../math/Point3.h\"\n#include \"../math/Random.h\"\n#include \"../math/TrigFuncs.h\"\n#include \"../math/Vec2.h\"\n#include \"../math/Vec3.h\"\n#include \"../utils/Concepts.h\"\n/// @brief custom mathematics implementaitons\nnamespace math { } // namespace math\n\n/// @brief utility types\nnamespace utils { } // namespace utils\n\nusing utils::concepts::ConstructibleFrom;\t\t// NOLINT\nusing utils::concepts::Copyable;\t\t\t\t// NOLINT\nusing utils::concepts::CopyOrMovable;\t\t\t// NOLINT\nusing utils::concepts::DefaultConstructible;\t// NOLINT\nusing utils::concepts::Derived;\t\t\t\t\t// NOLINT\nusing utils::concepts::FloatingPoint;\t\t\t// NOLINT\nusing utils::concepts::Integral;\t\t\t\t// NOLINT\nusing utils::concepts::Movable;\t\t\t\t\t// NOLINT\nusing utils::concepts::NotCopyable;\t\t\t\t// NOLINT\nusing utils::concepts::NotCopyOrMovable;\t\t// NOLINT\nusing utils::concepts::NotDefaultConstructible; // NOLINT\nusing utils::concepts::NotMovable;\t\t\t\t// NOLINT\nusing utils::concepts::NotPassable;\t\t\t\t// NOLINT\nusing utils::concepts::NotPointer;\t\t\t\t// NOLINT\nusing utils::concepts::NotReference;\t\t\t// NOLINT\nusing utils::concepts::NotSemiRegular;\t\t\t// NOLINT\nusing utils::concepts::Numeric;\t\t\t\t\t// NOLINT\nusing utils::concepts::Passable;\t\t\t\t// NOLINT\nusing utils::concepts::Pointer;\t\t\t\t\t// NOLINT\nusing utils::concepts::Reference;\t\t\t\t// NOLINT\nusing utils::concepts::SemiRegular;\t\t\t\t// NOLINT\nusing utils::concepts::SignedIntegral;\t\t\t// NOLINT\nusing utils::concepts::SignedNumeric;\t\t\t// NOLINT\n\nusing math::Constants;\t  // NOLINT\nusing math::Exponentials; // NOLINT\nusing math::General;\t  // NOLINT\nusing math::Point2;\t\t  // NOLINT\nusing math::Point2Idx;\t  // NOLINT\nusing math::Point3;\t\t  // NOLINT\nusing math::Point3Idx;\t  // NOLINT\nusing math::random_value; // NOLINT\nusing math::Trig;\t\t  // NOLINT\nusing math::Vec2;\t\t  // NOLINT\nusing math::Vec2Idx;\t  // NOLINT\nusing math::Vec3;\t\t  // NOLINT\nusing math::Vec3Idx;\t  // NOLINT\n\nusing gsl::narrow_cast; // NOLINT\ntemplate<typename T>\nusing NotNull = gsl::not_null<T*>; // NOLINT\ntemplate<typename T>\nusing Owner = gsl::owner<T*>; // NOLINT\n\ntemplate<FloatingPoint T = float>\ninline constexpr auto degrees_to_radians(T degrees) noexcept -> T {\n\treturn degrees * Constants<T>::pi / narrow_cast<T>(180.0);\n}\n\ntemplate<FloatingPoint T = float>\ninline constexpr auto radians_to_degrees(T radians) noexcept -> T {\n\treturn radians * narrow_cast<T>(180.0) / Constants<T>::pi;\n}\n\ntemplate<SignedNumeric T = float>\ninline constexpr auto clamp(T val, T min, T max) noexcept -> T {\n\tif(val < min) {\n\t\treturn min;\n\t}\n\telse if(val > max) {\n\t\treturn max;\n\t}\n\telse {\n\t\treturn val;\n\t}\n}\n\ntemplate<typename... Args>\ninline constexpr auto ignore(Args&&... args) noexcept -> void {\n\tstd::ignore = std::tuple<Args...>(args...);\n}\n\n// clang-format off\n#ifndef _MSC_VER\n\t// NOLINTNEXTLINE\n\t#define IGNORE_UNUSED_MACROS_START \\\n\t\t_Pragma(\"GCC diagnostic push\")\\\n\t\t_Pragma(\"GCC diagnostic ignored \\\"-Wunused-macros\\\"\")\n#else\n\t// NOLINTNEXTLINE\n\t#define IGNORE_UNUSED_MACROS_START\n#endif\n// clang-format on\n\n// clang-format off\n#ifndef _MSC_VER\n\t// NOLINTNEXTLINE\n\t#define IGNORE_UNUSED_MACROS_STOP \\\n\t\t_Pragma(\"GCC diagnostic pop\")\n#else\n\t// NOLINTNEXTLINE\n\t#define IGNORE_UNUSED_MACROS_STOP\n#endif\n// clang-format on\n\nIGNORE_UNUSED_MACROS_START\n\n// clang-format off\n#ifndef _MSC_VER\n\t// NOLINTNEXTLINE\n\t#define IGNORE_PADDING_START \\\n\t\t_Pragma(\"GCC diagnostic push\") \\\n\t\t_Pragma(\"GCC diagnostic ignored \\\"-Wpadded\\\"\")\n#else\n\t// NOLINTNEXTLINE\n\t#define IGNORE_PADDING_START \\\n\t\t_Pragma(\"warning( push )\") \\\n\t\t_Pragma(\"warning( disable : 4820 )\")\n#endif\n// clang-format on\n\n// clang-format off\n#ifndef _MSC_VER\n\t// NOLINTNEXTLINE\n\t#define IGNORE_PADDING_STOP \\\n\t\t_Pragma(\"GCC diagnostic pop\")\n#else\n\t// NOLINTNEXTLINE\n\t#define IGNORE_PADDING_STOP \\\n\t\t_Pragma(\"warning( pop )\")\n#endif\n// clang-format on\n\n// clang-format off\n#ifndef _MSC_VER\n\t// NOLINTNEXTLINE\n\t#define IGNORE_UNUSED_TEMPLATES_START \\\n\t\t_Pragma(\"GCC diagnostic push\")\\\n\t\t_Pragma(\"GCC diagnostic ignored \\\"-Wunused-template\\\"\")\n#else\n\t// NOLINTNEXTLINE\n\t#define IGNORE_UNUSED_TEMPLATES_START\n#endif\n// clang-format on\n\n// clang-format off\n#ifndef _MSC_VER\n\t// NOLINTNEXTLINE\n\t#define IGNORE_UNUSED_TEMPLATES_STOP \\\n\t\t_Pragma(\"GCC diagnostic pop\")\n#else\n\t// NOLINTNEXTLINE\n\t#define IGNORE_UNUSED_TEMPLATES_STOP\n#endif\n// clang-format on\n\nIGNORE_UNUSED_MACROS_STOP\n", "meta": {"hexsha": "d2f6d13e89c12bfb20a0f9a478179537557e350e", "size": 4501, "ext": "h", "lang": "C", "max_stars_repo_path": "src/base/StandardIncludes.h", "max_stars_repo_name": "braxtons12/ray_tracer", "max_stars_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/base/StandardIncludes.h", "max_issues_repo_name": "braxtons12/ray_tracer", "max_issues_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/StandardIncludes.h", "max_forks_repo_name": "braxtons12/ray_tracer", "max_forks_repo_head_hexsha": "274cadb7db4d434b5143503109d6cf58986fac9b", "max_forks_repo_licenses": ["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.4764705882, "max_line_length": 67, "alphanum_fraction": 0.7182848256, "num_tokens": 1346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.36971524648927734}}
{"text": "/*\n** TFCE heuristic\n**\n** M. Kuhlmann, MPI-KYB, Sept 2015\n*/\n\n#include <viaio/VImage.h>\n#include <viaio/Vlib.h>\n#include <viaio/mu.h>\n#include <via/via.h>\n\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <stdlib.h>\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_math.h>\n\n#define ABS(x) ((x) > 0 ? (x) : -(x))\n\nVImage tfce(VImage t_image,VImage map,int nstrata)\n{\n  int b,r,c,i,j,k;\n  size_t nslices = VImageNBands(t_image);\n  size_t nrows  = VImageNRows(t_image);\n  size_t ncols  = VImageNColumns(t_image);\n  double tiny = 1e-16;\n  \n  /* if pixel map is not given, compute it */\n  if(!map) {\n    VImage mask = VCreateImage(nslices,nrows,ncols,VBitRepn);\n    VFillImage(mask,VAllBands,0);\n    \n    size_t nvox = 0;\n    float u;\n    for (b=0; b<nslices; b++) {\n      for (r=0; r<nrows; r++) {\n\tfor (c=0; c<ncols; c++) {\n\t  u = VPixel(t_image,b,r,c,VFloat);\n\t  if (ABS(u) >= tiny) {\n\t    VPixel(mask,b,r,c,VBit) = 1;\n\t    nvox++;\n\t  }\n\t}\n      }\n    }\n\n    if(nvox == 0)\n      VError(\"TFCE: Number of voxels!=0 is zero.\");\n    /* voxel addresses */\n    map = VCreateImage(1,3,nvox,VShortRepn);\n    if (map == NULL) VError(\" error allocating addr map\");\n    VFillImage(map,VAllBands,0);\n    i = 0;\n    for (b=0; b<nslices; b++) {\n      for (r=0; r<nrows; r++) {\n\tfor (c=0; c<ncols; c++) {\n\t  if (VGetPixel(mask,b,r,c) < 0.5) continue;\n\t  VPixel(map,0,0,i,VShort) = b;\n\t  VPixel(map,0,1,i,VShort) = r;\n\t  VPixel(map,0,2,i,VShort) = c;\n\t  i++;\n\t}\n      }\n    }\n    VDestroyImage(mask);\n  }\n  \n  /* stratification */\n  /* set z strata */\n  size_t nvox = VImageNColumns(map);\n  double z;\n  \n  /* get an idea of z-value distribution */\n  double zmax=0;\n  for (i=0; i<nvox; i++) {\n    b = VPixel(map,0,0,i,VShort);\n    r = VPixel(map,0,1,i,VShort);\n    c = VPixel(map,0,2,i,VShort);\n    z = VPixel(t_image,b,r,c,VFloat);\n    if (z > zmax) zmax = z;\n  }\n\n  /* ini strata */\n  double step = zmax / (double)nstrata;\n  double *stratum = (double *) VCalloc(nstrata+1,sizeof(double));\n  for (j=0; j<=nstrata; j++) stratum[j] = step*j;\n\n  float *clustersize = (float *) VCalloc(nvox,sizeof(float));\n  if (!clustersize) VError(\" err allocating clustersize\");\n  float *cluster_cont = (float *) VCalloc(nvox,sizeof(float));\n  if (!cluster_cont) VError(\" err allocating cluster_cont\");\n  for (i=0; i<nvox; i++) {\n    clustersize[i] = 0;\n    cluster_cont[i] = 0;\n  }\n\n  /* output, create TFCE image */\n  VImage tfce  = VCreateImage(nslices,nrows,ncols,VFloatRepn);\n  if (!tfce) VError(\" err allocating tfce image\");\n  VFillImage(tfce,VAllBands,0);  \n  \n  /* ini images */\n  VImage bin_image = VCreateImage(nslices,nrows,ncols,VBitRepn);\n  if (!bin_image) VError(\" err allocating bin_image image\");\n  VImage label_image = VCreateImage(nslices,nrows,ncols,VShortRepn);\n  if (!label_image) VError(\" err allocating label_image image\");\n  \n  /* for each stratum */\n  double *strat_sq = (double *)VCalloc(nstrata,sizeof(double));\n  for (j=0; j<nstrata; j++)\n    strat_sq[j] = stratum[j] * stratum[j];\n  for (j=0; j<nstrata; j++) {\n    VFillImage(bin_image,VAllBands,0);\n    for (i=0; i<nvox; i++) {\n      b = VPixel(map,0,0,i,VShort);\n      r = VPixel(map,0,1,i,VShort);\n      c = VPixel(map,0,2,i,VShort);\n      z = VPixel(t_image,b,r,c,VFloat);\n      if (z > stratum[j]) {\n\tVPixel(bin_image,b,r,c,VBit) = 1;\n      }\n    }\n\n    /* get connected components (clusters) */\n    long nl=0;\n    VLabelImage3d(bin_image,label_image,26,VShortRepn,&nl);\n    if (nl < 1) continue;   /* no voxels in this stratum found */\n\n    /* compute cluster sizes */\n    int max_k = 0;\n    for (i=0; i<nvox; i++) clustersize[i] = 0;\n    for (i=0; i<nvox; i++) {\n      b = VPixel(map,0,0,i,VShort);\n      r = VPixel(map,0,1,i,VShort);\n      c = VPixel(map,0,2,i,VShort);\n      k = VPixel(label_image,b,r,c,VShort);\n      if (k > 0) clustersize[k]++;\n      if (k > max_k) max_k = k;\n    }\n\n    /* compute contribution of the cluster to the voxels in it */\n    for (i=0; i<=max_k; i++)\n      cluster_cont[i] = sqrt(clustersize[i]) * strat_sq[j];\n    \n    /* add cluster contribution to each voxel */\n    for (i=0; i<nvox; i++) {\n      b = VPixel(map,0,0,i,VShort);\n      r = VPixel(map,0,1,i,VShort);\n      c = VPixel(map,0,2,i,VShort);\n      k = VPixel(label_image,b,r,c,VShort);\n      VPixel(tfce,b,r,c,VFloat) += cluster_cont[k];\n    }\n  }\n  \n  /* thickness correction */\n  for (i=0; i<nvox; i++) {\n    b = VPixel(map,0,0,i,VShort);\n    r = VPixel(map,0,1,i,VShort);\n    c = VPixel(map,0,2,i,VShort);\n    k = VPixel(label_image,b,r,c,VShort);\n    VPixel(tfce,b,r,c,VFloat) *= step;\n  }\n  \n  VDestroyImage(bin_image);\n  VDestroyImage(label_image);\n  VFree(clustersize);\n  VFree(cluster_cont);\n  VFree(stratum);\n  VFree(strat_sq);\n    \n  return tfce;\n}\n", "meta": {"hexsha": "eb8b144fd2ac5cf1b46ec8091a4f594f5c9815c2", "size": 4748, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/utils/tfce.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/utils/tfce.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/utils/tfce.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 26.9772727273, "max_line_length": 68, "alphanum_fraction": 0.5943555181, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3696995790354639}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <gsl/gsl_sf_zeta.h>\n\n/* Calculate the Hurwitz zeta function by invoking the GNU scientific\n   library */\n/* Only intended to be used with R; not the most elegant integration but it\n   may do for now */\n\n/* Two arguments, the power used in the sum (s) and the baseline value (q) */\n\ndouble s, q, zeta; /* arguments to zeta, value */\nchar *program_name; /* name program is invoked under, for errors */\n\nint main(int argc, char* argv[]) {\n  void usage(void);\t/* Warn users about proper usage */\n\n  program_name = argv[0];\n  if (argc != 3) {\n    usage();\n  }\n  s = atof(&argv[1][0]);\n  if (s <= 1.0) {\n    usage();\n  }\n  q = atof(&argv[2][0]);\n  if (q <= 0.0) {\n    usage();\n  }\n  zeta = gsl_sf_hzeta(s,q);\n  printf(\"%.18e\\n\",zeta);\n  return(0);\n}\n\nvoid usage(void) {\n  (void) fprintf(stderr, \"Usage is %s [floating-point exponent > 1] [floating-point additive constant > 0]\\n\", program_name);\n  exit(8);\n}\n", "meta": {"hexsha": "0afe81f25966e9f2ece9cbd2a81df6d1cf4339e0", "size": 951, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/zeta-function/zeta_func.c", "max_stars_repo_name": "jguerber/spatialwarnings", "max_stars_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-07-06T14:32:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T11:21:19.000Z", "max_issues_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/zeta-function/zeta_func.c", "max_issues_repo_name": "jguerber/spatialwarnings", "max_issues_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2017-03-07T07:53:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T16:25:24.000Z", "max_forks_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/zeta-function/zeta_func.c", "max_forks_repo_name": "jguerber/spatialwarnings", "max_forks_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-12T08:50:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T10:29:33.000Z", "avg_line_length": 24.3846153846, "max_line_length": 125, "alphanum_fraction": 0.6256572029, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.36967456985843516}}
{"text": "/** @file */\n\n#ifndef __CCL_F1D_H_INCLUDED__\n#define __CCL_F1D_H_INCLUDED__\n\n#include <gsl/gsl_spline.h>\n\nCCL_BEGIN_DECLS\n\n\ntypedef enum ccl_f1d_extrap_t {\n  ccl_f1d_extrap_0 = 0,  // No extrapolation\n  ccl_f1d_extrap_const = 410,  // Constant extrapolation\n  ccl_f1d_extrap_linx_liny = 411,  // Linear x, linear y\n  ccl_f1d_extrap_linx_logy = 412,  // Linear x, log y\n  ccl_f1d_extrap_logx_liny = 413,  // Log x, linear y\n  ccl_f1d_extrap_logx_logy = 414,  // Log x, log y\n} ccl_f1d_extrap_t;\n\n\n/*\n * Spline wrapper\n * Used to take care of evaluations outside the supported range\n */\ntypedef struct {\n  gsl_spline *spline;\n  double y0,yf; //Constant values to use beyond interpolation limit\n  ccl_f1d_extrap_t extrap_lo_type;\n  ccl_f1d_extrap_t extrap_hi_type;\n  double x_ini, x_end; //Interpolation limits\n  double y_ini, y_end;\n  double der_lo;\n  double der_hi;\n} ccl_f1d_t;\n\n\nccl_f1d_t *ccl_f1d_t_new(int n,double *x,double *y,double y0,double yf,\n\t\t\t ccl_f1d_extrap_t extrap_lo_type,\n\t\t\t ccl_f1d_extrap_t extrap_hi_type, int *status);\n\ndouble ccl_f1d_t_eval(ccl_f1d_t *spl,double x);\n\nvoid ccl_f1d_t_free(ccl_f1d_t *spl);\n\nCCL_END_DECLS\n\n#endif\n", "meta": {"hexsha": "d1d15a457e0cb8cef8f37e75aebd5da5f88aa76b", "size": 1150, "ext": "h", "lang": "C", "max_stars_repo_path": "include/ccl_f1d.h", "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_issues_repo_path": "include/ccl_f1d.h", "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 703.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_forks_repo_path": "include/ccl_f1d.h", "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "avg_line_length": 23.9583333333, "max_line_length": 71, "alphanum_fraction": 0.7556521739, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.36957804096723523}}
{"text": "/**\n  * Copyright 2016 Jos\u00e9 Manuel Abu\u00edn Mosquera <josemanuel.abuin@usc.es>\n  * \n  * This file is part of Matrix Market Suite.\n  *\n  * Matrix Market Suite 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  * Matrix Market Suite 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 Matrix Market Suite. If not, see <http://www.gnu.org/licenses/>.\n  */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#include <cblas.h>\n\n#include \"DMxV.h\"\n#include \"basic.h\"\n\nvoid usageDMxV(){\n\n\tfprintf(stderr, \"\\n\");\n\tfprintf(stderr, \"Usage: MM-Suite DMxV [options] <input-matrix> <input-vector>\\n\");\n\tfprintf(stderr, \"\\nInput/output options:\\n\\n\");\n\tfprintf(stderr, \"       -o STR        Output file name. Default: stdout\\n\");\n\tfprintf(stderr, \"       -r            Input format is row per line. Default: False\\n\");\n\tfprintf(stderr, \"\\nParameters options:\\n\\n\");\n\tfprintf(stderr, \"       -a DOUBLE     Alpha. Default: 1.0\\n\");\n\tfprintf(stderr, \"       -b DOUBLE     Beta. Default: 0.0\\n\");\n\tfprintf(stderr, \"\\nPerformance options:\\n\\n\");\n\tfprintf(stderr, \"       -t INT        Number of threads to use in OpenBLAS. Default: 1\\n\");\n\tfprintf(stderr, \"\\n\");\n\n}\n\nint DMxV(int argc, char *argv[]) {\n\t\n\tint \t\t\tret_code = 1;\n\tint \t\t\toption;\n\t\n\tunsigned long \t\t*II;\n\tunsigned long \t\t*J;\n\tdouble \t\t\t*values;\n\t\n\tunsigned long \t\tM;\n\tunsigned long \t\tN;\n\tunsigned long long \tnz;\n\t\n\t\n\tdouble \t\t\t*vectorValues;\n\tunsigned long \t\tM_Vector;\n\tunsigned long \t\tN_Vector;\n\tunsigned long long \tnz_vector;\n\t\n\tchar\t\t\t*outputFileName = NULL;\n\t\n\tchar\t\t\t*inputMatrixFile = NULL;\n\tchar\t\t\t*inputVectorFile = NULL;\n\tchar\t\t\t*outputVectorFile = NULL;\n\t\n\tint\t\t\tinputFormatRow = 0;\n\tint\t\t\tbasicOps = 0;\n\tint\t\t\tnumThreads = 1;\n\t\n\tdouble\t\t\talpha = 1.0;\n\tdouble\t\t\tbeta = 0.0;\n\t\n\twhile ((option = getopt(argc, argv,\"ero:b:a:t:\")) >= 0) {\n\t\tswitch (option) {\n\t\t\tcase 'o' : \n\t\t\t\t//free(outputFileName);\n\t\t\t\t\n\t\t\t\toutputFileName = (char *) malloc(sizeof(char)*strlen(optarg)+1);\n\t\t\t\tstrcpy(outputFileName,optarg);\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'r':\n\t\t\t\tinputFormatRow = 1;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase 'e':\n\t\t\t\tbasicOps = 1;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase 'b':\n\t\t\t\tbeta = atof(optarg);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'a':\n\t\t\t\talpha = atof(optarg);\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase 't':\n\t\t\t\tnumThreads = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tdefault: break;\n\t\t}\n\t\n\t}\n\t\n\tif ((optind + 3 != argc) && (optind + 2 != argc)) {\n\t\tusageDMxV();\n\t\treturn 0;\n\t}\n\t\n\topenblas_set_num_threads(numThreads);\n\t\n\tif(optind + 3 == argc) { //We have an output vector\n\t\n\t\toutputVectorFile = (char *)malloc(sizeof(char)*strlen(argv[optind+2])+1);\n\t\tstrcpy(outputVectorFile,argv[optind+2]);\n\t}\n\t\n\tif(outputFileName == NULL) {\n\t\toutputFileName = (char *) malloc(sizeof(char)*7);\n\t\tsprintf(outputFileName,\"stdout\");\n\t}\n\t\n\tinputMatrixFile = (char *)malloc(sizeof(char)*strlen(argv[optind])+1);\n\t\n\tif(inputMatrixFile == NULL) {\n\t\tfprintf(stderr, \"[%s] Error reserving memory for input matrix file name\\n\",__func__);\n\t\treturn 0;\n\t}\n\t\n\tinputVectorFile = (char *)malloc(sizeof(char)*strlen(argv[optind+1])+1);\n\t\n\tif(inputVectorFile == NULL) {\n\t\tfprintf(stderr, \"[%s] Error reserving memory for input vector file name\\n\",__func__);\n\t\treturn 0;\n\t}\n\t\n\tstrcpy(inputMatrixFile,argv[optind]);\n\tstrcpy(inputVectorFile,argv[optind+1]);\n\t\n\t//Read matrix\n\tif(inputFormatRow){\n\t\n\t\tif(!readDenseCoordinateMatrixRowLine(inputMatrixFile,&II,&J,&values,&M,&N,&nz)){\n\t\t\tusageDMxV();\n\t\t\tfprintf(stderr, \"[%s] Can not read Matrix\\n\",__func__);\n\t\t\treturn 0;\n\t\t}\n\t\n\t}\n\telse {\n\t\tif(!readDenseCoordinateMatrix(inputMatrixFile,&II,&J,&values,&M,&N,&nz)){\n\t\t\tusageDMxV();\n\t\t\tfprintf(stderr, \"[%s] Can not read Matrix\\n\",__func__);\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\t\n\t\n\t//Read vector\n\tif(!readDenseVector(inputVectorFile, &vectorValues,&M_Vector,&N_Vector,&nz_vector)){\n\t\tusageDMxV();\n\t\tfprintf(stderr, \"[%s] Can not read Vector\\n\",__func__);\n\t\treturn 0;\n\t}\n\t\n\t/*\n\tvoid cblas_dgemv(const enum CBLAS_ORDER order,\n                 const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n                 const double alpha, const double *A, const int lda,\n                 const double *X, const int incX, const double beta,\n                 double *Y, const int incY);\n                 */\n        \n        double *result=(double *) malloc(nz_vector * sizeof(double));\n        \n        //Read output vector if any\n\tif(outputVectorFile != NULL) {\n\t\tif(!readDenseVector(outputVectorFile, &result,&M_Vector,&N_Vector,&nz_vector)){\n\t\t\tusageDMxV();\n\t\t\tfprintf(stderr, \"[%s] Can not read Vector %s\\n\",__func__, outputVectorFile);\n\t\t\treturn 0;\n\t\t}\n\t}\n        \n\t//cblas_dgemv(CblasColMajor,CblasNoTrans,M,N,1.0,values,N,vectorValues,1,0.0,result,1);\n\tdouble t_real = realtime();\n\tif(basicOps){\n\t\tmms_dgemv(M, N, alpha, values, vectorValues,beta, result);\n\t}\n\telse{\n\t\tcblas_dgemv(CblasRowMajor,CblasNoTrans,M,N,alpha,values,N,vectorValues,1,beta,result,1);\n\t}\n\t\n\tfprintf(stderr, \"\\n[%s] Time spent in cblas_dgemv: %.6f sec\\n\", __func__, realtime() - t_real);\n\t\n\twriteDenseVector(outputFileName, result,M_Vector,N_Vector,nz_vector);\n\t\n\t\n\treturn ret_code;\n}\n\n", "meta": {"hexsha": "c26125a057e5017d8bd7dec1d3c72e8dc5e3f053", "size": 5466, "ext": "c", "lang": "C", "max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/DMxV.c", "max_stars_repo_name": "vkeller/math-454", "max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z", "max_issues_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/DMxV.c", "max_issues_repo_name": "vkeller/math-454", "max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "max_issues_repo_licenses": ["BSD-2-Clause"], "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/CG/GENMAT/matrix-market-suite/src/operations/DMxV.c", "max_forks_repo_name": "vkeller/math-454", "max_forks_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01", "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.0285714286, "max_line_length": 96, "alphanum_fraction": 0.6465422613, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.3695694194843509}}
{"text": "/* ============================================================ *\n * lensing.h\t\t\t\t\t\t\t*\n *\t\t\t\t\t\t\t\t*\n * Martin Kilbinger, Karim Benabed 2006-2012\t\t\t*\n * ============================================================ */\n\n#ifndef __LENSING_H\n#define __LENSING_H\n\n#include <math.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <assert.h>\n#include <string.h>\n\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_monte_plain.h>\n#include <gsl/gsl_monte_miser.h>\n#include <gsl/gsl_monte_vegas.h>\n#include <gsl/gsl_rng.h>\n\n#include \"errorlist.h\"\n#include \"maths.h\"\n#include \"io.h\"\n#include \"mvdens.h\"\n#include \"par.h\"\n\n#include \"hod.h\"\n#include \"halomodel.h\"\n#include \"cosmo.h\"\n#include \"nofz.h\"\n#include \"decomp_eb.h\"\n#include \"reduced_fit.h\"\n\n\n/* Dimensions of interpolation tables */\n/* N_s was increased from 200 to 400, for linear tabulation of P_kappa */\n#define N_s     400\n#define N_theta 100\n\n/* Ranges of interpolation table for convergence power spectrum. *\n * Power-law extrapolation outside these ranges.\t\t */\n#define s_min     1.0e-2\n#define s_max     1.0e6\n\n/* Ranges of interpolation table for reduced-shear correction    *\n * power spectrum. No extrapolation outside these ranges.\t */\n#define ELL_MIN_REDUCED            0.1\n#define ELL_MAX_REDUCED            2.0e5\n#define THETA_P_MIN_REDUCED        (0.1*arcmin)\n#define THETA_M_MIN_REDUCED        (0.5*arcmin)\n#define THETA_MAP_MIN_REDUCED      (0.2*arcmin)\n#define THETA_GSQR_MIN_REDUCED     (0.1*arcmin)\n#define THETA_MAPGAUSS_MIN_REDUCED (0.1*arcmin)\n#define THETA_MAX_REDUCED          (1000.0*arcmin)\n\n#define NELL_REDUCED 50\n\n\n#define lensing_base                     -1400\n#define lensing_inconsistent             -1 + lensing_base\n#define lensing_baryon_fraction          -2 + lensing_base\n#define lensing_tomoij\t\t\t -3 + lensing_base\n#define lensing_initialised              -4 + lensing_base\n#define lensing_unknown                  -5 + lensing_base\n#define lensing_pm                       -6 + lensing_base\n#define lensing_type                     -7 + lensing_base\n#define lensing_fastxi                   -8 + lensing_base\n#define lensing_nperm                    -9 + lensing_base\n#define lensing_range                   -10 + lensing_base\n#define lensing_cosebi_n_max            -11 + lensing_base\n#define lensing_ia                      -12 + lensing_base\n#define lensing_angle_format            -13 + lensing_base\n#define lensing_nzbin                   -14 + lensing_base\n\n/* If Ob/Oc > BARYON_FRAC, chi2 produces an error */\n#define BARYON_FRAC 0.75\n\n\n/* Intrinsic alignment, constant amplitude C_1 * rho_crit, *\n * with C_1 = 5e-14 h^2 Mpc^3/M_sol.                       */\n#define ia_c1_rho_crit     0.0134\n\n\ntypedef enum {xipm, xip, xim, map2poly, map2gauss, gsqr, decomp_eb, nofz, pkappa, map3gauss,\n\t      map3gauss_diag, map2gauss_map3gauss_diag, map2gauss_map3gauss,\n\t      decomp_eb_map3gauss_diag, decomp_eb_map3gauss}\n  lensdata_t;\n#define slensdata_t(i) ( \\\n i==xipm      ? \"xipm\" : \\\n i==xip       ? \"xip\"  : \\\n i==xim       ? \"xim\"  : \\\n i==map2poly  ? \"map2poly\" : \\\n i==map2gauss ? \"map2gauss\" : \\\n i==gsqr      ? \"gsqr\" : \\\n i==decomp_eb ? \"decomp_eb\" : \\\n i==nofz      ? \"nofz\" : \\\n i==pkappa    ? \"pkappa\" : \\\n i==map3gauss ? \"map3gauss\" : \\\n i==map3gauss_diag ? \"map3gauss_diag\" : \\\n i==map2gauss_map3gauss_diag ? \"map2gauss_map3gauss_diag\" : \\\n i==map2gauss_map3gauss ? \"map2gauss_map3gauss\" : \\\n i==decomp_eb_map3gauss_diag ? \"decomp_eb_map3gauss_diag\" : \\\n i==decomp_eb_map3gauss ? \"decomp_eb_map3gauss\" : \\\n \"\")\n#define Nlensdata_t 15\n\ntypedef enum {decomp_eb_none, FK10_SN, FK10_FoM_eta10, FK10_FoM_eta50, COSEBIs_log} decomp_eb_filter_t;\n#define sdecomp_eb_filter_t(i) (\t\t\\\n i==decomp_eb_none ? \"none\" : \\\n i==FK10_SN        ? \"FK10_SN\" : \\\n i==FK10_FoM_eta10 ? \"FK10_FoM_eta10\" : \\\n i==FK10_FoM_eta50 ? \"FK10_FoM_eta50\" : \\\n i==COSEBIs_log    ? \"COSEBIs_log\" : \\\n \"\")\n#define Ndecomp_eb_filter_t 5\n\n/* The following arrays are defined in decomp_eb.c */\nextern const double a_FK10_SN[], a_FK10_FoM_eta10[], a_FK10_FoM_eta50[];\n// r_COSEB[];\n\ntypedef enum {angle_center, angle_mean, angle_wlinear, angle_wquadr} lensformat_t;\n#define slensformat_t(i) ( \\\n i==angle_center  ? \"angle_center\" : \\\n i==angle_mean    ? \"angle_mean\" : \\\n i==angle_wlinear ? \"angle_wlinear\" : \\\n i==angle_wquadr  ? \"angle_wquadr\" : \\\n \"\")\n#define Nlensformat_t 4\n\ntypedef enum {cov_const, cov_ESH09} cov_scaling_t;\n#define scov_scaling_t(i) ( \\\n  i==cov_const ? \"cov_const\" : \\\n  i==cov_ESH09 ? \"cov_ESH09\" : \\\n  \"__undef__\")\n#define Ncov_scaling_t 2\n\ntypedef enum {reduced_none, reduced_K10} reduced_t;\n#define sreduced_t(i) ( \\\n  i==reduced_none ? \"none\" : \\\n  i==reduced_K10  ? \"K10\" : \\\n  \"\")\n#define Nreduced_t 2\n\n/* Intrinsic alignment model */\ntypedef enum {ia_none, ia_HS04} ia_t;\n#define sia_t(i) ( \\\n  i==ia_none ? \"none\" :\t\\\n  i==ia_HS04 ? \"HS04\" : \\\n  \"\")\n#define Nia_t 2\n\n/* Bit-coded IA terms */\ntypedef enum {ia_undef, ia_GI_II, ia_only_GI, ia_only_II} ia_terms_t;\n#define sia_terms_t(i) (      \\\n  i==ia_undef   ? \"undef\" :   \\\n  i==ia_GI_II   ? \"GI_II\" :   \\\n  i==ia_only_GI ? \"only_GI\" : \\\n  i==ia_only_II ? \"only_II\" : \\\n  \"\")\n#define Nia_terms_t 4\n \ntypedef enum {second_order=2, third_order=3} order_t;\n\ntypedef enum {tomo_all, tomo_auto_only, tomo_cross_only} tomo_t;\n#define stomo_t(i) ( \\\n i==tomo_all        ? \"tomo_all\" : \\\n i==tomo_auto_only  ? \"tomo_auto_only\" : \\\n i==tomo_cross_only ? \"tomo_cross_only\" : \\\n \"\")\n#define Ntomo_t 3\n\ntypedef struct {\n  int n_max;\n  double th_min, th_max;\n  char path[1024];\n} cosebi_info_t;\n\ntypedef struct {\n\n  /* Basic cosmology */\n  cosmo *cosmo;\n\n  /* Redshift distribution(s) */\n  redshift_t *redshift;\n\n  /* Tomography type */\n  tomo_t tomo;\n\n  /* Reduced-shear correction */\n  reduced_t reduced;\n  double q_mag_size;  /* q_mag_size = 2(alpha+beta-1),         *\n\t\t       * alpha, beta: slopes of number density *\n\t\t       * with flux (alpha), size (beta)        */\n\n  /* Intrinsic aligmnent */\n  ia_t ia;\n  double A_ia;           /* IA amplitude */\n  ia_terms_t ia_terms;  /* Bit-coded terms, GG=1, GI=2, II=4 */\n\n  /* Halomodel stuff (only initialised if cosmo->nonlinear=halodm) */\n  cosmo_hm *hm;\n\n  /* ============================================================ *\n   * Precomputed stuff.\t\t\t\t\t\t  *\n   * ============================================================ */\n\n  interTable **g_source;\n  interTable **Pshear, **Pg1;\n\n  /* Shear second-order functions */\n  interTable **xiP, **xiM, **gamma, **map_gauss, **map_poly;\n  double *c_cosebi, psimin_cosebi, psimax_cosebi;\n  int N_cosebi;\n\n} cosmo_lens;\n\ntypedef struct {\n  double r;\n  cosmo_lens* self;\n} cosmo_lensANDdouble;\n\ntypedef struct {\n  int i;\n  double r;\n  cosmo_lens *self;\n} cosmo_lensANDintANDdouble;\n\ntypedef struct {\n  int i, j;\n  double r;\n  cosmo_lens *self;\n} cosmo_lensANDiid;\n\ntypedef struct {\n  int i, j, t;\n  double r;\n  cosmo_lens *self;\n} cosmo_lensANDiiid;\n\ntypedef struct {\n  int i_bin, j_bin, pm, n;\n  const double *c;\n  double thmin;\n  cosmo_lens *self;\n  error **err;\n} cosmo_lensANDextra;\n\ntypedef struct {\n   int Ntheta, Nzbin;  /* Number of angular and redshift bins */\n   int Ntheta2;        /* For combined 2nd and 3rd-order */\n   int Nzcorr;         /* Number of z-correlations, Nzcorr=Nzbin*(Nzbin+1)/2 */\n   int n;              /* Number of total entries in data vector, n=Ntheta*Nzcorr */\n   double *theta;      /* n-dimensional vector of angular scales */\n   double *theta2;     /* For angle_range lensformats: (theta,theta2) = (lower,upper) bin limits */ \n   double *data;       /* n-dimensional data vector */\n   double *var;        /* n-dimensional vector with variance */\n   double *cov[3];     /* Maximum three nxn-dimensional covariance matrix */\n   double a1, a2;      /* Coefficients for 'angle_wquadr' */\n   double lndetC;\n   int usecov;\n   lensdata_t type;\n   lensformat_t format;\n   order_t order;\n   decomp_eb_filter_t decomp_eb_filter;\n   cov_scaling_t cov_scaling;\n   cosmo_lens *fiducial;   /* Needed for ESH09 cov scaling */\n} datcov;\n\n\n/* ============================================================ *\n * Initialisation.\t\t\t\t\t\t*\n * ============================================================ */\n\ncosmo_lens *init_parameters_lens(double OMEGAM, double OMEGAV, double W0_DE, double W1_DE,\n\t\t\t\t double *W_POLY_DE, int N_POLY_DE,\n\t\t\t\t double H100, double OMEGAB, double OMEGANUMASS,\n\t\t\t\t double NEFFNUMASS, double NORM, double NSPEC,\n\t\t\t\t int Nzbin, const int *Nnz, const nofz_t *nofz, double *par_nz,\n\t\t\t\t nonlinear_t NONLINEAR, transfer_t TRANSFER,\n\t\t\t\t growth_t GROWTH, de_param_t DEPARAM,\n\t\t\t\t norm_t normmode, tomo_t TOMO, reduced_t REDUCED, double Q_MAG_SIZE,\n\t\t\t\t ia_t IA, ia_terms_t ia_terms, double A_IA, error **err);\n\nvoid consistency_parameters_lens(const cosmo_lens *self, error **err);\ncosmo_lens* copy_parameters_lens_only(cosmo_lens* source, error **err);\ncosmo_lens* copy_parameters_lens(cosmo_lens* source, sm2_error **err);\nvoid updateFrom_lens(cosmo_lens* avant, cosmo_lens* apres, error **err);\nvoid copy_parameters_lenshm_cosmo(cosmo_lens *model, error **err);\nvoid read_cosmological_parameters_lens(cosmo_lens **self, FILE *F, error **err);\ncosmo_lens* set_cosmological_parameters_to_default_lens(error **err);\nvoid free_parameters_lens(cosmo_lens** self);\nvoid dump_param_lens(cosmo_lens* self, FILE *F, int wnofz, error **err);\n\n/* ============================================================ *\n * Lensing functions.\t\t\t\t\t\t*\n * ============================================================ */\n\n/* Projection */\ndouble int_for_g(double aprime, void *intpar, error **err);\ndouble g_source(cosmo_lens*, double a, int n_bin, error **err);\ndouble G(cosmo_lens* self, double a, int n_bin, error **err);\ndouble int_for_p_2(double a, void *intpar,error **err);\ndouble P_NL_tot(cosmo_lens *self, double a, double k, error **err);\ndouble Pshear(cosmo_lens *self, double a, int i_bin, int j_bin, error **err);\ndouble P_projected_kappa(void *self, double l, int i_bin, int j_bin, error **err);\ndouble int_over_P_kappa(cosmo_lens *self, funcwithpars int_for_p, void *intpar, error **err);\n\ndouble int_for_p_GI(double a, void *intpar, error **err);\ndouble int_for_p_II(double a, void *intpar, error **err);\n\n\n/* Reduced-shear correction (K10) */\nextern const int parameter[M_PAR];\ncosmo *set_cosmological_parameters_to_WMAP7(const redshift_t *nofz, tomo_t tomo, error **err);\ndouble *par_to_pointer(cosmo *self, par_t par, error **err);\nvoid fill_dpar(cosmo *model, cosmo *wmap7, double *dpar, error **err);\ndouble Fbar(cosmo_lens *self, double a, int m_bin, int n_bin, error **err);\nvoid fill_Fbar_array(cosmo_lens *self, double *fbar, int m_bin, int n_bin, double amin, int N_a,\n\t\t     double da, error **err);\nvoid fill_dFbar_dp_array(cosmo_lens *self, par_t par, double *dfbar_dp, int m_bin, int n_bin, double amin,\n\t\t\t int N_a, double da, error **err);\ndouble Pg1(cosmo_lens *self, double s, int i_bin, int j_bin, error **err);\n\n/* Second-order shear functions */\ndouble xi(cosmo_lens*, int pm, double theta, int i_bin, int j_bin, error **err);\ndouble gamma2(cosmo_lens*, double theta, int i_bin, int j_bin, error **err);\ndouble map2_poly(cosmo_lens*, double theta, int i_bin, int j_bin, error **err);\ndouble map2_gauss(cosmo_lens*, double theta, int i_bin, int j_bin, error **err);\ndouble RR(cosmo_lens *lens, double THETA_MIN, double THETA_MAX, const double *a, int N,\n\t  poly_t poly, int pm, error **err);\ndouble E_cosebi(cosmo_lens *lens, int n, double Psimin, double Psimax, int i_bin, int j_bin,\n\t\tconst char *path, double *B_cosebi, error **err);\ndouble RR_cosebi(cosmo_lens *lens, double THETA_MIN, double THETA_MAX, int i_bin, int j_bin,\n\t\t int n, int pm, error **err);\ndouble dRR_cosebi_dz_MC(double *z, int ndim, void *intpar);\ndouble dRR_cosebi_dz(double z, void *intpar, error **err);\ndouble int_for_map2_slow(double ell, void *intpar, error **err);\ndouble map2_slow(cosmo_lens *self, double theta, tpstat_t tpstat, int i_bin, int j_bin, error **err);\n\n/* Reading data files */\ndatcov *init_data_cov_tomo(char* dataname, char *dataname2, char** covname_ptr, lensdata_t type,\n\t\t\t   decomp_eb_filter_t decomp_eb_filter, \n\t\t\t   lensformat_t format, double corr_invcov,\n\t\t\t   double a1, double a2, order_t order,\n\t\t\t   cov_scaling_t cov_scaling, error **err);\ndatcov *init_datcov_for_cov_only(int Nzbin, int Ntheta, error **err);\n\nvoid del_data_cov(datcov** dc);\nvoid read_data_tomo(datcov *dc, char data_name[], int Nzbin, order_t order, error **err);\nvoid read_cov_tomo(datcov* dc, char cov_name[], int icov, error **err);\nvoid datcov2xipm(const datcov *dc, int i_bin, int j_bin, double **xip, double **xim, double **theta,\n\t\t double **theta2, int *N, error **err);\n\n//void read_cov(datcov* dc, char cov_name[], error **err);\nvoid read_cov_col(datcov *dc, char cov_name[], error **err);\n\nint get_pm(lensdata_t type, int i, int Ntheta, error **err);\nint find_bin(double x, const double *list, int N, int prev, error **err);\nvoid scale_cosmic_variance_ESH09(cosmo_lens *model, gsl_matrix *cov, const datcov *dc, error **err);\nvoid scale_mixed_ESH09(const cosmo_lens *model, gsl_matrix *cov, const datcov *dc, error **err);\ndouble lensing_signal(cosmo_lens *model, double theta, int i_bin, int j_bin, lensdata_t type,\n\t\t      decomp_eb_filter_t decomp_eb_filter, const cosebi_info_t *cosebi_info, error **err);\ndouble chi2_lensing(cosmo_lens* csm, datcov* dc, int return_model, double **model_array, int *Nmodel,\n\t\t    const cosebi_info_t *cosebi_info, error **err);\n\n/* Some third-order stuff which is called from lensing.c */\nint Nperm_to_Ntheta(int Nperm, error **err);\nvoid read_data_3rd(datcov *dc, char data_name[], int Nzbin, error **err);\nvoid read_data_2nd_3rd(datcov *res, char *dataname, char *dataname2, error **err);\n\n\n#define CHANGE(fct) int change_##fct(cosmo_lens*, cosmo_lens*)\nCHANGE(g_source);\nCHANGE(Pshear);\nCHANGE(xi);\nCHANGE(gamma2);\nCHANGE(map2);\n#undef CHANGE\n\n\n#endif /* __LENSING_H */\n\n", "meta": {"hexsha": "704e979386ad38d8aa9a9bf11194a7e786e19faa", "size": 13880, "ext": "h", "lang": "C", "max_stars_repo_path": "src/nicaea_2.5/Cosmo/include/lensing.h", "max_stars_repo_name": "danielgruen/ccv", "max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z", "max_issues_repo_path": "src/nicaea_2.5/Cosmo/include/lensing.h", "max_issues_repo_name": "danielgruen/ccv", "max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nicaea_2.5/Cosmo/include/lensing.h", "max_forks_repo_name": "danielgruen/ccv", "max_forks_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_forks_repo_licenses": ["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.1458333333, "max_line_length": 106, "alphanum_fraction": 0.6680115274, "num_tokens": 4198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3695694097551545}}
{"text": "#ifndef __bvd_rng_h_\n#define __bvd_rng_h_\n\n#include \"Cow.h\"\n#include <cmath>\n#include <gsl/gsl_rng.h>\n#include <time.h>\n#include \"Model_Constants.h\"\n#include <cmath>\n#include <gsl/gsl_rng.h>\n#include <time.h>\n\nclass Random_Number_Generator\n{\n public:\n\tRandom_Number_Generator();\n\tRandom_Number_Generator( unsigned int seed );\n\tvoid init( unsigned int seed);\n\t/// draw a random integer/double between lo (inclusive) and hi (exclusive)\n\t/// from a uniform distribution.\n\tint          ran_unif_int(    int hi   , int lo=0);\n\tdouble       ran_unif_double( double hi, double lo=0 );\n\n\tint ran_triangular_int(double lo,double hi,double mod);\n\tdouble ran_triangular_double(double lo,double hi,double mod);\n\n\tint ran_poisson_int(int r, double mu);\n\n\t// true or false, depending on whether a calf ( age < bvd_const::age_threshold_calf ) just infected with BVD will die or not\n\tbool         will_TI_calf_die();\n\tdouble       time_of_death_infected_calf();\n\tdouble       time_of_next_infection(double rate);\n\tCalf_Status calf_outcome_from_infection      ( double  time_of_pregnancy );\n\tdouble       time_of_abortion_due_to_infection( double  time_of_pregnancy );\n\tdouble       time_of_rest_after_calving(int calving_number);\n\n\t// true or false if a birth is a deadbirth, assuming that the infection status of neither mother nor calf are known.\n\t// This depends on the age of the mother, as indicated in table 4.1 of the handout (\"Anteil nicht lebend ausgetragener K\u00e4lber, F\u00e4rsen/K\u00fchle\")\n\t// The wording of the handout is not clear whether in the figures of the handout also abortions are included.\n\t// In this function, abortions are *not* included.\n\tbool         is_this_a_deadbirth( bool first_pregnancy );\n\n\t//How long is a calf protected by the maternal antibodies in the colostrum.\n\tdouble       duration_of_MA();\n\n\t//Duration of an infection with BVD ( time that the infection state 'transiently infected' lasts )\n\tdouble       duration_of_infection();\n\tdouble         duration_of_pregnancy();\n\tdouble staggering_first_inseminations();\n\tint          number_of_calvings();\n\tvirtual bool         is_calf_female();\n\t//  double         lifetime_male_calves();\n\tdouble       first_insemination_age();\n\tdouble       lifetime_PI();\n\tdouble       time_of_death_as_calf();\n\tdouble       insemination_result( bool first_pregnancy , bool* conception );\n\tdouble       life_expectancy_male_cow();\n\n\n\n\t//It has to be decided whether a beginning pregnancy will lead to an abortion or a birth.\n\t// Also here, pointer *birth is meant for output. if false, abortion is the case. If true birth is the case.\n\t// The return value is the time until the event (in case of birth -> duration of pregnancy, in case of abortion -> time until abortion ).\n\t// afaik, in the statistics we have, only the total abortion rates are given.\n\t// We don't know yet (as of 10.12.2015) whether there is a correlation between abortion happening and the infection status of the mother or the age of the mother.\n\t// So for now, treat it as uncorrelated. And use the total abortion rates given in the handout.\n\tdouble       conception_result( double age_of_mother, Infection_Status is_of_mother, bool* birth );\n\n\tvoid getNRandomNumbersInRange(int n, int rangeLeft, int rangeRight, int* resultArray);\n\t//double cowWellTimeOfBirth(double time);\n\tbool bloodTestRightResult();\n\n\tdouble removeTimeAfterFirstTest();\n\tdouble removeTimeAfterSecondTest();\n\tdouble retestTime();\n\tunsigned int getSeed();\n\tbool \t\t cowGetsASecondChance();\n\tdouble \t\ttimeOfFirstTest();\n\tvirtual bool \t\tvaccinationWorks();\n private:\n  gsl_rng * generator;\nunsigned int seed ;\n};\n\n#endif\n", "meta": {"hexsha": "5d79517f9986766886af7e2409de0e461d37b890", "size": 3608, "ext": "h", "lang": "C", "max_stars_repo_path": "include/BVD_Random_Number_Generator.h", "max_stars_repo_name": "Yperidis/bvd_agent_based_model", "max_stars_repo_head_hexsha": "a42ae72ca05d966015bab92afd20130a2c6d848a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-11T09:27:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-11T09:27:02.000Z", "max_issues_repo_path": "include/BVD_Random_Number_Generator.h", "max_issues_repo_name": "Yperidis/bvd_agent_based_model", "max_issues_repo_head_hexsha": "a42ae72ca05d966015bab92afd20130a2c6d848a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-06-13T12:41:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-14T05:26:34.000Z", "max_forks_repo_path": "include/BVD_Random_Number_Generator.h", "max_forks_repo_name": "Yperidis/bvd_agent_based_model", "max_forks_repo_head_hexsha": "a42ae72ca05d966015bab92afd20130a2c6d848a", "max_forks_repo_licenses": ["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.9534883721, "max_line_length": 163, "alphanum_fraction": 0.7411308204, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3694222455444816}}
{"text": "// Data Structure and Routines for peak fiting\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_multifit_nlin.h>\n\n#include <errno.h>\n\n#include \"grid.h\"\n#include \"grid_operations.h\"\n#include \"minmax.h\"\n#include \"point.h\"\n\n#ifndef _FITTOFUNCTION_H_\n#define _FITTOFUNCTION_H_\n\ntypedef  struct {\n  size_t n;\n  double * y;\n} ObservedValues ;\n\nvoid fitToFunctionLorentz(Grid *image, double *fitx, double *fity, \n\t\t   double *background, double *intens,\n\t\t   double *widthx, double *widthy, double *tilt,double *chisq);\n\nvoid fitToFunctionGauss(Grid *image, double *fitx, double *fity, \n\t\t   double *background, double *intens,\n\t\t   double *widthx, double *widthy, double *tilt,double *chisq);\n\n\n#endif\n", "meta": {"hexsha": "9631c18c10ea512a572a4ebdbef6310924d57942", "size": 831, "ext": "h", "lang": "C", "max_stars_repo_path": "legacy/peaksearch/include/fitToFunction.h", "max_stars_repo_name": "carterbox/cold", "max_stars_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "legacy/peaksearch/include/fitToFunction.h", "max_issues_repo_name": "carterbox/cold", "max_issues_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2022-01-21T17:14:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:34:20.000Z", "max_forks_repo_path": "legacy/peaksearch/include/fitToFunction.h", "max_forks_repo_name": "carterbox/cold", "max_forks_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-21T17:48:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T17:48:28.000Z", "avg_line_length": 22.4594594595, "max_line_length": 67, "alphanum_fraction": 0.7232250301, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.36937476361280047}}
{"text": "/* hmm.c v0.0 \n \n \tAndrew D. Kern\t8/24/05\n*/\n\n\n#include \"hmm.h\"\n#include \"adkGSL.h\"\n#include <math.h>\n#include <assert.h>\n#include <string.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_randist.h>\n\n\n\n/* returns a pointer to a new instance of an HMM. \nCurrently an HMM is defined by a transition matrix (pMatrix), \nand a vector representing the starting probabilities.\nuse of initHMM() fills the log score matrices. \t*/\n\nHMM* newHMM(gsl_matrix *pMatrix, gsl_vector *piStart, gsl_vector *piEnd, gsl_vector *otherData ) {\n  HMM *hmm = (HMM*)malloc(sizeof(HMM));\n  int i;\n\n  hmm->transition_matrix = pMatrix;\n  hmm->piStart = piStart;\n  hmm->piEnd = piEnd;\n  hmm->nstates = pMatrix->size1;\n  hmm->transition_score_matrix = NULL;\n  hmm->piStart_scores = NULL;\n  hmm->piEnd_scores = NULL;\n  hmm->otherData = otherData;\n\n  /* if piStart are NULL, make them uniform */\n  if (piStart == NULL) {\n    hmm->piStart = gsl_vector_alloc(pMatrix->size1);\n    for (i = 0; i < pMatrix->size1; i++) \n      gsl_vector_set(hmm->piStart, i, 1.0/pMatrix->size1);\n  }\n  if (piEnd == NULL) {\n    hmm->piEnd = gsl_vector_alloc(pMatrix->size1);\n    for (i = 0; i < pMatrix->size1; i++) \n      gsl_vector_set(hmm->piEnd, i, 1.0/pMatrix->size1);\n  }\n\n  return hmm;\n}\n\n/* initialize an HMM, this makes sure that things are kosher,\nit checks that the row sums of the pMatrix == 1, that the sum\nof the piStart vector == 1. then it initializes scores */\n\nvoid initHMM(HMM *hmm){\n\tgsl_matrix *pMatrixLogs;\n\tgsl_vector *piStartLogs, *piEndLogs;\n\tint i, j;\n\tdouble piEndSum, piStartSum, prob;\n\t\n\t//check piStartSum == 1\n\tpiStartSum = gsl_vector_sum(hmm->piStart, hmm->nstates);\n\tassert(piStartSum == 1.0);\n\t\n\t//make log transformed start probs\n\tpiStartLogs = gsl_vector_alloc(hmm->nstates);\n\tfor (i = 0; i < hmm->nstates; i++){\n\t\tprob = gsl_vector_get(hmm->piStart, i);\n\t\tgsl_vector_set(piStartLogs, i, log(prob));\n\t\t}\n\t\n\t//set hmm piEnd_scores\n\thmm->piStart_scores = piStartLogs;\n\t\n\t//check piEndSum == 1\n\tpiEndSum = gsl_vector_sum(hmm->piEnd, hmm->nstates);\n\tassert(piEndSum == 1.0);\n\t\n\t//make log transformed start probs\n\tpiEndLogs = gsl_vector_alloc(hmm->nstates);\n\tfor (i = 0; i < hmm->nstates; i++){\n\t\tprob = gsl_vector_get(hmm->piEnd, i);\n\t\tgsl_vector_set(piEndLogs, i, log(prob));\n\t\t}\n\t\n\t//set hmm piEnd_scores\n\thmm->piEnd_scores = piEndLogs;\n\t\n\t//check row sums for markov matrix\n\tfor(i = 0; i < hmm->nstates; i++){\n\t\tassert(gsl_matrix_row_sum(hmm->transition_matrix, i, hmm->nstates) == 1.0);\n\t\t}\n\t//make log transformed transition matrix\n\tpMatrixLogs = gsl_matrix_alloc(hmm->nstates, hmm->nstates);\n\tfor (i = 0; i < hmm->nstates; i++){\n\t\tfor (j = 0; j < hmm->nstates; j++){\n\t\t\tprob = gsl_matrix_get(hmm->transition_matrix, i, j);\n\t\t\tgsl_matrix_set(pMatrixLogs, i, j, log(prob));\n\t\t\t}\n\t\t}\n\t\t\n\t//set hmm transition_score_matrix\t\n\thmm->transition_score_matrix = pMatrixLogs;\n}\n\t\n\n/* frees an entire hmm */\nvoid freeHMM(HMM *hmm){\n\t\n\tif (hmm->transition_matrix)\n\t\tgsl_matrix_free(hmm->transition_matrix);\n\tif (hmm->transition_score_matrix)\n\t\tgsl_matrix_free(hmm->transition_score_matrix);\n\tif (hmm->piStart)\n\t\tgsl_vector_free(hmm->piStart);\n\tif (hmm->piStart_scores)\n\t\tgsl_vector_free(hmm->piStart_scores);\n\tif (hmm->piEnd)\n\t\tgsl_vector_free(hmm->piEnd);\n\tif (hmm->piEnd_scores)\n\t\tgsl_vector_free(hmm->piEnd_scores);\n\tif (hmm->otherData)\n\t\tgsl_vector_free(hmm->otherData);\n\tfree(hmm);\n}\n\n/*output hmm values: nstates, transition matrix, piStarts */\nvoid printHMM(HMM *hmm){\n  printf(\"hmm output\\nstates: %d \\ntransition matrix:\\n\", hmm->nstates);\n  gsl_matrix_fprintf(stdout, hmm->transition_matrix, \"%f\");\n  printf(\"piStart vector:\\n\");\n  gsl_vector_fprintf(stdout, hmm->piStart, \"%f\");\n  printf(\"piEnd vector:\\n\");\n  gsl_vector_fprintf(stdout, hmm->piEnd, \"%f\");\n  if (hmm->transition_score_matrix != NULL){\n    printf(\"transition matrix (logs):\\n\");\n    gsl_matrix_fprintf(stdout, hmm->transition_score_matrix, \"%f\");\n  }\n  if (hmm->piStart_scores != NULL){\n    printf(\"piStart vector (logs):\\n\");\n    gsl_vector_fprintf(stdout, hmm->piStart_scores, \"%f\");\n  } \n  if (hmm->piEnd_scores != NULL){\n    printf(\"piEnd vector (logs):\\n\");\n    gsl_vector_fprintf(stdout, hmm->piEnd_scores, \"%f\");\n  } \n  if (hmm->otherData != NULL){\n    //    printf(\"other data:\\n\");\n    //gsl_vector_fprintf(stdout, hmm->otherData, \"%f\");\n  }\n  \n}\n\n/*output transition matrix of hmm values to file */\nvoid printTransitions(HMM *h, char *outfileName){\n  FILE *outfile;\n  int i,j;\n\n   outfile = fopen(outfileName, \"w\");\n   if (outfile == NULL){\n     fprintf(stderr,\"Error opening outfile! ARRRRR!!!!\\n\");\n     exit(1);\n   }\n   for(i = 0; i < h->nstates; i++){\n     for(j = 0; j < h->nstates; j++){\n       fprintf(outfile,\"%f\\t\",gsl_matrix_get(h->transition_matrix,i,j));\n     }\n     fprintf(outfile,\"\\n\");\n   }\n   fclose(outfile);\n}\n\n/* this normalizes the transition matrix so that rows sum to one */\nvoid hmm_normalize_transitions(HMM *hmm){\n  int i, j;\n  double rowSum, tempVal;\n\n  for(i=0; i < hmm->nstates; i++){\n    rowSum = 0;\n    for(j=0; j < hmm->nstates; j++){\n      rowSum += gsl_matrix_get(hmm->transition_matrix,i,j);\n    }\n    if(rowSum == 0){\n      gsl_matrix_set(hmm->transition_matrix, i, i, 1.0);\n    }\n    else{\n      for(j= 0; j < hmm->nstates;j++){\n\ttempVal =  gsl_matrix_get(hmm->transition_matrix, i, j) / rowSum;\n\tgsl_matrix_set(hmm->transition_matrix, i, j, tempVal);\n      }\n    }\n  }\n}\n\nvoid hmm_logify_transitions(HMM *hmm){\n  int i, j;\n  double prob;\n  //set log transition scores\n  for (i = 0; i < hmm->nstates; i++){\n    for (j = 0; j < hmm->nstates; j++){\n      prob = gsl_matrix_get(hmm->transition_matrix, i, j);\n      gsl_matrix_set(hmm->transition_score_matrix, i, j, log(prob));\n    }\n  }\n  //set log start and end scores\n  for (i = 0; i < hmm->nstates; i++){\n    prob = gsl_vector_get(hmm->piStart, i);\n    gsl_vector_set(hmm->piStart_scores, i, log(prob));\n    prob = gsl_vector_get(hmm->piEnd, i);\n    gsl_vector_set(hmm->piEnd_scores, i, log(prob));\n  }\n}\n\n/* forward algorithm- this fills a matrix (alphas) of Nstates * L observations\nwith the forward log probabilities. a matrix of emission probs (log!!!) with the same\ndimensions as the forward matrix must be allocated and passed to this function.\nreturns probFor. */\n\ndouble forwardAlg(HMM *hmm, gsl_matrix *alphas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){\n\tint i, j, power, last;\n\tdouble prob, emit, prevSum, pFor;\n\tgsl_vector_view prevCol;\n\tgsl_vector *tempProbs;\n\tgsl_matrix *logTransitions;\n\n\tassert(length > 0 && hmm != NULL);\n\tassert(alphas->size1 == hmm->nstates && alphas->size2 == length);\n\tassert(emisLogs->size1 == hmm->nstates && emisLogs->size2 == length);\n\n//initialization\n\tfor (i = 0; i < hmm->nstates; i++){\n\t\tprob = gsl_vector_get(hmm->piStart_scores, i);\n\t\temit = gsl_matrix_get(emisLogs, i, 0);\n\t\tgsl_matrix_set(alphas, i, 0, (prob + emit));\n\t}\n\n//are we using powers of the transition matrix? if so check to see we have location data\n\tif (transitionPowerFlag){\n\t\tassert(hmm->otherData != NULL);\n\t//set \"last\" equal to the first location (stored in otherData) here's a totally non general assumption... FIX ME!!!\n\t\tlast = gsl_vector_get(hmm->otherData,0);\n\t}\n\telse {\n\t\tlast = 0; /* not used */\n\t}\n\n//fill em up!\n\tfor (j = 1; j < length; j++){\t\t\t//iterate over obs\n\t\tfor (i = 0; i < hmm->nstates; i++){\t\t//iterate over states\n\t\t\temit = gsl_matrix_get(emisLogs, i, j);\n\t\t\t/* are we taking powers here? */\n\t\t\tif (transitionPowerFlag){\n\t\t\t//get power from data \n\t\t\t\tpower = gsl_vector_get(hmm->otherData,j) - last;\n\n\t\t\t\t//get power of matrix in log scale\n\t\t\t\tlogTransitions = gsl_matrix_power_logs(hmm->transition_matrix, power);\n\t\t\t\tprevSum = forwardSumPrevious(hmm, alphas, logTransitions, i, j);\n\t\t\t\tgsl_matrix_free(logTransitions);\n\t\t\t}\n\t\t\t/* no powers */\n\t\t\telse{\n\t\t\t\tprevSum = forwardSumPrevious(hmm, alphas, hmm->transition_score_matrix, i, j);\n\t\t\t//fprintf (stderr,\"forwardAlg state %2d, index %2d, log.prevSum %g, emit %g\\n\",i,j,prevSum,emit);\n\t\t\t}\n\t\t\tgsl_matrix_set(alphas, i, j, (emit + prevSum));\n\t\t}\n\t\tif (transitionPowerFlag){\n\t\t\tlast = gsl_vector_get(hmm->otherData,j);\n\t\t}\n\t}\t\n//return P(x)\n\ttempProbs = gsl_vector_alloc(hmm->nstates);\n\tprevCol = gsl_matrix_column(alphas,  length - 1);\n\tfor(i = 0; i < hmm->nstates; i++){\n\t\tgsl_vector_set(tempProbs, i, gsl_vector_get(&prevCol.vector, i));\n\t}\n\tpFor = log_sum(tempProbs);\n\tgsl_vector_free(tempProbs);\t\n\treturn(pFor);\n}\n\n\n/* forward algorithm offset- identical to the normal forward algorithm except starts at an arbitrary\noffset with respect to the observations. this is useful for getting probabilities from path subsets */\n\ndouble forwardAlgOffset(HMM *hmm, gsl_matrix *alphas, gsl_matrix *emisLogs, int length, int offset, int transitionPowerFlag){\n  int i, j, power, last;\n  double prob, emit, prevSum, pFor;\n  gsl_vector_view prevCol;\n  gsl_vector *tempProbs;\n  gsl_matrix *logTransitions;\n\t\n  assert(length > 0 && hmm != NULL);\n  assert(alphas->size1 == hmm->nstates && alphas->size2 == length);\n\t\n  //initialization\n  for (i = 0; i < hmm->nstates; i++){\n    prob = gsl_vector_get(hmm->piStart_scores, i);\n    emit = gsl_matrix_get(emisLogs, i, offset);\n    gsl_matrix_set(alphas, i, 0, (prob + emit));\n  }\n  \n  //are we using powers of the transition matrix? if so check to see we have location data\n  if (transitionPowerFlag){\n    assert(hmm->otherData != NULL);\n    //set \"last\" equal to the first location (stored in otherData) here's a totally non general assumption... FIX ME!!!\n    last = gsl_vector_get(hmm->otherData,offset);\n  }\n  else {\n      last = 0; /* not used */\n  }\n\n  //fill em up!\n  for (j = 1; j < length; j++){\t\t\t//iterate over obs\n    for (i = 0; i < hmm->nstates; i++){\t\t//iterate over states\n      emit = gsl_matrix_get(emisLogs, i, j + offset);\n      /* are we taking powers here? */\n      if (transitionPowerFlag){\n\t//get power from data \n\tpower = gsl_vector_get(hmm->otherData,j + offset) - last;\n\n\t//get power of matrix in log scale\n\tlogTransitions = gsl_matrix_power_logs(hmm->transition_matrix, power);\n\tprevSum = forwardSumPrevious(hmm, alphas, logTransitions, i, j);\n\tgsl_matrix_free(logTransitions);\n      }\n      /* no powers */\n      else{\n\tprevSum = forwardSumPrevious(hmm, alphas, hmm->transition_score_matrix, i, j);\n      }\n      gsl_matrix_set(alphas, i, j, (emit + prevSum));\n    }\n    if (transitionPowerFlag){\n\tlast = gsl_vector_get(hmm->otherData,j+offset);\n    }\n  }\t\n  //return P(x)\n  tempProbs = gsl_vector_alloc(hmm->nstates);\n  prevCol = gsl_matrix_column(alphas,  length - 1);\n  for(i = 0; i < hmm->nstates; i++){\n    gsl_vector_set(tempProbs, i, gsl_vector_get(&prevCol.vector, i));\n  }\n  pFor = log_sum(tempProbs);\n  gsl_vector_free(tempProbs);\t\n  return(pFor);\n}\n\n/* backward algorithm- this fills a matrix (betas) of Nstates * L observations\nwith the backward log probabilities. a matrix of emission probs (log!!!) with the same\ndimensions as the backward matrix must be allocated and passed to this function.\nreturns probBack. */\n\ndouble backwardAlg(HMM *hmm, gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){\n  int i, j, last, power;\n  gsl_vector_view nextCol;\n  gsl_vector *tempProbs;\n  gsl_matrix *logTransitions;\n  double pBack;\n\t\n  assert(length > 0 && hmm != NULL);\n  assert(betas->size1 == hmm->nstates && betas->size2 == length);\n  assert(emisLogs->size1 == hmm->nstates && emisLogs->size2 == length);\n\t\n  //initialization\n  for (i = 0; i < hmm->nstates; i++){\n    //prob = gsl_vector_get(hmm->piEnd_scores, i);\n    //emit = gsl_matrix_get(emisLogs, i, length - 1);\n    gsl_matrix_set(betas, i, length - 1, 0);\t\t//initialize to prob = 1.0, log = 0\n  }\n\n  //are we using powers of the transition matrix?\n  if (transitionPowerFlag){\n    assert(hmm->otherData != NULL);\n    //set \"last\" equal to the last location (stored in otherData) here's a totally non general assumption... FIX ME!!!\n    last = gsl_vector_get(hmm->otherData,length - 1);\n  }\n  else {\n      last = 0; /* not used */\n  }\n\t\n  //fill em up!\n  for (j =  length - 2; j >=0; j--){\t\t\t//iterate over obs\n    for (i = 0; i < hmm->nstates; i++){\t\t//iterate over states\n      /* are we taking powers here? */\n      if (transitionPowerFlag){\n\t//get power from data\n\tpower = last - gsl_vector_get(hmm->otherData,j);\n\n\t//get power of matrix in log scale\n\tlogTransitions = gsl_matrix_power_logs(hmm->transition_matrix, power);\n\tgsl_matrix_set(betas, i, j, backwardSumNext(hmm, betas,logTransitions,emisLogs, i, j));\n\tgsl_matrix_free(logTransitions);\n      }\n      else{\n\tgsl_matrix_set(betas, i, j, backwardSumNext(hmm, betas,hmm->transition_score_matrix,emisLogs, i, j));\n      }\n    }\n    if (transitionPowerFlag){\n\tlast = gsl_vector_get(hmm->otherData,j);\n    }\n  }\n  //return P(x)\n  tempProbs = gsl_vector_alloc(hmm->nstates);\n  nextCol = gsl_matrix_column(betas, 0);\n  for(i = 0; i < hmm->nstates; i++){\n    gsl_vector_set(tempProbs, i, (gsl_vector_get(&nextCol.vector, i) + gsl_matrix_get(emisLogs, i, 0) + gsl_vector_get(hmm->piStart_scores, i)));\n  }\n  pBack = log_sum(tempProbs); \n  gsl_vector_free(tempProbs);\t\n  return(pBack);\n}\n\n\n/* posterior probs- this fills a matrix (postProbMat) of nstates * L observations with the \nposterior prob (not log !!) of being in that state at time i given the observations and the model.\ncalls forwardAlg and backwardAlg, checks that prob of observations determined by\nforward and backward are (nearly) equal, and also (nearly) equal the sum of each column\nbefore normalization to postProbMat.\na matrix of emission probs (log!!!) of dimensions nstates * L observations must be supplied. */\n\nvoid posteriorProbs(HMM *hmm, gsl_matrix *postProbMat, gsl_matrix *emisLogs, int length, int transitionPowerFlag){\n\tgsl_matrix *alphas, *betas;\n\tgsl_vector *tempVec;\n\tint i, j;\n\tdouble pFor, pBack, sumProb;\n\t\n\t//allocate matrices for forwards and backwards algs.\n\talphas = gsl_matrix_alloc(hmm->nstates, length);\n\tbetas = gsl_matrix_alloc(hmm->nstates, length);\n\t\n\t//run forwards/backwards\n\tpFor = forwardAlg(hmm, alphas, emisLogs, length, transitionPowerFlag);\n\tpBack = backwardAlg(hmm, betas, emisLogs, length, transitionPowerFlag);\n\t\n\t//check that Forward and Backward look okay\n\t//assert(fabs(pFor - pBack) < 0.01);\n\t\n\t//do the posterior probability thing- okay sir pull the switch\n\ttempVec = gsl_vector_alloc(hmm->nstates);\n\tfor(j=0; j < length; j++){\n\t\t//first get sum for denominator\n\t\tfor(i = 0; i < hmm->nstates; i++){\n\t\t\tgsl_vector_set(tempVec, i, (gsl_matrix_get(alphas,i,j) +  gsl_matrix_get(betas,i,j))); \n\t\t}\n\t\tsumProb = log_sum(tempVec);\n\t\t\n\t\t//check that sum looks like pFor\n\t\tassert(fabs(pFor - sumProb) < 0.01);\n\t\t\n\t\t//then calculate marginal and set value (not log)\n\t\tfor(i = 0; i < hmm->nstates; i++){\n\t\t\tgsl_matrix_set(postProbMat, i, j, exp(gsl_matrix_get(alphas,i,j) +  gsl_matrix_get(betas,i,j) - sumProb));\n\t\t}\n\t}\n\t//cleanup\n\tgsl_matrix_free(alphas);\n\tgsl_matrix_free(betas);\n\tgsl_vector_free(tempVec);\n}\n\n/* posterior probs reduced- this fills a matrix of nstates * L observations with the \nposterior probs as above except this time takes alphas and betas as args */\n\nvoid posteriorProbsReduced(HMM *hmm, gsl_matrix *postProbMat, double pFor, gsl_matrix *alphas, gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){\n  gsl_vector *tempVec;\n  int i, j;\n  double  sumProb;\n  \n  //do the posterior probability thing- okay sir pull the switch\n  tempVec = gsl_vector_alloc(hmm->nstates);\n  for(j=0; j < length; j++){\n    //first get sum for denominator\n    for(i = 0; i < hmm->nstates; i++){\n      gsl_vector_set(tempVec, i, (gsl_matrix_get(alphas,i,j) +  gsl_matrix_get(betas,i,j))); \n    }\n    sumProb = log_sum(tempVec);\n\t\t\n    //check that sum looks like pFor\n      //assert(fabs(pFor - sumProb) < 0.01);\n    \n    //then calculate marginal and set value (not log)\n    for(i = 0; i < hmm->nstates; i++){\n      gsl_matrix_set(postProbMat, i, j, exp(gsl_matrix_get(alphas,i,j) +  gsl_matrix_get(betas,i,j) - sumProb));\n    }\n  }\n  //cleanup\n   gsl_vector_free(tempVec);\n}\n\n/* posterior probs reduced log- this fills a matrix of nstates * L observations with the \nposterior probs as above except this time takes alphas and betas as args */\n\nvoid posteriorProbsReducedLog(HMM *hmm, gsl_matrix *postProbMat, double pFor, gsl_matrix *alphas, gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){\n  gsl_vector *tempVec;\n  int i, j;\n  double  sumProb;\n  \n  //do the posterior probability thing- okay sir pull the switch\n  tempVec = gsl_vector_alloc(hmm->nstates);\n  for(j=0; j < length; j++){\n    //first get sum for denominator\n    for(i = 0; i < hmm->nstates; i++){\n      gsl_vector_set(tempVec, i, (gsl_matrix_get(alphas,i,j) +  gsl_matrix_get(betas,i,j))); \n    }\n    sumProb = log_sum(tempVec);\n\t\t\n    //check that sum looks like pFor\n    //assert(fabs(pFor - sumProb) < 0.01);\n    \n    //then calculate marginal and set value\n    for(i = 0; i < hmm->nstates; i++){\n      gsl_matrix_set(postProbMat, i, j, gsl_matrix_get(alphas,i,j) +  gsl_matrix_get(betas,i,j) - sumProb);\n    }\n  }\n  //cleanup\n   gsl_vector_free(tempVec);\n}\n\n\n/* meant to computer prob{state_i_t, state_j_t+1 | data, model} -- for restimating transitions, takes as an arg *jpMatArray an\narray of gsl_matrix structs representing joint posterior probabilities -- log scale so need log posts */\n\nvoid jointPosteriorProbsReduced(HMM *hmm, gsl_matrix **jpMatArray, double pFor, gsl_matrix *alphas, gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){\n  \n  int i, j, t;\n  double  sumProb, val = 0;\n  gsl_matrix *powTrans;\n  \n  //for each obs\n  for(t=0; t < length - 1; t++){\n    gsl_matrix_set_all(jpMatArray[t],0);\n    //iterate i,j states    \n    for(i = 0; i < hmm->nstates; i++){\n      for(j = 0; j < hmm->nstates; j++){\n\t//transition stuff\n\tif (transitionPowerFlag){\n\t  \n\t  if (gsl_vector_get(hmm->otherData,t+1) -  gsl_vector_get(hmm->otherData, t) > 1){\n\t    powTrans = gsl_matrix_power_logs(hmm->transition_matrix, gsl_vector_get(hmm->otherData,t+1) \\\n\t\t\t\t\t     -  gsl_vector_get(hmm->otherData, t));\n\t    val = gsl_matrix_get(alphas, i, t) + gsl_matrix_get(powTrans, i, j) \\\n\t      + gsl_matrix_get(emisLogs, j, t+1) + gsl_matrix_get(betas, j, t+1) - pFor;\n\t    gsl_matrix_free(powTrans);\n\t  }\n\t  else{\n\t    val = gsl_matrix_get(alphas, i, t) + gsl_matrix_get(hmm->transition_score_matrix, i, j) \\\n\t      + gsl_matrix_get(emisLogs, j, t+1) + gsl_matrix_get(betas, j, t+1) - pFor;\n\t  }\n\t}\n\telse{\n\t  val = gsl_matrix_get(alphas, i, t) + gsl_matrix_get(hmm->transition_score_matrix, i, j) \\\n\t\t    + gsl_matrix_get(emisLogs, j, t+1) + gsl_matrix_get(betas, j, t+1) - pFor;\n\t}\n\t//set i,j value in gsl_matrix at t\n\tgsl_matrix_set(jpMatArray[t], i, j, val);\n      }\n    } \n  }\n}\n\n/*restimateTransitions-- uses posteriors and joint posteriors to reestimate the transition matrix based on EM */\nvoid reestimateTransitions(HMM *hmm, gsl_matrix *postProbMat, gsl_matrix **jpMatArray, double pFor, gsl_matrix *alphas, \\\n\t\t\t   gsl_matrix *betas, gsl_matrix *emisLogs, int length, int transitionPowerFlag){\n  double sum_gamma, sum_cosi, val;\n  int i, j, t,k;\n  gsl_vector *tmpVec1, *tmpVec2;\n  gsl_matrix *tempTrans, *powTrans;\n  gsl_vector *rowSums;\n\n  /* this is the joint posterior method- currently not operational */\n  /*\n  //calculate joints, no reason to do it twice...\n  //  jointPosteriorProbsReduced(hmm, jpMatArray, pFor, alphas, betas, emisLogs, length ,transitionPowerFlag);\n  //allocate tmpVecs\n  tmpVec1 = gsl_vector_alloc(length - 2);\n  tmpVec2 = gsl_vector_alloc(length - 2);\n  //iterate over states \n  for(i = 0; i < hmm->nstates; i++){\n    for(j = 0; j < hmm->nstates; j++){\n      gsl_vector_set_all(tmpVec1,0);\n      gsl_vector_set_all(tmpVec2,0);\n      //sum up numerator and denom\n      for(t = 1; t < length - 1; t++){\n\t//\tgsl_vector_set(tmpVec1, t - 1, gsl_matrix_get(postProbMat,i,t));\n\t//gsl_vector_set(tmpVec2, t - 1, gsl_matrix_get(jpMatArray[t],i,j));\n\tsum_gamma += gsl_matrix_get(postProbMat,i,t);\n\tsum_cosi += gsl_matrix_get(jpMatArray[t],i,j);\n      }\n      \n      //gsl_matrix_set(hmm->transition_matrix, i, j, exp(log_sum(tmpVec1) - log_sum(tmpVec2)));\n      // hmm_logify_transitions(hmm);\n      gsl_matrix_set(hmm->transition_matrix, i, j, sum_cosi / sum_gamma);\n       gsl_matrix_set(hmm->transition_score_matrix, i, j, log(sum_cosi / sum_gamma));\n    }\n  }\n  */\n\n  /* older method */\n  tempTrans = gsl_matrix_alloc(hmm->nstates,hmm->nstates);\n  rowSums = gsl_vector_alloc(hmm->nstates);\n  \n  gsl_matrix_set_all(tempTrans,0.0);\n  gsl_vector_set_all(rowSums, 0.0);\n  for(i = 1; i < length - 1; i++){\n    for(j = 0; j < hmm->nstates; j++){\n      for(k = 0; k < hmm->nstates; k++){\n\tif (transitionPowerFlag){\n\t  if (gsl_vector_get(hmm->otherData,i + 1) -  gsl_vector_get(hmm->otherData, i ) > 1){\n\t    powTrans = gsl_matrix_power_logs(hmm->transition_matrix, \\\n\t\t\t\t\t     gsl_vector_get(hmm->otherData,i + 1) -  gsl_vector_get(hmm->otherData, i));\n\t    val = exp(gsl_matrix_get(alphas, j, i) + gsl_matrix_get(powTrans, j, k) \\\n\t\t      + gsl_matrix_get(emisLogs, k, i+1) + gsl_matrix_get(betas, k, i+1) - pFor);\n\t    gsl_matrix_free(powTrans);\n\t  }\n\t  else{\n\t    val = exp(gsl_matrix_get(alphas, j, i) + gsl_matrix_get(hmm->transition_score_matrix, j, k) \\\n\t\t      + gsl_matrix_get(emisLogs, k, i+1) + gsl_matrix_get(betas, k, i+1) - pFor);\n\t  }\n\t}\n\telse{\n\t    val = exp(gsl_matrix_get(alphas, j, i) + gsl_matrix_get(hmm->transition_score_matrix, j, k) \\\n\t\t      + gsl_matrix_get(emisLogs, k, i+1) + gsl_matrix_get(betas, k, i+1) - pFor);\n\t}\n      \tgsl_matrix_set(tempTrans, j, k, gsl_matrix_get(tempTrans,j,k) + val);\n\tgsl_vector_set(rowSums, j, gsl_vector_get(rowSums, j) + val);\n      }\n    }\n  }\n  \n  //update transition scores\n  for(j = 0; j < hmm->nstates; j++){\n    for(k = 0; k < hmm->nstates; k++){      \n      val = gsl_matrix_get(tempTrans, j, k) / gsl_vector_get(rowSums, j);\n      gsl_matrix_set(hmm->transition_matrix, j, k, val);\n      gsl_matrix_set(hmm->transition_score_matrix, j, k, log(val));\n    }\n  }\n  gsl_matrix_free(tempTrans);\n  gsl_vector_free(rowSums);\n}\n\n/*restimateTransitions_vanilla-- uses posteriors to reestimate the transition matrix based on EM */\nvoid reestimateTransitions_vanilla(HMM *hmm, double pFor, gsl_matrix *alphas, \\\ngsl_matrix *betas, gsl_matrix *emisLogs, int length){\n\tdouble val;\n\tint i, j,k;\n\tgsl_vector *rowSums;\n\tgsl_matrix *tempTrans;\n\n/* older method */\n  \ttempTrans = gsl_matrix_alloc(hmm->nstates,hmm->nstates);\n\tgsl_matrix_set_all(tempTrans,0.0);\n\trowSums = gsl_vector_alloc(hmm->nstates);\n\tgsl_vector_set_all(rowSums, 0.0);\n\tfor(i = 1; i < length - 1; i++){\n\t\tfor(j = 0; j < hmm->nstates; j++){\n\t\t\tfor(k = 0; k < hmm->nstates; k++){\n\t\t\t\tval = exp(gsl_matrix_get(alphas, j, i) + gsl_matrix_get(hmm->transition_score_matrix, j, k) \\\n\t\t\t\t\t+ gsl_matrix_get(emisLogs, k, i+1) + gsl_matrix_get(betas, k, i+1) - pFor);\n\n\t\t\t\tgsl_matrix_set(tempTrans, j, k, gsl_matrix_get(tempTrans,j,k) + val);\n\t\t\t\tgsl_vector_set(rowSums, j, gsl_vector_get(rowSums, j) + val);\n\t\t\t}\n\t\t}\n\t}\n\n//update transition scores\n\tfor(j = 0; j < hmm->nstates; j++){\n\t\tfor(k = 0; k < hmm->nstates; k++){      \n\t\t\tval = gsl_matrix_get(tempTrans, j, k) / gsl_vector_get(rowSums, j);\n\t\t\tgsl_matrix_set(hmm->transition_matrix, j, k, val);\n\t\t\tgsl_matrix_set(hmm->transition_score_matrix, j, k, log(val));\n\t\t}\n\t}\n\tgsl_matrix_free(tempTrans);\n\tgsl_vector_free(rowSums);\n}\n\n/* posteriorDecode-- fills a vector (posteriorPath) of length L observations\nwith the most probably state sequence based on posterior probabilities */\nvoid posteriorDecode(HMM *hmm, gsl_vector *posteriorPath, gsl_matrix *posts, int length){\n\tint i, j, maxState;\n\tdouble maxProb;\n\t\n\tassert(length > 0 && hmm != NULL);\n\tassert(posteriorPath->size == length);\n\tassert(posts->size1 == hmm->nstates && posts->size2 == length);\n\t\n\tfor(i=0; i < length; i++){\n\t\tmaxProb = 0;\n\t\tmaxState = 0;\n\t\tfor(j=0;j < hmm->nstates;j++){\n\t\t\tif (gsl_matrix_get(posts, j, i) > maxProb){\n\t\t\t\tmaxProb = gsl_matrix_get(posts, j, i);\n\t\t\t\tmaxState = j;\n\t\t\t}\n\t\t}\n\t\tgsl_vector_set(posteriorPath,i,maxState);\n\t}\n\t\n}\n\n/* viterbi algorithm- this fills a vector (viterbiPath) of length L observations with\nthe most probable state sequence. it returns the prob of the most probable path.\na matrix of emission probs (log!!!) of dimensions nstates * L observations must be supplied. */\n\n  double viterbi(HMM *hmm, gsl_vector *viterbiPath, gsl_matrix *emisLogs, int length, int transitionPowerFlag){\n  gsl_matrix *deltas, *psi, *logTransitions;\n\tgsl_vector_view col;\n\tint i, j, lastState, tmp, last, power;\n\tdouble tempProb,prob, emit;\n\tint point;\n\t\n\tassert(length > 0 && hmm != NULL);\n\tassert(viterbiPath->size == length);\n\tassert(emisLogs->size1 == hmm->nstates && emisLogs->size2 == length);\n\t\n\n\t//if using transition powers, then check that we have other data\n\tif (transitionPowerFlag){\n\t  assert(hmm->otherData != NULL);\n\t  //initialize last\n\t  last = gsl_vector_get(hmm->otherData,0);\n\t} \n\telse {\n\t    last = 0; /* not used */\n\t}\n\t\n\t//allocate matrices for deltas (log prob of most prob path to stateN,obsL) and psis (the backpointers)\n\tdeltas = gsl_matrix_alloc(hmm->nstates, length);\n\tpsi    = gsl_matrix_alloc(hmm->nstates, length);\n\t\n\t//initialization\n\tfor (i = 0; i < hmm->nstates; i++){\n\t\tprob = gsl_vector_get(hmm->piStart_scores, i);\n\t\temit = gsl_matrix_get(emisLogs, i, 0);\n\t\tgsl_matrix_set(deltas, i, 0, (prob + emit));\n\t\tgsl_matrix_set(psi, i, 0, 0);\n\t\t}\n\n\tpoint = 666;\n\t//recursion\n\tfor (j = 1; j < length; j++){\n\t  for(i = 0; i < hmm->nstates; i++){\n\t    /* transition powers? */\n\t    if (transitionPowerFlag){\n\t      power = gsl_vector_get(hmm->otherData,j) - last;\n\t      logTransitions = gsl_matrix_power_logs(hmm->transition_matrix, power);\n\t      tempProb = viterbiMaxPrevious(hmm, deltas, logTransitions, i, j, &point);\n\t      gsl_matrix_free(logTransitions);\n\t    }\n\t    else{\n\t      tempProb =  viterbiMaxPrevious(hmm, deltas, hmm->transition_matrix, i, j, &point);\n\t    }\n\t    gsl_matrix_set(deltas, i, j, tempProb + gsl_matrix_get(emisLogs, i, j));\n\t    gsl_matrix_set(psi, i ,j , point);\n\t  }\n\t  if (transitionPowerFlag){\n\t      last = gsl_vector_get(hmm->otherData,j);\n\t  }\n\t}\n\n\t//termination\n\tcol = gsl_matrix_column(deltas, length - 1);\n\tlastState = (int) gsl_vector_max_index(&col.vector);\n  \t\n\t//backtrack\n\tgsl_vector_set(viterbiPath, length - 1, lastState);\n\tfor (j = length - 2; j >= 0; j--){\n\t\ttmp = gsl_matrix_get(psi, lastState, j + 1);\n\t\tlastState =  tmp;\n\t\tgsl_vector_set(viterbiPath, j , (int) lastState);\n\t\t}\n\t\n\t\t\n\treturn gsl_vector_max(&col.vector);\n\tgsl_matrix_free(deltas);\n\tgsl_matrix_free(psi);\n}\t\n\t\n\n/* this returns the sum of the previous states for the forward probabilities */\n\ndouble forwardSumPrevious(HMM *hmm, gsl_matrix *alphas, gsl_matrix *transition_score_matrix_i, int state, int obsIndex){\n\tgsl_vector *tempProbs;\n\tgsl_vector_view prevCol;\n\tint i;\n\tdouble tempProb;\n\t\n\ttempProbs = gsl_vector_alloc(hmm->nstates);\n\tprevCol = gsl_matrix_column(alphas, obsIndex - 1);\n\tfor(i = 0; i < hmm->nstates; i++){\n\t\ttempProb = gsl_vector_get(&prevCol.vector, i) + gsl_matrix_get(transition_score_matrix_i, i, state);\n\t\tgsl_vector_set(tempProbs, i, tempProb);\n\t\t}\n\ttempProb = log_sum(tempProbs); \n\tgsl_vector_free(tempProbs);\n\treturn(tempProb);\n}\n\n/* this returns the sum of the \"next\" states for the backward probabilities */\n\ndouble backwardSumNext(HMM *hmm, gsl_matrix *betas, gsl_matrix *transition_score_matrix_j,gsl_matrix *emisLogs, int state, int obsIndex){\n\tgsl_vector *tempProbs;\n\tgsl_vector_view nextCol;\n\tint j;\n\tdouble tempProb;\n\t\n\ttempProbs = gsl_vector_alloc(hmm->nstates);\n\tnextCol = gsl_matrix_column(betas, obsIndex + 1);\n\tfor(j = 0; j < hmm->nstates; j++){\t\t//sum over begin states...\n\t\ttempProb = gsl_vector_get(&nextCol.vector, j) + gsl_matrix_get(transition_score_matrix_j, state, j) + gsl_matrix_get(emisLogs, j,obsIndex + 1) ;\n\t\tgsl_vector_set(tempProbs, j, tempProb);\n\t\t}\n\ttempProb = log_sum(tempProbs);\n\tgsl_vector_free(tempProbs);\n\treturn(tempProb); \n}\t\n\n/* this returns the max of the previous states for the viterbi algorithm. \nit also sets the back pointer (point) to that state. */\n\ndouble viterbiMaxPrevious(HMM *hmm, gsl_matrix *deltas, gsl_matrix *transition_score_matrix_i, int state, int obsIndex, int *point){\n\tgsl_vector *tempProbs;\n\tgsl_vector_view prevCol;\n\tint i;\n\tdouble tempProb;\n\t\n\ttempProbs = gsl_vector_alloc(hmm->nstates);\n\tprevCol = gsl_matrix_column(deltas, obsIndex - 1);\n\tfor(i = 0; i < hmm->nstates; i++){\n\t\ttempProb = gsl_vector_get(&prevCol.vector, i) + gsl_matrix_get(transition_score_matrix_i, i, state);\n\t\tgsl_vector_set(tempProbs, i, tempProb);\n\t\t}\n\t*point = gsl_vector_max_index(tempProbs);\n\ttempProb = gsl_vector_max(tempProbs);\n\tgsl_vector_free(tempProbs);\n\treturn(tempProb);\n}\t\n\t\n/* This computes the log likelihood of an subpath of the data, for a specified set of the states defined\n    in the vector stateInclusion (1 for include, 0 for exclude). */\ndouble hmm_subpath_score(HMM *hmm, gsl_matrix *emisLogs, gsl_vector *stateInclusion, int begin, int length, int transitionPowerFlag){\n  gsl_matrix *alphas, *real_trans ;\n  gsl_vector *real_begin;\n  int i, j, stateCount;\n  double score;\n    \n  //initialize some matrices\n  alphas = gsl_matrix_alloc(hmm->nstates, length);\n  real_trans = gsl_matrix_alloc(hmm->nstates, hmm->nstates);\n  real_begin = gsl_vector_alloc(hmm->nstates);\n\n  //count number of states under consideration\n  stateCount = 0;\n  for(i = 0; i < hmm->nstates; i++){\n    stateCount += gsl_vector_get(stateInclusion, i);\n  }\n\n  //keep track of original transition matrix and \"begin\" vector\n  gsl_matrix_memcpy(real_trans,hmm->transition_matrix);\n  gsl_vector_memcpy(real_begin, hmm->piStart);\n  \n  //set begin states to uniform distribution over states considered in subset\n  for(i = 0; i < hmm->nstates; i++){\n    if (gsl_vector_get(stateInclusion,i)){\n      gsl_vector_set(hmm->piStart, i, 1.0 / stateCount);\n    }\n    else{\n      gsl_vector_set(hmm->piStart, i, 0.0);\n    }\n  }\n\n  //renomalize transition matrix to reflect states included.\n  //go through transition matrix, shutting off those which aren't in subset\n  for(i = 0; i < hmm->nstates; i++){\n    for(j = 0; j < hmm->nstates; j++){\n      if (gsl_vector_get(stateInclusion,i) == 0 || gsl_vector_get(stateInclusion,j) == 0){\n\tgsl_matrix_set( hmm->transition_matrix, i, j, 0.0);\n      }\n    }\n  }\n \n  //one is the magic number...\n  hmm_normalize_transitions(hmm);\n  hmm_logify_transitions(hmm);\n\n  //run the forward algorithm to get our answer!\n  score = forwardAlgOffset(hmm, alphas, emisLogs, length, begin, transitionPowerFlag);\n\n  //cleanup\n  gsl_matrix_memcpy(hmm->transition_matrix, real_trans);\n  gsl_vector_memcpy(hmm->piStart, real_begin);\n  hmm_logify_transitions(hmm);\n  gsl_matrix_free(alphas);\n  gsl_matrix_free(real_trans);\n  gsl_vector_free(real_begin);\n  return(score);\n}\n  \n/* Calculates the log odds score for two competing sets of states, over a subset of the data\n   by comparing the ratio of their likelihoods */\ndouble hmm_subpath_log_odds(HMM *hmm, gsl_matrix *emisLogs, gsl_vector *stateInclusion1,\n\t\t\t     gsl_vector *stateInclusion2,int begin, int length,\n\t\t\t    int transitionPowerFlag){\n  double score1, score2;\n  score1 = hmm_subpath_score(hmm, emisLogs, stateInclusion1, begin,length,transitionPowerFlag);\n  score2 =  hmm_subpath_score(hmm, emisLogs, stateInclusion2, begin,length,transitionPowerFlag);\n  //printf(\"scores: %f %f\\n\",score1,score2);\n  return(score1 - score2);\n}\n\n\n/* simulatePath-- returns a vector snpNumber long that represents an instance\nof the simulated markov state path through the data. takes as arguments,an hmm,\n and a pointer to void which actually is an gsl random numb. gen, as well as the observation\n number */\ngsl_vector *simulatePath(HMM *h, void *r, int obsNumber){\n  int i, j, pastState;\n  double sum, rand;\n  gsl_rng * rn = (gsl_rng *) r;\n  gsl_vector *path;\n\n  path = gsl_vector_alloc(obsNumber);\n\n  /*choose initial state, set paths[0] */\n  rand = gsl_rng_uniform(rn);\n  sum = 0;\n  for(i = 0; i < h->nstates; i++){\n    sum += gsl_vector_get(h->piStart, i);\n    printf(\"%f %f\\n\",rand, sum);\n    if (rand <= sum){\n      printf(\"true\\n\");\n      gsl_vector_set(path,0,i);\n      rand = 2.0;\n    }\n  }\n   \n  /* now go through obs, using transition matrix to choose states */\n  \n  for(i = 1; i < obsNumber; i++){\n    pastState = gsl_vector_get(path, i-1);\n    rand = gsl_rng_uniform(rn);\n    sum = 0;\n    for(j = 0; j < h->nstates; j++){\n      sum += gsl_matrix_get(h->transition_matrix, pastState, j);\n      if (rand <= sum){\n\tgsl_vector_set(path,i,j);\n\trand = 2.0;\n      }\n    }\n  }\n  return(path);\n}\n\n\n/* simulatePathSpaced-- just like simulatePath except takes two\nadded parameters, a pointer to a gsl_vector which will contain the \nsimulated snp locations, and a double for the exponential mean */\ngsl_vector *simulatePathSpaced(HMM *h, void *r, int obsNumber, gsl_vector *locs, double mu){\n  int i, j, pastState;\n  double sum, rand;\n  gsl_rng * rn = (gsl_rng *) r;\n  gsl_vector *path;\n  gsl_matrix *matPower;\n\n  path = gsl_vector_alloc(obsNumber);\n\n  /*choose initial state, set paths[0] */\n  rand = gsl_rng_uniform(rn);\n  sum = 0;\n  for(i = 0; i < h->nstates; i++){\n    sum += gsl_vector_get(h->piStart, i);\n    printf(\"%f %f\\n\",rand, sum);\n    if (rand <= sum){\n      printf(\"true\\n\");\n      gsl_vector_set(path,0,i);\n      rand = 2.0;\n    }\n  }\n \n  /*set initial location to 1 by convention */\n  gsl_vector_set(locs,0,1);\n  //now go through obs and simulate spacing -- curently drawn from exp\n  for(i = 1; i < obsNumber; i++){\n    rand = gsl_ran_exponential(rn, mu);\n    gsl_vector_set(locs, i, gsl_vector_get(locs, i - 1) + ceil(rand));\n  }\n\n  /* now go through obs, using transition matrix and powers to choose states */\n  for(i = 1; i < obsNumber; i++){\n    pastState = gsl_vector_get(path, i-1);\n    matPower = gsl_matrix_power(h->transition_matrix, gsl_vector_get(locs,i) - gsl_vector_get(locs,i - 1));\n    rand = gsl_rng_uniform(rn);\n    sum = 0;\n    for(j = 0; j < h->nstates; j++){\n      sum += gsl_matrix_get(matPower, pastState, j);\n      if (rand <= sum){\n\tgsl_vector_set(path,i,j);\n\trand = 2.0;\n      }\n    }\n    gsl_matrix_free(matPower);\n  }\n  return(path);\n}\n", "meta": {"hexsha": "0fbd9c01646dfa064fb1e3d34aadba8c6ba483be", "size": 34103, "ext": "c", "lang": "C", "max_stars_repo_path": "hmm/hmm.c", "max_stars_repo_name": "andrewkern/segSiteHMM", "max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hmm/hmm.c", "max_issues_repo_name": "andrewkern/segSiteHMM", "max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hmm/hmm.c", "max_forks_repo_name": "andrewkern/segSiteHMM", "max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60", "max_forks_repo_licenses": ["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.865938431, "max_line_length": 178, "alphanum_fraction": 0.6803213794, "num_tokens": 10270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.36932798299490477}}
{"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk.c\n * \\brief Source file with common variables and functions to optimize\n *   Runge-Kutta methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <float.h>\n#include <math.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include <libintl.h>\n#include <gsl/gsl_rng.h>\n#if HAVE_MPI\n#include <mpi.h>\n#endif\n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_2_2.h\"\n#include \"rk_3_2.h\"\n#include \"rk_3_3.h\"\n#include \"rk_4_2.h\"\n#include \"rk_4_3.h\"\n#include \"rk_4_4.h\"\n#include \"rk_5_2.h\"\n#include \"rk_5_3.h\"\n#include \"rk_5_4.h\"\n#include \"rk_6_2.h\"\n#include \"rk_6_3.h\"\n#include \"rk_6_4.h\"\n\n#define DEBUG_RK 0              ///< macro to debug.\n\n/**\n * Function to print the t-b Runge-Kutta coefficients.\n */\nvoid\nrk_print_tb (Optimize * tb,     ///< Optimize struct.\n             char *label,       ///< label.\n             FILE * file)       ///< file.\n{\n  long double *x;\n  unsigned int i, j, k;\n  x = tb->coefficient;\n  fprintf (file, \"%s: t1=%.19Le\\n\", label, x[0]);\n  for (i = 2, k = 0; i <= tb->nsteps; ++i)\n    {\n      fprintf (file, \"%s: t%u=%.19Le\\n\", label, i, x[++k]);\n      for (j = 0; j < i; ++j)\n        fprintf (file, \"%s: b%u%u=%.19Le\\n\", label, i, j, x[++k]);\n    }\n}\n\n/**\n * Function to print the e Runge-Kutta coefficients.\n */\nvoid\nrk_print_e (Optimize * tb,      ///< Optimize struct.\n            char *label,        ///< label.\n            FILE * file)        ///< file.\n{\n  long double *x;\n  unsigned int i, k, nsteps;\n  x = tb->coefficient;\n  nsteps = tb->nsteps;\n  k = (nsteps + 2) * (nsteps + 1) / 2 - 2;\n  for (i = 0; i < nsteps - 1; ++i)\n    fprintf (file, \"%s: e%u%u=%.19Le\\n\", label, nsteps, i, x[k++]);\n}\n\n/**\n * Function to print in a maxima file the Runge-Kutta coefficients.\n */\nstatic void\nrk_print (RK * rk,              ///< RK struct.\n          FILE * file)          ///< file.\n{\n  Optimize *tb, *ac;\n  long double *x, *y;\n  unsigned int i, j, k, l, nsteps;\n  tb = rk->tb;\n  ac = rk->ac;\n  x = tb->coefficient;\n  y = ac->coefficient;\n  fprintf (file, \"t1:%.19Le;\\n\", x[0]);\n  nsteps = tb->nsteps;\n  for (i = 2, k = l = 0; i <= nsteps; ++i)\n    {\n      fprintf (file, \"t%u:%.19Le;\\n\", i, x[++k]);\n      for (j = 0; j < i; ++j)\n        fprintf (file, \"b%u%u:%.19Le;\\n\", i, j, x[++k]);\n      if (!rk->strong)\n        continue;\n      for (j = 0; j < i; ++j)\n        fprintf (file, \"a%u%u:%.19Le;\\n\", i, j, y[l++]);\n      for (j = 0; j < i; ++j)\n        fprintf (file, \"c%u%u:%.19Le;\\n\", i, j, y[l++]);\n    }\n  if (rk->pair)\n    for (i = 0; i < nsteps - 1; ++i)\n      fprintf (file, \"e%u%u:%.19Le;\\n\", nsteps, i, x[++k]);\n}\n\n/**\n * Function to print a maxima format file to check the accuracy order of the\n * Runge-Kutta simple stable methods.\n */\nstatic void\nrk_print_maxima (FILE * file,   ///< file.\n                 unsigned int nsteps,   ///< steps number.\n                 unsigned int ncoefficients,    ///< coefficients number.\n                 unsigned int order,    ///< accuracy order.\n                 char label)    ///< coefficient label.\n{\n  unsigned int i, j, k, l;\n  // b_{ij}=1 (1st order)\n  for (i = 0; i < ncoefficients; ++i)\n    fprintf (file, \"%c%u%u+\", label, nsteps, i);\n  fprintf (file, \"-1;\\n\");\n  // b_{ij}t_j=1/2 (2nd order)\n  for (i = 1; i < ncoefficients; ++i)\n    fprintf (file, \"%c%u%u*t%u+\", label, nsteps, i, i);\n  fprintf (file, \"-1/2;\\n\");\n  if (order < 2)\n    return;\n  // b_{ij}t_j^2=1/3 (3rd order)\n  for (i = 1; i < ncoefficients; ++i)\n    fprintf (file, \"%c%u%u*t%u^2+\", label, nsteps, i, i);\n  fprintf (file, \"-1/3;\\n\");\n  if (order < 3)\n    return;\n  // b_{ij}b_{jk}t_k=1/6 (3rd order)\n  for (i = 2; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*(\", label, nsteps, i);\n      for (j = 1; j < i; ++j)\n        fprintf (file, \"b%u%u*t%u+\", i, j, j);\n      fprintf (file, \"0)+\");\n    }\n  fprintf (file, \"-1/6;\\n\");\n  // b_{ij}t_j^3=1/4 (4th order)\n  for (i = 1; i < ncoefficients; ++i)\n    fprintf (file, \"%c%u%u*t%u^3+\", label, nsteps, i, i);\n  fprintf (file, \"-1/4;\\n\");\n  if (order < 4)\n    return;\n  // b_{ij}b_{jk}b_{kl}t_l=1/24 (4th order)\n  for (i = 3; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*(\", label, nsteps, i);\n      for (j = 2; j < i; ++j)\n        {\n          fprintf (file, \"b%u%u*(\", i, j);\n          for (k = 1; k < j; ++k)\n            fprintf (file, \"b%u%u*t%u+\", j, k, k);\n          fprintf (file, \"0)+\");\n        }\n      fprintf (file, \"0)+\");\n    }\n  fprintf (file, \"-1/24;\\n\");\n  // b_{ij}b_{jk}t_k^2=1/12 (4th order)\n  for (i = 2; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*(\", label, nsteps, i);\n      for (j = 1; j < i; ++j)\n        fprintf (file, \"b%u%u*t%u^2+\", i, j, j);\n      fprintf (file, \"0)+\");\n    }\n  fprintf (file, \"-1/12;\\n\");\n  // b_{ij}t_jb_{jk}t_k=1/8 (4th order)\n  for (i = 2; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*t%u*(\", label, nsteps, i, i);\n      for (j = 1; j < i; ++j)\n        fprintf (file, \"b%u%u*t%u+\", i, j, j);\n      fprintf (file, \"0)+\");\n    }\n  fprintf (file, \"-1/8;\\n\");\n  // b_{ij}t_j^4=1/5 (5th order)\n  for (i = 1; i < ncoefficients; ++i)\n    fprintf (file, \"%c%u%u*t%u^4+\", label, nsteps, i, i);\n  fprintf (file, \"-1/5;\\n\");\n  if (order < 5)\n    return;\n  // b_{ij}t_j^2b_{jk}t_k^2=1/10 (5th order)\n  for (i = 2; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*t%u^2*(\", label, nsteps, i, i);\n      for (j = 1; j < i; ++j)\n        fprintf (file, \"b%u%u*t%u+\", i, j, j);\n      fprintf (file, \"0)+\");\n    }\n  fprintf (file, \"-1/10;\\n\");\n  // b_{ij}b_{jk}t_k^3=1/20 (5th order)\n  for (i = 2; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*(\", label, nsteps, i);\n      for (j = 1; j < i; ++j)\n        fprintf (file, \"b%u%u*t%u^3+\", i, j, j);\n      fprintf (file, \"0)+\");\n    }\n  fprintf (file, \"-1/20;\\n\");\n  // b_{ij}(b_{jk}t_k)^2=1/20 (5th order)\n  for (i = 2; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*(\", label, nsteps, i);\n      for (j = 1; j < i; ++j)\n        fprintf (file, \"b%u%u*t%u+\", i, j, j);\n      fprintf (file, \"0)^2+\");\n    }\n  fprintf (file, \"-1/20;\\n\");\n  // b_{ij}t_jb_{jk}t_k^2=1/15 (5th order)\n  for (i = 2; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*t%u*(\", label, nsteps, i, i);\n      for (j = 1; j < i; ++j)\n        fprintf (file, \"b%u%u*t%u^2+\", i, j, j);\n      fprintf (file, \"0)+\");\n    }\n  fprintf (file, \"-1/8;\\n\");\n  // b_{ij}t_jb_{jk}b_{kl}t_l=1/24 (5th order)\n  for (i = 3; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*t%u*(\", label, nsteps, i, i);\n      for (j = 2; j < i; ++j)\n        {\n          fprintf (file, \"b%u%u*(\", i, j);\n          for (k = 1; k < j; ++k)\n            fprintf (file, \"b%u%u*t%u+\", j, k, k);\n          fprintf (file, \"0)+\");\n        }\n      fprintf (file, \"0)+\");\n    }\n  fprintf (file, \"-7/120;\\n\");\n  // b_{ij}b_{jk}b_{kl}t_l^2=1/60 (5th order)\n  for (i = 3; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*(\", label, nsteps, i);\n      for (j = 2; j < i; ++j)\n        {\n          fprintf (file, \"b%u%u*(\", i, j);\n          for (k = 1; k < j; ++k)\n            fprintf (file, \"b%u%u*t%u^2+\", j, k, k);\n          fprintf (file, \"0)+\");\n        }\n      fprintf (file, \"0)+\");\n    }\n  fprintf (file, \"-1/60;\\n\");\n  // b_{ij}b_{jk}b_{kl}b_{lm}t_m=1/120 (5th order)\n  for (i = 4; i < ncoefficients; ++i)\n    {\n      fprintf (file, \"%c%u%u*(\", label, nsteps, i);\n      for (j = 3; j < i; ++j)\n        {\n          fprintf (file, \"b%u%u*(\", i, j);\n          for (k = 2; k < j; ++k)\n            {\n              fprintf (file, \"b%u%u*(\", j, k);\n              for (l = 1; l < k; ++l)\n                fprintf (file, \"b%u%u*t%u+\", k, l, l);\n              fprintf (file, \"0)+\");\n            }\n          fprintf (file, \"0)+\");\n        }\n      fprintf (file, \"0)+\");\n    }\n  fprintf (file, \"-1/120;\\n\");\n  // b_{ij}t_j^5=1/6 (6th order)\n  for (i = 1; i < ncoefficients; ++i)\n    fprintf (file, \"%c%u%u*t%u^5+\", label, nsteps, i, i);\n  fprintf (file, \"-1/6;\\n\");\n}\n\n/**\n * Function to print in a maxima file the a-c Runge-Kutta equations.\n */\nstatic void\nac_print_maxima (FILE * file,   ///< file.\n                 unsigned int nsteps)   ///< steps number.\n{\n  unsigned int i, j, k;\n  for (i = 2; i <= nsteps; ++i)\n    {\n      // a_{i,j}=1\n      for (j = 0; j < i; ++j)\n        fprintf (file, \"a%u%u+\", i, j);\n      fprintf (file, \"-1;\\n\");\n      // a_{i0}c_{i0}+a_{ij}b_{j0}=b_{i0}\n      fprintf (file, \"a%u0*c%u0+a%u1*t1+\", i, i, i);\n      for (j = 2; j < i; ++j)\n        fprintf (file, \"a%u%u*b%u0+\", i, j, j);\n      fprintf (file, \"-b%u0;\\n\", i);\n      // a_{ij}c_{ij}+a_{ik}b_{kj}=b_{ij}\n      for (j = 1; j < i; ++j)\n        {\n          fprintf (file, \"a%u%u*c%u%u+\", i, j, i, j);\n          for (k = j; ++k < i;)\n            fprintf (file, \"a%u%u*b%u%u+\", i, k, k, j);\n          fprintf (file, \"-b%u%u;\\n\", i, j);\n        }\n    }\n}\n\n/**\n * Function to get \\f$a_{ij}\\f$ and \\f$c_{ij}\\f$ coefficients of the Runge-Kutta\n * 2nd step.\n */\nstatic int\nrk_ac_2 (RK * rk)               ///< RK struct.\n{\n  long double *tb, *ac, *r;\n  register long double ac0;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_ac_2: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  ac = rk->ac->coefficient;\n  r = rk->ac->random_data;\n  c21 (ac) = r[0];\n  a21 (ac) = b21 (tb) / c21 (ac);\n  a20 (ac) = 1.L - a21 (ac);\n  ac0 = b20 (tb) - a21 (ac) * t1 (tb);\n  c20 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / a20 (ac);\n#if DEBUG_RK\n  fprintf (stderr, \"rk_ac_2: a20=%Lg c20=%Lg\\n\", a20 (ac), c20 (ac));\n  fprintf (stderr, \"rk_ac_2: a21=%Lg c21=%Lg\\n\", a21 (ac), c21 (ac));\n  fprintf (stderr, \"rk_ac_2: end\\n\");\n#endif\n  if (isnan (c20 (ac)) || isnan (a21 (ac)))\n    return 0;\n  return 1;\n}\n\n/**\n * Function to get \\f$a_{ij}\\f$ and \\f$c_{ij}\\f$ coefficients of the Runge-Kutta\n * 3rd step.\n */\nstatic int\nrk_ac_3 (RK * rk)               ///< RK struct.\n{\n  long double *tb, *ac, *r;\n  register long double ac0;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_ac_3: start\\n\");\n#endif\n  if (!rk_ac_2 (rk))\n    {\n#if DEBUG_RK\n      fprintf (stderr, \"rk_ac_3: end\\n\");\n#endif\n      return 0;\n    }\n  tb = rk->tb->coefficient;\n  ac = rk->ac->coefficient;\n  r = rk->ac->random_data;\n  c31 (ac) = r[1];\n  c32 (ac) = r[2];\n  a32 (ac) = b32 (tb) / c32 (ac);\n  ac0 = b31 (tb) - a32 (ac) * b21 (tb);\n  a31 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c31 (ac);\n  a30 (ac) = 1.L - a31 (ac) - a32 (ac);\n  ac0 = b30 (tb) - a31 (ac) * t1 (tb) - a32 (ac) * b20 (tb);\n  c30 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / a30 (ac);\n#if DEBUG_RK\n  fprintf (stderr, \"rk_ac_3: a30=%Lg c30=%Lg\\n\", a30 (ac), c30 (ac));\n  fprintf (stderr, \"rk_ac_3: a31=%Lg c31=%Lg\\n\", a31 (ac), c31 (ac));\n  fprintf (stderr, \"rk_ac_3: a32=%Lg c32=%Lg\\n\", a32 (ac), c32 (ac));\n  fprintf (stderr, \"rk_ac_3: end\\n\");\n#endif\n  if (isnan (c30 (ac)) || isnan (a31 (ac)) || isnan (a32 (ac)))\n    return 0;\n  return 1;\n}\n\n/**\n * Function to get \\f$a_{ij}\\f$ and \\f$c_{ij}\\f$ coefficients of the Runge-Kutta\n * 4th step.\n */\nstatic int\nrk_ac_4 (RK * rk)               ///< RK struct.\n{\n  long double *tb, *ac, *r;\n  register long double ac0;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_ac_4: start\\n\");\n#endif\n  if (!rk_ac_3 (rk))\n    {\n#if DEBUG_RK\n      fprintf (stderr, \"rk_ac_4: end\\n\");\n#endif\n      return 0;\n    }\n  tb = rk->tb->coefficient;\n  ac = rk->ac->coefficient;\n  r = rk->ac->random_data;\n  c41 (ac) = r[3];\n  c42 (ac) = r[4];\n  c43 (ac) = r[5];\n  a43 (ac) = b43 (tb) / c43 (ac);\n  ac0 = b42 (tb) - a43 (ac) * b32 (tb);\n  a42 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c42 (ac);\n  ac0 = b41 (tb) - a42 (ac) * b21 (tb) - a43 (ac) * b31 (tb);\n  a41 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c41 (ac);\n  a40 (ac) = 1.L - a41 (ac) - a42 (ac) - a43 (ac);\n  ac0 = b40 (tb) - a41 (ac) * t1 (tb) - a42 (ac) * b20 (tb)\n    - a43 (ac) * b30 (tb);\n  c40 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / a40 (ac);\n#if DEBUG_RK\n  fprintf (stderr, \"rk_ac_4: a40=%Lg c40=%Lg\\n\", a40 (ac), c40 (ac));\n  fprintf (stderr, \"rk_ac_4: a41=%Lg c41=%Lg\\n\", a41 (ac), c41 (ac));\n  fprintf (stderr, \"rk_ac_4: a42=%Lg c42=%Lg\\n\", a42 (ac), c42 (ac));\n  fprintf (stderr, \"rk_ac_4: a43=%Lg c43=%Lg\\n\", a43 (ac), c43 (ac));\n  fprintf (stderr, \"rk_ac_4: end\\n\");\n#endif\n  if (isnan (c40 (ac)) || isnan (a41 (ac)) || isnan (a42 (ac))\n      || isnan (a43 (ac)))\n    return 0;\n  return 1;\n}\n\n/**\n * Function to get \\f$a_{ij}\\f$ and \\f$c_{ij}\\f$ coefficients of the Runge-Kutta\n * 5th step.\n */\nstatic int\nrk_ac_5 (RK * rk)               ///< RK struct.\n{\n  long double *tb, *ac, *r;\n  register long double ac0;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_ac_5: start\\n\");\n#endif\n  if (!rk_ac_4 (rk))\n    {\n#if DEBUG_RK\n      fprintf (stderr, \"rk_ac_5: end\\n\");\n#endif\n      return 0;\n    }\n  tb = rk->tb->coefficient;\n  ac = rk->ac->coefficient;\n  r = rk->ac->random_data;\n  c51 (ac) = r[6];\n  c52 (ac) = r[7];\n  c53 (ac) = r[8];\n  c54 (ac) = r[9];\n  a54 (ac) = b54 (tb) / c54 (ac);\n  ac0 = b53 (tb) - a54 (ac) * b43 (tb);\n  a53 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c53 (ac);\n  ac0 = b52 (tb) - a53 (ac) * b32 (tb) - a54 (ac) * b42 (tb);\n  a52 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c52 (ac);\n  ac0 = b51 (tb) - a52 (ac) * b21 (tb) - a53 (ac) * b31 (tb)\n    - a54 (ac) * b41 (tb);\n  a51 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c51 (ac);\n  a50 (ac) = 1.L - a51 (ac) - a52 (ac) - a53 (ac) - a54 (ac);\n  ac0 = b50 (tb) - a51 (ac) * t1 (tb) - a52 (ac) * b20 (tb)\n    - a53 (ac) * b30 (tb) - a54 (ac) * b40 (tb);\n  c50 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / a50 (ac);\n#if DEBUG_RK\n  fprintf (stderr, \"rk_ac_5: a50=%Lg c50=%Lg\\n\", a50 (ac), c50 (ac));\n  fprintf (stderr, \"rk_ac_5: a51=%Lg c51=%Lg\\n\", a51 (ac), c51 (ac));\n  fprintf (stderr, \"rk_ac_5: a52=%Lg c52=%Lg\\n\", a52 (ac), c52 (ac));\n  fprintf (stderr, \"rk_ac_5: a53=%Lg c53=%Lg\\n\", a53 (ac), c53 (ac));\n  fprintf (stderr, \"rk_ac_5: a54=%Lg c54=%Lg\\n\", a54 (ac), c54 (ac));\n  fprintf (stderr, \"rk_ac_5: end\\n\");\n#endif\n  if (isnan (c50 (ac)) || isnan (a51 (ac)) || isnan (a52 (ac))\n      || isnan (a53 (ac)) || isnan (a54 (ac)))\n    return 0;\n  return 1;\n}\n\n/**\n * Function to get \\f$a_{ij}\\f$ and \\f$c_{ij}\\f$ coefficients of the Runge-Kutta\n * 6th step.\n */\nstatic int\nrk_ac_6 (RK * rk)               ///< RK struct.\n{\n  long double *tb, *ac, *r;\n  register long double ac0;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_ac_6: start\\n\");\n#endif\n  if (!rk_ac_5 (rk))\n    {\n#if DEBUG_RK\n      fprintf (stderr, \"rk_ac_6: end\\n\");\n#endif\n      return 0;\n    }\n  tb = rk->tb->coefficient;\n  ac = rk->ac->coefficient;\n  r = rk->ac->random_data;\n  c61 (ac) = r[10];\n  c62 (ac) = r[11];\n  c63 (ac) = r[12];\n  c64 (ac) = r[13];\n  c65 (ac) = r[14];\n  a65 (ac) = b65 (tb) / c65 (ac);\n  ac0 = b64 (tb) - a65 (ac) * b54 (tb);\n  a64 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c64 (ac);\n  ac0 = b63 (tb) - a64 (ac) * b43 (tb) - a65 (ac) * b53 (tb);\n  a63 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c63 (ac);\n  ac0 = b62 (tb) - a63 (ac) * b32 (tb) - a64 (ac) * b42 (tb)\n    - a65 (ac) * b52 (tb);\n  a62 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c62 (ac);\n  ac0 = b61 (tb) - a62 (ac) * b21 (tb) - a63 (ac) * b31 (tb)\n    - a64 (ac) * b41 (tb) - a65 (ac) * b51 (tb);\n  a61 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / c61 (ac);\n  a60 (ac) = 1.L - a61 (ac) - a62 (ac) - a63 (ac) - a64 (ac) - a65 (ac);\n  ac0 = b60 (tb) - a61 (ac) * t1 (tb) - a62 (ac) * b20 (tb)\n    - a63 (ac) * b30 (tb) - a64 (ac) * b40 (tb) - a65 (ac) * b50 (tb);\n  c60 (ac) = fabsl (ac0) < LDBL_EPSILON ? 0.L : ac0 / a60 (ac);\n#if DEBUG_RK\n  fprintf (stderr, \"rk_ac_6: a60=%Lg c60=%Lg\\n\", a60 (ac), c60 (ac));\n  fprintf (stderr, \"rk_ac_6: a61=%Lg c61=%Lg\\n\", a61 (ac), c61 (ac));\n  fprintf (stderr, \"rk_ac_6: a62=%Lg c62=%Lg\\n\", a62 (ac), c62 (ac));\n  fprintf (stderr, \"rk_ac_6: a63=%Lg c63=%Lg\\n\", a63 (ac), c63 (ac));\n  fprintf (stderr, \"rk_ac_6: a64=%Lg c64=%Lg\\n\", a64 (ac), c64 (ac));\n  fprintf (stderr, \"rk_ac_6: a65=%Lg c65=%Lg\\n\", a65 (ac), c65 (ac));\n  fprintf (stderr, \"rk_ac_6: end\\n\");\n#endif\n  if (isnan (c60 (ac)) || isnan (a61 (ac)) || isnan (a62 (ac))\n      || isnan (a63 (ac)) || isnan (a64 (ac)) || isnan (a65 (ac)))\n    return 0;\n  return 1;\n}\n\n/**\n * Function to get the objective function of 2 steps Runge-Kutta methods.\n *\n * \\return objective function value.\n */\nstatic long double\nrk_objective_ac_2 (RK * rk)     ///< RK struct.\n{\n  long double *tb, *ac;\n  long double k;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_objective ac_2: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  ac = rk->ac->coefficient;\n  k = fminl (0.L, a20 (ac));\n  if (a21 (ac) < 0.L)\n    k += a21 (ac);\n  if (k < 0.L)\n    {\n      k = 20.L - k;\n      goto end;\n    }\n  k = fminl (0.L, c20 (ac));\n  if (c21 (ac) < 0.L)\n    k += c21 (ac);\n  if (k < 0.L)\n    {\n      k = 10.L - k;\n      goto end;\n    }\n  k = 1.L / rk_cfl_2 (tb, ac);\nend:\n#if DEBUG_RK\n  fprintf (stderr, \"rk_objective ac_2: objective=%Lg\\n\", k);\n  fprintf (stderr, \"rk_objective ac_2: end\\n\");\n#endif\n  return k;\n}\n\n/**\n * Function to get the objective function of 3 steps Runge-Kutta methods.\n *\n * \\return objective function value.\n */\nstatic long double\nrk_objective_ac_3 (RK * rk)     ///< RK struct.\n{\n  long double *tb, *ac;\n  long double k;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_objective ac_3: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  ac = rk->ac->coefficient;\n  k = fminl (0.L, a20 (ac));\n  if (a21 (ac) < 0.L)\n    k += a21 (ac);\n  if (a30 (ac) < 0.L)\n    k += a30 (ac);\n  if (a31 (ac) < 0.L)\n    k += a31 (ac);\n  if (a32 (ac) < 0.L)\n    k += a32 (ac);\n  if (k < 0.L)\n    {\n      k = 20.L - k;\n      goto end;\n    }\n  k = fminl (0.L, c20 (ac));\n  if (c21 (ac) < 0.L)\n    k += c21 (ac);\n  if (c30 (ac) < 0.L)\n    k += c30 (ac);\n  if (c31 (ac) < 0.L)\n    k += c31 (ac);\n  if (c32 (ac) < 0.L)\n    k += c32 (ac);\n  if (k < 0.L)\n    {\n      k = 10.L - k;\n      goto end;\n    }\n  k = 1.L / rk_cfl_3 (tb, ac);\nend:\n#if DEBUG_RK\n  fprintf (stderr, \"rk_objective ac_3: objective=%Lg\\n\", k);\n  fprintf (stderr, \"rk_objective ac_3: end\\n\");\n#endif\n  return k;\n}\n\n/**\n * Function to get the objective function of 4 steps Runge-Kutta methods.\n *\n * \\return objective function value.\n */\nstatic long double\nrk_objective_ac_4 (RK * rk)     ///< RK struct.\n{\n  long double *tb, *ac;\n  long double k;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_objective ac_4: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  ac = rk->ac->coefficient;\n  k = fminl (0.L, a20 (ac));\n  if (a21 (ac) < 0.L)\n    k += a21 (ac);\n  if (a30 (ac) < 0.L)\n    k += a30 (ac);\n  if (a31 (ac) < 0.L)\n    k += a31 (ac);\n  if (a32 (ac) < 0.L)\n    k += a32 (ac);\n  if (a40 (ac) < 0.L)\n    k += a40 (ac);\n  if (a41 (ac) < 0.L)\n    k += a41 (ac);\n  if (a42 (ac) < 0.L)\n    k += a42 (ac);\n  if (a43 (ac) < 0.L)\n    k += a43 (ac);\n  if (k < 0.L)\n    {\n      k = 20.L - k;\n      goto end;\n    }\n  k = fminl (0.L, c20 (ac));\n  if (c21 (ac) < 0.L)\n    k += c21 (ac);\n  if (c30 (ac) < 0.L)\n    k += c30 (ac);\n  if (c31 (ac) < 0.L)\n    k += c31 (ac);\n  if (c32 (ac) < 0.L)\n    k += c32 (ac);\n  if (c40 (ac) < 0.L)\n    k += c40 (ac);\n  if (c41 (ac) < 0.L)\n    k += c41 (ac);\n  if (c42 (ac) < 0.L)\n    k += c42 (ac);\n  if (c43 (ac) < 0.L)\n    k += c43 (ac);\n  if (k < 0.L)\n    {\n      k = 10.L - k;\n      goto end;\n    }\n  k = 1.L / rk_cfl_4 (tb, ac);\nend:\n#if DEBUG_RK\n  fprintf (stderr, \"rk_objective ac_4: objective=%Lg\\n\", k);\n  fprintf (stderr, \"rk_objective ac_4: end\\n\");\n#endif\n  return k;\n}\n\n/**\n * Function to get the objective function of 5 steps Runge-Kutta methods.\n *\n * \\return objective function value.\n */\nstatic long double\nrk_objective_ac_5 (RK * rk)     ///< RK struct.\n{\n  long double *tb, *ac;\n  long double k;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_objective ac_5: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  ac = rk->ac->coefficient;\n  k = fminl (0.L, a20 (ac));\n  if (a21 (ac) < 0.L)\n    k += a21 (ac);\n  if (a30 (ac) < 0.L)\n    k += a30 (ac);\n  if (a31 (ac) < 0.L)\n    k += a31 (ac);\n  if (a32 (ac) < 0.L)\n    k += a32 (ac);\n  if (a40 (ac) < 0.L)\n    k += a40 (ac);\n  if (a41 (ac) < 0.L)\n    k += a41 (ac);\n  if (a42 (ac) < 0.L)\n    k += a42 (ac);\n  if (a43 (ac) < 0.L)\n    k += a43 (ac);\n  if (a50 (ac) < 0.L)\n    k += a50 (ac);\n  if (a51 (ac) < 0.L)\n    k += a51 (ac);\n  if (a52 (ac) < 0.L)\n    k += a52 (ac);\n  if (a53 (ac) < 0.L)\n    k += a53 (ac);\n  if (a54 (ac) < 0.L)\n    k += a54 (ac);\n  if (k < 0.L)\n    {\n      k = 20.L - k;\n      goto end;\n    }\n  k = fminl (0.L, c20 (ac));\n  if (c21 (ac) < 0.L)\n    k += c21 (ac);\n  if (c30 (ac) < 0.L)\n    k += c30 (ac);\n  if (c31 (ac) < 0.L)\n    k += c31 (ac);\n  if (c32 (ac) < 0.L)\n    k += c32 (ac);\n  if (c40 (ac) < 0.L)\n    k += c40 (ac);\n  if (c41 (ac) < 0.L)\n    k += c41 (ac);\n  if (c42 (ac) < 0.L)\n    k += c42 (ac);\n  if (c43 (ac) < 0.L)\n    k += c43 (ac);\n  if (c50 (ac) < 0.L)\n    k += c50 (ac);\n  if (c51 (ac) < 0.L)\n    k += c51 (ac);\n  if (c52 (ac) < 0.L)\n    k += c52 (ac);\n  if (c53 (ac) < 0.L)\n    k += c53 (ac);\n  if (c54 (ac) < 0.L)\n    k += c54 (ac);\n  if (k < 0.L)\n    {\n      k = 10.L - k;\n      goto end;\n    }\n  k = 1.L / rk_cfl_5 (tb, ac);\nend:\n#if DEBUG_RK\n  fprintf (stderr, \"rk_objective ac_5: objective=%Lg\\n\", k);\n  fprintf (stderr, \"rk_objective ac_5: end\\n\");\n#endif\n  return k;\n}\n\n/**\n * Function to get the objective function of 6 steps Runge-Kutta methods.\n *\n * \\return objective function value.\n */\nstatic long double\nrk_objective_ac_6 (RK * rk)     ///< RK struct.\n{\n  long double *tb, *ac;\n  long double k;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_objective ac_6: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  ac = rk->ac->coefficient;\n  k = fminl (0.L, a20 (ac));\n  if (a21 (ac) < 0.L)\n    k += a21 (ac);\n  if (a30 (ac) < 0.L)\n    k += a30 (ac);\n  if (a31 (ac) < 0.L)\n    k += a31 (ac);\n  if (a32 (ac) < 0.L)\n    k += a32 (ac);\n  if (a40 (ac) < 0.L)\n    k += a40 (ac);\n  if (a41 (ac) < 0.L)\n    k += a41 (ac);\n  if (a42 (ac) < 0.L)\n    k += a42 (ac);\n  if (a43 (ac) < 0.L)\n    k += a43 (ac);\n  if (a50 (ac) < 0.L)\n    k += a50 (ac);\n  if (a51 (ac) < 0.L)\n    k += a51 (ac);\n  if (a52 (ac) < 0.L)\n    k += a52 (ac);\n  if (a53 (ac) < 0.L)\n    k += a53 (ac);\n  if (a54 (ac) < 0.L)\n    k += a54 (ac);\n  if (a60 (ac) < 0.L)\n    k += a60 (ac);\n  if (a61 (ac) < 0.L)\n    k += a61 (ac);\n  if (a62 (ac) < 0.L)\n    k += a62 (ac);\n  if (a63 (ac) < 0.L)\n    k += a63 (ac);\n  if (a64 (ac) < 0.L)\n    k += a64 (ac);\n  if (a65 (ac) < 0.L)\n    k += a65 (ac);\n  if (k < 0.L)\n    {\n      k = 20.L - k;\n      goto end;\n    }\n  k = fminl (0.L, c20 (ac));\n  if (c21 (ac) < 0.L)\n    k += c21 (ac);\n  if (c30 (ac) < 0.L)\n    k += c30 (ac);\n  if (c31 (ac) < 0.L)\n    k += c31 (ac);\n  if (c32 (ac) < 0.L)\n    k += c32 (ac);\n  if (c40 (ac) < 0.L)\n    k += c40 (ac);\n  if (c41 (ac) < 0.L)\n    k += c41 (ac);\n  if (c42 (ac) < 0.L)\n    k += c42 (ac);\n  if (c43 (ac) < 0.L)\n    k += c43 (ac);\n  if (c50 (ac) < 0.L)\n    k += c50 (ac);\n  if (c51 (ac) < 0.L)\n    k += c51 (ac);\n  if (c52 (ac) < 0.L)\n    k += c52 (ac);\n  if (c53 (ac) < 0.L)\n    k += c53 (ac);\n  if (c54 (ac) < 0.L)\n    k += c54 (ac);\n  if (c60 (ac) < 0.L)\n    k += c60 (ac);\n  if (c61 (ac) < 0.L)\n    k += c61 (ac);\n  if (c62 (ac) < 0.L)\n    k += c62 (ac);\n  if (c63 (ac) < 0.L)\n    k += c63 (ac);\n  if (c64 (ac) < 0.L)\n    k += c64 (ac);\n  if (c65 (ac) < 0.L)\n    k += c65 (ac);\n  if (k < 0.L)\n    {\n      k = 10.L - k;\n      goto end;\n    }\n  k = 1.L / rk_cfl_6 (tb, ac);\nend:\n#if DEBUG_RK\n  fprintf (stderr, \"rk_objective ac_6: objective=%Lg\\n\", k);\n  fprintf (stderr, \"rk_objective ac_6: end\\n\");\n#endif\n  return k;\n}\n\n/**\n * Function to init required variables on a RK struct data.\n */\nstatic inline void\nrk_init (RK * rk,               ///< RK struct.\n         gsl_rng * rng,         ///< GSL pseudo-random number generator struct.\n         unsigned int thread)   ///< thread number.\n{\n  optimize_init (rk->tb, rng, thread);\n  if (rk->strong)\n    optimize_init (rk->ac0, rng, 0);\n}\n\n/**\n * Function to free the memory allocated by a RK struct.\n */\nstatic inline void\nrk_delete (RK * rk)             ///< RK struct.\n{\n  if (rk->strong)\n    optimize_delete (rk->ac0);\n  optimize_delete (rk->tb);\n}\n\n/**\n * Function to perform every optimization step for the a-c Runge-Kutta \n * coefficients.\n */\nstatic inline void\nrk_step_ac (RK * rk)            ///< RK struct.\n{\n  Optimize *tb, *ac;\n  long double *is, *vo, *vo2;\n  long double o, o2, v, f;\n  unsigned long long int ii, nsimulations;\n  unsigned int i, j, k, n, nfree;\n\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_ac: start\\n\");\n#endif\n\n  // save optimal values\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_ac: save optimal values\\n\");\n#endif\n  tb = rk->tb;\n  ac = rk->ac;\n  nfree = ac->nfree;\n  o2 = INFINITY;\n  vo = (long double *) alloca (nfree * sizeof (long double));\n  vo2 = (long double *) alloca (nfree * sizeof (long double));\n  memcpy (vo, ac->value_optimal, nfree * sizeof (long double));\n\n  // optimzation algorithm sampling\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_ac: optimization algorithm sampling\\n\");\n  fprintf (stderr, \"rk_step_ac: nsimulations=%Lu nclimbings=%u nfree=%u\\n\",\n           ac->nsimulations, ac->nclimbings, ac->nfree);\n#endif\n  nsimulations = ac->nsimulations;\n  for (ii = 0L; ii < nsimulations; ++ii)\n    {\n\n      // random freedom degrees\n#if DEBUG_RK\n      fprintf (stderr, \"rk_step_ac: random freedom degrees\\n\");\n#endif\n      optimize_generate_freedom (ac, ii);\n\n      // method coefficients\n#if DEBUG_RK\n      fprintf (stderr, \"rk_step_ac: method coefficients\\n\");\n#endif\n      if (!ac->method ((Optimize *) rk))\n        o = INFINITY;\n      else\n        o = ac->objective ((Optimize *) rk);\n#if DEBUG_RK\n      fprintf (stderr, \"rk_step_ac: objective=%Lg o2=%Lg\\n\", o, o2);\n#endif\n      if (o < o2)\n        {\n          o2 = o;\n          memcpy (vo, ac->random_data, nfree * sizeof (long double));\n        }\n      if (file_variables)\n        {\n          g_mutex_lock (mutex);\n          print_variables (tb->random_data, tb->nfree, file_variables);\n          print_variables (ac->random_data, nfree, file_variables);\n          fprintf (file_variables, \"%.19Le\\n\", o);\n          g_mutex_unlock (mutex);\n        }\n    }\n\n  // array of intervals to climb around the optimal\n#if DEBUG_RK\n  fprintf (stderr,\n           \"rk_step_ac: array of intervals to climb around the optimal\\n\");\n  fprintf (stderr, \"rk_step_ac: nclimbings=%u climbing_factor=%Lg\\n\",\n           ac->nclimbings, ac->climbing_factor);\n#endif\n  is = (long double *) alloca (nfree * sizeof (long double));\n  for (j = 0; j < nfree; ++j)\n    is[j] = ac->interval0[j] * ac->climbing_factor;\n#if DEBUG_RK\n  for (j = 0; j < nfree; ++j)\n    fprintf (stderr, \"rk_step_ac: i=%u is=%Lg\\n\", j, is[j]);\n#endif\n\n  // hill climbing algorithm bucle\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_ac: hill climbing algorithm bucle\\n\");\n#endif\n  memcpy (vo2, vo, nfree * sizeof (long double));\n  memcpy (ac->random_data, vo, nfree * sizeof (long double));\n  n = ac->nclimbings;\n  for (i = 0; i < n; ++i)\n    {\n#if DEBUG_RK\n      for (j = 0; j < nfree; ++j)\n        fprintf (stderr, \"rk_step_ac: j=%u is=%Lg\\n\", j, is[j]);\n#endif\n      for (j = k = 0; j < nfree; ++j)\n        {\n          v = vo[j];\n          ac->random_data[j] = v + is[j];\n#if DEBUG_RK\n          fprintf (stderr, \"rk_step_ac: j=%u random=%Lg\\n\", j,\n                   ac->random_data[j]);\n#endif\n          if (!ac->method ((Optimize *) rk))\n            o = INFINITY;\n          else\n            o = ac->objective ((Optimize *) rk);\n#if DEBUG_RK\n          fprintf (stderr, \"rk_step_ac: k=%u objective=%Lg o2=%Lg\\n\", k, o, o2);\n#endif\n          if (o < o2)\n            {\n              k = 1;\n              o2 = o;\n              memcpy (vo2, ac->random_data, nfree * sizeof (long double));\n            }\n          if (file_variables)\n            {\n              g_mutex_lock (mutex);\n              print_variables (tb->random_data, tb->nfree, file_variables);\n              print_variables (ac->random_data, nfree, file_variables);\n              fprintf (file_variables, \"%.19Le\\n\", o);\n              g_mutex_unlock (mutex);\n            }\n          ac->random_data[j] = fmaxl (0.L, v - is[j]);\n          if (!ac->method ((Optimize *) rk))\n            o = INFINITY;\n          else\n            o = ac->objective ((Optimize *) rk);\n#if DEBUG_RK\n          fprintf (stderr, \"rk_step_ac: k=%u objective=%Lg o2=%Lg\\n\", k, o, o2);\n#endif\n          if (o < o2)\n            {\n              k = 1;\n              o2 = o;\n              memcpy (vo2, ac->random_data, nfree * sizeof (long double));\n            }\n          if (file_variables)\n            {\n              g_mutex_lock (mutex);\n              print_variables (tb->random_data, tb->nfree, file_variables);\n              print_variables (ac->random_data, nfree, file_variables);\n              fprintf (file_variables, \"%.19Le\\n\", o);\n              g_mutex_unlock (mutex);\n            }\n          ac->random_data[j] = v;\n        }\n\n\n      // update optimal values and increase or reduce intervals if converging or\n      // not\n      if (!k)\n        f = 0.5L;\n      else\n        {\n          f = 1.2L;\n          memcpy (vo, vo2, nfree * sizeof (long double));\n        }\n      for (j = 0; j < nfree; ++j)\n        is[j] *= f;\n    }\n\n  // update optimal values\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_ac: update optimal values\\n\");\n  fprintf (stderr, \"rk_step_ac: optimal=%Lg o2=%Lg\\n\", *ac->optimal, o2);\n#endif\n  if (o2 < *ac->optimal)\n    {\n      *ac->optimal = o2;\n      memcpy (ac->value_optimal, vo2, nfree * sizeof (long double));\n    }\n\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_ac: end\\n\");\n#endif\n}\n\n/**\n * Function to do the optimization bucle for the a-c Runge-Kutta coefficients.\n */\nvoid\nrk_bucle_ac (RK * rk)           ///< RK struct.\n{\n  Optimize *tb, *ac, *ac0;\n  long double *vo;\n  long double optimal;\n  unsigned int i, nfree;\n\n#if DEBUG_RK\n  fprintf (stderr, \"rk_bucle_ac: start\\n\");\n#endif\n\n  tb = rk->tb;\n  ac = rk->ac;\n  ac0 = rk->ac0;\n  nfree = ac0->nfree;\n  vo = (long double *) alloca (nfree * sizeof (long double));\n\n  // Init some parameters\n#if DEBUG_RK\n  fprintf (stderr, \"rk_bucle_ac: nfree=%u optimal=%Lg\\n\", nfree, *tb->optimal);\n#endif\n  *ac0->optimal = optimal = *tb->optimal;\n  for (i = 0; i < nfree; ++i)\n    vo[i] = ac0->minimum[i] + 0.5L * ac0->interval[i];\n  memcpy (ac, ac0, sizeof (Optimize));\n  ac->optimal = &optimal;\n  ac->value_optimal = vo;\n  optimize_init (ac, ac0->rng, 0);\n#if DEBUG_RK\n  for (i = 0; i < tb->nfree; ++i)\n    fprintf (stderr, \"rk_bucle_ac: i=%u random=%Lg\\n\", i, tb->random_data[i]);\n  for (i = 0; i < nfree; ++i)\n    fprintf (stderr, \"rk_bucle_ac: i=%u minimum=%Lg interval=%Lg type=%u\\n\",\n             i, ac->minimum[i], ac->interval[i], ac->random_type[i]);\n#endif\n\n  // Iterate\n#if DEBUG_RK\n  fprintf (stderr, \"rk_bucle_ac: iterate\\n\");\n#endif\n  for (i = 0; i < ac->niterations; ++i)\n    {\n\n      // Optimization step\n      rk_step_ac (rk);\n\n      // Updating coefficient intervals to converge\n      optimize_converge (ac);\n\n      // Iterate\n#if DEBUG_RK\n      fprintf (stderr, \"Iteration ac %u\\n\", i);\n#endif\n    }\n\n  // Check and save optimal\n  if (optimal < *ac0->optimal)\n    {\n#if DEBUG_RK\n      fprintf (stderr, \"rk_bucle_ac: optimal=%Lg\\n\", *ac0->optimal);\n#endif\n      g_mutex_lock (mutex);\n      *ac0->optimal = optimal;\n      memcpy (ac0->value_optimal, vo, nfree * sizeof (long double));\n      g_mutex_unlock (mutex);\n#if DEBUG_RK\n      fprintf (stderr, \"rk_bucle_ac: optimal=%Lg\\n\", *ac0->optimal);\n      for (i = 0; i < ac0->nfree; ++i)\n        fprintf (stderr, \"rk_bucle_ac: vo%u=%Lg\\n\", i, ac0->value_optimal[i]);\n#endif\n    }\n\n  // Free memory\n  optimize_delete (ac);\n\n#if DEBUG_RK\n  fprintf (stderr, \"rk_bucle_ac: end\\n\");\n#endif\n}\n\n/**\n * Function to perform every optimization step for the t-b Runge-Kutta \n * coefficients.\n */\nstatic inline void\nrk_step_tb (RK * rk)            ///< RK struct.\n{\n  Optimize *tb;\n  long double *is, *vo;\n  long double o, v, f;\n  unsigned long long int ii, nrandom;\n  unsigned int b, i, j, k, n, nfree;\n\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_tb: start\\n\");\n#endif\n\n  // save optimal values\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_tb: save optimal values\\n\");\n#endif\n  tb = rk->tb;\n  nfree = tb->nfree;\n  vo = (long double *) alloca (nfree * sizeof (long double));\n  b = (file_variables && !rk->strong) ? 1 : 0;\n\n  // optimization algorithm sampling\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_tb: optimization algorithm sampling\\n\");\n  fprintf (stderr, \"rk_step_tb: nsimulations=%Lu nclimbings=%u\\n\",\n           tb->nsimulations, tb->nclimbings);\n#endif\n  ii = tb->nsimulations * (rank * nthreads + tb->thread) / (nnodes * nthreads);\n  nrandom = tb->nsimulations * (rank * nthreads + tb->thread + 1)\n    / (nnodes * nthreads);\n  for (; ii < nrandom; ++ii)\n    {\n\n      // random freedom degrees\n#if DEBUG_RK\n      fprintf (stderr, \"rk_step_tb: random freedom degrees\\n\");\n#endif\n      optimize_generate_freedom (tb, ii);\n\n      // method coefficients\n#if DEBUG_RK\n      fprintf (stderr, \"rk_step_tb: method coefficients\\n\");\n#endif\n      if (!tb->method (tb))\n        o = INFINITY;\n      else\n        o = tb->objective (tb);\n      if (o < *tb->optimal)\n        {\n          g_mutex_lock (mutex);\n          *tb->optimal = o;\n          memcpy (tb->value_optimal, tb->random_data,\n                  nfree * sizeof (long double));\n          g_mutex_unlock (mutex);\n        }\n      if (b)\n        {\n          g_mutex_lock (mutex);\n          print_variables (tb->random_data, nfree, file_variables);\n          fprintf (file_variables, \"%.19Le\\n\", o);\n          g_mutex_unlock (mutex);\n        }\n    }\n\n  // array of intervals to climb around the optimal\n#if DEBUG_RK\n  fprintf (stderr,\n           \"rk_step_tb: array of intervals to climb around the optimal\\n\");\n#endif\n  is = (long double *) alloca (nfree * sizeof (long double));\n  for (j = 0; j < nfree; ++j)\n    is[j] = tb->interval0[j] * tb->climbing_factor;\n\n  // hill climbing algorithm bucle\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_tb: hill climbing algorithm bucle\\n\");\n#endif\n  memcpy (tb->random_data, tb->value_optimal, nfree * sizeof (long double));\n  memcpy (vo, tb->value_optimal, nfree * sizeof (long double));\n  n = tb->nclimbings;\n  for (i = 0; i < n; ++i)\n    {\n      for (j = k = 0; j < nfree; ++j)\n        {\n          v = vo[j];\n          tb->random_data[j] = v + is[j];\n          if (!tb->method (tb))\n            o = INFINITY;\n          else\n            o = tb->objective (tb);\n          if (o < *tb->optimal)\n            {\n              k = 1;\n              g_mutex_lock (mutex);\n              *tb->optimal = o;\n              memcpy (tb->value_optimal, tb->random_data,\n                      nfree * sizeof (long double));\n              g_mutex_unlock (mutex);\n            }\n          if (b)\n            {\n              g_mutex_lock (mutex);\n              print_variables (tb->random_data, nfree, file_variables);\n              fprintf (file_variables, \"%.19Le\\n\", o);\n              g_mutex_unlock (mutex);\n            }\n          tb->random_data[j] = fmaxl (0.L, v - is[j]);\n          if (!tb->method (tb))\n            o = INFINITY;\n          else\n            o = tb->objective (tb);\n          if (o < *tb->optimal)\n            {\n              k = 1;\n              g_mutex_lock (mutex);\n              *tb->optimal = o;\n              memcpy (tb->value_optimal, tb->random_data,\n                      nfree * sizeof (long double));\n              g_mutex_unlock (mutex);\n            }\n          if (b)\n            {\n              g_mutex_lock (mutex);\n              print_variables (tb->random_data, nfree, file_variables);\n              fprintf (file_variables, \"%.19Le\\n\", o);\n              g_mutex_unlock (mutex);\n            }\n          tb->random_data[j] = v;\n        }\n\n      // increase or reduce intervals if converging or not\n      if (!k)\n        f = 0.5L;\n      else\n        {\n          f = 1.2L;\n          memcpy (vo, tb->value_optimal, nfree * sizeof (long double));\n        }\n      for (j = 0; j < nfree; ++j)\n        is[j] *= f;\n    }\n#if DEBUG_RK\n  fprintf (stderr, \"rk_step_tb: end\\n\");\n#endif\n}\n\n/**\n * Function to do the optimization bucle.\n */\nstatic inline void\nrk_bucle_tb (RK * rk)           ///< RK struct.\n{\n  GThread *thread[nthreads];\n  Optimize *tb, *ac;\n#if HAVE_MPI\n  long double *vo;\n  MPI_Status status;\n#endif\n  unsigned int i, j, nfree, nfree2, strong;\n\n#if DEBUG_RK\n  fprintf (stderr, \"rk_bucle_tb: start\\n\");\n#endif\n\n  // Allocate local array of optimal values\n#if DEBUG_RK\n  fprintf (stderr, \"rk_bucle_tb: allocate local array of optimal values\\n\");\n#endif\n  tb = rk->tb;\n  nfree = tb->nfree;\n  strong = rk->strong;\n  if (strong)\n    {\n      ac = rk->ac0;\n      nfree2 = ac->nfree;\n    }\n  else\n    nfree2 = 0;\n#if HAVE_MPI\n  vo = (long double *) alloca ((1 + nfree + nfree2) * sizeof (long double));\n#endif\n\n  // Init some parameters\n#if DEBUG_RK\n  fprintf (stderr, \"rk_bucle_tb: init some parameters\\n\");\n  fprintf (stderr, \"rk_bucle_tb: nfree=%u\\n\", nfree);\n#endif\n  *tb->optimal = INFINITY;\n  for (i = 0; i < nfree; ++i)\n    tb->value_optimal[i] = tb->minimum[i] + 0.5L * tb->interval[i];\n  if (strong)\n    for (i = 0; i < nfree2; ++i)\n      ac->value_optimal[i] = ac->minimum[i] + 0.5L * ac->interval[i];\n\n  // Iterate\n#if DEBUG_RK\n  fprintf (stderr, \"rk_bucle_tb: iterate\\n\");\n#endif\n  for (i = 0; i < tb->niterations; ++i)\n    {\n\n      // Optimization step parallelized for every node by GThreads\n      if (nthreads > 1)\n        {\n          for (j = 0; j < nthreads; ++j)\n            thread[j]\n              = g_thread_new (NULL,\n                              (GThreadFunc) (void (*)(void)) rk_step_tb,\n                              (void *) (rk + j));\n          for (j = 0; j < nthreads; ++j)\n            g_thread_join (thread[j]);\n        }\n      else\n        rk_step_tb (rk);\n\n#if HAVE_MPI\n      if (rank > 0)\n        {\n\n          // Secondary nodes send the optimal coefficients to the master node\n          vo[0] = *tb->optimal;\n          memcpy (vo + 1, tb->value_optimal, nfree * sizeof (long double));\n          if (strong)\n            memcpy (vo + 1 + nfree, ac->value_optimal,\n                    nfree2 * sizeof (long double));\n          MPI_Send (vo, 1 + nfree + nfree2, MPI_LONG_DOUBLE, 0, 1,\n                    MPI_COMM_WORLD);\n\n          // Secondary nodes receive the optimal coefficients\n          MPI_Recv (vo, 1 + nfree + nfree2, MPI_LONG_DOUBLE, 0, 1,\n                    MPI_COMM_WORLD, &status);\n          *tb->optimal = *ac->optimal = vo[0];\n          memcpy (tb->value_optimal, vo + 1, nfree * sizeof (long double));\n          if (strong)\n            memcpy (ac->value_optimal, vo + 1 + nfree,\n                    nfree2 * sizeof (long double));\n        }\n      else\n        {\n          printf (\"rank=%d optimal=%.19Le\\n\", rank, *tb->optimal);\n\n          for (j = 1; j < nnodes; ++j)\n            {\n\n              // Master node receives the optimal coefficients obtained by\n              // secondary nodes\n              MPI_Recv (vo, 1 + nfree + nfree2, MPI_LONG_DOUBLE, j, 1,\n                        MPI_COMM_WORLD, &status);\n\n              // Master node selects the optimal coefficients\n              if (vo[0] < *tb->optimal)\n                {\n                  *tb->optimal = *ac->optimal = vo[0];\n                  memcpy (tb->value_optimal, vo + 1,\n                          nfree * sizeof (long double));\n                  if (strong)\n                    memcpy (ac->value_optimal, vo + 1 + nfree,\n                            nfree2 * sizeof (long double));\n                }\n            }\n\n          // Master node sends the optimal coefficients to secondary nodes\n          vo[0] = *tb->optimal;\n          memcpy (vo + 1, tb->value_optimal, nfree * sizeof (long double));\n          if (strong)\n            memcpy (vo + 1 + nfree, ac->value_optimal,\n                    nfree2 * sizeof (long double));\n          for (j = 1; j < nnodes; ++i)\n            MPI_Send (vo, 1 + nfree + nfree2, MPI_LONG_DOUBLE, j, 1,\n                      MPI_COMM_WORLD);\n        }\n\n#endif\n\n      // Print the optimal coefficients\n#if DEBUG_RK\n      optimize_print_random (tb, stderr);\n      if (strong)\n        optimize_print_random (ac, stderr);\n      fprintf (stderr, \"optimal=%.19Le\\n\", *tb->optimal);\n#endif\n\n      // Updating coefficient intervals to converge\n      optimize_converge (tb);\n\n      // Iterate\n      printf (\"Iteration %u Optimal %.19Le\\n\", i, *tb->optimal);\n    }\n\n#if DEBUG_RK\n  fprintf (stderr, \"rk_bucle_tb: end\\n\");\n#endif\n}\n\n/**\n * Function to select the Runge-Kutta method.\n *\n * \\return 1 on success, 0 on error.\n */\nstatic inline int\nrk_select (RK * rk,             ///< RK struct.\n           unsigned int nsteps, ///< steps number.\n           unsigned int order)  ///< accuracy order.\n{\n  static int (*tb_method[7][6]) (Optimize *) =\n  {\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_2_2, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_3_2, &rk_tb_3_3, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_4_2, &rk_tb_4_3, &rk_tb_4_4, NULL},\n    {\n    NULL, NULL, &rk_tb_5_2, &rk_tb_5_3, &rk_tb_5_4, NULL},\n    {\n    NULL, NULL, &rk_tb_6_2, &rk_tb_6_3, &rk_tb_6_4, NULL}\n  };\n  static int (*tb_method_t[7][6]) (Optimize *) =\n  {\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_2_2t, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_3_2t, &rk_tb_3_3t, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_4_2t, &rk_tb_4_3t, &rk_tb_4_4t, NULL},\n    {\n    NULL, NULL, &rk_tb_5_2t, &rk_tb_5_3t, &rk_tb_5_4t, NULL},\n    {\n    NULL, NULL, &rk_tb_6_2t, &rk_tb_6_3t, &rk_tb_6_4t, NULL}\n  };\n  static int (*tb_method_p[7][6]) (Optimize *) =\n  {\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_2_2p, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_3_2p, &rk_tb_3_3p, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_4_2p, &rk_tb_4_3p, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_5_2p, &rk_tb_5_3p, &rk_tb_5_4p, NULL},\n    {\n    NULL, NULL, &rk_tb_6_2p, &rk_tb_6_3p, &rk_tb_6_4p, NULL}\n  };\n  static int (*tb_method_tp[7][6]) (Optimize *) =\n  {\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_2_2tp, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_3_2tp, &rk_tb_3_3tp, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_4_2tp, &rk_tb_4_3tp, NULL, NULL},\n    {\n    NULL, NULL, &rk_tb_5_2tp, &rk_tb_5_3tp, &rk_tb_5_4tp, NULL},\n    {\n    NULL, NULL, &rk_tb_6_2tp, &rk_tb_6_3tp, &rk_tb_6_4tp, NULL}\n  };\n  static long double (*tb_objective[7][6]) (RK *) =\n  {\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_2_2, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_2_2, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_3_2, &rk_objective_tb_3_3, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_4_2, &rk_objective_tb_4_3,\n        &rk_objective_tb_4_4, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_5_2, &rk_objective_tb_5_3,\n        &rk_objective_tb_5_4, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_6_2, &rk_objective_tb_6_3,\n        &rk_objective_tb_6_4, NULL}\n  };\n  static long double (*tb_objective_t[7][6]) (RK *) =\n  {\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_2_2t, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_2_2t, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_3_2t, &rk_objective_tb_3_3t, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_4_2t, &rk_objective_tb_4_3t,\n        &rk_objective_tb_4_4t, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_5_2t, &rk_objective_tb_5_3t,\n        &rk_objective_tb_5_4t, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_6_2t, &rk_objective_tb_6_3t,\n        &rk_objective_tb_6_4t, NULL}\n  };\n  static long double (*tb_objective_p[7][6]) (RK *) =\n  {\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_2_2, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_3_2, &rk_objective_tb_3_3p, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_4_2, &rk_objective_tb_4_3p, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_5_2, &rk_objective_tb_5_3p,\n        &rk_objective_tb_5_4p, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_6_2, &rk_objective_tb_6_3p,\n        &rk_objective_tb_6_4p, NULL}\n  };\n  static long double (*tb_objective_tp[7][6]) (RK *) =\n  {\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_2_2t, NULL, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_3_2t, &rk_objective_tb_3_3tp, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_4_2t, &rk_objective_tb_4_3tp, NULL, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_5_2t, &rk_objective_tb_5_3tp,\n        &rk_objective_tb_5_4tp, NULL},\n    {\n    NULL, NULL, &rk_objective_tb_6_2t, &rk_objective_tb_6_3tp,\n        &rk_objective_tb_6_4tp, NULL}\n  };\n  static int (*ac_method[7]) (RK *) =\n  {\n  NULL, NULL, &rk_ac_2, &rk_ac_3, &rk_ac_4, &rk_ac_5, &rk_ac_6};\n  static long double (*ac_objective[7]) (RK * rk) =\n  {\n  NULL, NULL, &rk_objective_ac_2, &rk_objective_ac_3, &rk_objective_ac_4,\n      &rk_objective_ac_5, &rk_objective_ac_6};\n  const unsigned int nequations[6] = { 0, 1, 2, 4, 8, 16 };\n  Optimize *tb, *ac;\n#if DEBUG_RK\n  fprintf (stderr, \"rk_select: start\\n\");\n#endif\n  tb = rk->tb;\n  ac = rk->ac;\n  tb->nsteps = nsteps;\n  tb->order = order;\n  tb->size = nsteps * (nsteps + 3) / 2 - 1;\n  tb->nfree = tb->size - nsteps + 1 - nequations[order];\n  if (rk->pair)\n    {\n      tb->size += nsteps - 1;\n      if (rk->time_accuracy)\n        {\n          tb->method = tb_method_tp[nsteps][order];\n          tb->objective = (OptimizeObjective) tb_objective_tp[nsteps][order];\n        }\n      else\n        {\n          tb->method = tb_method_p[nsteps][order];\n          tb->objective = (OptimizeObjective) tb_objective_p[nsteps][order];\n        }\n    }\n  else\n    {\n      if (rk->time_accuracy)\n        {\n          tb->method = tb_method_t[nsteps][order];\n          tb->objective = (OptimizeObjective) tb_objective_t[nsteps][order];\n        }\n      else\n        {\n          tb->method = tb_method[nsteps][order];\n          tb->objective = (OptimizeObjective) tb_objective[nsteps][order];\n        }\n    }\n  if (!tb->method)\n    goto exit_on_error;\n  if (rk->time_accuracy)\n    {\n      --tb->nfree;\n      if (rk->pair)\n        switch (nsteps)\n          {\n          case 5:\n            switch (order)\n              {\n              case 4:\n                --tb->nfree;\n              }\n            break;\n          case 6:\n            switch (order)\n              {\n              case 4:\n                --tb->nfree;\n              }\n            break;\n          }\n    }\n  tb->minimum0\n    = (long double *) g_slice_alloc (tb->nfree * sizeof (long double));\n  tb->interval0\n    = (long double *) g_slice_alloc (tb->nfree * sizeof (long double));\n  tb->random_type\n    = (unsigned int *) g_slice_alloc (tb->nfree * sizeof (unsigned int));\n  if (rk->strong)\n    {\n      ac = rk->ac0;\n      ac->size = nsteps * (nsteps + 1) - 2;\n      ac->nfree = nsteps * (nsteps - 1) / 2;\n      ac->minimum0\n        = (long double *) g_slice_alloc (ac->nfree * sizeof (long double));\n      ac->interval0\n        = (long double *) g_slice_alloc (ac->nfree * sizeof (long double));\n      ac->random_type\n        = (unsigned int *) g_slice_alloc (ac->nfree * sizeof (unsigned int));\n      ac->method = (OptimizeMethod) ac_method[nsteps];\n      if (!ac->method)\n        goto exit_on_error;\n      ac->objective = (OptimizeObjective) ac_objective[nsteps];\n    }\n\n#if DEBUG_RK\n  fprintf (stderr, \"rk_select: end\\n\");\n#endif\n  return 1;\n\nexit_on_error:\n  error_message = g_strdup (_(\"Unknown method\"));\n#if DEBUG_RK\n  fprintf (stderr, \"rk_select: end\\n\");\n#endif\n  return 0;\n}\n\n/**\n * Function to read the Runge-Kutta method data on a XML node.\n *\n * \\return 1 on success, 0 on error.\n */\nint\nrk_run (xmlNode * node,         ///< XML node.\n        gsl_rng ** rng)         ///< array of gsl_rng structs.\n{\n  RK rk[nthreads];\n  char filename[64];\n  Optimize *tb, *ac;\n  gchar *buffer;\n  xmlChar *prop;\n  FILE *file;\n  long double *value_optimal, *value_optimal2;\n  long double optimal, optimal2;\n  int code;\n  unsigned int i, j, nsteps, order, nfree, nfree2;\n\n#if DEBUG_RK\n  fprintf (stderr, \"rk_run: start\\n\");\n#endif\n\n  tb = rk->tb;\n  nsteps = xml_node_get_uint (node, XML_STEPS, &code);\n  if (code)\n    {\n      error_message = g_strdup (_(\"Bad steps number\"));\n      goto exit_on_error;\n    }\n  order = xml_node_get_uint (node, XML_ORDER, &code);\n  if (code)\n    {\n      error_message = g_strdup (_(\"Bad order\"));\n      goto exit_on_error;\n    }\n  prop = xmlGetProp (node, XML_STRONG);\n  if (!prop || !xmlStrcmp (prop, XML_NO))\n    rk->strong = 0;\n  else if (!xmlStrcmp (prop, XML_YES))\n    rk->strong = 1;\n  else\n    {\n      error_message = g_strdup (_(\"Bad strong stability\"));\n      goto exit_on_error;\n    }\n  xmlFree (prop);\n  prop = xmlGetProp (node, XML_PAIR);\n  if (!prop || !xmlStrcmp (prop, XML_NO))\n    rk->pair = 0;\n  else if (!xmlStrcmp (prop, XML_YES))\n    rk->pair = 1;\n  else\n    {\n      error_message = g_strdup (_(\"Bad pair\"));\n      goto exit_on_error;\n    }\n  xmlFree (prop);\n  prop = xmlGetProp (node, XML_TIME_ACCURACY);\n  if (!prop || !xmlStrcmp (prop, XML_NO))\n    rk->time_accuracy = 0;\n  else if (!xmlStrcmp (prop, XML_YES))\n    rk->time_accuracy = 1;\n  else\n    {\n      error_message = g_strdup (_(\"Bad time accuracy\"));\n      goto exit_on_error;\n    }\n  xmlFree (prop);\n  if (!rk_select (rk, nsteps, order))\n    goto exit_on_error;\n  if (!optimize_read (tb, node))\n    goto exit_on_error;\n  nfree = tb->nfree;\n  value_optimal = (long double *) g_slice_alloc (nfree * sizeof (long double));\n  optimize_create (tb, &optimal, value_optimal);\n  node = node->children;\n  for (i = 0; i < nfree; ++i, node = node->next)\n    if (!read_variable (node, tb->minimum0, tb->interval0, tb->random_type, i))\n      goto exit_on_error;\n  if (rk->strong)\n    {\n      ac = rk->ac0;\n      if (!node)\n        {\n          error_message = g_strdup (_(\"No a-c coefficients data\"));\n          goto exit_on_error;\n        }\n      if (xmlStrcmp (node->name, XML_AC))\n        {\n          error_message = g_strdup (_(\"Bad a-c coefficients XML node\"));\n          goto exit_on_error;\n        }\n      if (!optimize_read (ac, node))\n        {\n          buffer = error_message;\n          error_message\n            = g_strconcat (_(\"a-c coefficients\"), \":\\n\", error_message, NULL);\n          g_free (buffer);\n          goto exit_on_error;\n        }\n      nfree2 = ac->nfree;\n      value_optimal2\n        = (long double *) g_slice_alloc (nfree2 * sizeof (long double));\n      optimize_create (ac, &optimal2, value_optimal2);\n      for (i = 0; i < nfree2; ++i)\n        {\n          node = node->next;\n          if (!read_variable (node, ac->minimum0, ac->interval0,\n                              ac->random_type, i))\n            goto exit_on_error;\n        }\n    }\n  for (i = 1; i < nthreads; ++i)\n    memcpy (rk + i, rk, sizeof (RK));\n  j = rank * nthreads;\n  for (i = 0; i < nthreads; ++i)\n    rk_init (rk + i, rng[j + i], i);\n\n  // Method bucle\n  printf (\"Optimize bucle\\n\");\n  rk_bucle_tb (rk);\n\n  // Print the optimal coefficients\n  printf (\"Print the optimal coefficients\\n\");\n  memcpy (tb->random_data, tb->value_optimal, nfree * sizeof (long double));\n  code = tb->method (tb);\n  if (rk->strong)\n    {\n      memcpy (ac->random_data, ac->value_optimal,\n              nfree2 * sizeof (long double));\n      memcpy (rk->ac, ac, sizeof (Optimize));\n      code = ac->method ((Optimize *) rk);\n    }\n  snprintf (filename, 64, \"rk-%u-%u-%u-%u-%u.mc\",\n            nsteps, order, rk->time_accuracy, rk->pair, rk->strong);\n  file = fopen (filename, \"w\");\n  print_maxima_precision (file);\n  rk_print (rk, file);\n  rk_print_maxima (file, nsteps, nsteps, order, 'b');\n  if (rk->pair)\n    rk_print_maxima (file, nsteps, nsteps - 1, order - 1, 'e');\n  if (rk->strong)\n    ac_print_maxima (file, nsteps);\n  fclose (file);\n  snprintf (filename, 64, \"sed -i 's/e+/b+/g' rk-%u-%u-%u-%u-%u.mc\",\n            nsteps, order, rk->time_accuracy, rk->pair, rk->strong);\n  code = system (filename);\n  snprintf (filename, 64, \"sed -i 's/e-/b-/g' rk-%u-%u-%u-%u-%u.mc\",\n            nsteps, order, rk->time_accuracy, rk->pair, rk->strong);\n  code = system (filename);\n\n  // Free memory\n  if (rk->strong)\n    {\n      g_slice_free1 (nfree2 * sizeof (unsigned int), ac->random_type);\n      g_slice_free1 (nfree2 * sizeof (long double), ac->interval0);\n      g_slice_free1 (nfree2 * sizeof (long double), ac->minimum0);\n      g_slice_free1 (nfree2 * sizeof (long double), value_optimal2);\n    }\n  for (i = 0; i < nthreads; ++i)\n    rk_delete (rk + i);\n  g_slice_free1 (nfree * sizeof (unsigned int), tb->random_type);\n  g_slice_free1 (nfree * sizeof (long double), tb->interval0);\n  g_slice_free1 (nfree * sizeof (long double), tb->minimum0);\n  g_slice_free1 (nfree * sizeof (long double), value_optimal);\n\n\n#if DEBUG_RK\n  fprintf (stderr, \"rk_run: end\\n\");\n#endif\n  return 1;\n\nexit_on_error:\n  buffer = error_message;\n  error_message = g_strconcat (\"Runge-Kutta:\\n\", buffer, NULL);\n  g_free (buffer);\n#if DEBUG_RK\n  fprintf (stderr, \"rk_run: end\\n\");\n#endif\n  return 0;\n}\n", "meta": {"hexsha": "a1b461ac2cdef278333faf9bc25f1ba8cbd318a8", "size": 54651, "ext": "c", "lang": "C", "max_stars_repo_path": "rk.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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": "rk.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9116445352, "max_line_length": 80, "alphanum_fraction": 0.538764158, "num_tokens": 19362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.36923303623853154}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <mpi.h>\n#include <cblas.h>\n#include \"utils.h\"\n\n#ifndef MATRIX_SIZE\n#define MATRIX_SIZE 128\n#pragma message \"Using default matrix size\"\n#endif\n#define MIN_BUFF_SIZE MATRIX_SIZE*MATRIX_SIZE*sizeof(double)\n#ifndef REUSE_BUFFER\n#define REUSE_BUFFER 1\n#endif\n#if REUSE_BUFFER\n#pragma message \"Using the same buffers for communications and computations\"\n#else\n#pragma message \"Using different buffers for communications and computations\"\n#endif\n#define MAX_NAME_SIZE 100\n#define NB_RUNS 10\n\nstatic void *my_send_buffer;\nstatic void *my_recv_buffer;\nstatic void *aux_buffer;\nstatic double *matrix_A, *matrix_B, *matrix_C;\nstatic int op_id = 0;\n\n\nFILE *open_file(const char *dir_name, const char *file_prefix){\n    char* filename= malloc(MAX_NAME_SIZE*sizeof(char));\n    int my_rank;\n    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);\n    sprintf(filename, \"%s/%s_%d.csv\", dir_name, file_prefix, my_rank);\n    FILE *file = fopen(filename, \"w\");\n    if(!file) {\n        perror(\"open_file\");\n        fprintf(stderr, \"Maybe directory %s does not exist?\\n\", dir_name);\n        exit(errno);\n    }\n    free(filename);\n    MPI_Barrier(MPI_COMM_WORLD);\n    return file;\n}\n\n\nvoid send_msg(int size, int dst, FILE *file, int args[], int nb_args, unsigned long long base_time) {\n    unsigned long long start_time=get_time();\n    MPI_Send(my_send_buffer, size, MPI_CHAR, dst, 0, MPI_COMM_WORLD);\n    unsigned long long total_time=get_time()-start_time;\n    print_in_file(file, \"MPI_Send\", args, nb_args, start_time-base_time, total_time);\n}\n\nvoid recv_msg(int size, int src, FILE *file, int args[], int nb_args, unsigned long long base_time, int busy_waiting) {\n    int flag = 0;\n    // Meanwhile we are waiting for a message to be there, we call dgemm\n    while(busy_waiting & !flag) {\n        cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, MATRIX_SIZE, MATRIX_SIZE, MATRIX_SIZE, 1., matrix_A,\n                MATRIX_SIZE, matrix_B, MATRIX_SIZE, 1., matrix_C, MATRIX_SIZE);\n        MPI_Iprobe(src, 0, MPI_COMM_WORLD, &flag, MPI_STATUS_IGNORE);\n    }\n    unsigned long long start_time=get_time();\n    MPI_Recv(my_recv_buffer, size, MPI_CHAR, src, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n    unsigned long long total_time=get_time()-start_time;\n    print_in_file(file, \"MPI_Recv\", args, nb_args, start_time-base_time, total_time);\n}\n\nvoid get_ring(FILE *file, int size, int nb_it, unsigned long long base_time) {\n    static int my_rank = -1;\n    static int nb_ranks = -1;\n    if(my_rank < 0) {\n        MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);\n        MPI_Comm_size(MPI_COMM_WORLD, &nb_ranks);\n    }\n    for(int i=0; i<nb_it; i++) {\n        int args[] = {my_rank, size, op_id++};\n        int recv_from = (my_rank-1+nb_ranks)%nb_ranks;\n        int send_to = (my_rank+1)%nb_ranks;\n// I am the root of the broadcast, I send\n        if(my_rank == 0) {\n            send_msg(size, send_to, file, args, sizeof(args)/sizeof(args[0]), base_time);\n        }\n// I receive\n        recv_msg(size, recv_from, file, args, sizeof(args)/sizeof(args[0]), base_time, 1);\n// I am *not* the root of the broadcast, I send\n        if(my_rank != 0) {\n            send_msg(size, send_to, file, args, sizeof(args)/sizeof(args[0]), base_time);\n        }\n    }\n}\n\nvoid get_ringrong(FILE *file, int size, int nb_it, unsigned long long base_time) {\n    static int my_rank = -1;\n    static int nb_ranks = -1;\n    if(my_rank < 0) {\n        MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);\n        MPI_Comm_size(MPI_COMM_WORLD, &nb_ranks);\n    }\n    for(int i=0; i<nb_it; i++) {\n        int args[] = {my_rank, size, op_id++};\n        int prev = (my_rank-1+nb_ranks)%nb_ranks;\n        int next = (my_rank+1)%nb_ranks;\n        if(my_rank == 0) {\n            send_msg(size, next, file, args, sizeof(args)/sizeof(args[0]), base_time);\n            recv_msg(size, next, file, args, sizeof(args)/sizeof(args[0]), base_time, 0);\n            recv_msg(size, prev, file, args, sizeof(args)/sizeof(args[0]), base_time, 1);\n            send_msg(size, prev, file, args, sizeof(args)/sizeof(args[0]), base_time);\n        }\n        else {\n            recv_msg(size, prev, file, args, sizeof(args)/sizeof(args[0]), base_time, 1);\n            send_msg(size, prev, file, args, sizeof(args)/sizeof(args[0]), base_time);\n            send_msg(size, next, file, args, sizeof(args)/sizeof(args[0]), base_time);\n            recv_msg(size, next, file, args, sizeof(args)/sizeof(args[0]), base_time, 0);\n        }\n    }\n}\n\nstatic const char *names[] = {\"Ring\", \"RingRong\", NULL};\nstatic const void (*functions[])(FILE*, int, int, unsigned long long) = {get_ring, get_ringrong};\n\nvoid test_op(FILE *result_file, experiment_t *exp, int nb_runs, unsigned long long base_time) {\n    functions[exp->op_id](result_file, exp->sizes[0], nb_runs, base_time);\n}\n\nvoid *allocate_buffer(int size) {\n    if(size < MIN_BUFF_SIZE)\n        size = MIN_BUFF_SIZE;\n    char *buffer = (void*)malloc(size);\n    if(buffer == NULL){\n        fprintf(stderr, \"Can't allocate memory (%g GB), decrease max size of the messages \\n\",\n            size*1e-9);\n        perror(\"malloc\");\n        exit(1);\n    }\n    for(int i = 0; i < size; i++) {\n        buffer[i] = rand();\n    }\n    return(buffer);\n}\n\nint main(int argc, char *argv[]) {\n    printf(\"Matrix size: %d\\n\", MATRIX_SIZE);\n    if(argc != 3) {\n        fprintf(stderr, \"Syntax: %s <input_file> <output_directory>\\n\");\n        exit(1);\n    }\n    const char *input = argv[1];\n    const char *output = argv[2];\n    MPI_Init(&argc, &argv);\n\n\n    int nb_exp, largest_size;\n    experiment_t *experiments = parse_experiment_file(names, input, &nb_exp, &largest_size, -1, (int)1e9, 1);\n    FILE *result_file = open_file(output, \"result\");\n    my_recv_buffer = allocate_buffer(largest_size);\n    my_send_buffer = allocate_buffer(largest_size);\n    aux_buffer = allocate_buffer(largest_size);\n#if REUSE_BUFFER\n    matrix_A = my_recv_buffer;\n    matrix_B = my_send_buffer;\n    matrix_C = aux_buffer;\n#else\n    matrix_A = allocate_buffer(MIN_BUFF_SIZE);\n    matrix_B = allocate_buffer(MIN_BUFF_SIZE);\n    matrix_C = allocate_buffer(MIN_BUFF_SIZE);\n#endif\n\n    MPI_Barrier(MPI_COMM_WORLD);\n    unsigned long long base_time=get_time();\n    for(int j = 0; j < nb_exp; j++) {\n        test_op(result_file, &experiments[j], NB_RUNS, base_time);\n    }\n    MPI_Finalize();\n\n    fflush(result_file);\n    fclose(result_file);\n    free(experiments);\n    free(my_recv_buffer);\n    free(my_send_buffer);\n    free(aux_buffer);\n#if REUSE_BUFFER\n#else\n    free(matrix_A);\n    free(matrix_B);\n    free(matrix_C);\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "f35ccbbf77dcadee4a30545fbf495eec29ce55e1", "size": 6610, "ext": "c", "lang": "C", "max_stars_repo_path": "src/calibration/test_ring.c", "max_stars_repo_name": "Ezibenroc/platform-calibration", "max_stars_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-06T16:12:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-06T16:12:26.000Z", "max_issues_repo_path": "src/calibration/test_ring.c", "max_issues_repo_name": "Ezibenroc/platform-calibration", "max_issues_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2022-01-13T10:44:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:50:51.000Z", "max_forks_repo_path": "src/calibration/test_ring.c", "max_forks_repo_name": "Ezibenroc/platform-calibration", "max_forks_repo_head_hexsha": "899f044658246fb86f24e4efc96489df546ad3d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-07T15:52:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-07T15:52:04.000Z", "avg_line_length": 34.7894736842, "max_line_length": 119, "alphanum_fraction": 0.658698941, "num_tokens": 1779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.36923303623853154}}
{"text": "/**************************************************************************/\n/* Common definitions for the c vader routines                            */\n/**************************************************************************/\n\n\n/**************************************************************************/\n/* General note on naming conventions: arrays without subscripts have     */\n/* indices that range from 0 to nr-1, with no ghost zones, and are cell-  */\n/* centered. Arrays with _h are edge centered and have indices that run   */\n/* from 0 to nr. Arrays with _g are cell-centered with one ghost zone,    */\n/* and have indices that go from 0 to nr+1; indices 0 and nr are the      */\n/* ghost zones.                                                           */\n/**************************************************************************/\n\n#ifndef _vader_common_h_\n#define _vader_common_h_\n\n#include <gsl/gsl_vector.h>\n#include <float.h>\n#include <stdbool.h>\n#include <time.h>\n\n/* Slope limit parameter */\n#define SLOPELIMIT  0.1\n\n/* Descriptor for a grid */\ntypedef struct {\n  unsigned long nr;            /* Number of real cells */\n  bool linear;                 /* Is this a linear or logarithmic grid? */\n  double *r_g, *r_h;           /* Cell center, edge locations */\n  double *dr_g;                /* Cell sizes / log sizes */\n  double *area;                /* Area of a zone */\n  double *vphi_g, *vphi_h;     /* Rotation curve */\n  double *beta_g, *beta_h;     /* Logarithmic index of rotation curve */\n  double *psiEff_g, *psiEff_h; /* Effective gravitational potential */\n  double *g_h;                 /* Factor appearing in derivatives */\n} grid;\n\n/* Workspace for calculations */\ntypedef struct {\n  double *pres_g, *presNew_g, *colNew, *colTmp;\n  double *alpha_g, *hint_g, *hintL_g, *hintR_g;\n  double *ppmwksp_g;\n  double *fmLast_h, *fmNew_h;\n  double *ftLast_h, *feLast_h;\n  double *massSrcLast, *massSrcNew, *intEnSrc;\n  double *eIntTmp, *eIntNew;\n  double *gammaLast, *deltaLast, *gammaNew, *deltaNew;\n  double *mSrc, *eSrc;\n  gsl_vector *ud_g, *ld_g, *diag_g, *rhs_g, *presTmp_g;\n#if AA_M > 0\n  double *colHist, *presHist, *eIntHist;\n  double *colResid, *presResid, *eIntResid;\n  gsl_vector *constraint;\n#endif\n} wksp;\n\n/* Pressure boundary condition types */\ntypedef enum { FIXED_MASS_FLUX, FIXED_TORQUE_FLUX, FIXED_TORQUE } \n  pres_bc_type;\n\n/* Enthalpy boundary condition types */\ntypedef enum { FIXED_ENTHALPY_VALUE, FIXED_ENTHALPY_GRADIENT } \n  enth_bc_type;\n\n/* IO status indicators */\ntypedef enum { GOOD_IO, IO_ERROR, ALLOCATION_ERROR } iostatus;\n\n/* Startup status indicators */\ntypedef enum { GOOD_START, RESTART_ERROR, MEMORY_ERROR, FIRST_DT_ERROR }\n  setup_status;\n\n/* Simulation status indicators */\ntypedef enum { RUNNING, NORMAL_EXIT, ZENO_ERROR, TOO_MANY_STEPS }\n  status;\n\n/* Macros used various places in code */\n#define SQR(x) ((x)*(x))\n#define LARGE DBL_MAX\n#define SMALL DBL_MIN\n\n#endif \n/* end _vader_common_h_ */\n", "meta": {"hexsha": "a1c382acf517db0bc745c09dfa9e1d7e4c6a72d6", "size": 2964, "ext": "h", "lang": "C", "max_stars_repo_path": "src/amuse/community/vader/src/vader_common.h", "max_stars_repo_name": "franciscaconcha/amuse-vader", "max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/amuse/community/vader/src/vader_common.h", "max_issues_repo_name": "franciscaconcha/amuse-vader", "max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/amuse/community/vader/src/vader_common.h", "max_forks_repo_name": "franciscaconcha/amuse-vader", "max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z", "avg_line_length": 35.2857142857, "max_line_length": 76, "alphanum_fraction": 0.5941295547, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3687284168802605}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2015 Free Software Foundation, Inc.\n *\n * This is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published\n * by the Free Software Foundation; either version 3, or (at your\n * option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; see the file COPYING.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street,\n * Boston, MA 02110-1301, USA.\n */\n\n#ifndef INCLUDED_ldpc_G_matrix_impl_H\n#define INCLUDED_ldpc_G_matrix_impl_H\n\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_blas.h>\n\n#include \"fec_mtrx_impl.h\"\n#include <gnuradio/fec/ldpc_G_matrix.h>\n#include <gnuradio/fec/ldpc_H_matrix.h>\n#include <gnuradio/logger.h>\n\nnamespace gr {\n  namespace fec {\n    namespace code {\n      /*!\n       * \\brief Class for storing H or G matrix\n       * \\ingroup error_coding_blk\n       *\n       * \\details\n       * This class stores a GSL matrix variable, specifically\n       * either a:\n       *\n       * 1) Generator matrix, G, in the standard format G = [I P],\n       *    where I is an identity matrix and P is the parity\n       *    submatrix.\n       *\n       * or\n       *\n       * 2) Parity matrix, H, in the standard format H = [P' I],\n       *    where P' is the transpose of the parity submatrix and I\n       *    is an identity matrix.\n       *\n       * This variable can used by the ldpc_gen_mtrx_encoder and\n       * ldpc_bit_flip_decoder classes.\n       */\n      class ldpc_G_matrix_impl\n        : public fec_mtrx_impl, public ldpc_G_matrix\n      {\n      private:\n        // GSL matrix structure for transpose of G\n        gsl_matrix *d_G_transp_ptr;\n\n        gsl_matrix *d_H_obj;\n\n        //! Get the generator matrix (used during encoding)\n        const gsl_matrix *G_transpose() const;\n\n        gr::logger_ptr d_logger;\n        gr::logger_ptr d_debug_logger;\n\n      public:\n        ldpc_G_matrix_impl(const std::string filename);\n\n        void encode(unsigned char *outbuffer,\n                    const unsigned char *inbuffer) const;\n\n        void decode(unsigned char *outbuffer,\n                    const float *inbuffer,\n                    unsigned int frame_size,\n                    unsigned int max_iterations) const;\n\n        unsigned int n() const { return fec_mtrx_impl::n(); }\n\n        unsigned int k() const { return fec_mtrx_impl::k(); }\n\n        gsl_matrix* generate_H();\n\n        gr::fec::code::fec_mtrx_sptr get_base_sptr();\n\n        /*!\n         * \\brief Destructor\n         * \\details\n         * Calls the gsl_matrix_free function to free memory.\n         */\n        virtual ~ldpc_G_matrix_impl();\n      };\n\n    }\n  }\n}\n\n#endif /* INCLUDED_ldpc_G_matrix_impl_H */\n", "meta": {"hexsha": "5c2c44fef15458394861268b30a91485853557a0", "size": 3087, "ext": "h", "lang": "C", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-fec/lib/ldpc_G_matrix_impl.h", "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-fec/lib/ldpc_G_matrix_impl.h", "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gnuradio-3.7.13.4/gr-fec/lib/ldpc_G_matrix_impl.h", "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4, "max_line_length": 68, "alphanum_fraction": 0.6368642695, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.36868975099657275}}
{"text": "// This is a plugin program that serves mainly as an example of how\n// analysis programs for ssv should be written, and gives people\n// something to cut and paste from.  It computes and prints histogram\n// information about the tiles it analyzes.\n\n#include <stdlib.h>\n\n#include <glib.h>\n#include <gsl/gsl_histogram.h>\n\n#include <float_image.h>\n\n// As specified in the analysis interface provided by ssv, the first\n// argument (after argv[0], the invocation name) is the number of\n// tiles being passed into the analysis plugin.  The second and\n// succeeding arguments are also as as described in the output\n// produced by 'ssv --help'.\n#define TILE_COUNT_ARGUMENT_POSITION 1\n\n// This type describes the information that we get passed for each\n// tile.\ntypedef struct {\n  GString *base_name;\n  size_t width, height;\n  GString *file_name;\n  FloatImage *tile;\n} tile_spec_type;\n\nint\nmain (int argc, char **argv)\n{\n  char *prog_name = argv[0];\n  prog_name = prog_name;   // You might use this for reporting errors.\n\n  // How many image tiles are we getting passed?\n  int tile_count = atoi (argv[TILE_COUNT_ARGUMENT_POSITION]);\n\n  // Print a string showing how we were invoked.\n  GString *invocation = g_string_new (\"\");\n  int ii;\n  for ( ii = 0 ; ii < argc ; ii++ ) {\n    g_string_append_printf (invocation, \"%s \", argv[ii]);\n  }\n  g_print (\"\\nRunning analysis program '%s'...\\n\", invocation->str);\n  g_string_free (invocation, TRUE);\n\t   \n\n  // Read the argument into an array of tile_spec_type structures.\n  GPtrArray *tile_specs = g_ptr_array_new ();\n  int current_arg = TILE_COUNT_ARGUMENT_POSITION + 1;\n  for ( ii = 0 ; ii < tile_count ; ii++ ) {\n    tile_spec_type *cs = g_new (tile_spec_type, 1); // Current spec.\n    cs->base_name = g_string_new (argv[current_arg++]);\n    cs->width = atoi (argv[current_arg++]);\n    cs->height = atoi (argv[current_arg++]);\n    cs->file_name = g_string_new (argv[current_arg++]);\n    cs->tile = float_image_new_from_file (cs->width, cs->height,\n\t\t\t\t\t  cs->file_name->str, 0,\n\t\t\t\t\t  FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN);\n    g_ptr_array_add (tile_specs, cs);\n  }\n\t  \n  g_print (\"\\nGot %d total structures to process.\\n\", tile_count);\n\n  // Compute and print histograms and other information for each tile.\n  for ( ii = 0 ; ii < tile_specs->len ; ii++ ) {\n    // Current tile spec.\n    tile_spec_type *cs = g_ptr_array_index (tile_specs, ii);\n    g_print (\"\\nTile from image %s\\n\", cs->base_name->str);\n    g_print (\"Width: %llu\\n\", (long long unsigned int) cs->width);\n    g_print (\"Height: %llu\\n\", (long long unsigned int) cs->height);\n    if ( cs->width == 0 || cs->height == 0 ) {\n      g_print (\"Tile of zero area, nothing to analyze.\\n\");\n    }\n    else {\n      g_print (\"Histogram:\\n\");\n      const size_t bin_count = 20;\n      gsl_histogram *hg = gsl_histogram_alloc (bin_count);\n      // The test data I use is from an originally byte-valued image; if\n      // you have a different sort of image a histogram covering only\n      // this data region may be pretty dull.\n      gsl_histogram_set_ranges_uniform (hg, 0.0, 255.0);\n      guint jj, kk;\n      for ( jj = 0 ; jj < cs->width ; jj++ ) {\n\tfor ( kk = 0 ; kk < cs->height ; kk++ ) {\n\t  float pv = float_image_get_pixel (cs->tile, jj, kk);\n\t  gsl_histogram_increment (hg, pv);\n\t}\n      }\n      g_print (\"  Range Start     Range End    Occurences\\n\");\n      g_print (\"-----------------------------------------\\n\");\n      gsl_histogram_fprintf (stdout, hg, \"%13.2f\", \"%13.0f\");\n      gsl_histogram_free (hg);\n    }\n    g_print (\"\\n\");\n  }\n\n  // Free the tile specifications array.\n  for ( ii = 0 ; ii < tile_specs->len ; ii++ ) {\n    tile_spec_type *cs = g_ptr_array_index (tile_specs, ii);\n    float_image_free (cs->tile);\n    g_string_free (cs->file_name, TRUE);\n    g_string_free (cs->base_name, TRUE);\n    g_free (cs);\n  }\n  g_ptr_array_free (tile_specs, TRUE);\n\n  exit (EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "4100a63328c2127c8e71d94e71e873974e2d3ef4", "size": 3885, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ssv/plugin_histogram.c", "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_issues_repo_path": "src/ssv/plugin_histogram.c", "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssv/plugin_histogram.c", "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "avg_line_length": 35.3181818182, "max_line_length": 72, "alphanum_fraction": 0.6545688546, "num_tokens": 1042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.3686789340526035}}
{"text": "/*\n *  Copyright 2014 NVIDIA 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 the ATLAS headers */\n\nextern \"C\"\n{\n#include <cblas.h>\n}\n\n/* choose precision to train and classify.  Only float and double are \n * currently suppored\n */\n\ntypedef float floatType_t;\n\n/* macro to convert 2d coords to 1d offset */\n\n#define INDX(row,col,ld) (((col) * (ld)) + (row))\n\n/* macros for max/min to combine with argmin */\n\n#define MYMAX(val,array,i,index) \\\nif( array[i] > val ) \\\n{ \\\n  val = array[i]; \\\n  index = i; \\\n} \\\n\n#define MYMIN(val,array,i,index) \\\nif( array[i] < val ) \\\n{ \\\n  val = array[i]; \\\n  index = i; \\\n} \\\n\n/* macro to clip values from min to max */\n\n#define CLIP(val,min,max) \\\nif( (val) < (min) ) val = (min); \\\nelse if( (val) > (max) ) val = (max);\n\n/* hardcoded constants for training and test set size and feature\n * vector size\n */\n\n#define FEATURE_VECTOR_SIZE (1899)\n#define TRAINING_SET_SIZE (4000)\n#define TEST_SET_SIZE (1000)\n\n/* CUDA debugging */\n\n#ifdef DEBUG\n#define CUDA_CALL(F)  if( (F) != cudaSuccess ) \\\n  {printf(\"Error %s at %s:%d\\n\", cudaGetErrorString(cudaGetLastError()), \\\n   __FILE__,__LINE__); exit(-1);}\n#define CUDA_CHECK()  if( (cudaPeekAtLastError()) != cudaSuccess ) \\\n  {printf(\"Error %s at %s:%d\\n\", cudaGetErrorString(cudaGetLastError()), \\\n   __FILE__,__LINE__-1); exit(-1);}\n#else\n#define CUDA_CALL(F) (F)\n#define CUDA_CHECK()\n#endif\n\n/* function defs */\n\nvoid readMatrixFromFile( char *, int *, const int, const int );\n\nvoid calculateBI( floatType_t const *,\n                  floatType_t const *,\n                  floatType_t const *,\n                  int ,\n                  floatType_t *, floatType_t *,\n                  int *, int *,\n                  floatType_t const );\n\nvoid svmTrain( floatType_t const *, floatType_t const *, floatType_t const,\n               const int, const int,\n               const floatType_t, floatType_t * );\n\nvoid svmPredict( floatType_t const *, floatType_t const *,\n                 int const, int const, int * );\n", "meta": {"hexsha": "10e3a3036bcfb289c80a8a0db91f2de2458ddafa", "size": 2540, "ext": "h", "lang": "C", "max_stars_repo_path": "exercises/cuda/svm_challenge/original/headers.h", "max_stars_repo_name": "ardila/gpu_workshop", "max_stars_repo_head_hexsha": "6846c1d24b3725824696d0aaf75908b67422ea2f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercises/cuda/svm_challenge/original/headers.h", "max_issues_repo_name": "ardila/gpu_workshop", "max_issues_repo_head_hexsha": "6846c1d24b3725824696d0aaf75908b67422ea2f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercises/cuda/svm_challenge/original/headers.h", "max_forks_repo_name": "ardila/gpu_workshop", "max_forks_repo_head_hexsha": "6846c1d24b3725824696d0aaf75908b67422ea2f", "max_forks_repo_licenses": ["Apache-2.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.4583333333, "max_line_length": 76, "alphanum_fraction": 0.6381889764, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.36867891872966624}}
{"text": "/* specfunc/bessel_K0.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include \"gsl_sf_exp.h\"\n#include \"gsl_sf_bessel.h\"\n\n#include \"error.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/* based on SLATEC bk0(), bk0e() */\n\n/* chebyshev expansions \n\n series for bk0        on the interval  0.\t    to  4.00000d+00\n\t\t\t\t\twith weighted error   3.57e-19\n\t\t\t\t\t log weighted error  18.45\n\t\t\t       significant figures required  17.99\n\t\t\t\t    decimal places required  18.97\n\n series for ak0        on the interval  1.25000d-01 to  5.00000d-01\n\t\t\t\t\twith weighted error   5.34e-17\n\t\t\t\t\t log weighted error  16.27\n\t\t\t       significant figures required  14.92\n\t\t\t\t    decimal places required  16.89\n\n series for ak02       on the interval  0.\t    to  1.25000d-01\n\t\t\t\t\twith weighted error   2.34e-17\n\t\t\t\t\t log weighted error  16.63\n\t\t\t       significant figures required  14.67\n\t\t\t\t    decimal places required  17.20\n*/\n\nstatic double bk0_data[11] = {\n  -0.03532739323390276872,\n   0.3442898999246284869, \n   0.03597993651536150163,\n   0.00126461541144692592,\n   0.00002286212103119451,\n   0.00000025347910790261,\n   0.00000000190451637722,\n   0.00000000001034969525,\n   0.00000000000004259816,\n   0.00000000000000013744,\n   0.00000000000000000035\n};\nstatic cheb_series bk0_cs = {\n  bk0_data,\n  10,\n  -1, 1,\n  10\n};\n\nstatic double ak0_data[17] = {\n  -0.07643947903327941,\n  -0.02235652605699819,\n   0.00077341811546938,\n  -0.00004281006688886,\n   0.00000308170017386,\n  -0.00000026393672220,\n   0.00000002563713036,\n  -0.00000000274270554,\n   0.00000000031694296,\n  -0.00000000003902353,\n   0.00000000000506804,\n  -0.00000000000068895,\n   0.00000000000009744,\n  -0.00000000000001427,\n   0.00000000000000215,\n  -0.00000000000000033,\n   0.00000000000000005\n};\nstatic cheb_series ak0_cs = {\n  ak0_data,\n  16,\n  -1, 1,\n  10\n};\n\nstatic double ak02_data[14] = {\n  -0.01201869826307592,\n  -0.00917485269102569,\n   0.00014445509317750,\n  -0.00000401361417543,\n   0.00000015678318108,\n  -0.00000000777011043,\n   0.00000000046111825,\n  -0.00000000003158592,\n   0.00000000000243501,\n  -0.00000000000020743,\n   0.00000000000001925,\n  -0.00000000000000192,\n   0.00000000000000020,\n  -0.00000000000000002\n};\nstatic cheb_series ak02_cs = {\n  ak02_data,\n  13,\n  -1, 1,\n  8\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_bessel_K0_scaled_e(const double x, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x <= 2.0) {\n    const double lx = log(x);\n    const double ex = exp(x);\n    int stat_I0;\n    gsl_sf_result I0;\n    gsl_sf_result c;\n    cheb_eval_e(&bk0_cs, 0.5*x*x-1.0, &c);\n    stat_I0 = gsl_sf_bessel_I0_e(x, &I0);\n    result->val  = ex * ((-lx+M_LN2)*I0.val - 0.25 + c.val);\n    result->err  = ex * ((M_LN2+fabs(lx))*I0.err + c.err);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return stat_I0;\n  }\n  else if(x <= 8.0) {\n    const double sx = sqrt(x);\n    gsl_sf_result c;\n    cheb_eval_e(&ak0_cs, (16.0/x-5.0)/3.0, &c);\n    result->val  = (1.25 + c.val) / sx;\n    result->err  = c.err / sx;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    const double sx = sqrt(x);\n    gsl_sf_result c;\n    cheb_eval_e(&ak02_cs, 16.0/x-1.0, &c);\n    result->val  = (1.25 + c.val) / sx;\n    result->err  = (c.err + GSL_DBL_EPSILON) / sx;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  } \n}\n\n\nint gsl_sf_bessel_K0_e(const double x, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x <= 2.0) {\n    const double lx = log(x);\n    int stat_I0;\n    gsl_sf_result I0;\n    gsl_sf_result c;\n    cheb_eval_e(&bk0_cs, 0.5*x*x-1.0, &c);\n    stat_I0 = gsl_sf_bessel_I0_e(x, &I0);\n    result->val  = (-lx+M_LN2)*I0.val - 0.25 + c.val;\n    result->err  = (fabs(lx) + M_LN2) * I0.err + c.err;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return stat_I0;\n  }\n  else {\n    gsl_sf_result K0_scaled;\n    int stat_K0 = gsl_sf_bessel_K0_scaled_e(x, &K0_scaled);\n    int stat_e  = gsl_sf_exp_mult_err_e(-x, GSL_DBL_EPSILON*fabs(x),\n                                           K0_scaled.val, K0_scaled.err,\n\t\t\t\t\t   result);\n    return GSL_ERROR_SELECT_2(stat_e, stat_K0);\n  }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_bessel_K0_scaled(const double x)\n{\n  EVAL_RESULT(gsl_sf_bessel_K0_scaled_e(x, &result));\n}\n\ndouble gsl_sf_bessel_K0(const double x)\n{\n  EVAL_RESULT(gsl_sf_bessel_K0_e(x, &result));\n}\n\n", "meta": {"hexsha": "9ef4b73c8fd319288f3fe73faeed57ed3f856fca", "size": 5523, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_K0.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_K0.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/specfunc/bessel_K0.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 25.688372093, "max_line_length": 76, "alphanum_fraction": 0.6460257107, "num_tokens": 1958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3685790870887205}}
{"text": "/* Copyright (c) 2011-2012, J\u00e9r\u00e9my Fix. All rights reserved. */\n\n/* Redistribution and use in source and binary forms, with or without */\n/* modification, are permitted provided that the following conditions are met: */\n\n/* * Redistributions of source code must retain the above copyright notice, */\n/* this list of conditions and the following disclaimer. */\n/* * Redistributions in binary form must reproduce the above copyright notice, */\n/* this list of conditions and the following disclaimer in the documentation */\n/* and/or other materials provided with the distribution. */\n/* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */\n\n/* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND */\n/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */\n/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */\n/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */\n/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */\n/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */\n/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */\n/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */\n/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */\n/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */\n\n\n#ifndef UKF_PARAMETER_SCALAR_H\n#define UKF_PARAMETER_SCALAR_H\n\n#include <gsl/gsl_linalg.h> // For the Cholesky decomposition\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_blas.h>\n\n#include \"ukf_types.h\"\n#include \"ukf_math.h\"\n\nnamespace ukf\n{\n    /**\n      * @short UKF for parameter estimation.\n      * The notations follow \"Sigma-Point Kalman Filters for Probabilistic Inference in Dynamic State-Space Models\",p93, PhD, van Der Merwe\n      */\n    namespace parameter\n    {\n        /**\n         * @short Allocation of the vectors/matrices and initialization\n         *\n         */\n        inline void ukf_scalar_init(ukf_param &p, ukf_scalar_state &s)\n        {\n            // Init the lambda\n            p.lambda = p.alpha * p.alpha * (p.n + p.kpa) - p.n;\n            p.gamma = sqrt(p.n + p.lambda);\n            p.nbSamples = 2 * p.n + 1;\n\n            // Init the matrices used to iterate\n            s.Kk = gsl_vector_alloc(p.n); // Kalman gain\n            gsl_vector_set_zero(s.Kk);\n\n            s.Kk_mat = gsl_matrix_alloc(p.n,1);\n            gsl_matrix_set_zero(s.Kk_mat);\n\n            s.Kk_mat_T = gsl_matrix_alloc(1,p.n);\n            gsl_matrix_set_zero(s.Kk_mat_T);\n\n            s.Pwdk = gsl_vector_alloc(p.n); // Covariance of the parameters and output\n            gsl_vector_set_zero(s.Pwdk);\n\n            // Whatever the type of evolution noise, its covariance is set to evolution_noise\n            s.Prrk = gsl_matrix_alloc(p.n,p.n);\n            p.evolution_noise->init(p,s);\n\n            s.Peek = p.observation_noise; // Covariance of the observation noise\n\n            s.Pddk = 0.0; // Covariance of the output\n\n            s.w = gsl_vector_alloc(p.n); // Parameter vector\n            gsl_vector_set_zero(s.w);\n\n            s.wk = gsl_vector_alloc(p.n); // Vector holding one sigma point\n            gsl_vector_set_zero(s.wk);\n\n            s.Pk = gsl_matrix_alloc(p.n,p.n); // Covariance matrix\n            gsl_matrix_set_identity(s.Pk);\n            gsl_matrix_scale(s.Pk,p.prior_pi);\n\n            s.Sk = gsl_matrix_alloc(p.n,p.n); // Matrix holding the cholesky decomposition of Pk\n            // Initialize Sk to the cholesky decomposition of Pk\n            gsl_matrix_memcpy(s.Sk, s.Pk);\n            gsl_linalg_cholesky_decomp(s.Sk);\n            // Set all the elements of Lpi strictly above the diagonal to zero\n            for(int k = 0 ; k < p.n ; k++)\n                for(int j = 0 ; j < k ; j++)\n                    gsl_matrix_set(s.Sk,j,k,0.0);\n\n            s.cSk = gsl_vector_alloc(p.n); // Vector holding one column of Lpi\n            gsl_vector_set_zero(s.cSk);\n\n            s.wm  = gsl_vector_alloc(p.nbSamples); // Weights used to compute the mean of the sigma points images\n            s.wc = gsl_vector_alloc(p.nbSamples); // Weights used to update the covariance matrices\n\n            // Set the weights\n            gsl_vector_set(s.wm, 0, p.lambda / (p.n + p.lambda));\n            gsl_vector_set(s.wc, 0, p.lambda / (p.n + p.lambda) + (1.0 - p.alpha*p.alpha + p.beta));\n            for(int j = 1 ; j < p.nbSamples; j ++)\n            {\n                gsl_vector_set(s.wm, j, 1.0 / (2.0 * (p.n + p.lambda)));\n                gsl_vector_set(s.wc, j, 1.0 / (2.0 * (p.n + p.lambda)));\n            }\n\n            s.dk = gsl_vector_alloc(p.nbSamples); // Holds the image of the sigma points\n            gsl_vector_set_zero(s.dk);\n\n            s.d_mean = 0; // Holds the mean of the sigma points images\n\n            s.sigmaPoints = gsl_matrix_alloc(p.n,p.nbSamples); // Holds the sigma points in the columns\n            gsl_matrix_set_zero(s.sigmaPoints);\n\n            s.temp_n = gsl_vector_alloc(p.n);\n            gsl_vector_set_zero(s.temp_n);\n\n            s.temp_n_n = gsl_matrix_alloc(p.n,p.n);\n            gsl_matrix_set_zero(s.temp_n_n);\n        }\n\n        /**\n         * @short Free of memory allocation\n         *\n         */\n        inline void ukf_scalar_free(ukf_param &p, ukf_scalar_state &s)\n        {\n            gsl_vector_free(s.Kk);\n            gsl_matrix_free(s.Kk_mat);\n            gsl_matrix_free(s.Kk_mat_T);\n            gsl_vector_free(s.Pwdk);\n            gsl_matrix_free(s.Prrk);\n\n            gsl_vector_free(s.w);\n            gsl_vector_free(s.wk);\n\n            gsl_matrix_free(s.Pk);\n            gsl_matrix_free(s.Sk);\n            gsl_vector_free(s.cSk);\n\n            gsl_vector_free(s.wm);\n            gsl_vector_free(s.wc);\n\n            gsl_vector_free(s.dk);\n\n            gsl_matrix_free(s.sigmaPoints);\n\n            gsl_vector_free(s.temp_n);\n            gsl_matrix_free(s.temp_n_n);\n        }\n\n        /**\n         * @short Iteration for UKF for parameter estimation, in case of a scalar output\n         *\n         */\n\ttemplate<typename GFUNC>\n        void ukf_scalar_iterate(ukf_param &p, ukf_scalar_state &s, \n\t\t\t\t       GFUNC g, \n\t\t\t\t       gsl_vector * xk, double dk)\n        {\n            // Here, we implement the UKF for parameter estimation in the scalar case\n            // The notations follow p93 of the PhD thesis of Van Der Merwe, \"Sigma-Point Kalman Filters for Probabilistic Inference in Dynamic State-Space Models\"\n\n            // ************************************************** //\n            // ************ Time update equations    ************ //\n            // ************************************************** //\n            // Add the evolution noise to the parameter covariance Eq 3.137\n            gsl_matrix_add(s.Pk, s.Prrk);\n\n            // ************************************************** //\n            // ************ Compute the sigma points ************ //\n            // ************************************************** //\n            // Equations 3.138\n            // w_k^j = w_(k-1)  <-- this is here denoted s.w\n            // w_k^j = w_(k-1) + gamma Sk_j for 1 <= j <= n\n            // w_k^j = w_(k-1) - gamma Sk_j for n+1 <= j <= 2n\n\n            // Perform a cholesky decomposition of Pk\n            gsl_matrix_memcpy(s.Sk, s.Pk);\n            gsl_linalg_cholesky_decomp(s.Sk);\n            // Set all the elements of Lpi strictly above the diagonal to zero\n            for(int k = 0 ; k < p.n ; k++)\n                for(int j = 0 ; j < k ; j++)\n                    gsl_matrix_set(s.Sk,j,k,0.0);\n\n            gsl_matrix_set_col(s.sigmaPoints,0, s.w);\n            for(int j = 1 ; j < p.n+1 ; ++j)\n                for(int i = 0 ; i < p.n ; ++i)\n                    gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) + p.gamma * gsl_matrix_get(s.Sk,i,j-1));\n\n            for(int j = p.n+1 ; j < p.nbSamples ; ++j)\n                for(int i = 0 ; i < p.n ; ++i)\n                    gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) - p.gamma * gsl_matrix_get(s.Sk,i,j-(p.n+1)));\n\n            // ************************************************** //\n            // ***** Compute the images of the sigma points ***** //\n            // ************************************************** //\n\n            // Compute the images of the sigma points\n            // and the mean of the yj\n            s.d_mean = 0.0;\n            gsl_vector_set_zero(s.dk);\n            for(int j = 0 ; j < p.nbSamples ; j++)\n            {\n                // Equation 3.139\n                gsl_matrix_get_col(s.wk, s.sigmaPoints,j);\n                s.dk->data[j] = g(s.wk,xk);\n\n                // Update the mean : y_mean = sum_[j=0..2n] wm_j y_j\n                // Equation 3.140\n                s.d_mean += s.wm->data[j] * s.dk->data[j];\n            }\n\n            // ************************************************** //\n            // ************** Update the statistics ************* //\n            // ************************************************** //\n\n            gsl_vector_set_zero(s.Pwdk);\n            // The covariance of the output is initialized with the observation noise covariance\n            // Eq 3.142\n            s.Pddk = s.Peek;\n            for(int j = 0 ; j < p.nbSamples ; j++)\n            {\n                // Eq 3.142\n                s.Pddk += s.wc->data[j] * gsl_pow_2(s.dk->data[j] - s.d_mean);\n                // Eq 3.143\n                for(int i = 0 ; i < p.n ; ++i)\n                {\n                    s.Pwdk->data[i] = s.Pwdk->data[i] + s.wc->data[j] * (gsl_matrix_get(s.sigmaPoints,i,j) - s.w->data[i]) * (s.dk->data[j] - s.d_mean) ;\n                }\n            }\n\n            // ************************************************** //\n            // ******* Kalman gain and parameters update ******** //\n            // ************************************************** //\n\n            //if(s.Pddk == 0.0)\n            //    printf(\"[Error] Output covariance is null !\");\n            // May not occur as soon as the observation noise covariance is set != 0.0\n\n            // Eq. 3.144\n            for(int i = 0 ; i < p.n ; ++i)\n                s.Kk->data[i] = s.Pwdk->data[i] / s.Pddk;\n\n            // Eq 3.145\n            // wk = w_(k-1) + Kk * (dk - d_mean)\n            s.ino_dk = dk - s.d_mean;\n            for(int i = 0 ; i < p.n ; ++i)\n                s.w->data[i] = s.w->data[i] + s.Kk->data[i] * s.ino_dk;\n\n            // Eq. 3.146\n            // Pk = P_(k-1) - Pddk . Kk Kk^T\n            for(int i = 0 ; i < p.n ; ++i)\n            {\n                gsl_matrix_set(s.Kk_mat, i, 0, s.Kk->data[i]);\n                gsl_matrix_set(s.Kk_mat_T, 0, i, s.Kk->data[i]);\n            }\n            gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,-s.Pddk, s.Kk_mat, s.Kk_mat_T,1.0,s.Pk);\n\n            // Update of the evolution noise\n            p.evolution_noise->updateEvolutionNoise(p,s);\n        }\n\n        /**\n        * @short Evaluation of the output from the sigma points\n        *\n        */\n        void ukf_scalar_evaluate(ukf_param &p, ukf_scalar_state &s, \n\t\t\t\t double(*g)(gsl_vector*, gsl_vector*), \n\t\t\t\t gsl_vector * xk, double &dk)\n        {\n            // ************************************************** //\n            // ************ Compute the sigma points ************ //\n            // ************************************************** //\n\n            // 1- Compute the cholesky decomposition of Pk\n            gsl_matrix_memcpy(s.temp_n_n, s.Pk);\n            gsl_linalg_cholesky_decomp(s.temp_n_n);\n\n            // 2 - Set all the elements of Sk_temp strictly above the diagonal to zero\n            for(int k = 0 ; k < p.n ; k++)\n                for(int j = 0 ; j < k ; j++)\n                    gsl_matrix_set(s.temp_n_n,j,k,0.0);\n            // Now Sk_temp is a lower triangular matrix containing the cholesky decomposition of Pk\n\n            // 3- Compute the sigma points\n            // Equations 3.138\n            // w_k^j = w_(k-1)  <-- this is here denoted s.w\n            // w_k^j = w_(k-1) + gamma Sk_j for 1 <= j <= n\n            // w_k^j = w_(k-1) - gamma Sk_j for n+1 <= j <= 2n\n            gsl_matrix_set_col(s.sigmaPoints,0, s.w);\n            for(int j = 1 ; j < p.n+1 ; j++)\n                for(int i = 0 ; i < p.n ; ++i)\n                    gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) + p.gamma * gsl_matrix_get(s.temp_n_n,i,j-1));\n\n            for(int j = p.n+1 ; j < p.nbSamples ; j++)\n                for(int i = 0 ; i < p.n ; ++i)\n                    gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) - p.gamma * gsl_matrix_get(s.temp_n_n,i,j-(p.n+1)));\n\n            // ************************************************** //\n            // ***** Compute the images of the sigma points ***** //\n            // ************************************************** //\n\n            // Compute the images of the sigma points\n            // and their mean\n            dk = 0.0;\n            for(int j = 0 ; j < p.nbSamples ; j++)\n            {\n                gsl_matrix_get_col(s.wk, s.sigmaPoints,j);\n                // Update the mean : d_mean = sum_[j=0..2n] w_j y_j\n                dk += gsl_vector_get(s.wm,j) * g(s.wk,xk);\n            }\n        }\n\n    } // parameter\n} // ukf\n\n#endif // UKF_PARAMETER_SCALAR_H\n", "meta": {"hexsha": "f4dec0256622722ba4b754035e7cad8123d1f2f7", "size": 13438, "ext": "h", "lang": "C", "max_stars_repo_path": "src/ukf_parameter_scalar.h", "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_issues_repo_path": "src/ukf_parameter_scalar.h", "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_forks_repo_path": "src/ukf_parameter_scalar.h", "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 52.0, "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "avg_line_length": 41.8629283489, "max_line_length": 162, "alphanum_fraction": 0.5034231284, "num_tokens": 3313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.36835055128475697}}
{"text": "\r\n\r\n#ifndef __MATH_FUNCTINS_H__\r\n#define __MATH_FUNCTINS_H__\r\n\r\n#include <stdint.h>\r\n#include <cmath>  // for std::fabs and std::signbit\r\n#include <cblas.h>\r\n#include <cudnn.h>\r\n#include <cublas_v2.h>\r\n#include <cuda.h>\r\n#include <cuda_runtime.h>\r\n#include <curand.h>\r\n#include <driver_types.h>  // cuda driver types\r\n#include <algorithm>\r\n\r\n#include <glog/logging.h>\r\n#define PERMUTELAYER_ORDERNUM 4\r\n#define BLOCK 512\r\n//\r\n// CUDA macros\r\n//\r\n\r\n// CUDA: various checks for different function calls.\r\n#define CUDA_CHECK(condition) \\\r\n  /* Code block avoids redefinition of cudaError_t error */ \\\r\n  do { \\\r\n    cudaError_t error = condition; \\\r\n    CHECK_EQ(error, cudaSuccess) << \" \" << cudaGetErrorString(error); \\\r\n  } while (0)\r\n\r\n#define CUBLAS_CHECK(condition) \\\r\n  do { \\\r\n    cublasStatus_t status = condition; \\\r\n    CHECK_EQ(status, CUBLAS_STATUS_SUCCESS) << \" \" \\\r\n      << cublasGetErrorString(status); \\\r\n  } while (0)\r\n\r\n#define CURAND_CHECK(condition) \\\r\n  do { \\\r\n    curandStatus_t status = condition; \\\r\n    CHECK_EQ(status, CURAND_STATUS_SUCCESS) << \" \" \\\r\n      << curandGetErrorString(status); \\\r\n  } while (0)\r\n\r\n// CUDA: grid stride looping\r\n#define CUDA_KERNEL_LOOP(i, n) \\\r\n  for (int i = blockIdx.x * blockDim.x + threadIdx.x; \\\r\n       i < (n); \\\r\n       i += blockDim.x * gridDim.x)\r\n\r\n// CUDA: check for error after kernel execution and exit loudly if there is one.\r\n#define CUDA_POST_KERNEL_CHECK CUDA_CHECK(cudaPeekAtLastError())\r\n\r\n\r\n// CUDA: library error reporting.\r\nconst char* cublasGetErrorString(cublasStatus_t error);\r\nconst char* curandGetErrorString(curandStatus_t error);\r\n\r\n// CUDA: use 512 threads per block\r\nconst int TENSORRT_CUDA_NUM_THREADS = 256;\r\n\r\n// CUDA: number of blocks for threads.\r\ninline int TENSORRT_GET_BLOCKS(const int N) {\r\n  return (N + TENSORRT_CUDA_NUM_THREADS - 1) / TENSORRT_CUDA_NUM_THREADS;\r\n}\r\n\r\n\r\n/* \r\n * function: X[i] = alpha,initialize X with constant alpha\r\n * \r\n */\r\ntemplate <typename Dtype>\r\nvoid tensorrt_gpu_set(const int N, const Dtype alpha, Dtype *X);\r\n\r\n/*\r\n * function: y[index] = pow(a[index], alpha)\r\n *@params n: the dims of matrix a\r\n *@params a: matrix\r\n *@params y: vector\r\n */\r\ntemplate <typename Dtype>\r\nvoid tensorrt_gpu_powx(const int n, const Dtype* a, const Dtype alpha, Dtype* y);\r\n\r\n\r\n/*\r\n *function:y = alpha*A*x + beta*y;\r\n *@params handle: handle\r\n *@params TransA: transpose flag\r\n *@params M: the rows of A\r\n *@params N: the cols of A\r\n *@params alpha: the coefficient of A*x\r\n *@params A: matrix [M x N]\r\n *@params x: vector x\r\n *@params beta: the coefficient of y\r\n *@params y: vector y\r\n */\r\ntemplate <typename Dtype>\r\nvoid tensorrt_gpu_gemv(cublasHandle_t handle,const CBLAS_TRANSPOSE TransA, const int M, const int N,\r\n    const Dtype alpha, const Dtype* A, const Dtype* x, const Dtype beta,\r\n    Dtype* y);\r\n\r\n\r\n\r\ntemplate <typename Dtype>\r\nvoid tensorrt_gpu_divbsx(const int nthreads, const Dtype* A,\r\n    const Dtype* v, const int rows, const int cols, const CBLAS_TRANSPOSE trans,\r\n    Dtype* B);\r\n\r\ntemplate <typename Dtype>\r\nvoid tensorrt_gpu_mulbsx(const int nthreads, const Dtype* A,\r\n    const Dtype* v, const int rows, const int cols, const CBLAS_TRANSPOSE trans,\r\n    Dtype* B);\r\ncudaError_t tensorrt_gpu_permute(const int nthreads,float* const  bottom_data,const bool forward,\r\n\tconst int* permute_order,const int* old_steps,const int* new_steps,const int num_axes,float* const top_data,cudaStream_t stream);\r\n\r\ncudaError_t SoftmaxLayer(const float *bottom_data, int count, int channels, int outer_num_, int inner_num_, float *scale_data, float *top_data, cudaStream_t stream);\r\n\r\ncudaError_t ConcatLayer(int nthreads, const float *bottom_data, bool kForward, int num_concats_, int concat_input_size_, int top_concat_axis, int bottom_concat_axis, int offset_concat_axis, float *top_data, cudaStream_t stream);\r\n\r\n//cudaError_t cudaSoftmax(int n, int channels,  float* x, float*y, cudaStream_t stream);\r\n\r\n//virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);\r\ncudaError_t cudaSoftmax_caffe(int count,int channels,float* x,float* y, cudaStream_t stream);\r\n\r\ncudaError_t cudaDetectionOutput_caffe( int bottom0_count,\r\n                                       int bottom1_count,\r\n                                       float* loc_data,\r\n                                       float* bottom1,\r\n                                       float* prior_data,\r\n                                       float* bottom3,\r\n                                       float* bottom4,\r\n                                       float* y,\r\n                                       cudaStream_t stream);\r\n\r\n#endif\r\n", "meta": {"hexsha": "82d73a61d10e6ec509bed909fa21fdccc25a7046", "size": 4645, "ext": "h", "lang": "C", "max_stars_repo_path": "include/mathFunctions.h", "max_stars_repo_name": "niekai1982/MultiCamer-tx2", "max_stars_repo_head_hexsha": "accae48e081f9fc55df64273c4c1285572283fdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-21T06:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-21T06:20:59.000Z", "max_issues_repo_path": "include/mathFunctions.h", "max_issues_repo_name": "niekai1982/MultiCamer-tx2", "max_issues_repo_head_hexsha": "accae48e081f9fc55df64273c4c1285572283fdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mathFunctions.h", "max_forks_repo_name": "niekai1982/MultiCamer-tx2", "max_forks_repo_head_hexsha": "accae48e081f9fc55df64273c4c1285572283fdf", "max_forks_repo_licenses": ["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.9051094891, "max_line_length": 229, "alphanum_fraction": 0.6630785791, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3682903980214067}}
{"text": "#pragma once\n\n#ifndef __GREEK_LETTERS_H__\n#define __GREEK_LETTERS_H__\n\n#include <cstring>\n#include <string>\n\n#include <gsl/gsl_math.h>\n\n#include \"../../Utils/BinarySearch.h\"\n\nconstexpr const int numGreekLetters = 49;\nconstexpr const char* greekLetterNames[numGreekLetters] = {\n\t\"Alpha\", \"Beta\", \"Chi\", \"Delta\", \"Epsilon\", \"Eta\", \"Gamma\", \"Iota\", \"Kappa\", \"Lambda\",\n\t\"Mu\", \"Nu\", \"Omega\", \"Omicron\", \"Phi\", \"Pi\", \"Psi\", \"Rho\", \"Sigma\", \"Tau\", \"Theta\",\n\t\"Upsilon\", \"Xi\", \"Zeta\", \"alpha\", \"beta\", \"chi\", \"delta\", \"epsilon\", \"eta\", \"gamma\",\n\t\"iota\", \"kappa\", \"lambda\", \"mu\", \"nu\", \"omega\", \"omicron\", \"phi\", \"pi\", \"psi\", \"rho\",\n\t\"sigma\", \"tau\", \"theta\", \"upsilon\", \"vphi\", \"xi\", \"zeta\"\n};\nconstexpr const int shortestGreekLetterName = 2;\nconstexpr const int longestGreekLetterName = 7;\nconstexpr const int greekLetterLength = 2;\nconst std::string greekLetters[numGreekLetters] = {\n\tu8\"\\u0391\", u8\"\\u0392\", u8\"\\u03A7\", u8\"\\u0394\", u8\"\\u0395\", u8\"\\u0397\", u8\"\\u0393\",\n\tu8\"\\u0399\", u8\"\\u039A\", u8\"\\u039B\", u8\"\\u039C\", u8\"\\u039D\", u8\"\\u03A9\", u8\"\\u039F\",\n\tu8\"\\u03A6\", u8\"\\u03A0\", u8\"\\u03A8\", u8\"\\u03A1\", u8\"\\u03A3\", u8\"\\u03A4\", u8\"\\u0398\",\n\tu8\"\\u03A5\", u8\"\\u039E\", u8\"\\u0396\", u8\"\\u03B1\", u8\"\\u03B2\", u8\"\\u03C7\", u8\"\\u03B4\",\n\tu8\"\\u03B5\", u8\"\\u03B7\", u8\"\\u03B3\", u8\"\\u03B9\", u8\"\\u03BA\", u8\"\\u03BB\", u8\"\\u03BC\",\n\tu8\"\\u03BD\", u8\"\\u03C9\", u8\"\\u03BF\", u8\"\\u03C6\", u8\"\\u03C0\", u8\"\\u03C8\", u8\"\\u03C1\",\n\tu8\"\\u03C3\", u8\"\\u03C4\", u8\"\\u03B8\", u8\"\\u03C5\", u8\"\\u03d5\", u8\"\\u03BE\", u8\"\\u03B6\"\n};\n\n/*\nReturns index of the constant in the constants array.\n\nUses binary search under the hood to search for the index.\n\nParameters\n----------\nname: The name of the constantaddMissingRParens\nThe index or -1 if the provided name is not a constant.\n*/\nCONSTEXPR_BINARY_SEARCH(getGreekLetterNameIndex, greekLetterNames, numGreekLetters)\n\nstatic int getGreekLetterIndex(const std::string& name){\n    if (name.size() <= greekLetterLength){\n        for (int i = 0; i < numGreekLetters; ++i){\n            if (name == greekLetters[i]){\n                return i;\n            }\n        }\n    }\n    return getGreekLetterNameIndex(name.c_str());\n}\n\n#endif // __GREEK_LETTERS_H__\n", "meta": {"hexsha": "1717bfe0670ab81ace43f2fd2a39ef934f027738", "size": 2138, "ext": "h", "lang": "C", "max_stars_repo_path": "MathEngine/Expressions/VariableExpressions/GreekLetters.h", "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathEngine/Expressions/VariableExpressions/GreekLetters.h", "max_issues_repo_name": "antoniojkim/CalcPlusPlus", "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathEngine/Expressions/VariableExpressions/GreekLetters.h", "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_forks_repo_licenses": ["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.8620689655, "max_line_length": 87, "alphanum_fraction": 0.6384471469, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.63341027751814, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.368203351967167}}
{"text": "/*\n * Copyright (c) 2015, Aleksas Mazeliauskas and Derek Teaney\n * All rights reserved.\n *\n * rnavier is distributed under MIT license;\n * see the LICENSE file that should be present in the root\n * of the source distribution, or alternately available at:\n * https://github.com/rnavier/rnavier/\n */\n#ifndef RN_TEOSLats95p_h\n#define RN_TEOSLats95p_h\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n#include \"TEOS.h\"\n#include \"numeric.h\"\n\n\n\n\n// Lattice EoS s95p_v0 by Huovinen and Petreczky. Data files are stored in /s95p, correspondingly\n// in *par*.dat (T, \\mu_1, \\mu_2) and *dens*.dat (e, P, s, n_B, plasma ratio), with natural units,\n// e.g., T-GeV, \\mu-GeV, e-GeV/fm^3. Each file is \n// particularly available in its range.\n// file1: T~[0.0159,0.1801], e~[0.001,1.001]\n// file2: T~[0.1801,0.2810], e~[1.001,11.00]\n// file3: T~[0.2810,0.4243], e~[11.00,61.00]\n// file4: T~[0.2423,0.6335], e~[61.00,311.0]\n// There are also files avaiable for T<180MeV, with 28 non-zero chemical potential for baryon, \n// strangeness, etc. For the time being, and for simplicity we ignore these files. So basically\n// we have \\mu = 0 and n_B = 0. \n\nclass TEOSs95p : public virtual TEOS {\n\n   private:\n\n      //minimum table values\n      double fEmin;\n      double fSmin;\n      double fTmin;\n      double fPmin;\n\t\n      gsl_interp_accel *acc_eVSp;\n      gsl_spline *eVSp;\n      \n      gsl_interp_accel *acc_tVSx;\n      gsl_spline *tVSx;\n      \n      gsl_interp_accel *acc_eVSt;\n      gsl_spline *eVSt;\n      \n      gsl_interp_accel *acc_eVSs;\n      gsl_spline *eVSs;\n      \n      gsl_interp_accel *acc_sVSe;\n      gsl_spline *sVSe;\n\n      void eos(const double &e, double &p, double &cs)  ;\n      void st(const double &e, double &s, double &t)  ; \n      \n      double fEtaOverS ;    //!< The Shear viscosity/entropy \n      double fEtaOverSHad ; //!< The Shear viscosity/entropy \n      double fSigmaOverS ;  //!< The Shear viscosity/entropy \n      double fKappaTOverS ; //!< The Conductivity/entropy\n      double fTPi_EtaST ;  //!< tau_pi / (eta/sT)\n      double fL1_EtaTPi ;  //!< lambda_1 /(eta*tau_pi)\n      double fL2_EtaTPi ;  //!< lambda_2 /(eta*tau_pi)\n \n\n   public:\n\n      TEOSs95p ();\n      ~TEOSs95p ();\n\n      virtual void read(std::istream &in)  ;\n\n      virtual void write(std::ostream &out) ;\n\n      virtual void eos(const double &e, const double &n, \n            double &p, double &cs) ;\n\n      virtual double eofs(const double &s, const double &n) ;\n\n      virtual void stmu(const double &e, const double &n, \n            double &s, double &t, double &mu) ;\n\n      virtual void viscosity(const double &e, const double &n, \n         double &sigma_overs, double &kappaT_overs, double &eta_overs) ;\n\n      virtual void getBRSSSParams(const double &e, const double &n, double &tpi_etast, double &l1_ntpi, double &l2_ntpi) \n      { tpi_etast =  fTPi_EtaST ; l1_ntpi = fL1_EtaTPi ; l2_ntpi = fL2_EtaTPi ; }\n\n      void tmux(const double &e, const double &n, double &t, double &mub, double &mus, double &x) ;\n\n} ;\n\nstd::unique_ptr<TEOS> make_eos_eoss95p(TRNavier3DBj *rn, const std::string &icname) ;\n#endif \n", "meta": {"hexsha": "83e48a33971897b4721d58643f27a0aceea30642", "size": 3108, "ext": "h", "lang": "C", "max_stars_repo_path": "src/eoss95p/TEOSs95p.h", "max_stars_repo_name": "rnavier/rnavier", "max_stars_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-08-04T14:02:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T15:03:33.000Z", "max_issues_repo_path": "src/eoss95p/TEOSs95p.h", "max_issues_repo_name": "rnavier/rnavier", "max_issues_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eoss95p/TEOSs95p.h", "max_forks_repo_name": "rnavier/rnavier", "max_forks_repo_head_hexsha": "6f30abc9969daa1a8e6b72d0c1069e2a477ad610", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3939393939, "max_line_length": 121, "alphanum_fraction": 0.6460746461, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3681877566264566}}
{"text": "/* gsl_histogram2d_oper.c\n * Copyright (C) 2000  Simone Piccardi\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n/***************************************************************\n *\n * File gsl_histogram2d_oper.c: \n * Routine to make operation on 2D histograms. \n * Need GSL library and header.\n * Contains the routines:\n * gsl_histogram2d_same_binning check if two histograms have the same binning \n * gsl_histogram2d_add          add two histogram\n * gsl_histogram2d_sub          subctract two histogram\n * gsl_histogram2d_mult         multiply two histogram\n * gsl_histogram2d_div          divide two histogram\n * gsl_histogram2d_scale        scale histogram contents\n *\n * Author: S. Piccardi\n * Jan. 2000\n *\n ***************************************************************/\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_histogram2d.h>\n\n/* \n * gsl_histogram2d_same_binning:\n * control if two histogram have the\n * same binning\n */\nint\ngsl_histogram2d_equal_bins_p (const gsl_histogram2d * h1,\n                              const gsl_histogram2d * h2)\n{\n\n  if ((h1->nx != h2->nx) || (h1->ny != h2->ny))\n    {\n      return 0;\n    }\n  {\n    size_t i;\n    /* init ranges */\n    for (i = 0; i <= (h1->nx); i++)\n      {\n        if (h1->xrange[i] != h2->xrange[i])\n          {\n            return 0;\n          }\n      }\n    for (i = 0; i <= (h1->ny); i++)\n      {\n        if (h1->yrange[i] != h2->yrange[i])\n          {\n            return 0;\n          }\n      }\n  }\n  return 1;\n}\n\n/* \n * gsl_histogram2d_add:\n * add two histogram\n */\n\nint \ngsl_histogram2d_add (gsl_histogram2d * h1, const gsl_histogram2d * h2)\n{\n  size_t i;\n\n  if (!gsl_histogram2d_equal_bins_p (h1, h2))\n    {\n      GSL_ERROR (\"histograms have different binning\", GSL_EINVAL);\n    }\n\n  for (i = 0; i < (h1->nx) * (h1->ny); i++)\n    {\n      h1->bin[i] += h2->bin[i];\n    }\n\n  return GSL_SUCCESS;\n}\n\n/* \n * gsl_histogram2d_sub:\n * subtract two histogram\n */\n\nint \ngsl_histogram2d_sub (gsl_histogram2d * h1, const gsl_histogram2d * h2)\n{\n  size_t i;\n\n  if (!gsl_histogram2d_equal_bins_p (h1, h2))\n    {\n      GSL_ERROR (\"histograms have different binning\", GSL_EINVAL);\n    }\n\n  for (i = 0; i < (h1->nx) * (h1->ny); i++)\n    {\n      h1->bin[i] -= h2->bin[i];\n    }\n\n  return GSL_SUCCESS;\n}\n\n/* \n * gsl_histogram2d_mult:\n * multiply two histogram\n */\n\nint \ngsl_histogram2d_mul (gsl_histogram2d * h1, const gsl_histogram2d * h2)\n{\n  size_t i;\n\n  if (!gsl_histogram2d_equal_bins_p (h1, h2))\n    {\n      GSL_ERROR (\"histograms have different binning\", GSL_EINVAL);\n    }\n\n  for (i = 0; i < (h1->nx) * (h1->ny); i++)\n    {\n      h1->bin[i] *= h2->bin[i];\n    }\n\n  return GSL_SUCCESS;\n}\n\n/* \n * gsl_histogram2d_div:\n * divide two histogram\n */\n\nint \ngsl_histogram2d_div (gsl_histogram2d * h1, const gsl_histogram2d * h2)\n{\n  size_t i;\n\n  if (!gsl_histogram2d_equal_bins_p (h1, h2))\n    {\n      GSL_ERROR (\"histograms have different binning\", GSL_EINVAL);\n    }\n\n  for (i = 0; i < (h1->nx) * (h1->ny); i++)\n    {\n      h1->bin[i] /= h2->bin[i];\n    }\n\n  return GSL_SUCCESS;\n}\n\n/* \n * gsl_histogram2d_scale:\n * scale a histogram by a numeric factor\n */\n\nint \ngsl_histogram2d_scale (gsl_histogram2d * h, double scale)\n{\n  size_t i;\n\n  for (i = 0; i < (h->nx) * (h->ny); i++)\n    {\n      h->bin[i] *= scale;\n    }\n  \n  return GSL_SUCCESS;\n}\n\n/* \n * gsl_histogram2d_shift:\n * shift a histogram by a numeric offset\n */\n\nint \ngsl_histogram2d_shift (gsl_histogram2d * h, double shift)\n{\n  size_t i;\n\n  for (i = 0; i < (h->nx) * (h->ny); i++)\n    {\n      h->bin[i] += shift;\n    }\n  \n  return GSL_SUCCESS;\n}\n\n", "meta": {"hexsha": "bd6b72e8cf8338d3730ec402f82209de9bd9dcd3", "size": 4269, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/histogram/oper2d.c", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/histogram/oper2d.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/histogram/oper2d.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 20.9264705882, "max_line_length": 78, "alphanum_fraction": 0.5956898571, "num_tokens": 1269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.36816641964831787}}
{"text": "#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n#include <math.h>\n#include <gbpLib.h>\n#include <gbpRNG.h>\n#include <gbpMCMC.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_fit.h>\n#include <gsl/gsl_interp.h>\n\nvoid generate_MCMC_proposition(MCMC_info *MCMC, int flag_chain_init) {\n    // Set the parameters for first trial parameters for the proposition\n    switch(flag_chain_init) {\n        case GBP_TRUE:\n            memcpy(MCMC->P_new, MCMC->P_init, (size_t)MCMC->n_P * sizeof(double));\n            memcpy(MCMC->P_last, MCMC->P_init, (size_t)MCMC->n_P * sizeof(double));\n            memcpy(MCMC->P_chain, MCMC->P_init, (size_t)MCMC->n_P * sizeof(double));\n            MCMC->flag_init_chain = GBP_FALSE;\n            MCMC->n_success       = 0;\n            MCMC->n_fail          = 0;\n            MCMC->n_propositions  = 0;\n            break;\n        case GBP_FALSE:\n            generate_MCMC_parameters(MCMC);\n            break;\n    }\n\n    // Keep generating new parameter sets until the mapping function is satisfied\n    while(MCMC->map_P_to_M(MCMC->P_new, MCMC, MCMC->M_new)) {\n        MCMC->n_map_calls++;\n        MCMC->first_map_call = GBP_FALSE;\n        generate_MCMC_parameters(MCMC);\n    }\n    MCMC->first_map_call = GBP_FALSE;\n    MCMC->n_map_calls++;\n\n    // Produce likelihood for this proposition\n    MCMC->compute_MCMC_ln_likelihood(\n        MCMC, MCMC->M_new, MCMC->P_new, MCMC->ln_likelihood_DS, MCMC->n_DoF_DS, &(MCMC->ln_likelihood_new), &(MCMC->n_DoF));\n    if(!SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_PARALLEL)) {\n        SID_Bcast(MCMC->ln_likelihood_DS, MCMC->n_DS, SID_DOUBLE, SID_MASTER_RANK, MCMC->comm);\n        SID_Bcast(MCMC->n_DoF_DS, MCMC->n_DS, SID_INT, SID_MASTER_RANK, MCMC->comm);\n        SID_Bcast(&(MCMC->ln_likelihood_new), 1, SID_DOUBLE, SID_MASTER_RANK, MCMC->comm);\n        SID_Bcast(&(MCMC->n_DoF), 1, SID_INT, SID_MASTER_RANK, MCMC->comm);\n    }\n\n    MCMC->first_likelihood_call = GBP_FALSE;\n    if(flag_chain_init) {\n        MCMC->ln_likelihood_chain = MCMC->ln_likelihood_new;\n        MCMC->ln_likelihood_best  = MCMC->ln_likelihood_new;\n        memcpy(MCMC->P_best, MCMC->P_new, (size_t)MCMC->n_P * sizeof(double));\n        MCMC->ln_Pr_chain = 0.;\n        MCMC->ln_Pr_new   = 0.;\n    }\n    // Keep track of the best proposition\n    else if(MCMC->ln_likelihood_new > MCMC->ln_likelihood_best) {\n        MCMC->ln_likelihood_best = MCMC->ln_likelihood_new;\n        memcpy(MCMC->P_best, MCMC->P_new, (size_t)MCMC->n_P * sizeof(double));\n    }\n}\n", "meta": {"hexsha": "1774b21bf59603d47f16d6a7cc633b3b4b59d302", "size": 2502, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMCMC/generate_MCMC_proposition.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpMath/gbpMCMC/generate_MCMC_proposition.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpMath/gbpMCMC/generate_MCMC_proposition.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 40.3548387097, "max_line_length": 124, "alphanum_fraction": 0.6518784972, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.36793791383335905}}
{"text": "/**\n *\n * @file zcposv.c\n *\n *  PLASMA computational routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Emmanuel Agullo\n * @date 2010-11-15\n * @precisions mixed zc -> ds\n *\n **/\n#include <stdlib.h>\n#include <math.h>\n#include <lapacke.h>\n#include \"common.h\"\n\n#define PLASMA_zlag2c(_descA, _descSB)                \\\n  plasma_parallel_call_4(plasma_pzlag2c,              \\\n                         PLASMA_desc,      (_descA),  \\\n                         PLASMA_desc,      (_descSB), \\\n                         PLASMA_sequence*, sequence,  \\\n                         PLASMA_request*,  request)\n\n#define PLASMA_clag2z(_descSA, _descB)                \\\n  plasma_parallel_call_4(plasma_pclag2z,              \\\n                         PLASMA_desc,      (_descSA), \\\n                         PLASMA_desc,      (_descB),  \\\n                         PLASMA_sequence*, sequence,  \\\n                         PLASMA_request*,  request)\n\n#define PLASMA_zlange(_norm, _descA, _result, _work)   \\\n  _result = 0;                                         \\\n  plasma_parallel_call_6(plasma_pzlange,               \\\n                         PLASMA_enum,      (_norm),    \\\n                         PLASMA_desc,      (_descA),   \\\n                         double*,          (_work),    \\\n                         double*,          &(_result), \\\n                         PLASMA_sequence*, sequence,   \\\n                         PLASMA_request*,  request);\n\n#define PLASMA_zlanhe(_norm, _uplo, _descA, _result, _work) \\\n  _result = 0;                                              \\\n  plasma_parallel_call_7(plasma_pzlanhe,                    \\\n                         PLASMA_enum,      (_norm),         \\\n                         PLASMA_enum,      (_uplo),         \\\n                         PLASMA_desc,      (_descA),        \\\n                         double*,          (_work),         \\\n                         double*,          &(_result),      \\\n                         PLASMA_sequence*, sequence,        \\\n                         PLASMA_request*,  request);\n\n#define PLASMA_zlacpy(_descA, _descB)                        \\\n  plasma_parallel_call_5(plasma_pzlacpy,                     \\\n                         PLASMA_enum,      PlasmaUpperLower, \\\n                         PLASMA_desc,      (_descA),         \\\n                         PLASMA_desc,      (_descB),         \\\n                         PLASMA_sequence*, sequence,         \\\n                         PLASMA_request*,  request)\n\n#define PLASMA_zgeadd(_alpha, _descA, _descB)           \\\n  plasma_parallel_call_5(plasma_pzgeadd,                \\\n                         PLASMA_Complex64_t, (_alpha),  \\\n                         PLASMA_desc,        (_descA),  \\\n                         PLASMA_desc,        (_descB),  \\\n                         PLASMA_sequence*,   sequence,  \\\n                         PLASMA_request*,    request)\n\n/***************************************************************************//**\n *\n * @ingroup PLASMA_Complex64_t\n *\n *  PLASMA_zcposv - Computes the solution to a system of linear equations A * X = B,\n *  where A is an N-by-N symmetric positive definite (or Hermitian positive definite\n *  in the complex case) matrix and X and B are N-by-NRHS matrices.\n *  The Cholesky decomposition is used to factor A as\n *\n *    A = U**H * U, if uplo = PlasmaUpper, or\n *    A = L * L**H, if uplo =  PlasmaLower,\n *\n *  where U is an upper triangular matrix and  L is a lower triangular matrix.\n *  The factored form of A is then used to solve the system of equations A * X = B.\n *\n *  PLASMA_zcposv first attempts to factorize the matrix in COMPLEX and use this\n *  factorization within an iterative refinement procedure to produce a\n *  solution with COMPLEX*16 normwise backward error quality (see below).\n *  If the approach fails the method switches to a COMPLEX*16\n *  factorization and solve.\n *\n *  The iterative refinement is not going to be a winning strategy if\n *  the ratio COMPLEX performance over COMPLEX*16 performance is too\n *  small. A reasonable strategy should take the number of right-hand\n *  sides and the size of the matrix into account. This might be done\n *  with a call to ILAENV in the future. Up to now, we always try\n *  iterative refinement.\n *\n *  The iterative refinement process is stopped if ITER > ITERMAX or\n *  for all the RHS we have: RNRM < N*XNRM*ANRM*EPS*BWDMAX\n *  where:\n *\n *  - ITER is the number of the current iteration in the iterative refinement process\n *  - RNRM is the infinity-norm of the residual\n *  - XNRM is the infinity-norm of the solution\n *  - ANRM is the infinity-operator-norm of the matrix A\n *  - EPS is the machine epsilon returned by DLAMCH('Epsilon').\n *\n *  Actually, in its current state (PLASMA 2.1.0), the test is slightly relaxed.\n *\n *  The values ITERMAX and BWDMAX are fixed to 30 and 1.0D+00 respectively.\n *\n *******************************************************************************\n *\n * @param[in] uplo\n *          Specifies whether the matrix A is upper triangular or lower triangular:\n *          = PlasmaUpper: Upper triangle of A is stored;\n *          = PlasmaLower: Lower triangle of A is stored.\n *\n * @param[in] N\n *          The number of linear equations, i.e., the order of the matrix A. N >= 0.\n *\n * @param[in] NRHS\n *          The number of right hand sides, i.e., the number of columns of the matrix B.\n *          NRHS >= 0.\n *\n * @param[in] A\n *          The N-by-N symmetric positive definite (or Hermitian) coefficient matrix A.\n *          If uplo = PlasmaUpper, the leading N-by-N upper triangular part of A\n *          contains the upper triangular part of the matrix A, and the strictly lower triangular\n *          part of A is not referenced.\n *          If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower\n *          triangular part of the matrix A, and the strictly upper triangular part of A is not\n *          referenced.\n *          This matrix is not modified.\n *\n * @param[in] LDA\n *          The leading dimension of the array A. LDA >= max(1,N).\n *\n * @param[in] B\n *          The N-by-NRHS matrix of right hand side matrix B.\n *\n * @param[in] LDB\n *          The leading dimension of the array B. LDB >= max(1,N).\n *\n * @param[out] X\n *          If return value = 0, the N-by-NRHS solution matrix X.\n *\n * @param[in] LDX\n *          The leading dimension of the array B. LDX >= max(1,N).\n *\n * @param[out] ITER\n *          The number of the current iteration in the iterative refinement process\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *          \\retval <0 if -i, the i-th argument had an illegal value\n *          \\retval >0 if i, the leading minor of order i of A is not positive definite, so the\n *               factorization could not be completed, and the solution has not been computed.\n *\n *******************************************************************************\n *\n * @sa PLASMA_zcposv_Tile\n * @sa PLASMA_zcposv_Tile_Async\n * @sa PLASMA_dsposv\n * @sa PLASMA_zposv\n *\n ******************************************************************************/\nint PLASMA_zcposv(PLASMA_enum uplo, int N, int NRHS,\n                  PLASMA_Complex64_t *A, int LDA,\n                  PLASMA_Complex64_t *B, int LDB,\n                  PLASMA_Complex64_t *X, int LDX, int *ITER)\n{\n    int NB;\n    int status;\n    PLASMA_desc  descA;\n    PLASMA_desc  descB;\n    PLASMA_desc  descX;\n    plasma_context_t *plasma;\n    PLASMA_sequence *sequence = NULL;\n    PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_zcposv\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n\n    *ITER = 0;\n\n    /* Check input arguments */\n    if (uplo != PlasmaUpper && uplo != PlasmaLower) {\n        plasma_error(\"PLASMA_zcposv\", \"illegal value of uplo\");\n        return -1;\n    }\n    if (N < 0) {\n        plasma_error(\"PLASMA_zcposv\", \"illegal value of N\");\n        return -2;\n    }\n    if (NRHS < 0) {\n        plasma_error(\"PLASMA_zcposv\", \"illegal value of NRHS\");\n        return -3;\n    }\n    if (LDA < max(1, N)) {\n        plasma_error(\"PLASMA_zcposv\", \"illegal value of LDA\");\n        return -5;\n    }\n    if (LDB < max(1, N)) {\n        plasma_error(\"PLASMA_zcposv\", \"illegal value of LDB\");\n        return -7;\n    }\n    if (LDX < max(1, N)) {\n        plasma_error(\"PLASMA_zcposv\", \"illegal value of LDX\");\n        return -9;\n    }\n    /* Quick return - currently NOT equivalent to LAPACK's\n     * LAPACK does not have such check for ZCPOSV */\n    if (min(N, NRHS) == 0)\n        return PLASMA_SUCCESS;\n\n    /* Tune NB depending on M, N & NRHS; Set NBNBSIZE */\n    status = plasma_tune(PLASMA_FUNC_ZCPOSV, N, N, NRHS);\n    if (status != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_zcposv\", \"plasma_tune() failed\");\n        return status;\n    }\n\n    NB = PLASMA_NB;\n\n    plasma_sequence_create(plasma, &sequence);\n\n    /* DOUBLE PRECISION INITIALIZATION */\n    if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n        plasma_zooplap2tile( descA, A, NB, NB, LDA, N,    0, 0, N, N,    sequence, &request,\n                             plasma_desc_mat_free(&(descA)) );\n        plasma_zooplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS, sequence, &request,\n                             plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB)) );\n        plasma_zdesc_alloc(  descX, NB, NB, N, NRHS, 0, 0, N, NRHS, plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB)); plasma_desc_mat_free(&(descX)) );\n    } else {\n        plasma_ziplap2tile( descA, A, NB, NB, LDA, N,    0, 0, N, N,   \n                            sequence, &request);\n        plasma_ziplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS,\n                            sequence, &request);\n\n        descX = plasma_desc_init(\n            PlasmaComplexDouble, NB, NB, (NB*NB), \n            LDX, NRHS, 0, 0, N, NRHS);\n        descX.mat = X;\n    }\n\n    /* Call the native interface */\n    status = PLASMA_zcposv_Tile_Async(uplo, &descA, &descB, &descX, ITER, sequence, &request);\n\n    if (status == PLASMA_SUCCESS) {\n        if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n            plasma_zooptile2lap( descX, X, NB, NB, LDX, NRHS,  sequence, &request);\n            plasma_dynamic_sync();\n            plasma_desc_mat_free(&descA);\n            plasma_desc_mat_free(&descB);\n            plasma_desc_mat_free(&descX);\n        } else {\n            plasma_ziptile2lap( descA, A, NB, NB, LDA, N,     sequence, &request);\n            plasma_ziptile2lap( descB, B, NB, NB, LDB, NRHS,  sequence, &request);\n            plasma_ziptile2lap( descX, X, NB, NB, LDX, NRHS,  sequence, &request);\n            plasma_dynamic_sync();\n        }\n    }\n\n    status = sequence->status;\n    plasma_sequence_destroy(plasma, sequence);\n    return status;\n}\n\n\n/***************************************************************************//**\n *\n * @ingroup PLASMA_Complex64_t_Tile\n *\n *  PLASMA_zcposv_Tile - Solves a symmetric positive definite or Hermitian positive definite\n *  system of linear equations using the Cholesky factorization and mixed-precision iterative refinement.\n *  Tile equivalent of PLASMA_zcposv().\n *  Operates on matrices stored by tiles.\n *  All matrices are passed through descriptors.\n *  All dimensions are taken from the descriptors.\n *\n *******************************************************************************\n *\n * @param[in] uplo\n *          Specifies whether the matrix A is upper triangular or lower triangular:\n *          = PlasmaUpper: Upper triangle of A is stored;\n *          = PlasmaLower: Lower triangle of A is stored.\n *\n * @param[in,out] A\n *          On entry, the N-by-N symmetric positive definite (or Hermitian) coefficient matrix A.\n *          If uplo = PlasmaUpper, the leading N-by-N upper triangular part of A\n *          contains the upper triangular part of the matrix A, and the strictly lower triangular\n *          part of A is not referenced.\n *          If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower\n *          triangular part of the matrix A, and the strictly upper triangular part of A is not\n *          referenced.\n *          - If the iterative refinement converged, A is not modified;\n *          - otherwise, it falled backed to double precision solution,\n *\n * @param[in] B\n *          On entry, the N-by-NRHS matrix of right hand side matrix B.\n *\n * @param[out] X\n *          On exit, if return value = 0, the N-by-NRHS solution matrix X.\n *\n * @param[out] ITER\n *          The number of the current iteration in the iterative refinement process\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *          \\retval >0 if i, the leading minor of order i of A is not positive definite, so the\n *               factorization could not be completed, and the solution has not been computed.\n *\n *******************************************************************************\n *\n * @sa PLASMA_zcposv\n * @sa PLASMA_zcposv_Tile_Async\n * @sa PLASMA_dsposv_Tile\n * @sa PLASMA_zposv_Tile\n *\n ******************************************************************************/\nint PLASMA_zcposv_Tile(PLASMA_enum uplo, PLASMA_desc *A, PLASMA_desc *B,\n                       PLASMA_desc *X, int *ITER)\n{\n    plasma_context_t *plasma;\n    PLASMA_sequence *sequence = NULL;\n    PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n    int status;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_zcposv_Tile\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n    plasma_sequence_create(plasma, &sequence);\n    status = PLASMA_zcposv_Tile_Async(uplo, A, B, X, ITER, sequence, &request);\n    if (status != PLASMA_SUCCESS)\n        return status;\n    plasma_dynamic_sync();\n    status = sequence->status;\n    plasma_sequence_destroy(plasma, sequence);\n    return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup PLASMA_Complex64_t_Tile_Async\n *\n *  PLASMA_zcposv_Tile_Async - Solves a symmetric positive definite or Hermitian\n *  positive definite system of linear equations using the Cholesky factorization\n *  and mixed-precision iterative refinement.\n *  Non-blocking equivalent of PLASMA_zcposv_Tile().\n *  May return before the computation is finished.\n *  Allows for pipelining of operations at runtime.\n *\n *******************************************************************************\n *\n * @param[in] sequence\n *          Identifies the sequence of function calls that this call belongs to\n *          (for completion checks and exception handling purposes).\n *\n * @param[out] request\n *          Identifies this function call (for exception handling purposes).\n *\n *******************************************************************************\n *\n * @sa PLASMA_zcposv\n * @sa PLASMA_zcposv_Tile\n * @sa PLASMA_dsposv_Tile_Async\n * @sa PLASMA_zposv_Tile_Async\n *\n ******************************************************************************/\nint PLASMA_zcposv_Tile_Async(PLASMA_enum uplo, PLASMA_desc *A, PLASMA_desc *B,\n                             PLASMA_desc *X, int *ITER,\n                             PLASMA_sequence *sequence, PLASMA_request *request)\n{\n    int N, NB;\n    PLASMA_desc descA;\n    PLASMA_desc descB;\n    PLASMA_desc descX;\n    plasma_context_t *plasma;\n    double *work;\n    PLASMA_desc descR, descSA, descSX;\n\n    const int itermax = 30;\n    const double bwdmax = 1.0;\n    const PLASMA_Complex64_t negone = -1.0;\n    const PLASMA_Complex64_t one = 1.0;\n    int iiter;\n    double Anorm, cte, eps, Rnorm, Xnorm;\n    *ITER=0;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_zcposv_Tile_Async\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n    if (sequence == NULL) {\n        plasma_fatal_error(\"PLASMA_zcposv_Tile_Async\", \"NULL sequence\");\n        return PLASMA_ERR_UNALLOCATED;\n    }\n    if (request == NULL) {\n        plasma_fatal_error(\"PLASMA_zcposv_Tile_Async\", \"NULL request\");\n        return PLASMA_ERR_UNALLOCATED;\n    }\n    /* Check sequence status */\n    if (sequence->status == PLASMA_SUCCESS)\n        request->status = PLASMA_SUCCESS;\n    else\n        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n\n    /* Check descriptors for correctness */\n    if (plasma_desc_check(A) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_zcposv_Tile_Async\", \"invalid first descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descA = *A;\n    }\n    if (plasma_desc_check(B) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_zcposv_Tile_Async\", \"invalid second descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descB = *B;\n    }\n    if (plasma_desc_check(X) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_zcposv_Tile_Async\", \"invalid third descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descX = *X;\n    }\n    /* Check input arguments */\n    if (descA.nb != descA.mb || descB.nb != descB.mb || descX.nb != descX.mb) {\n        plasma_error(\"PLASMA_zcposv_Tile_Async\", \"only square tiles supported\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    }\n    if (uplo != PlasmaUpper && uplo != PlasmaLower) {\n        plasma_error(\"PLASMA_zcposv_Tile_Async\", \"illegal value of uplo\");\n        return -1;\n    }\n    /* Quick return - currently NOT equivalent to LAPACK's\n     * LAPACK does not have such check for DPOSV */\n\n/*\n    if (min(N, NRHS) == 0)\n        return PLASMA_SUCCESS;\n*/\n\n    /* Set N, NRHS */\n    N  = descA.m;\n    NB = descA.nb;\n\n    work = (double *)plasma_shared_alloc(plasma, PLASMA_SIZE, PlasmaRealDouble);\n    if (work == NULL) {\n        plasma_error(\"PLASMA_zcposv_Tile_Async\", \"plasma_shared_alloc() failed\");\n        plasma_shared_free(plasma, work);\n        return PLASMA_ERR_OUT_OF_RESOURCES;\n    }\n\n    plasma_zdesc_alloc( descR,  NB, NB, descB.m, descB.n, 0, 0, descB.m, descB.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR) );\n    plasma_cdesc_alloc( descSA, NB, NB, descA.m, descA.n, 0, 0, descA.m, descA.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA) );\n    plasma_cdesc_alloc( descSX, NB, NB, descX.m, descX.n, 0, 0, descX.m, descX.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descSX) );\n\n    /* Compute some constants */\n    PLASMA_zlanhe(PlasmaInfNorm, uplo, descA, Anorm, work);\n    eps = LAPACKE_dlamch_work('e');\n\n    /* Convert B from double precision to single precision and store\n       the result in SX. */\n    PLASMA_zlag2c(descB, descSX);\n    if (sequence->status != PLASMA_SUCCESS)\n        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n\n    /* Convert A from double precision to single precision and store\n       the result in SA. */\n    PLASMA_zlag2c(descA, descSA);\n    if (sequence->status != PLASMA_SUCCESS)\n        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n\n    /* Compute the Cholesky factorization of SA */\n    plasma_parallel_call_4(plasma_pcpotrf,\n        PLASMA_enum, uplo,\n        PLASMA_desc, descSA,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    /* Solve the system SA*SX = SB */\n    /* Forward substitution */\n    plasma_parallel_call_9(plasma_pctrsm,\n        PLASMA_enum, PlasmaLeft,\n        PLASMA_enum, uplo,\n        PLASMA_enum, uplo == PlasmaUpper ? PlasmaConjTrans : PlasmaNoTrans,\n        PLASMA_enum, PlasmaNonUnit,\n        PLASMA_Complex32_t, 1.0,\n        PLASMA_desc, descSA,\n        PLASMA_desc, descSX,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    /* Backward substitution */\n    plasma_parallel_call_9(plasma_pctrsm,\n        PLASMA_enum, PlasmaLeft,\n        PLASMA_enum, uplo,\n        PLASMA_enum, uplo == PlasmaUpper ? PlasmaNoTrans : PlasmaConjTrans,\n        PLASMA_enum, PlasmaNonUnit,\n        PLASMA_Complex32_t, 1.0,\n        PLASMA_desc, descSA,\n        PLASMA_desc, descSX,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    /* Convert SX back to double precision */\n    PLASMA_clag2z(descSX, descX);\n\n    /* Compute R = B - AX. */\n    PLASMA_zlacpy(descB,descR);\n    plasma_parallel_call_9(plasma_pzhemm,\n        PLASMA_enum, PlasmaLeft,\n        PLASMA_enum, uplo,\n        PLASMA_Complex64_t, negone,\n        PLASMA_desc, descA,\n        PLASMA_desc, descX,\n        PLASMA_Complex64_t, one,\n        PLASMA_desc, descR,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    /* Check whether the NRHS normwise backward error satisfies the\n       stopping criterion. If yes return. Note that ITER=0 (already set). */\n    PLASMA_zlange(PlasmaInfNorm, descX, Xnorm, work);\n    PLASMA_zlange(PlasmaInfNorm, descR, Rnorm, work);\n\n    /* Wait for the end of Anorm, Xnorm and Bnorm computations */\n    plasma_dynamic_sync();\n\n    cte = Anorm*eps*((double) N)*bwdmax;\n    if (Rnorm < Xnorm * cte){\n        /* The NRHS normwise backward errors satisfy the\n           stopping criterion. We are good to exit. */\n        plasma_desc_mat_free(&descSA);\n        plasma_desc_mat_free(&descSX);\n        plasma_desc_mat_free(&descR);\n        plasma_shared_free(plasma, work);\n        return PLASMA_SUCCESS;\n    }\n\n    /* Iterative refinement */\n    for (iiter = 0; iiter < itermax; iiter++){\n\n        /* Convert R from double precision to single precision\n           and store the result in SX. */\n        PLASMA_zlag2c(descR, descSX);\n\n        /* Solve the system SA*SX = SR */\n        /* Forward substitution */\n        plasma_parallel_call_9(plasma_pctrsm,\n            PLASMA_enum, PlasmaLeft,\n            PLASMA_enum, uplo,\n            PLASMA_enum, uplo == PlasmaUpper ? PlasmaConjTrans : PlasmaNoTrans,\n            PLASMA_enum, PlasmaNonUnit,\n            PLASMA_Complex32_t, 1.0,\n            PLASMA_desc, descSA,\n            PLASMA_desc, descSX,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        /* Backward substitution */\n        plasma_parallel_call_9(plasma_pctrsm,\n            PLASMA_enum, PlasmaLeft,\n            PLASMA_enum, uplo,\n            PLASMA_enum, uplo == PlasmaUpper ? PlasmaNoTrans : PlasmaConjTrans,\n            PLASMA_enum, PlasmaNonUnit,\n            PLASMA_Complex32_t, 1.0,\n            PLASMA_desc, descSA,\n            PLASMA_desc, descSX,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        /* Convert SX back to double precision and update the current\n           iterate. */\n        PLASMA_clag2z(descSX, descR);\n        PLASMA_zgeadd(one, descR, descX);\n\n        /* Compute R = B - AX. */\n        PLASMA_zlacpy(descB,descR);\n        plasma_parallel_call_9(plasma_pzhemm,\n            PLASMA_enum, PlasmaLeft,\n            PLASMA_enum, uplo,\n            PLASMA_Complex64_t, negone,\n            PLASMA_desc, descA,\n            PLASMA_desc, descX,\n            PLASMA_Complex64_t, one,\n            PLASMA_desc, descR,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        /* Check whether the NRHS normwise backward errors satisfy the\n           stopping criterion. If yes, set ITER=IITER>0 and return. */\n        PLASMA_zlange(PlasmaInfNorm, descX, Xnorm, work);\n        PLASMA_zlange(PlasmaInfNorm, descR, Rnorm, work);\n\n        /* Wait for the end of Xnorm and Bnorm computations */\n        plasma_dynamic_sync();\n\n        if (Rnorm < Xnorm * cte){\n            /* The NRHS normwise backward errors satisfy the\n               stopping criterion. We are good to exit. */\n            *ITER = iiter;\n\n            plasma_desc_mat_free(&descSA);\n            plasma_desc_mat_free(&descSX);\n            plasma_desc_mat_free(&descR);\n            plasma_shared_free(plasma, work);\n            return PLASMA_SUCCESS;\n        }\n    }\n\n    /* We have performed ITER=itermax iterations and never satisified\n       the stopping criterion, set up the ITER flag accordingly and\n       follow up on double precision routine. */\n    *ITER = -itermax - 1;\n\n    plasma_desc_mat_free(&descSA);\n    plasma_desc_mat_free(&descSX);\n    plasma_desc_mat_free(&descR);\n    plasma_shared_free(plasma, work);\n\n    /* Single-precision iterative refinement failed to converge to a\n       satisfactory solution, so we resort to double precision. */\n\n    plasma_parallel_call_4(plasma_pzpotrf,\n        PLASMA_enum, uplo,\n        PLASMA_desc, descA,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    PLASMA_zlacpy(descB,descX);\n\n    plasma_parallel_call_9(plasma_pztrsm,\n        PLASMA_enum, PlasmaLeft,\n        PLASMA_enum, uplo,\n        PLASMA_enum, uplo == PlasmaUpper ? PlasmaConjTrans : PlasmaNoTrans,\n        PLASMA_enum, PlasmaNonUnit,\n        PLASMA_Complex64_t, 1.0,\n        PLASMA_desc, descA,\n        PLASMA_desc, descX,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    plasma_parallel_call_9(plasma_pztrsm,\n        PLASMA_enum, PlasmaLeft,\n        PLASMA_enum, uplo,\n        PLASMA_enum, uplo == PlasmaUpper ? PlasmaNoTrans : PlasmaConjTrans,\n        PLASMA_enum, PlasmaNonUnit,\n        PLASMA_Complex64_t, 1.0,\n        PLASMA_desc, descA,\n        PLASMA_desc, descX,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "9a61790380ac1fcc5cf4514046a2a9a29bf169dc", "size": 25757, "ext": "c", "lang": "C", "max_stars_repo_path": "compute/zcposv.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/zcposv.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/zcposv.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.4432835821, "max_line_length": 211, "alphanum_fraction": 0.5906743798, "num_tokens": 6688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.367937913833359}}
{"text": "/*\n * Implement Heap sort -- direct and indirect sorting\n * Based on descriptions in Sedgewick \"Algorithms in C\"\n *\n * Copyright (C) 1999  Thomas Walter\n *\n * 18 February 2000: Modified for GSL by Brian Gough\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the\n * Free Software Foundation; either version 2, or (at your option) any\n * later version.\n *\n * This source is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n * for more details.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_heapsort.h>\n\nstatic inline void swap (void *base, size_t size, size_t i, size_t j);\nstatic inline void downheap (void *data, const size_t size, const size_t N, size_t k, gsl_comparison_fn_t compare);\n\n/* Inline swap function for moving objects around */\n\nstatic inline void\nswap (void *base, size_t size, size_t i, size_t j)\n{\n  register char *a = size * i + (char *) base;\n  register char *b = size * j + (char *) base;\n  register size_t s = size;\n\n  if (i == j)\n    return;\n\n  do\n    {\n      char tmp = *a;\n      *a++ = *b;\n      *b++ = tmp;\n    }\n  while (--s > 0);\n}\n\n#define CMP(data,size,j,k) (compare((char *)(data) + (size) * (j), (char *)(data) + (size) * (k)))\n\nstatic inline void\ndownheap (void *data, const size_t size, const size_t N, size_t k, gsl_comparison_fn_t compare)\n{\n  while (k <= N / 2)\n    {\n      size_t j = 2 * k;\n\n      if (j < N && CMP (data, size, j, j + 1) < 0)\n        {\n          j++;\n        }\n\n      if (CMP (data, size, k, j) < 0)\n        {\n          swap (data, size, j, k);\n        }\n      else\n        {\n          break;\n        }\n\n      k = j;\n    }\n}\n\nvoid\ngsl_heapsort (void *data, size_t count, size_t size, gsl_comparison_fn_t compare)\n{\n  /* Sort the array in ascending order. This is a true inplace\n     algorithm with N log N operations. Worst case (an already sorted\n     array) is something like 20% slower */\n\n  size_t N;\n  size_t k;\n\n  if (count == 0)\n    {\n      return;                   /* No data to sort */\n    }\n\n  /* We have n_data elements, last element is at 'n_data-1', first at\n     '0' Set N to the last element number. */\n\n  N = count - 1;\n\n  k = N / 2;\n  k++;                          /* Compensate the first use of 'k--' */\n  do\n    {\n      k--;\n      downheap (data, size, N, k, compare);\n    }\n  while (k > 0);\n\n  while (N > 0)\n    {\n      /* first swap the elements */\n      swap (data, size, 0, N);\n\n      /* then process the heap */\n      N--;\n\n      downheap (data, size, N, 0, compare);\n    }\n}\n", "meta": {"hexsha": "9e86ab0b076ab1b13c3a82238d529b9ef7e7e984", "size": 2719, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/sort/sort.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/sort/sort.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/sort/sort.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 23.6434782609, "max_line_length": 115, "alphanum_fraction": 0.586244943, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.36758939790918216}}
{"text": "/**\n * @file      DiscreteRangeDecorators.h\n *\n * @brief     This file contains some decorator functions for DiscreteRange\n * types\n *\n * @author    Stefan Reinhold\n * @copyright Copyright (C) 2018 Stefan Reinhold  -- All Rights Reserved.\n * You may use, distribute and modify this code under the terms of the\n * AFL 3.0 license; see LICENSE for full license details.\n */\n\n#include \"DiscreteRange.h\"\n\n#include <Eigen/Core>\n#include <gsl/gsl>\n\nnamespace CortidQCT {\nnamespace Internal {\n\n/**\n * @brief Returns all element of the given discrete range as a vector\n * @param range DiscreteRange object\n * @return An Eigen vector containing all element of `range`\n */\ntemplate <class T>\nEigen::Matrix<T, Eigen::Dynamic, 1>\ndiscreteRangeElementVector(DiscreteRange<T> const &range) {\n  using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\n  Vector t(gsl::narrow<Eigen::Index>(range.numElements()));\n\n  for (auto i = 0; i < t.rows(); ++i) {\n    t(i) = range.min + static_cast<T>(i) * range.stride;\n  }\n\n  return t;\n}\n\n} // namespace Internal\n} // namespace CortidQCT\n", "meta": {"hexsha": "ec0393b7fbc87c4704527115aa6fc0513353f9e5", "size": 1060, "ext": "h", "lang": "C", "max_stars_repo_path": "lib/DiscreteRangeDecorators.h", "max_stars_repo_name": "ithron/CortidQCT", "max_stars_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-21T17:30:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T17:30:23.000Z", "max_issues_repo_path": "lib/DiscreteRangeDecorators.h", "max_issues_repo_name": "ithron/CortidQCT", "max_issues_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2018-10-23T10:51:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-22T08:11:33.000Z", "max_forks_repo_path": "lib/DiscreteRangeDecorators.h", "max_forks_repo_name": "ithron/CortidQCT", "max_forks_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2380952381, "max_line_length": 75, "alphanum_fraction": 0.6943396226, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.3675893943195701}}
{"text": "/* -*- linux-c -*- */\n/* binsingle.c\n\n   Copyright (C) 2002-2004 John M. Fregeau\n   \n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n   \n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n   \n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n*/\n\n#include <stdio.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <getopt.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_rng.h>\n#include \"fewbody.h\"\n#include \"binsingle_simple.h\"\n\n/* calculate the units used */\nint calc_units(fb_obj_t *single, fb_obj_t *binary, fb_units_t *units)\n{\n\tunits->v = sqrt(FB_CONST_G*(single->m + binary->m)/(single->m * binary->m) * \\\n\t\t\t(binary->obj[0]->m * binary->obj[1]->m / binary->a));\n\tunits->l = binary->a;\n\tunits->t = units->l / units->v;\n\tunits->m = units->l * fb_sqr(units->v) / FB_CONST_G;\n\tunits->E = units->m * fb_sqr(units->v);\n\t\n\treturn(0);\n}\n\n/* the main attraction */\nint main(int argc, char *argv[])\n{\n\tint i, n;\n\tunsigned long int seed;\n\tdouble m0, m10, m11, r0, r10, r11, a1, e1;\n\tdouble rtid, vinf, b, m1, M, mu, Ei, t;\n\tfb_hier_t hier;\n\tfb_input_t input;\n\tfb_ret_t retval;\n\tfb_units_t units;\n\tchar string1[FB_MAX_STRING_LENGTH], string2[FB_MAX_STRING_LENGTH];\n\tgsl_rng *rng;\n\tconst gsl_rng_type *rng_type=gsl_rng_mt19937;\n\n\t/* set parameters to default values */\n\tm0 = FB_M0;\n\tm10 = FB_M10;\n\tm11 = FB_M11;\n\tr0 = FB_R0;\n\tr10 = FB_R10;\n\tr11 = FB_R11;\n\ta1 = FB_A1;\n\te1 = FB_E1;\n\tvinf = FB_VINF;\n\tb = FB_B;\n\tinput.ks = FB_KS;\n\tinput.tstop = FB_TSTOP;\n\tinput.Dflag = 0;\n\tinput.dt = FB_DT;\n\tinput.tcpustop = FB_TCPUSTOP;\n\tinput.absacc = FB_ABSACC;\n\tinput.relacc = FB_RELACC;\n\tinput.ncount = FB_NCOUNT;\n\tinput.tidaltol = FB_TIDALTOL;\n\tinput.fexp = FB_FEXP;\n\tseed = FB_SEED;\n\tfb_debug = FB_DEBUG;\n\n\t/* initialize a few things for integrator */\n\tt = 0.0;\n\tfbui_new_hier(&hier, 3);\n\n\t/* initialize GSL rng */\n\tgsl_rng_env_setup();\n\trng = gsl_rng_alloc(rng_type);\n\tgsl_rng_set(rng, seed);\n\n\t/* create binary */\n\tfbui_make_pair(fbui_hierarchy_binary(&hier, 0), \n\t\t       fbui_hierarchy_single(&hier, 1), fbui_hierarchy_single(&hier, 2));\n\tfbui_obj_t_set(fbui_hierarchy_binary(&hier, 0), t);\n\n\t/* give the objects some properties */\n\tfbui_initialize_single(fbui_hierarchy_single(&hier, 0), 0, \"0\");\n\tfbui_initialize_single(fbui_hierarchy_single(&hier, 1), 1, \"1\");\n\tfbui_initialize_single(fbui_hierarchy_single(&hier, 2), 2, \"2\");\n\t\n\tfbui_obj_radius_set(fbui_hierarchy_single(&hier, 0), r0);\n\tfbui_obj_radius_set(fbui_hierarchy_single(&hier, 1), r10);\n\tfbui_obj_radius_set(fbui_hierarchy_single(&hier, 2), r11);\n\n\tfbui_obj_mass_set(fbui_hierarchy_single(&hier, 0), m0);\n\tfbui_obj_mass_set(fbui_hierarchy_single(&hier, 1), m10);\n\tfbui_obj_mass_set(fbui_hierarchy_single(&hier, 2), m11);\n\n\tfbui_obj_mass_set(fbui_hierarchy_binary(&hier, 0), m10+m11);\n\t\n\tfbui_obj_a_set(fbui_hierarchy_binary(&hier, 0), a1);\n\tfbui_obj_e_set(fbui_hierarchy_binary(&hier, 0), e1);\n\n\t/* get the units and normalize */\n\tcalc_units(fbui_hierarchy_single(&hier, 0), fbui_hierarchy_binary(&hier, 0), &units);\n\tfb_normalize(&hier, units);\n\t\n\t/* move hierarchies analytically in from infinity along hyperbolic orbit */\n\tm0 = fbui_obj_mass_get(fbui_hierarchy_single(&hier, 0));\n\tm1 = fbui_obj_mass_get(fbui_hierarchy_binary(&hier, 0));\n\tM = m0 + m1;\n\tmu = m0 * m1 / M;\n\n\tEi = 0.5 * mu * fb_sqr(vinf);\n\n\ta1 = fbui_obj_a_get(fbui_hierarchy_binary(&hier, 0));\n\te1 = fbui_obj_e_get(fbui_hierarchy_binary(&hier, 0));\n\tm10 = fbui_obj_mass_get(fbui_obj_left_child_get(fbui_hierarchy_binary(&hier, 0)));\n\tm11 = fbui_obj_mass_get(fbui_obj_right_child_get(fbui_hierarchy_binary(&hier, 0)));\n\n\trtid = pow(2.0*(m0+m1)/(m1*input.tidaltol), 1.0/3.0) * a1 * (1.0+e1);\n\n\tfb_init_scattering(fbui_hierarchy_single(&hier, 0), fbui_hierarchy_binary(&hier, 0), vinf, b, rtid);\n\n\t/* trickle down the binary properties, then back up */\n\tfb_randorient(fbui_hierarchy_binary(&hier, 0), rng);\n\tfb_downsync(fbui_hierarchy_binary(&hier, 0), t);\n\t\n\t/* call fewbody! */\n\tretval = fewbody(input, &hier, &t);\n\n\t/* print information to screen */\n\tfprintf(stderr, \"OUTCOME:\\n\");\n\tif (retval.retval == 1) {\n\t\tfprintf(stderr, \"  encounter complete:  t=%.6g (%.6g yr)  %s  (%s)\\n\\n\",\n\t\t\tt, t * units.t/FB_CONST_YR,\n\t\t\tfb_sprint_hier(hier, string1),\n\t\t\tfb_sprint_hier_hr(hier, string2));\n\t} else {\n\t\tfprintf(stderr, \"  encounter NOT complete:  t=%.6g (%.6g yr)  %s  (%s)\\n\\n\",\n\t\t\tt, t * units.t/FB_CONST_YR,\n\t\t\tfb_sprint_hier(hier, string1),\n\t\t\tfb_sprint_hier_hr(hier, string2));\n\t}\n\n\tfb_dprintf(\"there were %ld integration steps\\n\", retval.count);\n\tfb_dprintf(\"fb_classify() was called %ld times\\n\", retval.iclassify);\n\t\n\tfprintf(stderr, \"FINAL:\\n\");\n\tfprintf(stderr, \"  t_final=%.6g (%.6g yr)  t_cpu=%.6g s\\n\", \\\n\t\tt, t*units.t/FB_CONST_YR, retval.tcpu);\n\n\tfprintf(stderr, \"  DeltaL/L0=%.6g  DeltaL=%.6g\\n\", retval.DeltaLfrac, retval.DeltaL);\n\tfprintf(stderr, \"  DeltaE/E0=%.6g  DeltaE=%.6g\\n\", retval.DeltaEfrac, retval.DeltaE);\n\tfprintf(stderr, \"  Rmin=%.6g (%.6g RSUN)  Rmin_i=%d  Rmin_j=%d\\n\", \\\n\t\tretval.Rmin, retval.Rmin*units.l/FB_CONST_RSUN, retval.Rmin_i, retval.Rmin_j);\n\tfprintf(stderr, \"  Nosc=%d (%s)\\n\", retval.Nosc, (retval.Nosc>=1?\"resonance\":\"non-resonance\"));\n\t\n\tfprintf(stderr, \"Resulting objects:\\n\");\n\tfor (i=0; i<hier.nobj; i++) {\n\t\tn = fbui_obj_n_get(fbui_tree(&hier, i));\n\t\tif (n == 1) {\n\t\t\tfprintf(stderr, \"  single: m=%g idstring=%s\\n\", \n\t\t\t\tfbui_obj_mass_get(fbui_tree(&hier, i)) * units.m / FB_CONST_MSUN,\n\t\t\t\tfbui_obj_idstring_get(fbui_tree(&hier, i)));\n\t\t} else if (n == 2) {\n\t\t\tfprintf(stderr, \"  binary: m_i=%g,%g a=%g e=%g idstring=%s\\n\",\n\t\t\t\tfbui_obj_mass_get(fbui_obj_left_child_get(fbui_tree(&hier, i))) * units.m / FB_CONST_MSUN,\n\t\t\t\tfbui_obj_mass_get(fbui_obj_right_child_get(fbui_tree(&hier, i))) * units.m / FB_CONST_MSUN,\n\t\t\t\tfbui_obj_a_get(fbui_tree(&hier, i)) * units.l / FB_CONST_AU, \n\t\t\t\tfbui_obj_e_get(fbui_tree(&hier, i)), \n\t\t\t\tfbui_obj_idstring_get(fbui_tree(&hier, i)));\n\t\t}\n\t}\n\n\t/* free GSL stuff */\n\tgsl_rng_free(rng);\n\n\t/* free our own stuff */\n\tfbui_delete_hier(&hier);\n\n\t/* done! */\n\treturn(0);\n}\n", "meta": {"hexsha": "58b9dd4c16400ac6ac57f410f4585b946a0ed516", "size": 6586, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/binsingle_simple.c", "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": ["PSF-2.0"], "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/fewbod/fewbody-0.26/binsingle_simple.c", "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_licenses": ["PSF-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/binsingle_simple.c", "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": ["PSF-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2626262626, "max_line_length": 101, "alphanum_fraction": 0.694351655, "num_tokens": 2195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.3675893907299583}}
{"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk_5_4.c\n * \\brief Source file to optimize Runge-Kutta 5 steps 4th order methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include <string.h>\n#include <math.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include <libintl.h>\n#include <gsl/gsl_rng.h>\n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_5_4.h\"\n\n#define DEBUG_RK_5_4 0          ///< macro to debug.\n\n/**\n * Function to obtain the coefficients of a 5 steps 4th order Runge-Kutta \n * method.\n */\nint\nrk_tb_5_4 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *tb, *r;\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_tb_5_4: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t5 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  b21 (tb) = r[2];\n  t3 (tb) = r[3];\n  b31 (tb) = r[4];\n  b32 (tb) = r[5];\n  t4 (tb) = r[6];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = t4 (tb);\n  E[0] = 0.5L;\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = D[0] * t4 (tb);\n  E[1] = 1.L / 3.L;\n  A[2] = A[1] * t1 (tb);\n  B[2] = B[1] * t2 (tb);\n  C[2] = C[1] * t3 (tb);\n  D[2] = D[1] * t4 (tb);\n  E[2] = 0.25L;\n  A[3] = D[3] = 0.L;\n  B[3] = b21 (tb) * t1 (tb) * (t2 (tb) - t4 (tb));\n  C[3] = (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb)) * (t3 (tb) - t4 (tb));\n  E[3] = 0.125L - 1.L / 6.L * t4 (tb);\n  solve_4 (A, B, C, D, E);\n  if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))\n    return 0;\n  b54 (tb) = E[3];\n  b53 (tb) = E[2];\n  b52 (tb) = E[1];\n  b51 (tb) = E[0];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = 1.L / 6.L - b52 (tb) * b21 (tb) * t1 (tb)\n    - b53 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = 1.L / 12.L - b52 (tb) * b21 (tb) * sqr (t1 (tb))\n    - b53 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)));\n  A[2] = 0.L;\n  B[2] = b21 (tb) * t1 (tb);\n  C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);\n  D[2] = 1.L / 24.L - b53 (tb) * b32 (tb) * b21 (tb) * t1 (tb);\n  solve_3 (A, B, C, D);\n  b43 (tb) = D[2] / b54 (tb);\n  if (isnan (b43 (tb)))\n    return 0;\n  b42 (tb) = D[1] / b54 (tb);\n  if (isnan (b42 (tb)))\n    return 0;\n  b41 (tb) = D[0] / b54 (tb);\n  if (isnan (b41 (tb)))\n    return 0;\n  rk_b_5 (tb);\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_tb_5_4: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 5 steps 4th order, 5th order in\n * equations depending only on time, Runge-Kutta method.\n */\nint\nrk_tb_5_4t (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *tb, *r;\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_tb_5_4t: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t5 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  t3 (tb) = r[2];\n  t4 (tb) = r[3];\n  b31 (tb) = r[4];\n  b21 (tb) = r[5];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = t4 (tb);\n  E[0] = 0.5L;\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = D[0] * t4 (tb);\n  E[1] = 1.L / 3.L;\n  A[2] = A[1] * t1 (tb);\n  B[2] = B[1] * t2 (tb);\n  C[2] = C[1] * t3 (tb);\n  D[2] = D[1] * t4 (tb);\n  E[2] = 0.25L;\n  A[3] = A[2] * t1 (tb);\n  B[3] = B[2] * t2 (tb);\n  C[3] = C[2] * t3 (tb);\n  D[3] = D[2] * t4 (tb);\n  E[3] = 0.2L;\n  solve_4 (A, B, C, D, E);\n  if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))\n    return 0;\n  b54 (tb) = E[3];\n  b53 (tb) = E[2];\n  b52 (tb) = E[1];\n  b51 (tb) = E[0];\n  b32 (tb) = (1.L / 6.L * t4 (tb) - 0.125L\n              - t1 (tb) * (b52 (tb) * b21 (tb) * (t4 (tb) - t2 (tb))\n                           + b53 (tb) * b31 (tb) * (t4 (tb) - t3 (tb))))\n    / (b53 (tb) * t2 (tb) * (t4 (tb) - t3 (tb)));\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = 1.L / 6.L - b52 (tb) * b21 (tb) * t1 (tb)\n    - b53 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = 1.L / 12.L - b52 (tb) * b21 (tb) * sqr (t1 (tb))\n    - b53 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)));\n  A[2] = 0.L;\n  B[2] = b21 (tb) * t1 (tb);\n  C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);\n  D[2] = 1.L / 24.L - b53 (tb) * b32 (tb) * b21 (tb) * t1 (tb);\n  solve_3 (A, B, C, D);\n  b43 (tb) = D[2] / b54 (tb);\n  if (isnan (b43 (tb)))\n    return 0;\n  b42 (tb) = D[1] / b54 (tb);\n  if (isnan (b42 (tb)))\n    return 0;\n  b41 (tb) = D[0] / b54 (tb);\n  if (isnan (b41 (tb)))\n    return 0;\n  rk_b_5 (tb);\n#if DEBUG_RK_5_4\n  rk_print_tb (optimize, \"rk_tb_5_4t\", stderr);\n  fprintf (stderr, \"rk_tb_5_4t: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 5 steps 3rd-4th order Runge-Kutta \n * pair.\n */\nint\nrk_tb_5_4p (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *tb;\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_tb_5_4p: start\\n\");\n#endif\n  if (!rk_tb_5_4 (optimize))\n    return 0;\n  tb = optimize->coefficient;\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = 0.5L;\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = 1.L / 3.L;\n  A[2] = 0.L;\n  B[2] = b21 (tb) * t1 (tb);\n  C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);\n  D[2] = 1.L / 6.L;\n  solve_3 (A, B, C, D);\n  if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))\n    return 0;\n  e53 (tb) = D[2];\n  e52 (tb) = D[1];\n  e51 (tb) = D[0];\n  rk_e_5 (tb);\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_tb_5_4p: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 5 steps 3th-4th order, 4th-5th order\n * in equations depending only on time, Runge-Kutta pair.\n */\nint\nrk_tb_5_4tp (Optimize * optimize)       ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *tb, *r;\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_tb_5_4tp: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t5 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  t3 (tb) = r[2];\n  t4 (tb) = r[3];\n  b31 (tb) = r[4];\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = t4 (tb);\n  E[0] = 0.5L;\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = D[0] * t4 (tb);\n  E[1] = 1.L / 3.L;\n  A[2] = A[1] * t1 (tb);\n  B[2] = B[1] * t2 (tb);\n  C[2] = C[1] * t3 (tb);\n  D[2] = D[1] * t4 (tb);\n  E[2] = 0.25L;\n  A[3] = A[2] * t1 (tb);\n  B[3] = B[2] * t2 (tb);\n  C[3] = C[2] * t3 (tb);\n  D[3] = D[2] * t4 (tb);\n  E[3] = 0.2L;\n  solve_4 (A, B, C, D, E);\n  if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))\n    return 0;\n  b54 (tb) = E[3];\n  b53 (tb) = E[2];\n  b52 (tb) = E[1];\n  b51 (tb) = E[0];\n  e53 (tb) = (0.25L - 1.L / 3.L * t1 (tb)\n              - (1.L / 3.L - 0.5L * t1 (tb)) * t2 (tb))\n    / (t3 (tb) * (t3 (tb) - t2 (tb)) * (t3 (tb) - t1 (tb)));\n  if (isnan (e53 (tb)))\n    return 0;\n  e52 (tb) = (1.L / 3.L - 0.5L * t1 (tb)\n              - t3 (tb) * (t3 (tb) - t1 (tb)) * e53 (tb))\n    / (t2 (tb) * (t2 (tb) - t1 (tb)));\n  if (isnan (e52 (tb)))\n    return 0;\n  e51 (tb) = (0.5L - t2 (tb) * e52 (tb) - t3 (tb) * e53 (tb)) / t1 (tb);\n  if (isnan (e51 (tb)))\n    return 0;\n  b21 (tb) = (1.L / 6.L * b53 (tb) * (t4 (tb) - t3 (tb))\n              + e53 (tb) * (0.125L - 1.L / 6.L * t4 (tb)))\n    / (t1 (tb) * (e52 (tb) * b53 (tb) * (t4 (tb) - t3 (tb))\n                  - e53 (tb) * b52 (tb) * (t4 (tb) - t2 (tb))));\n  if (isnan (b21 (tb)))\n    return 0;\n  b32 (tb) = (1.L / 6.L * t4 (tb) - 0.125L\n              - t1 (tb) * (b52 (tb) * b21 (tb) * (t4 (tb) - t2 (tb))\n                           + b53 (tb) * b31 (tb) * (t4 (tb) - t3 (tb))))\n    / (b53 (tb) * t2 (tb) * (t4 (tb) - t3 (tb)));\n  if (isnan (b32 (tb)))\n    return 0;\n  A[0] = t1 (tb);\n  B[0] = t2 (tb);\n  C[0] = t3 (tb);\n  D[0] = 1.L / 6.L - b52 (tb) * b21 (tb) * t1 (tb)\n    - b53 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));\n  A[1] = A[0] * t1 (tb);\n  B[1] = B[0] * t2 (tb);\n  C[1] = C[0] * t3 (tb);\n  D[1] = 1.L / 12.L - b52 (tb) * b21 (tb) * sqr (t1 (tb))\n    - b53 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)));\n  A[2] = 0.L;\n  B[2] = b21 (tb) * t1 (tb);\n  C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);\n  D[2] = 1.L / 24.L - b53 (tb) * b32 (tb) * b21 (tb) * t1 (tb);\n  solve_3 (A, B, C, D);\n  b43 (tb) = D[2] / b54 (tb);\n  if (isnan (b43 (tb)))\n    return 0;\n  b42 (tb) = D[1] / b54 (tb);\n  if (isnan (b42 (tb)))\n    return 0;\n  b41 (tb) = D[0] / b54 (tb);\n  if (isnan (b41 (tb)))\n    return 0;\n  rk_b_5 (tb);\n  rk_e_5 (tb);\n#if DEBUG_RK_5_4\n  rk_print_tb (optimize, \"rk_tb_5_4tp\", stderr);\n  fprintf (stderr, \"rk_tb_5_4tp: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to calculate the objective function of a 5 steps 4th order \n * Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_5_4 (RK * rk)   ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_objective_tb_5_4: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b41 (tb) < 0.L)\n    o += b41 (tb);\n  if (b42 (tb) < 0.L)\n    o += b42 (tb);\n  if (b43 (tb) < 0.L)\n    o += b43 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (b54 (tb) < 0.L)\n    o += b54 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_objective_tb_5_4: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_5_4: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 5 steps 4th order, 5th\n * order in equations depending only on time, Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_5_4t (RK * rk)  ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_objective_tb_5_4t: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n#if DEBUG_RK_5_4\n  rk_print_tb (optimize, \"rk_objective_tb_5_4t\", stderr);\n#endif\n  o = fminl (0.L, b20 (tb));\n  if (b21 (tb) < 0.L)\n    o += b21 (tb);\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b32 (tb) < 0.L)\n    o += b32 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b41 (tb) < 0.L)\n    o += b41 (tb);\n  if (b42 (tb) < 0.L)\n    o += b42 (tb);\n  if (b43 (tb) < 0.L)\n    o += b43 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (b54 (tb) < 0.L)\n    o += b54 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_objective_tb_5_4t: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_5_4t: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 5 steps 3rd-4th order \n * Runge-Kutta pair.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_5_4p (RK * rk)  ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_objective_tb_5_4p: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b41 (tb) < 0.L)\n    o += b41 (tb);\n  if (b42 (tb) < 0.L)\n    o += b42 (tb);\n  if (b43 (tb) < 0.L)\n    o += b43 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (b54 (tb) < 0.L)\n    o += b54 (tb);\n  if (e50 (tb) < 0.L)\n    o += e50 (tb);\n  if (e51 (tb) < 0.L)\n    o += e51 (tb);\n  if (e52 (tb) < 0.L)\n    o += e52 (tb);\n  if (e53 (tb) < 0.L)\n    o += e53 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_objective_tb_5_4p: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_5_4p: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 5 steps 3th-4th order,\n * 4th-5th order in equations depending only on time, Runge-Kutta pair.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_5_4tp (RK * rk) ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_objective_tb_5_4t: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n#if DEBUG_RK_5_4\n  rk_print_tb (optimize, \"rk_objective_tb_5_4tp\", stderr);\n#endif\n  o = fminl (0.L, b20 (tb));\n  if (b21 (tb) < 0.L)\n    o += b21 (tb);\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b32 (tb) < 0.L)\n    o += b32 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b41 (tb) < 0.L)\n    o += b41 (tb);\n  if (b42 (tb) < 0.L)\n    o += b42 (tb);\n  if (b43 (tb) < 0.L)\n    o += b43 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b51 (tb) < 0.L)\n    o += b51 (tb);\n  if (b52 (tb) < 0.L)\n    o += b52 (tb);\n  if (b53 (tb) < 0.L)\n    o += b53 (tb);\n  if (b54 (tb) < 0.L)\n    o += b54 (tb);\n  if (e50 (tb) < 0.L)\n    o += e50 (tb);\n  if (e51 (tb) < 0.L)\n    o += e51 (tb);\n  if (e52 (tb) < 0.L)\n    o += e52 (tb);\n  if (e53 (tb) < 0.L)\n    o += e53 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_5_4\n  fprintf (stderr, \"rk_objective_tb_5_4tp: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_5_4tp: end\\n\");\n#endif\n  return o;\n}\n", "meta": {"hexsha": "d604974d932739a3c5852cbd6c5cccf605a863ab", "size": 15625, "ext": "c", "lang": "C", "max_stars_repo_path": "rk_5_4.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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": "rk_5_4.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk_5_4.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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.6147540984, "max_line_length": 80, "alphanum_fraction": 0.506816, "num_tokens": 7059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.3675189648337022}}
{"text": "/* Utility functions for working with GSL data types. */\n\n#include <math.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_sort_vector.h>\n#include <gsl/gsl_spmatrix.h>\n#include <gsl/gsl_statistics.h>\n#include <hdf5.h>\n#include <hdf5_hl.h>\n#include <osqp/osqp.h>\n\n#include \"qdm.h\"\n\ngsl_vector *\nqdm_vector_seq(double from, double to, double by)\n{\n  size_t size = fabs(to - from) / by;\n  gsl_vector *s = gsl_vector_alloc(size + 1);\n\n  double value = from;\n  for (size_t i = 0; i < s->size; i++) {\n    gsl_vector_set(s, i, value);\n    value += by;\n  }\n\n  return s;\n}\n\nvoid\nqdm_vector_set_seq(gsl_vector *v, double from, double to)\n{\n  double by = (to - from) / (double)(v->size - 1);\n\n  double value = from;\n  for (size_t i = 0; i < v->size; i++) {\n    gsl_vector_set(v, i, value);\n    value += by;\n  }\n}\n\nsize_t\nqdm_vector_search(const gsl_vector *v, double needle)\n{\n  double x = 0;\n  size_t i = v->size - 1;\n\n  for (; i > 0; i--) {\n    x = gsl_vector_get(v, i);\n    \n    if (needle >= x) {\n      break;\n    }\n  }\n\n  return i;\n}\n\nvoid\nqdm_vector_csv_fwrite(FILE *f, const gsl_vector *v)\n{\n  for (size_t i = 0; i < v->size; i++) {\n    fprintf(f, \"%.17g\", gsl_vector_get(v, i));\n    if (i < v->size - 1) {\n      fprintf(f, \",\");\n    }\n  }\n  fprintf(f, \"\\n\");\n}\n\nvoid\nqdm_matrix_csv_fwrite(FILE *f, const gsl_matrix *m)\n{\n  if (m != NULL) {\n    for (size_t i = 0; i < m->size1; i++) {\n      gsl_vector_const_view row = gsl_matrix_const_row(m, i);\n      qdm_vector_csv_fwrite(f, &row.vector);\n    }\n  }\n}\n\n/* Compute M^T * M */\nint\nqdm_matrix_tmm(gsl_matrix *m, gsl_matrix *result)\n{\n  return gsl_blas_dgemm(\n      CblasTrans , CblasNoTrans , 1.0 ,\n      m          , m            ,\n      0.0        , result\n  );\n}\n\n/* Compute det(M^T * M) */\nint\nqdm_matrix_det_tmm(gsl_matrix *m, double *det)\n{\n  int status = 0;\n  gsl_matrix *c = gsl_matrix_alloc(m->size2, m->size2);\n  gsl_permutation *p = gsl_permutation_alloc(c->size1);\n\n  status = gsl_blas_dgemm(\n      CblasTrans , CblasNoTrans , 1.0 ,\n      m          , m            ,\n      0.0        , c\n  );\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  int signum = 0;\n  status = gsl_linalg_LU_decomp(c, p, &signum);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  *det = gsl_linalg_LU_det(c, signum);\n\ncleanup:\n  gsl_permutation_free(p);\n  gsl_matrix_free(c);\n\n  return status;\n}\n\n/* Create a sorted copy of the vector v. */\ngsl_vector *\nqdm_vector_sorted(const gsl_vector *v)\n{\n  gsl_vector *s = gsl_vector_alloc(v->size);\n\n  gsl_vector_memcpy(s, v);\n  gsl_sort_vector(s);\n\n  return s;\n}\n\ngsl_vector *\nqdm_vector_quantile(gsl_vector *data, gsl_vector *probs)\n{\n  gsl_vector *sorted = qdm_vector_sorted(data);\n  gsl_vector *quantiles = gsl_vector_alloc(probs->size);\n\n  for (size_t i = 0; i < probs->size; i++) {\n    double q = gsl_stats_quantile_from_sorted_data(\n        sorted->data,\n        sorted->stride,\n        sorted->size,\n        gsl_vector_get(probs, i)\n    );\n\n    gsl_vector_set(quantiles, i, q);\n  }\n\n  free(sorted);\n\n  return quantiles;\n}\n\n/* Compute the residual sum of squares:\n *\n * sum((y[i] - f(x[i])) ^ 2)\n */\ndouble\nqdm_vector_rss(const gsl_vector *y, const gsl_vector *fx)\n{\n  int status = 0;\n  double rss = 0.0;\n\n  gsl_vector *se = gsl_vector_alloc(y->size);\n  status = gsl_vector_memcpy(se, y);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = gsl_vector_sub(se, fx);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  status = gsl_vector_mul(se, se);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  rss = qdm_vector_sum(se);\n\ncleanup:\n  gsl_vector_free(se);\n\n  return rss;\n}\n\n/* Compute the summation of the vector.\n *\n * This uses the \"iterative Kahan-Babuska algorithm\" (aka Klein summation) as\n * outlined here:\n *\n * https://en.wikipedia.org/wiki/Kahan_summation_algorithm\n */\ndouble\nqdm_vector_sum(gsl_vector *v)\n{\n  double s = 0.0;\n  double cs = 0.0;\n  double ccs = 0.0;\n\n  for (size_t i = 0; i < v->size; i++) {\n    double t = s + gsl_vector_get(v, i);\n\n    double c;\n    if (fabs(s) >= fabs(gsl_vector_get(v, i))) {\n      c = (s - t) + gsl_vector_get(v, i);\n    } else {\n      c = (gsl_vector_get(v, i) - t) + s;\n    }\n\n    s = t;\n    t = cs + c;\n\n    double cc;\n    if (fabs(cs) >= fabs(c)) {\n      cc = (cs - t) + c;\n    } else {\n      cc = (c - t) + cs;\n    }\n\n    cs = t;\n    ccs = ccs + cc;\n  }\n\n  return s + cs + ccs;\n}\n\n/* Return the first index with a value greater than the value. */\nsize_t\nqdm_vector_greater_than(const gsl_vector *v, double value)\n{\n  for (size_t i = 0; i < v->size; i++) {\n    if (gsl_vector_get(v, i) > value) {\n      return i;\n    }\n  }\n\n  return 0;\n}\n\n/* Select the elements in the upper triangle of the matrix. All other elements\n * will be set to zero.\n */\nvoid\nqdm_matrix_select_upper_triangle(gsl_matrix *m)\n{\n  for (size_t i = 0; i < m->size1; i++) {\n    for (size_t j = 0; j < m->size2; j++) {\n      if (j < i) {\n        gsl_matrix_set(m, i, j, 0);\n      }\n    }\n  }\n}\n\nint\nqdm_matrix_to_csc_matrix(csc **result, gsl_matrix *input)\n{\n  int status = 0;\n\n  gsl_spmatrix *sm = gsl_spmatrix_alloc(input->size1, input->size2);\n\n  status = gsl_spmatrix_d2sp(sm, input);\n  if (status != 0) {\n    goto cleanup_sm;\n  }\n\n  gsl_spmatrix *sm_csc = gsl_spmatrix_compress(sm, GSL_SPMATRIX_CSC);\n\n  int m = sm_csc->size1;\n  int n = sm_csc->size2;\n  int nzmax = gsl_spmatrix_nnz(sm_csc);\n\n  size_t x_size = sizeof(double) * nzmax;\n  double *x = malloc(x_size);\n  memcpy(x, sm_csc->data, x_size);\n\n  size_t i_size = sizeof(int) * nzmax;\n  int *i = malloc(i_size);\n  memcpy(i, sm_csc->i, i_size);\n\n  size_t p_size = sizeof(int) * (n + 1);\n  int *p = malloc(p_size);\n  memcpy(p, sm_csc->p, p_size);\n\n  *result = csc_matrix(\n      m,     // m     First dimension (rows)\n      n,     // n     Second dimension (columns)\n      nzmax, // nzmax Maximum number of nonzero elements\n      x,     // x     Vector of data (size nzmax)\n      i,     // i     Vector of row indices (size nzmax)\n      p      // p     Vector of column pointers (size n+1)\n  );\n\n  gsl_spmatrix_free(sm_csc);\n\ncleanup_sm:\n  gsl_spmatrix_free(sm);\n\n  return status;\n}\n\ngsl_vector *\nqdm_vector_copy(const gsl_vector *src)\n{\n  gsl_vector *dst = gsl_vector_alloc(src->size);\n  gsl_vector_memcpy(dst, src);\n\n  return dst;\n}\n\ngsl_matrix *\nqdm_matrix_copy(const gsl_matrix *src)\n{\n  gsl_matrix *dst = gsl_matrix_alloc(src->size1, src->size2);\n  gsl_matrix_memcpy(dst, src);\n\n  return dst;\n}\n\nint create_hd5(\n    const char *file_path,\n    const char *group_path\n)\n{\n  int status = 0;\n\n  hid_t file  = -1;\n  hid_t group = -1;\n  hid_t gcpl  = -1;\n\n  /* Save old error handler */\n  herr_t (*old_func)(hid_t, void*) = NULL;\n  void *old_client_data = NULL;\n  H5Eget_auto(H5E_DEFAULT, &old_func, &old_client_data);\n\n  /* Turn off error handling */\n  H5Eset_auto(H5E_DEFAULT, NULL, NULL);\n\n  file = H5Fopen(file_path, H5F_ACC_RDWR, H5P_DEFAULT);\n  if (file < 0) {\n    file = H5Fcreate(file_path, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  }\n  if (file < 0) {\n    status = file;\n    goto cleanup;\n  }\n\n  group = H5Gopen(file, group_path, H5P_DEFAULT);\n  if (group < 0) {\n    gcpl = H5Pcreate(H5P_LINK_CREATE);\n    if (gcpl < 0) {\n      status = gcpl;\n      goto cleanup;\n    }\n\n    status = H5Pset_create_intermediate_group(gcpl, 1);\n    if (status < 0) {\n      goto cleanup;\n    }\n\n    group = H5Gcreate(file, group_path, gcpl, H5P_DEFAULT, H5P_DEFAULT);\n\n    if (group < 0) {\n      status = group;\n      goto cleanup;\n    }\n  }\n\ncleanup:\n  if (gcpl >= 0) {\n    H5Pclose(gcpl);\n  }\n\n  if (group >= 0) {\n    H5Gclose(group);\n  }\n\n  if (file >= 0) {\n    H5Fclose(file);\n  }\n\n  /* Restore previous error handler */\n  H5Eset_auto(H5E_DEFAULT, old_func, old_client_data);\n\n  if (status < 0) {\n    H5Eprint(H5E_DEFAULT, stderr);\n  }\n\n  return status;\n}\n\nint\nqdm_vector_hd5_read(\n    hid_t id,\n    const char *name,\n    gsl_vector **v\n)\n{\n  int status = 0;\n\n  int rank = 0;\n\n  status = H5LTget_dataset_ndims(id, name, &rank);\n  if (status < 0) {\n    return status;\n  }\n\n  hsize_t dims[rank];\n\n  status = H5LTget_dataset_info(id, name, dims, NULL, NULL);\n  if (status < 0) {\n    return status;\n  }\n\n  size_t size = 1;\n  for (int i = 0; i < rank; i++) {\n    size *= dims[i];\n  }\n\n  gsl_vector *tmp = gsl_vector_alloc(size);\n\n  status = H5LTread_dataset_double(id, name, tmp->data);\n  if (status < 0) {\n    gsl_vector_free(tmp);\n\n    return status;\n  }\n\n  *v = tmp;\n\n  return status;\n}\n\nint\nqdm_vector_hd5_write(\n    hid_t id,\n    const char *name,\n    const gsl_vector *v\n)\n{\n  int status = 0;\n\n  hid_t datatype  = -1;\n  hid_t dataspace = -1;\n  hid_t dataset   = -1;\n  hid_t dcpl      = -1;\n\n  if (v == NULL) {\n    goto cleanup;\n  }\n\n  datatype = H5Tcopy(H5T_NATIVE_DOUBLE);\n\n  status = H5Tset_order(datatype, H5T_ORDER_LE);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  hsize_t dims[1] = {\n    v->size,\n  };\n  dataspace = H5Screate_simple(1, dims, NULL);\n  if (dataspace < 0) {\n    status = dataspace;\n    goto cleanup;\n  }\n\n  dcpl = H5Pcreate(H5P_DATASET_CREATE);\n  if (dcpl < 0) {\n    status = dcpl;\n\n    goto cleanup;\n  }\n\n  /* Only enable compression on larger vectors. */\n  /*\n  if (v->size > 1024) {\n    status = H5Pset_deflate(dcpl, 9);\n    if (status != 0) {\n      goto cleanup;\n    }\n\n    hsize_t chunk_dims[1] = {\n      v->size,\n    };\n    status = H5Pset_chunk(dcpl, 1, chunk_dims);\n    if (status != 0) {\n      goto cleanup;\n    }\n  }\n  */\n\n  dataset = H5Dcreate(id, name, datatype, dataspace, H5P_DEFAULT, dcpl, H5P_DEFAULT);\n  if (dataset < 0) {\n    status = dataset;\n    goto cleanup;\n  }\n\n  status = H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, v->data);\n  if (status != 0) {\n    goto cleanup;\n  }\n\ncleanup: \n  if (dcpl >= 0) {\n    H5Pclose(dcpl);\n  }\n\n  if (dataset >= 0) {\n    H5Dclose(dataset);\n  }\n\n  if (dataspace >= 0) {\n    H5Sclose(dataspace);\n  }\n\n  if (datatype >= 0) {\n    H5Tclose(datatype);\n  }\n\n  H5Oflush(id);\n\n  return status;\n}\n\nint\nqdm_matrix_hd5_read(\n    hid_t id,\n    const char *name,\n    gsl_matrix **m\n)\n{\n  int status = 0;\n\n  int rank = 0;\n\n  status = H5LTget_dataset_ndims(id, name, &rank);\n  if (status < 0) {\n    return status;\n  }\n\n  if (rank < 2) {\n    return -1;\n  }\n\n  hsize_t dims[rank];\n\n  status = H5LTget_dataset_info(id, name, dims, NULL, NULL);\n  if (status < 0) {\n    return status;\n  }\n\n  size_t size1 = dims[0];\n  size_t size2 = 1;\n  for (int i = 1; i < rank; i++) {\n    size2 *= dims[i];\n  }\n\n  gsl_matrix *tmp = gsl_matrix_alloc(size1, size2);\n\n  status = H5LTread_dataset_double(id, name, tmp->data);\n  if (status < 0) {\n    gsl_matrix_free(tmp);\n\n    return status;\n  }\n\n  *m = tmp;\n\n  return status;\n}\n\nint\nqdm_matrix_hd5_write(\n    hid_t id,\n    const char *name,\n    const gsl_matrix *m\n)\n{\n  int status = 0;\n\n  hid_t datatype  = -1;\n  hid_t dataspace = -1;\n  hid_t dataset   = -1;\n  hid_t dcpl      = -1;\n\n  if (m == NULL) {\n    goto cleanup;\n  }\n\n  datatype = H5Tcopy(H5T_NATIVE_DOUBLE);\n\n  status = H5Tset_order(datatype, H5T_ORDER_LE);\n  if (status != 0) {\n    goto cleanup;\n  }\n\n  hsize_t dims[2] = {\n    m->size1,\n    m->size2,\n  };\n  dataspace = H5Screate_simple(2, dims, NULL);\n  if (dataspace < 0) {\n    status = dataspace;\n\n    goto cleanup;\n  }\n\n  dcpl = H5Pcreate(H5P_DATASET_CREATE);\n  if (dcpl < 0) {\n    status = dcpl;\n\n    goto cleanup;\n  }\n\n  /* Only enable compression on larger matrices. */\n  /*\n  if (m->size1 * m->size2 > 1024) {\n    status = H5Pset_deflate(dcpl, 9);\n    if (status != 0) {\n      goto cleanup;\n    }\n\n    hsize_t chunk_dims[2] = {\n      m->size1,\n      m->size2\n    };\n    status = H5Pset_chunk(dcpl, 2, chunk_dims);\n    if (status != 0) {\n      goto cleanup;\n    }\n  }\n  */\n\n  dataset = H5Dcreate(id, name, datatype, dataspace, H5P_DEFAULT, dcpl, H5P_DEFAULT);\n  if (dataset < 0) {\n    status = dataset;\n\n    goto cleanup;\n  }\n\n  status = H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, m->data);\n  if (status != 0) {\n    goto cleanup;\n  }\n\ncleanup:\n  if (dcpl >= 0) {\n    H5Pclose(dcpl);\n  }\n\n  if (dataset >= 0) {\n    H5Dclose(dataset);\n  }\n\n  if (dataspace >= 0) {\n    H5Sclose(dataspace);\n  }\n\n  if (datatype >= 0) {\n    H5Tclose(datatype);\n  }\n\n  H5Oflush(id);\n\n  return status;\n}\n\ngsl_vector *\nqdm_matrix_filter(\n    const gsl_matrix *m,\n    size_t needle_column,\n    double needle_value,\n    size_t select_column\n)\n{\n  size_t size = 0;\n\n  for (size_t i = 0; i < m->size1; i++) {\n    if (gsl_matrix_get(m, i, needle_column) == needle_value) {\n      size++;\n    }\n  }\n\n  gsl_vector *v = gsl_vector_alloc(size);\n\n  size_t j = 0;\n  for (size_t i = 0; i < m->size1; i++) {\n    double select_value = gsl_matrix_get(m, i, select_column);\n\n    if (gsl_matrix_get(m, i, needle_column) == needle_value) {\n      gsl_vector_set(v, j, select_value);\n      j++;\n    }\n  }\n\n  return v; \n}\n", "meta": {"hexsha": "9ca42ca63b8d10ff4b2a944c6de755acf3b9f36a", "size": 12766, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gsl.c", "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gsl.c", "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_forks_repo_path": "src/gsl.c", "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9802816901, "max_line_length": 88, "alphanum_fraction": 0.5968980103, "num_tokens": 4232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.36711337951895906}}
{"text": "#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <nlopt.h>\n#include <unistd.h>\n#include <sys/time.h>\n\nvoid quadbezier(const double *a, const double *b, const double *c,\n\t\tdouble t, double *out)\n{\n  double onemt = 1.0 - t;\n  out[0] = onemt * (onemt * a[0] + t * b[0]) + t * (onemt * b[0] + t * c[0]);\n  out[1] = onemt * (onemt * a[1] + t * b[1]) + t * (onemt * b[1] + t * c[1]);\n}\n\nvoid linearinterp(const double *a, const double *b,\n\t\t  double t, double *out)\n{\n  out[0] = (b[0] - a[0]) * t + a[0];\n  out[1] = (b[1] - a[1]) * t + a[1];\n}\n\ntypedef struct {\n  int N;\n  int steps;\n  double *starts;\n  double *stops;\n  double *scratch;\n} problem_t;\n\ndouble randd()\n{\n  int n = rand() % (1<<24);\n  return ((double)n) / ((double)(1<<24));\n}\n\ndouble distance(const double *a, const double *b)\n{\n  return sqrt((b[0] - a[0]) * (b[0] - a[0]) +\n\t      (b[1] - a[1]) * (b[1] - a[1]));\n}\n\n#define RADIUS 5.0\n\ndouble errorf(unsigned n, const double *pts, double *grad,\n\t      void *data)\n{\n  problem_t *setup = (problem_t *)data;\n  double error = 0.0;\n\n  for(int step=0; step<setup->steps; step++) {\n    double t = (1.0+step) / (1.0+setup->steps);\n    for(int i=0; i<setup->N; i++)\n      quadbezier(&setup->starts[2*i],\n\t\t &pts[2*i],\n\t\t &setup->stops[2*i],\n\t\t t,\n\t\t &setup->scratch[2*i]);\n\n    for(int i=0; i<setup->N; i++)\n      for(int j=i+1; j<setup->N; j++) {\n\tdouble d = distance(&setup->scratch[2*i],\n\t\t\t    &setup->scratch[2*j]);\n\td /= RADIUS;\n\terror += (1.0/d) * (1.0/d);\n      }\n  }\n\n  return error / setup->steps;\n}\n\nint main(int argc, char *argv[])\n{\n  int N = 12;\n\n  double *starts = (double *)malloc(sizeof(double)*N*2);\n  double *stops = (double *)malloc(sizeof(double)*N*2);\n\n  srand(2);\n  nlopt_srand(1);\n\n  double scaling = 100.0;\n  for(int i=0; i<N; i++) {\n    starts[2*i+0] = scaling * randd();\n    starts[2*i+1] = scaling * randd();\n    stops[2*i+0]  = scaling * randd();\n    stops[2*i+1]  = scaling * randd();\n  }\n\n  double hs = scaling / 2.0;\n  for(int i=0; i<N; i++) {\n    double theta = ((double)i)/N * 2 * 3.141592;\n    starts[2*i+0] = hs * cos(theta) + hs;\n    starts[2*i+1] = hs * sin(theta) + hs;\n    stops[2*i+0]  = hs * cos(theta + 3.141592) + hs;\n    stops[2*i+1]  = hs * sin(theta + 3.141592) + hs;\n  }\n  \n  struct timeval start, stop;\n  \n  double *guesses = (double *)malloc(sizeof(double)*N*2);\n\n  gettimeofday(&start, NULL);\n  for(int i=0; i<N; i++) {\n    linearinterp(&starts[2*i], &stops[2*i], 0.5, &guesses[2*i]);\n  }\n\n  nlopt_opt global = nlopt_create(NLOPT_GN_ISRES, 2*N);\n  nlopt_opt local = nlopt_create(NLOPT_LN_SBPLX, 2*N);\n\n  problem_t *setup = (problem_t *)malloc(sizeof(problem_t));\n  setup->N = N;\n  setup->starts = starts;\n  setup->stops = stops;\n  setup->steps = 50;\n  setup->scratch = (double *)malloc(sizeof(double)*N*2);\n\n  nlopt_result res;\n  \n  res = nlopt_set_min_objective(global, errorf, setup);\n  if(res!=1) { exit(-1); }\n\n  res = nlopt_set_lower_bounds1(global, -25.0);\n  if(res!=1) { exit(-1); }\n\n  res = nlopt_set_upper_bounds1(global, 125.0);\n  if(res!=1) { exit(-1); }\n\n  res = nlopt_set_stopval(global, 1.0);\n  if(res!=1) { exit(-1); }\n\n  res = nlopt_set_maxeval(global, 100);\n  if(res!=1) { exit(-1); }\n\n  double final_error;\n  res = nlopt_optimize(global, guesses, &final_error);\n\n  res = nlopt_set_min_objective(local, errorf, setup);\n  if(res!=1) { exit(-1); }\n\n  res = nlopt_set_lower_bounds1(local, -25.0);\n  if(res!=1) { exit(-1); }\n\n  res = nlopt_set_upper_bounds1(local, 125.0);\n  if(res!=1) { exit(-1); }\n\n  res = nlopt_set_stopval(local, 1.0);\n  if(res!=1) { exit(-1); }\n\n  res = nlopt_set_maxeval(local, 1000);\n  if(res!=1) { exit(-1); }\n\n  res = nlopt_optimize(local, guesses, &final_error);\n  gettimeofday(&stop, NULL);\n\n  fprintf(stderr, \"final: %f\\n\", final_error);\n\n  for(int i=0; i<N; i++) {\n    printf(\"%f %f %f %f %f %f\\n\",\n\t   starts[2*i+0], starts[2*i+1],\n\t   guesses[2*i+0], guesses[2*i+1],\n\t   stops[2*i+0], stops[2*i+1]);\n  }\n\n  double startd, stopd;\n  startd = start.tv_sec;\n  startd += ((double)(start.tv_usec)) / 1e6;\n  stopd = stop.tv_sec;\n  stopd += ((double)(stop.tv_usec)) / 1e6;\n\n  //printf(\"%f\\n\", stopd - startd);\n}\n", "meta": {"hexsha": "dfb138a07781e91a0347fb1a6e00fadeeaa5133d", "size": 4119, "ext": "c", "lang": "C", "max_stars_repo_path": "discs.c", "max_stars_repo_name": "jkominek/discs", "max_stars_repo_head_hexsha": "349177e38fae31eff407c7188b243c641807dc16", "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": "discs.c", "max_issues_repo_name": "jkominek/discs", "max_issues_repo_head_hexsha": "349177e38fae31eff407c7188b243c641807dc16", "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": "discs.c", "max_forks_repo_name": "jkominek/discs", "max_forks_repo_head_hexsha": "349177e38fae31eff407c7188b243c641807dc16", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8092485549, "max_line_length": 77, "alphanum_fraction": 0.5741684875, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.36706050142263474}}
{"text": "\n\n#include <errno.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/time.h>\n#include <time.h>\n#include <clapack.h>\n#include <cblas.h>\n#include <omp.h>\n\n#define DIM 16\n#define NB 256\n\n//#define DIM 96\n//#define NB 128\n\n\nextern void spotrf_(char *, int *, float *, int *, int *);\n\n\n/*#pragma css task input(NB) inout(A[NB][NB]) highpriority */\nvoid smpSs_spotrf_tile(float *A)\n{\n\nunsigned char LO='L';\nint INFO;\nint nn=NB;\n   spotrf_(&LO,\n          &nn,\n          A,&nn,\n          &INFO);\n}\n\n/*#pragma css task input(A[NB][NB], B[NB][NB], NB) inout(C[NB][NB])*/\nvoid smpSs_sgemm_tile(float  *A, float *B, float *C)\n{\nunsigned char TR='T', NT='N';\nfloat DONE=1.0, DMONE=-1.0;\n    cblas_sgemm(\n        CblasColMajor,\n        CblasNoTrans, CblasTrans,\n        NB, NB, NB,\n        -1.0, A, NB,\n              B, NB,\n         1.0, C, NB);\n\n}\n\n/*#pragma css task input(T[NB][NB], NB) inout(B[NB][NB])*/\nvoid smpSs_strsm_tile(float *T, float *B)\n{\nunsigned char LO='L', TR='T', NU='N', RI='R';\nfloat DONE=1.0;\n\n    cblas_strsm(\n        CblasColMajor,\n        CblasRight, CblasLower, CblasTrans, CblasNonUnit,\n        NB, NB,\n        1.0, T, NB,\n             B, NB);\n\n}\n\n/*#pragma css task input(A[NB][NB], NB) inout(C[NB][NB])*/\nvoid smpSs_ssyrk_tile( float *A, float *C)\n{\nunsigned char LO='L', NT='N';\nfloat DONE=1.0, DMONE=-1.0;\n\n    cblas_ssyrk(\n        CblasColMajor,\n        CblasLower,CblasNoTrans,\n        NB, NB,\n        -1.0, A, NB,\n         1.0, C, NB);\n\n}\n\n\nvoid compute(struct timeval *start, struct timeval *stop, float *A[DIM][DIM])\n{\n#pragma omp parallel num_threads(48) \n#pragma omp single\n{\n gettimeofday(start,NULL);\n  double t1 = omp_get_wtime();\n\n  long j,k,i;\n  for (j = 0; j < DIM; j++)\n  {\n    for (k= 0; k< j; k++)\n    {\n      for (i = j+1; i < DIM; i++) \n      {\n      #pragma omp task shared(A) firstprivate(i,k,j)  depend(in : A[i][k], A[j][k]) depend(inout:A[i][j]) \n        smpSs_sgemm_tile(  A[i][k], A[j][k], A[i][j]);\n      }\n    }\n    for (i = 0; i < j; i++)\n    {\n    #pragma omp task shared(A) firstprivate(i,j) depend (in : A[j][i]) depend(inout : A[j][j])\n      smpSs_ssyrk_tile( A[j][i], A[j][j]);\n    }\n\n   #pragma omp task shared(A) firstprivate(j) depend(inout : A[j][j])\n    smpSs_spotrf_tile( A[j][j]);\n\n    for (i = j+1; i < DIM; i++)\n    {\n  #pragma omp task shared(A) firstprivate(i,j) depend(in : A[j][j]) depend (inout : A[i][j])\n      smpSs_strsm_tile( A[j][j], A[i][j]);\n    }\n   \n  }\n#pragma omp taskwait\n\t\n  double t2 = omp_get_wtime();\n  fprintf(stderr,\"Time: %f\\n\",t2-t1);\n}\n gettimeofday(stop,NULL);\n exit(0);\n}\n\n\nstatic void init(int argc, char **argv,  long *N_p);\n\nfloat **A;\nfloat * Alin; \n\n\nlong N;\n\nint\nmain(int argc, char *argv[])\n{\n \nunsigned char LO='L';\nint  INFO;\n \n  struct timeval start;\n  struct timeval stop;\n  unsigned long elapsed;\n\n  init(argc, argv, &N);\n  fprintf(stderr,\"Computing cholesky...\\n\");\n\n  compute(&start, &stop, (void *)A);\n\n  int nn=N;\n\n  elapsed = 1000000 * (stop.tv_sec - start.tv_sec);\n  elapsed += stop.tv_usec - start.tv_usec;\n\n  printf (\"%lu;\\t\", elapsed);\n  printf(\"%d\\n\", (int)((0.33*N*N*N+0.5*N*N+0.17*N)/elapsed));\n\n  printf(\"par_sec_time_us:%lu\\n\",elapsed);\n  return 0;\n}\n\n\nstatic void convert_to_blocks(long N, float *Alin, float *A[DIM][DIM])\n{\n  long i,j;\n  for (i = 0; i < N; i++)\n  {\n    for (j = 0; j < N; j++)\n    {\n      A[j/NB][i/NB][(i%NB)*NB+j%NB] = Alin[i*N+j];\n    }\n  }\n\n}\n\n\n\nvoid fill_random(float *Alin, int NN)\n{\n  int i;\n  for (i = 0; i < NN; i++)\n  {\n    Alin[i]=((float)rand())/((float)RAND_MAX);\n  }\n}\n\n\nstatic void init(int argc, char **argv,  long *N_p)\n{\n  long ISEED[4] = {0,0,0,1};\n  long IONE=1;\n\n\n  \n  \n  long N = NB*DIM;\n  long NN = N * N;\n\n  *N_p = N;\n\n   Alin = (float *) malloc(NN * sizeof(float));\n\n  fill_random(Alin,NN);\n  long i;\n  for(i=0; i<N; i++)\n  {\n    Alin[i*N + i] += N;\n  }\n  \n  A = (float **) malloc(DIM*DIM*sizeof(float *));\n  for ( i = 0; i < DIM*DIM; i++)\n    {\n//     #pragma omp memory\n     A[i] = (float *) malloc(NB*NB*sizeof(float));\n      int z;\n      for (z=0;z<DIM*DIM;z++)\n\t   { float *zz = (float *) A[i];\n\t     zz[z] = Alin[(DIM*DIM)*i + z]; }\n    }\n\n  convert_to_blocks(N, Alin, (void *)A);\n\n}\n", "meta": {"hexsha": "d1a12d0e051f6ec942c511ad321b67a80106ff15", "size": 4190, "ext": "c", "lang": "C", "max_stars_repo_path": "Benchmarks/cholesky/cholesky.c", "max_stars_repo_name": "podobas/BLYSK", "max_stars_repo_head_hexsha": "75c67b5aedf6e9820672beeeca2f748e67c48672", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-18T11:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-21T18:10:24.000Z", "max_issues_repo_path": "Benchmarks/cholesky/cholesky.c", "max_issues_repo_name": "podobas/BLYSK", "max_issues_repo_head_hexsha": "75c67b5aedf6e9820672beeeca2f748e67c48672", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Benchmarks/cholesky/cholesky.c", "max_forks_repo_name": "podobas/BLYSK", "max_forks_repo_head_hexsha": "75c67b5aedf6e9820672beeeca2f748e67c48672", "max_forks_repo_licenses": ["BSD-3-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.5398230088, "max_line_length": 106, "alphanum_fraction": 0.5486873508, "num_tokens": 1477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.36705046862139373}}
{"text": "/* tt.h:\n /   This file contains everything related to the tensor_train struct\n*/\n\n#ifndef TENSOR_TRAIN_H\n#define TENSOR_TRAIN_H\n\n#include <lapacke.h>\n#include <mpi.h>\n#include \"tensor.h\"\n\ntypedef struct tensor_train {\n    int d;           // dimension of tensor\n    int* n;          // tensor size of each dimension\n    int* r;          // tensor-train ranks\n\n    double** trains; // array of pointers storing the address of the trains\n} tensor_train;\n\ntensor_train* TT_init(const int d, const int* restrict n);\ntensor_train* TT_init_rank(const int d, const int* restrict n, const int* restrict r);\ntensor_train* TT_copy(tensor_train* X);\nvoid TT_free(tensor_train* sim);\nvoid TT_print(tensor_train* tt);\n\n// Broadcast a tensor train to all nodes\nvoid tt_broadcast(MPI_Comm comm, tensor_train* tt);\n\n// Find how much the tensor_train has compressed the tensor\ndouble get_compression(const tensor_train* tt);\n\n#endif\n", "meta": {"hexsha": "00831f3de6f9493502a87223286e71436795ec29", "size": 917, "ext": "h", "lang": "C", "max_stars_repo_path": "include/tt.h", "max_stars_repo_name": "SidShi/Parallel_TT_sketching", "max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/tt.h", "max_issues_repo_name": "SidShi/Parallel_TT_sketching", "max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/tt.h", "max_forks_repo_name": "SidShi/Parallel_TT_sketching", "max_forks_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_forks_repo_licenses": ["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.7878787879, "max_line_length": 86, "alphanum_fraction": 0.7230098146, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.366944343432683}}
{"text": "\n#ifndef TFDH_GSL_WRAPPERS_H\n#define TFDH_GSL_WRAPPERS_H\n\n#include <gsl/gsl_spline.h>\n#include <vector>\n\n\nnamespace GSL {\n\n  // simple functor class to help interfacing with gsl_function.\n  // derived classes representing a function f(x) should hold any needed\n  // parameters as member variables, and operator()(double x) should evaluate\n  // the function f(x).\n  //\n  // NOTE: the GSL wrappers below could in principle take C++11 lambdas instead\n  //       of this custom function object, however i did not find an elegant\n  //       way to call these lambdas using GSL's C interfaces...\n  class FunctionObject {\n    public:\n      virtual ~FunctionObject() = default;\n      virtual double operator()(double x) const = 0;\n  };\n\n  // simple wrapper class around GSL splines\n  class Spline {\n    private:\n      gsl_interp_accel* acc;\n      gsl_spline* spline;\n    public:\n      Spline(const std::vector<double>& x, const std::vector<double>& f);\n      ~Spline();\n      double eval(double r) const;\n  };\n\n  // find a root of func in the interval x1 to x2\n  // one of (x1,x2) or (x2,x1) MUST bracket a root\n  // implemented using GSL's Brent rootfinder method\n  double findRoot(const GSL::FunctionObject& func, double x1, double x2,\n      double eps_abs, double eps_rel);\n\n  // definite integral of func from x1 to x2\n  // implemented using GSL's adaptive Gauss quadrature\n  double integrate(const GSL::FunctionObject& func, double x1, double x2,\n      double eps_abs, double eps_rel);\n\n}\n\n\n#endif // TFDH_GSL_WRAPPERS_H\n", "meta": {"hexsha": "083613107f2cb25d58921a5ac40a4192136c7597", "size": 1518, "ext": "h", "lang": "C", "max_stars_repo_path": "src/GslWrappers.h", "max_stars_repo_name": "fmahebert/tfdh", "max_stars_repo_head_hexsha": "92f9b3eb757092dbdc09709530cc1cae85fdd40b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GslWrappers.h", "max_issues_repo_name": "fmahebert/tfdh", "max_issues_repo_head_hexsha": "92f9b3eb757092dbdc09709530cc1cae85fdd40b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GslWrappers.h", "max_forks_repo_name": "fmahebert/tfdh", "max_forks_repo_head_hexsha": "92f9b3eb757092dbdc09709530cc1cae85fdd40b", "max_forks_repo_licenses": ["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.7647058824, "max_line_length": 79, "alphanum_fraction": 0.6949934124, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.36684778996095824}}
{"text": "#pragma once\n\n#include <memory>\n\n#include <gsl/gsl_rng.h>\n\nextern std::unique_ptr<gsl_rng, decltype(&gsl_rng_free)> rng;\n", "meta": {"hexsha": "69d0ea2d37efb9e7cf3a0b9f627892f6f82ebd83", "size": 121, "ext": "h", "lang": "C", "max_stars_repo_path": "MathEngine/Utils/Random.h", "max_stars_repo_name": "antoniojkim/CalcPlusPlus", "max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathEngine/Utils/Random.h", "max_issues_repo_name": "antoniojkim/CalcPlusPlus", "max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathEngine/Utils/Random.h", "max_forks_repo_name": "antoniojkim/CalcPlusPlus", "max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.125, "max_line_length": 61, "alphanum_fraction": 0.7438016529, "num_tokens": 34, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.36673049578507216}}
{"text": "#ifndef bfkl_H_INCLUDED\n#define bfkl_H_INCLUDED\n\n#include <stdio.h>\n#include <math.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include \"cubature.h\"\n#include \"string.h\"\n#include \"alphas.h\"\n#include \"wf.h\"\n\n//number of tabulated points in z and x for BFKL Kernel\n#define Nz 94\n#define Nx 1201\n#define Nhar 24 \n#define ZMIN (0.15)\n#define ZMAX (4.8)\n#define XMAX (100.00)\n\nvoid ReadInBFKL();\ndouble BFKLfunc(double z, double x, int n);\ndouble d2N_BFKL(double pT, double qT, double phi, double yp, double yq, double rts);\n\nstruct bfkl_params {\n\tdouble pT;\n\tdouble qT;\n\tdouble phi;\n\tdouble x1, x2;\n    double dy;\n\t} ;\n\n#endif\n", "meta": {"hexsha": "13ff8d1013a1cae53b1bfafa8d6d7f3ad59369c7", "size": 695, "ext": "h", "lang": "C", "max_stars_repo_path": "src/bfkl.h", "max_stars_repo_name": "kdusling/mpc", "max_stars_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bfkl.h", "max_issues_repo_name": "kdusling/mpc", "max_issues_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bfkl.h", "max_forks_repo_name": "kdusling/mpc", "max_forks_repo_head_hexsha": "ccdc1f5ddcdba6cfc6ea5413ef5cc180ffe682bc", "max_forks_repo_licenses": ["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.3055555556, "max_line_length": 84, "alphanum_fraction": 0.7179856115, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.3666893107291808}}
{"text": "#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_sf_gamma.h>\n\nint\nmain(int argc, char *argv[]){\n\tgsl_permutation *P;\n\tsize_t l;\n\n\tif(2!=argc){\n\t\treturn 1;\n\t}\n\n\tl=strlen(argv[1]);\n\n\tif(GSL_SF_FACT_NMAX<l){\n\t\tprintf(\"String too long\\n\");\n\t\treturn 1;\n\t}\n\n\tP=gsl_permutation_calloc(l);\n\tassert(NULL!=P);\n\n\tdo{\n\t\tsize_t *d=gsl_permutation_data(P),i;\n\n\t\tfor(i=0;i<l;i++)\n\t\t\tprintf(\"%c\",argv[1][d[i]]);\n\n\t\tprintf(\"\\n\");\n\t}while(GSL_SUCCESS==gsl_permutation_next(P));\n\n\treturn 0;\n}\n", "meta": {"hexsha": "1d6cb55cf104a13a55f03000eab8e70c0bbd587e", "size": 535, "ext": "c", "lang": "C", "max_stars_repo_path": "permutation/permutation.c", "max_stars_repo_name": "blindsay7/gsl-tools", "max_stars_repo_head_hexsha": "3686e1c674845fd9679ed02c25b8d3e0fad73373", "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": "permutation/permutation.c", "max_issues_repo_name": "blindsay7/gsl-tools", "max_issues_repo_head_hexsha": "3686e1c674845fd9679ed02c25b8d3e0fad73373", "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": "permutation/permutation.c", "max_forks_repo_name": "blindsay7/gsl-tools", "max_forks_repo_head_hexsha": "3686e1c674845fd9679ed02c25b8d3e0fad73373", "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": 14.4594594595, "max_line_length": 46, "alphanum_fraction": 0.646728972, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.366559543472004}}
{"text": "/**\n *\n * @file core_stsmlq_corner.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @author Mathieu Faverge\n * @author Azzam Haidar\n * @date 2010-11-15\n * @generated s Tue Jan  7 11:44:48 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n#undef COMPLEX\n#define REAL\n\n/***************************************************************************//**\n *\n * @ingroup CORE_float\n *\n *  CORE_stsmlq_corner: see CORE_stsmlq\n *\n * This kernel applies left and right transformations as depicted below:\n * |I -VTV'| * | A1  A2 | * |I - VT'V'|\n *             | A2' A3 |\n * where A1 and A3 are symmetric matrices.\n * Only the lower part is referenced.\n * This is an adhoc implementation, can be further optimized...\n *\n *******************************************************************************\n *\n * @param[in] m1\n *         The number of rows of the tile A1. m1 >= 0.\n *\n * @param[in] n1\n *         The number of columns of the tile A1. n1 >= 0.\n *\n * @param[in] m2\n *         The number of rows of the tile A2. m2 >= 0.\n *\n * @param[in] n2\n *         The number of columns of the tile A2. n2 >= 0.\n *\n * @param[in] m3\n *         The number of rows of the tile A3. m3 >= 0.\n *\n * @param[in] n3\n *         The number of columns of the tile A3. n3 >= 0.\n *\n * @param[in] k\n *         The number of elementary reflectors whose product defines\n *         the matrix Q.\n *\n * @param[in] ib\n *         The inner-blocking size.  ib >= 0.\n *\n * @param[in] nb\n *         The blocking size.  nb >= 0.\n *\n * @param[in,out] A1\n *         On entry, the m1-by-n1 tile A1.\n *         On exit, A1 is overwritten by the application of Q.\n *\n * @param[in] lda1\n *         The leading dimension of the array A1. lda1 >= max(1,m1).\n *\n * @param[in,out] A2\n *         On entry, the m2-by-n2 tile A2.\n *         On exit, A2 is overwritten by the application of Q.\n *\n * @param[in] lda2\n *         The leading dimension of the tile A2. lda2 >= max(1,m2).\n *\n * @param[in,out] A3\n *         On entry, the m3-by-n3 tile A3.\n *\n * @param[in] lda3\n *         The leading dimension of the tile A3. lda3 >= max(1,m3).\n *\n * @param[in] V\n *         The i-th row must contain the vector which defines the\n *         elementary reflector H(i), for i = 1,2,...,k, as returned by\n *         CORE_STSLQT in the first k rows of its array argument V.\n *\n * @param[in] ldv\n *         The leading dimension of the array V. ldv >= max(1,K).\n *\n * @param[in] T\n *         The IB-by-n1 triangular factor T of the block reflector.\n *         T is upper triangular by block (economic storage);\n *         The rest of the array is not referenced.\n *\n * @param[in] ldt\n *         The leading dimension of the array T. ldt >= IB.\n *\n * @param[out] WORK\n *         Workspace array of size\n *             LDWORK-by-m1 if side == PlasmaLeft\n *             LDWORK-by-IB if side == PlasmaRight\n *\n * @param[in] ldwork\n *         The leading dimension of the array WORK.\n *             LDWORK >= max(1,IB) if side == PlasmaLeft\n *             LDWORK >= max(1,n1) if side == PlasmaRight\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *          \\retval <0 if -i, the i-th argument had an illegal value\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_stsmlq_corner = PCORE_stsmlq_corner\n#define CORE_stsmlq_corner PCORE_stsmlq_corner\n#define CORE_stsmlq PCORE_stsmlq\nint  CORE_stsmlq(PLASMA_enum side, PLASMA_enum trans,\n                 int m1, int n1, int m2, int n2, int K, int IB,\n                 float *A1, int lda1,\n                 float *A2, int lda2,\n                 const float *V, int ldv,\n                 const float *T, int ldt,\n                 float *WORK, int LDWORK);\n#endif\nint CORE_stsmlq_corner( int m1, int n1, int m2, int n2, int m3, int n3,\n                        int k, int ib, int nb,\n                        float *A1, int lda1,\n                        float *A2, int lda2,\n                        float *A3, int lda3,\n                        const float *V, int ldv,\n                        const float *T, int ldt,\n                        float *WORK, int ldwork)\n{\n    PLASMA_enum side;\n    PLASMA_enum trans;\n    int i, j;\n\n    if ( m1 != n1 ) {\n        coreblas_error(1, \"Illegal value of M1, N1\");\n        return -1;\n    }\n\n    /* Rebuild the symmetric block: WORK <- A1 */\n    for (i = 0; i < m1; i++)\n        for (j = i; j < n1; j++){\n            *(WORK + i + j*ldwork) = *(A1 + i + j*lda1);\n            if (j > i){\n                *(WORK + j + i*ldwork) =  ( *(WORK + i + j*ldwork) );\n            }\n        }\n\n    /*  Copy the transpose of A2: WORK+nb*ldwork <- A2' */\n    for (j = 0; j < n2; j++)\n        for (i = 0; i < m2; i++){\n            *(WORK + j + (i + nb) * ldwork) = ( *(A2 + i + j*lda2) );\n        }\n\n    side = PlasmaRight;\n    trans = PlasmaTrans;\n\n    /*  Right application on |A1 A2| */\n    CORE_stsmlq(side, trans, m1, n1, m2, n2, k, ib,\n                WORK, ldwork, A2, lda2,\n                V, ldv, T, ldt,\n                WORK+3*nb*ldwork, ldwork);\n\n    /*  Rebuild the symmetric block: WORK+2*nb*ldwork <- A3 */\n    for (i = 0; i < m3; i++)\n        for (j = i; j < n3; j++){\n            *(WORK + i + (j + 2*nb) * ldwork) = *(A3 + i + j*lda3);\n            if (j > i){\n                *(WORK + j + (i + 2*nb) * ldwork) =   ( *(WORK + i + (j + 2*nb) * ldwork) );\n            }\n        }\n\n    /*  Right application on | A2' A3 | */\n    CORE_stsmlq(side, trans, n2, m2, m3, n3, k, ib,\n                WORK+nb*ldwork, ldwork, WORK+2*nb*ldwork, ldwork,\n                V, ldv, T, ldt,\n                WORK + 3*nb*ldwork, ldwork);\n\n    side = PlasmaLeft;\n    trans = PlasmaNoTrans;\n\n    /*  Left application on | A1  | */\n    /*                      | A2' | */\n    CORE_stsmlq(side, trans, m1, n1, n2, m2, k, ib,\n                WORK, ldwork, WORK+nb*ldwork, ldwork,\n                V, ldv, T, ldt,\n                WORK + 3*nb*ldwork, ldwork);\n\n    /*  Copy back the final result to the upper part of A1 */\n    /*  A1 = WORK */\n    for (i = 0; i < m1; i++)\n        for (j = i; j < n1; j++)\n            *(A1 + i + j*lda1) = *(WORK + i + j*ldwork);\n\n    /*  Left application on | A2 | */\n    /*                      | A3 | */\n    CORE_stsmlq(side, trans, m2, n2, m3, n3, k, ib,\n                A2, lda2, WORK+2*nb*ldwork, ldwork,\n                V, ldv, T, ldt,\n                WORK + 3*nb*ldwork, ldwork);\n\n    /*  Copy back the final result to the upper part of A3 */\n    /*  A3 = WORK+2*nb*ldwork */\n    for (i = 0; i < m3; i++)\n        for (j = i; j < n3; j++)\n            *(A3 + i + j*lda3) = *(WORK + i + (j+ 2*nb) * ldwork);\n\n    return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "65f1fcba3e50f15d82db4eb4b60876989d7d104f", "size": 6903, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_stsmlq_corner.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_stsmlq_corner.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_stsmlq_corner.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.6651376147, "max_line_length": 92, "alphanum_fraction": 0.4874692163, "num_tokens": 2124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3663104509884946}}
{"text": "/**\n * @copyright (c) 2017 King Abdullah University of Science and Technology (KAUST).\n *                     All rights reserved.\n **/\n/**\n * @file time_zpotrf_tile.c\n *\n * This file shows how to generate tile low-rank (TLR) matrix and factorize it using Cholesky factorization.\n *\n * HiCMA is a software package provided by King Abdullah University of Science and Technology (KAUST)\n *\n * @version 0.1.1\n * @author Kadir Akbudak\n * @date 2018-11-08\n **/\n\n/*\n * @copyright (c) 2009-2014 The University of Tennessee and The University\n *                          of Tennessee Research Foundation.\n *                          All rights reserved.\n * @copyright (c) 2012-2016 Inria. All rights reserved.\n * @copyright (c) 2012-2014 Bordeaux INP, CNRS (LaBRI UMR 5800), Inria, Univ. Bordeaux. All rights reserved.\n */\n\n/**\n * The meaning of the descriptors:\n * - AUV: U and V, side by side\n * - AD : U*V\n * - A  : the original, non-approximated problem\n * - Ark: rank of U and V, each tile of the matrix is a single integer in fact a double.\n *\n **/\n\n#include \"morse.h\"\n#include \"timing.h\"\n#include \"hicma_constants.h\"\n#include \"hicma_struct.h\"\n#include \"hicma_z.h\"\n#include <stdio.h>\n#include <time.h>\n#include <sys/time.h>\n//#include <mpi.h> //MPI_Wtime()\n\n#include \"starpu.h\"\n#ifdef MKL\n#include <mkl.h>\n//#pragma message(\"MKL is used\")\n#else\n#include <cblas.h>\n#ifdef LAPACKE_UTILS\n#include <lapacke_utils.h>\n#endif\n#include <lapacke.h>\n//#pragma message(\"MKL is NOT used\")\n#endif\n\n#include \"starsh-spatial.h\"\n\n#include <assert.h>\n#include \"hicma_z.h\"\n#include \"auxcompute_z.h\"\n#include \"auxdescutil.h\"\n#include \"hicma.h\"\n#include <math.h>\n#include <time.h>\n\n#undef  CBLAS_SADDR\n#define CBLAS_SADDR(_val) (_val)\n\n// zgytlr uses starsh in MPI mode.\nSTARSH_blrf *mpiF;\n\nint print_progress = 1;   // Print progress about the execution\nchar datebuf[128];\ntime_t timer;\nstruct tm* tm_info;\n#define PROGRESS(str) \\\n    if(print_progress){ \\\n        int myrank = MORSE_My_Mpi_Rank();\\\n        time(&timer); \\\n        tm_info = localtime(&timer); \\\n        strftime(datebuf, 26, \"%Y-%m-%d %H:%M:%S\",tm_info); \\\n        fprintf(stderr, \"%d:%s\\t%d\\t%s\\t%s\\n\", myrank, datebuf, __LINE__, __func__, str);\\\n        fflush(stderr);\\\n    }\n//#undef PROGRESS\n//#define PROGRESS(str)\n\nint store_only_diagonal_tiles = 0;\nint global_check = 0;\nint global_always_fixed_rank = 0;\nint global_fixed_rank = 0;\nint global_omit_computation = 1;\nint num_mpi_ranks;\nint run_potrf = 1;\nint diag_nrows = 0;\nint main_print_index = 0;\nint print_index = 0;\nint print_index_end = 0;\nint main_print_mat = 0;\nint print_mat = 0;\nint use_scratch = 1; // Use scratch memory provided by starpu\nint calc_rank_stat = 1; \n\nvoid fwrite_array(int m, int n, int ld, double* arr, char* file){\n        FILE* fp = fopen(file, \"w\");\n        if(fp == NULL){\n            fprintf(stderr, \"File %s cannot be opened to write\\n\", file);\n            exit(1);\n        }\n        int i, j;\n        fprintf(fp, \"%d %d\\n\", m, n);\n        for(i = 0; i < m; i++){\n            for(j = 0; j < n; j++){\n                fprintf(fp, \"%d\\t\", (int)arr[ld*j+i] );\n            }\n            fprintf(fp, \"\\n\" );\n        }\n        fclose(fp);\n}\n\ndouble timediff(struct timeval begin, struct timeval end){\n    double elapsed = (end.tv_sec - begin.tv_sec) +\n        ((end.tv_usec - begin.tv_usec)/1000000.0);\n    return elapsed;\n}\n\n\n\n    int\nRunTest(int *iparam, double *dparam, morse_time_t *t_, char* rankfile)\n{\n    // print progress info only on ROOT process\n    if(MORSE_My_Mpi_Rank() != 0)\n        print_progress = 0;\n    PROGRESS(\"RunTest started\");\n\n    // this paramater enables storing only diagonal tiles in a tall and skinny matrix\n    store_only_diagonal_tiles = 1;\n    //chameleon/runtime/starpu/control/runtime_descriptor.c\n    //MORSE_user_tag_size(31,26);\n    //MORSE_user_tag_size(31,29);\n    MORSE_user_tag_size(31,27);// When I added tile_to_lapack for descArk, I got not enough number of desc error\n\n    // get parameters coming from command line\n    PASTE_CODE_IPARAM_LOCALS( iparam );\n\n    // set global variable so that p.. files can fill dense matrix\n    global_check = check;\n    // calculate total number of mpi processes (it is not used for now)\n    num_mpi_ranks = P*Q;\n    print_index = iparam[IPARAM_HICMA_PRINTINDEX];\n    print_index_end = iparam[IPARAM_HICMA_PRINTINDEXEND];\n    print_mat   = iparam[IPARAM_HICMA_PRINTMAT];\n    int64_t _nb = iparam[IPARAM_NB];\n    LDA = chameleon_max(M, iparam[IPARAM_LDA]);\n    int hicma_maxrank  = iparam[IPARAM_HICMA_MAXRANK];\n    global_always_fixed_rank = iparam[IPARAM_HICMA_ALWAYS_FIXED_RANK];\n\n    int saveNB = NB;\n    NB = MB;\n    size_t ncols_AD;\n    int saveP = P;\n    int saveQ = Q;\n    if (store_only_diagonal_tiles == 1) {\n        ncols_AD = MB;\n    } else {\n        ncols_AD = M;\n    }\n    int saveN = N;\n    N = ncols_AD;\n    PASTE_CODE_ALLOCATE_MATRIX_TILE( descAD, 1, double, MorseRealDouble, LDA, M, N );\n    N = saveN;\n    P = saveP;\n    Q = saveQ;\n    PROGRESS(\"descAD is allocated\");\n\n    size_t ncols_Dense;\n    size_t ld_Dense;\n    int saveMB = MB;\n    if(check == 0) {\n        ncols_Dense = MT;\n        MB = NB = 1;\n        ld_Dense = MT;\n    } else {\n        ncols_Dense = M;\n        ld_Dense = M;\n    }\n    /*descDense is full matrix if numerical accuracy will be checked.\n     * Otherwise it is MB-by-MB matrix with 1-by-1 tiles */\n    PASTE_CODE_ALLOCATE_MATRIX_TILE( descDense, 1, double, MorseRealDouble, ld_Dense, ncols_Dense, ncols_Dense );\n    if(check == 0) {\n        MB = saveMB;\n    } else {\n    }\n    PROGRESS(\"descDense is allocated\");\n    NB = saveNB;\n\n    int MTMB = MT * MB; // roundup number of rows/columns for AUV \n    int nrows_AUV = MTMB;\n    int ld_AUV = MTMB;\n    // allocate descUV\n    saveN = N;\n    N = N * 2;\n    saveNB = NB;\n    NB = NB * 2;\n    //printf(\"N:%d NB:%d\\n\", N, NB);\n    PASTE_CODE_ALLOCATE_MATRIX_TILE( descAUV, 1, double, MorseRealDouble, ld_AUV, nrows_AUV, N );\n    N = saveN;\n    NB = saveNB;\n    PROGRESS(\"descAUV is allocated\");\n\n    /* tile dimension of rank descriptor must be 1 */\n    /* when LD for rk matrices is 1, program exits*/\n    int bigMB = MB;\n    int bigNB = NB;\n    MB = NB = 1;\n    PASTE_CODE_ALLOCATE_MATRIX_TILE( descArk, 1, double, MorseRealDouble, MT, MT, NT);\n    PROGRESS(\"descA's are allocated\");\n    MB = bigMB;\n    NB = bigNB;\n\n    int diag_dense = 1;\n    int fixedrank = iparam[IPARAM_RK]; //genargs->k\n    double fixedacc = pow(10, -1.0*iparam[IPARAM_ACC]);\n\n    char sym;\n    if (run_potrf)\n        sym = 'S';\n    else\n        sym = 'N';\n    int probtype = iparam[IPARAM_HICMA_STARSH_PROB];\n    int maxrank  = iparam[IPARAM_HICMA_STARSH_MAXRANK];\n    //double ddecay = pow(10, -1.0*iparam[IPARAM_HICMA_STARSH_DECAY]);\n    double ddecay = dparam[IPARAM_HICMA_STARSH_DECAY];\n\n\n    int  initial_maxrank, final_maxrank;\n    double initial_avgrank, final_avgrank;\n    HICMA_problem_t hicma_problem;\n\n    hicma_problem.ndim = 2;\n\n    //BEGIN: rndtiled\n    if(iparam[IPARAM_HICMA_STARSH_PROB] == HICMA_STARSH_PROB_RND) {\n        hicma_problem.noise    = 1.0; //value added to diagonal\n    }\n    //END:   rndtiled\n\n    //BEGIN: geostat\n    //double theta[3] = {1, 0.1, 0.5}; //initially\n    double theta[3] = {\n        1.0, //sigma \n        0.01, //beta\n        10.0 //nu Aleks used 10.0 in his paper\n    };\n    if(iparam[IPARAM_HICMA_STARSH_PROB] == HICMA_STARSH_PROB_GEOSTAT) {\n        hicma_problem.theta = theta;\n        hicma_problem.noise = 0.0;\n        hicma_problem.noise = 1.e-2;\n        hicma_problem.kernel_type = STARSH_SPATIAL_MATERN2_SIMD;\n    }\n    //END: geostat\n\n    //BEGIN: ss\n    if(iparam[IPARAM_HICMA_STARSH_PROB] == HICMA_STARSH_PROB_SS) {\n        //sigma=1.0 default value line 193 of stars-h/src/applications/spatial.c \n        // Correlation length\n        hicma_problem.beta  = 0.1;\n        //If fixed rank is required set beta=1 and a sample case will be like this nb=25 maxrank=10 m=2500 So ranks will decrease.\n\n        // Smoothing parameter for Matern kernel\n        hicma_problem.nu    = 0.5;\n        // Shift added to diagonal elements\n        hicma_problem.noise = 1.e-4; //not enough for matrices larger than 600K\n        hicma_problem.noise = 5.e-4; //works for 640K but does not work for 10M\n        hicma_problem.noise = 1.e-2; //\n    }\n    //END: ss\n    \n    //BEGIN: edsin\n    if(iparam[IPARAM_HICMA_STARSH_PROB] == HICMA_STARSH_PROB_EDSIN) {\n        // Wave number, >= 0\n        hicma_problem.wave_k = dparam[IPARAM_HICMA_STARSH_WAVE_K];\n        hicma_problem.diag = M; \n    //printf(\"%s %d: %g\\n\", __FILE__, __LINE__, hicma_problem.wave_k);\n    }\n    //END: edsin\n\n    PROGRESS(\"generating coordinates started\");\n    struct timeval tvalBefore, tvalAfter;  // removed comma\n    gettimeofday (&tvalBefore, NULL);\n    HICMA_zgenerate_problem(probtype, sym, ddecay, M, MB, MT, NT, &hicma_problem);\n    gettimeofday (&tvalAfter, NULL);\n    if(MORSE_My_Mpi_Rank()==0){\n        printf(\"Tproblem:%g\\n\",\n                (tvalAfter.tv_sec - tvalBefore.tv_sec)\n                 +(tvalAfter.tv_usec - tvalBefore.tv_usec)/1000000.0\n              );\n        fflush(stderr);\n        fflush(stdout);\n    }\n    PROGRESS(\"generating coordinates ended\");\n    mpiF = hicma_problem.starsh_format; // This is assignment will be hidden from user in release\n\n\t// DO NOT enforce compression of diagonal tiles\n\tint compress_diag = 0;\n    PROGRESS(\"nompi zgytlr starting\");\n    //descDense original problem\n    gettimeofday (&tvalBefore, NULL);\n    HICMA_zgytlr_Tile(MorseLower, descAUV, descAD, descArk, 0, maxrank, fixedacc, compress_diag, descDense);\n    gettimeofday (&tvalAfter, NULL);\n    if(MORSE_My_Mpi_Rank()==0){\n        printf(\"Tcompress:%g\\n\", \n                (tvalAfter.tv_sec - tvalBefore.tv_sec)\n                 +(tvalAfter.tv_usec - tvalBefore.tv_usec)/1000000.0\n                );\n        fflush(stderr);\n        fflush(stdout);\n    }\n    PROGRESS(\"nompi zgytlr finished\");\n    fflush(stderr);\n    fflush(stdout);\n    /*return 0; //TODO*/\n\n    if(calc_rank_stat == 1) {\n        PASTE_TILE_TO_LAPACK( descArk, Ark_initial, 1, double, MT, NT );\n        if(MORSE_My_Mpi_Rank()==0){\n\n            sprintf(rankfile, \"%s-1\", rankfile);\n            fwrite_array(descArk->m, descArk->n, descArk->m, Ark_initial, rankfile);\n\n            HICMA_stat_t hicma_statrk_initial;\n            zget_stat(MorseLower, Ark_initial, MT, NT, MT,  &hicma_statrk_initial);\n            printf(\"initial_ranks:\");\n            zprint_stat(hicma_statrk_initial);\n            fflush(stderr);\n            fflush(stdout);\n        }\n    }\n\n    if (global_always_fixed_rank == 1) {\n        fprintf(stderr, \"%s %d Fixed rank: %d\\n\", __FILE__, __LINE__, global_fixed_rank);\n    }\n\n    if(0 && num_mpi_ranks == 1 && initial_maxrank > N){ //FIXME Enable for distributed mem\n        fprintf(stderr,\"%s %d %d\\t|N:%d is less than actual maxrank:%d\\n\", __FILE__, __LINE__, MORSE_My_Mpi_Rank(), N, initial_maxrank);\n        exit(1);\n    }\n    int set_diag = 0;\n\n    /* Save A for check */\n    PROGRESS(\"pasting original dense descAD into Adense and Adense2 started\");\n    // Adense: original dense problem.\n    PASTE_TILE_TO_LAPACK( descDense, Adense, check, double, LDA, M );\n    double one = 1.0, zero = 0.0, minusone = -1.0, diagVal = M;\n    double* swork = NULL;\n    //double* cp_L_Adense =  calloc(LDA*M, sizeof(double)); \n    if(check){\n        swork  = calloc(2*M, sizeof(double));\n        {size_t i, j;\n            double* orgAdense = calloc(LDA*M, sizeof(double));\n            for(j = 0; j < M; j++){\n                for(i = 0; i < M; i++){\n                    orgAdense[j*LDA+i] = Adense[j*LDA+i];\n                }\n            }\n            int info = LAPACKE_dpotrf_work(\n                    LAPACK_COL_MAJOR,\n                    'L',\n                    M, orgAdense, LDA);\n            if(0 && info != 0){ //FIXME\n                fprintf(stderr, \"%s\\t|%d\\t|Error in LAPACK potrf. info:%d, This errors means \"\n                        \"that the matrix generated is not positive definite\\n\", __FILE__, __LINE__, info);\n            }\n            for(j = 0; j < M; j++){\n                for(i = 0; i < j; i++){\n                    orgAdense[j*LDA+i] = zero;\n                }\n            }\n            /*for(j = 0; j < M; j++) {                */\n                /*for(i = 0; i < M; i++){*/\n                    /*cp_L_Adense[j*LDA+i] = orgAdense[j*LDA+i];*/\n                /*}*/\n            /*}*/\n            if(main_print_mat ){printf(\"L of Adense\\n\");printmat(orgAdense,M,M,LDA,MB, MB);}\n            double normOrgAdense = 0.0;\n            /*HICMA_znormest(M, M, orgAdense, &normOrgAdense, swork);*/\n            /*printf(\"norm_L_OrgAdense:%e\\n\",normOrgAdense);*/\n            free(orgAdense);\n        }\n    }\n    PASTE_TILE_TO_LAPACK( descDense, Adense2, check, double, LDA, M );\n    PROGRESS(\"pasting original dense descAD into Adense and Adense2 finished\");\n    PROGRESS(\"potrf started\");\n    START_TIMING();\n    HICMA_zpotrf_Tile(MorseLower, descAUV, descAD, descArk, fixedrank, maxrank, fixedacc );\n    STOP_TIMING();\n    fflush(stderr);\n    fflush(stdout);\n    PROGRESS(\"potrf finished\");\n    if(check){\n        HICMA_zuncompress(MorseLower, descAUV, descDense, descArk);\n        HICMA_zdiag_vec2mat(descAD, descDense);\n        PASTE_CODE_FREE_MATRIX( descAD ); //@KADIRLBL001  \n        descAD = descDense; // descAD was only diagonals.\n        // After this line, descAD is dense matrix containing approximate L\n        // So no need to adapt below code for descAD containg only diagonals.\n    }\n    if(calc_rank_stat == 1) {\n        PASTE_TILE_TO_LAPACK( descArk, Ark_final, 1, double, MT, NT );\n        if(MORSE_My_Mpi_Rank()==0){\n            sprintf(rankfile, \"%s-2\", rankfile);\n            fwrite_array(descArk->m, descArk->n, descArk->m, Ark_final, rankfile);\n            HICMA_stat_t hicma_statrk_final;\n            zget_stat(MorseLower, Ark_final, MT, NT, MT,  &hicma_statrk_final);\n            printf(\"final_ranks:\");\n            zprint_stat(hicma_statrk_final);\n            fflush(stderr);\n            fflush(stdout);\n        }\n    }\n\n    int check_dense = 0;\n    int check_app = 1;\n    if(check == 0){\n        check_dense = check_app = 0;\n    }\n    if(check_app ) {\n        PROGRESS(\"checking accuracy\");\n        if( MORSE_My_Mpi_Rank()==0){\n#ifndef COMPLEX\n            if(main_print_mat){printf(\"Adense2\\n\");printmat(Adense2,M,M,LDA,MB, MB);}\n            double normA;\n            {size_t i, j;\n                for(j = 0; j < M; j++){\n                    for(i = 0; i < j; i++){\n                        Adense2[j*LDA+i] = zero;\n                    }\n                }\n            }\n            PROGRESS(\"normaA started\");\n            HICMA_znormest(M, M, Adense2, &normA, swork);\n            // Ahicma: result of TLR potrf\n            PASTE_TILE_TO_LAPACK( descAD, Ahicma, check, double, LDA, M );\n            /*if(0){size_t i,j;*/\n                /*for(j = 0; j < M; j++) {                */\n                    /*for(i = 0; i < M; i++){*/\n                        /*Ahicma[j*LDA+i] = cp_L_Adense[j*LDA+i];*/\n                    /*}*/\n                /*}*/\n            /*}*/\n            double normAhicma = 0.0;\n            {size_t i, j;\n                for(j = 0; j < M; j++){\n                    for(i = 0; i < j; i++){\n                        Ahicma[j*LDA+i] = zero;\n                    }\n                }\n                double* orgAhicma = calloc(LDA*M, sizeof(double));\n                for(j = 0; j < M; j++){\n                    for(i = 0; i < M; i++){\n                        orgAhicma[j*LDA+i] = Ahicma[j*LDA+i];\n                    }\n                }\n                HICMA_znormest(M, M, orgAhicma, &normAhicma, swork);\n                free(orgAhicma);\n            }\n            if(set_diag){size_t j; for(j = 0; j < M; j++){ Ahicma[j*LDA+j] = diagVal; } }\n            if(main_print_mat){printf(\"Ahicma\\n\");printmat(Ahicma,M,M,LDA, MB, MB);}\n            //LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', M, Ahicma, LDA);\n            // AhicmaT: transpose of Ahicma\n            PROGRESS(\"copy descAd into AhicmaT started\");\n            PASTE_TILE_TO_LAPACK( descAD,  AhicmaT, check, double, LDA, M );\n\n            {size_t i, j;\n                for(j = 0; j < M; j++){\n                    for(i = 0; i < j; i++){\n                        Adense[j*LDA+i] = zero;\n                    }\n                }\n            }\n\n            if(main_print_mat){printf(\"Ahicma-upperzero\\n\");printmat(Ahicma,M,M,LDA, MB, MB);}\n            PROGRESS(\"Transpose A started\");\n            LAPACKE_dge_trans(LAPACK_COL_MAJOR, M, M, Ahicma, LDA, AhicmaT, LDA);\n            if(main_print_mat){printf(\"AhicmaT\\n\");printmat(AhicmaT,M,M,LDA, MB, MB);}\n            PROGRESS(\"TRMM started\");\n            cblas_dtrmm (CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit, M, M, one, Ahicma, LDA, AhicmaT, LDA);\n            if(main_print_mat){printf(\"Ahicma*AhicmaT\\n\");printmat(AhicmaT,M,M,LDA, MB, MB);}\n            //double tmpnorm;normest(M, M, AhicmaT, &tmpnorm, swork);printf(\"tmpnorm:%e\\n\",tmpnorm);\n            {size_t i, j;\n                for(j = 0; j < M; j++){\n                    for(i = 0; i < j; i++){\n                        AhicmaT[j*LDA+i] = zero;\n                    }\n                }\n            }\n\n            size_t nelm = M * M;\n            if(main_print_mat)printf(\"nelm:%zu M:%d N:%d\\n\", nelm, M, N);\n            PROGRESS(\"DAXPY started\");\n            cblas_daxpy(nelm, minusone, AhicmaT, 1, Adense, 1);\n            if(main_print_mat){printf(\"Adense-(Ahicma*AhicmaT)\\n\");printmat(Adense,M,M,LDA, MB, MB);}\n\n            double normDenseAppDiff;\n            PROGRESS(\"Norm of difference started\");\n            HICMA_znormest(M, M, Adense, &normDenseAppDiff, swork);\n            double accuracyDenseAppDiff = normDenseAppDiff/normA;\n            //printf(\"normA:%.2e normDenseAppdiff:%.2e Accuracy: %.2e\\n\", normA, normDenseAppDiff,  accuracyDenseAppDiff);\n            dparam[IPARAM_RES] = normDenseAppDiff;\n            dparam[IPARAM_ANORM] = normA;\n            dparam[IPARAM_XNORM] = normA;\n            dparam[IPARAM_BNORM] = normAhicma;\n#endif\n        } else {\n            PASTE_TILE_TO_LAPACK( descAD, Ahicma, check, double, LDA, M );\n            PASTE_TILE_TO_LAPACK( descAD,  AhicmaT, check, double, LDA, M );\n        }\n        PROGRESS(\"checking accuracy is finished\");\n    }\n\n    PASTE_CODE_FREE_MATRIX( descAUV );\n    PROGRESS(\"descAUV is freed\");\n    if(check == 0) { // If there is no check, then descAD and descDense are different. Refer to @KADIRLBL001\n        PASTE_CODE_FREE_MATRIX( descAD );\n        PROGRESS(\"descAD is freed\");\n    }\n    PASTE_CODE_FREE_MATRIX( descArk );\n    PROGRESS(\"descArk is freed\");\n    PASTE_CODE_FREE_MATRIX( descDense );\n    PROGRESS(\"descDense is freed\");\n    PROGRESS(\"freed descs\");\n    return 0;\n}\n", "meta": {"hexsha": "c59d8e055c23094fe639c75a8d8009b72c278acc", "size": 18748, "ext": "c", "lang": "C", "max_stars_repo_path": "timing/time_zpotrf_tile.c", "max_stars_repo_name": "Quansight/hicma", "max_stars_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "timing/time_zpotrf_tile.c", "max_issues_repo_name": "Quansight/hicma", "max_issues_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-08T11:06:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T11:06:39.000Z", "max_forks_repo_path": "timing/time_zpotrf_tile.c", "max_forks_repo_name": "isabella232/hicma", "max_forks_repo_head_hexsha": "c8287eed9ea9a803fc88ab067426ac6baacaa534", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-08T11:05:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T11:05:38.000Z", "avg_line_length": 34.9776119403, "max_line_length": 136, "alphanum_fraction": 0.5805419245, "num_tokens": 5515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.63341026367784, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.3657914915350755}}
{"text": "/* PSICOV - Protein Sparse Inverse COVariance analysis program */\n\n/* by David T. Jones August 2011 - Copyright (C) 2011 University College London */\n\n/* Version 1.05 - Last Edit 13/2/12 */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n#include <unistd.h>\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_linalg.h>\n\n#define FALSE 0\n#define TRUE 1\n\n#define SQR(x) ((x)*(x))\n#define MAX(x,y) ((x)>(y)?(x):(y))\n#define MIN(x,y) ((x)<(y)?(x):(y))\n\n#define MAXSEQLEN 5000\n#define MINSEQS 50\n#define MINEFSEQS 100\n\n\nextern glasso_(int *, double *, double *, int *, int *, int *, int *, double *, int *, double *, double *, int *, double *, int *);\n\n\n/* Dump a rude message to standard error and exit */\nvoid\n                fail(char *errstr)\n{\n    fprintf(stderr, \"\\n*** %s\\n\\n\", errstr);\n    exit(-1);\n}\n\n/* Convert AA letter to numeric code (0-21) */\nint\n                aanum(int ch)\n{\n    const static int aacvs[] =\n    {\n\t999, 0, 3, 4, 3, 6, 13, 7, 8, 9, 21, 11, 10, 12, 2,\n\t21, 14, 5, 1, 15, 16, 21, 19, 17, 21, 18, 6\n    };\n\n    return (isalpha(ch) ? aacvs[ch & 31] : 20);\n}\n\n/* Allocate matrix */\nvoid           *allocmat(int rows, int columns, int size)\n{\n    int             i;\n    void          **p, *rp;\n\n    rp = malloc(rows * sizeof(void *) + sizeof(int));\n\n    if (rp == NULL)\n\tfail(\"allocmat: malloc [] failed!\");\n\n    *((int *)rp) = rows;\n\n    p = rp + sizeof(int);\n\n    for (i = 0; i < rows; i++)\n\tif ((p[i] = calloc(columns, size)) == NULL)\n\t    fail(\"allocmat: malloc [][] failed!\");\n\n    return p;\n}\n\n/* Free matrix */\nvoid\n                freemat(void *rp)\n{\n    int             rows;\n    void **p = rp;\n\n    rows = *((int *)(rp - sizeof(int)));\n\n    while (rows--)\n\tfree(p[rows]);\n\n    free(rp - sizeof(int));\n}\n\n/* Allocate vector */\nvoid           *allocvec(int columns, int size)\n{\n    void          *p;\n\n    p = calloc(columns, size);\n\n    if (p == NULL)\n\tfail(\"allocvec: calloc failed!\");\n\n    return p;\n}\n\nstruct sc_entry\n{\n    float sc;\n    int i, j;\n} *sclist;\n\n/* Sort descending */\nint cmpfn(const void *a, const void *b)\n{\n    if (((struct sc_entry *)a)->sc == ((struct sc_entry *)b)->sc)\n\treturn 0;\n\n    if (((struct sc_entry *)a)->sc < ((struct sc_entry *)b)->sc)\n\treturn 1;\n\n    return -1;\n}\n    \n\nint             main(int argc, char **argv)\n{\n    int             a, b, i, j, k, seqlen, nids, s, nseqs, ncon, opt, ndim, approxflg=0, initflg=0, debugflg=0, diagpenflg=1, apcflg=1, maxit=10000, npair, nnzero, niter, jerr, shrinkflg=1, rawscflg = 1, pseudoc = 1, minseqsep = 5;\n    unsigned int *wtcount;\n    double thresh=1e-4, del, sum, score, (**pab)[21][21], **pa, wtsum, pc, **pcmat, *pcsum, pcmean, rhodefault = -1.0, lambda, smean, fnzero, lastfnzero, trialrho, rfact, r2, targfnzero = 0.0, scsum, scsumsq, mean, sd, zscore, ppv;    \n    float *weight, idthresh = -1.0, maxgapf = 0.9;\n    char            buf[4096], seq[MAXSEQLEN], *blockfn = NULL, **aln;\n    FILE *ifp;\n\n    while ((opt = getopt(argc, argv, \"alnpr:b:i:t:c:g:d:j:\")) >= 0)\n\tswitch (opt)\n\t{\n\tcase 'a':\n\t    approxflg = 1;\n\t    break;\n\tcase 'n':\n\t    shrinkflg = 0;\n\t    break;\n\tcase 'p':\n\t    rawscflg = 0;\n\t    break;\n\tcase 'l':\n\t    apcflg = 0;\n\t    break;\n\tcase 'r':\n\t    rhodefault = atof(optarg);\n\t    break;\n\tcase 'd':\n\t    targfnzero = atof(optarg);\n\t    break;\n\tcase 't':\n\t    thresh = atof(optarg);\n\t    break;\n\tcase 'i':\n\t    idthresh = 1.0 - atof(optarg)/100.0;\n\t    break;\n\tcase 'c':\n\t    pseudoc = atoi(optarg);\n\t    break;\n\tcase 'j':\n\t    minseqsep = atoi(optarg);\n\t    break;\n\tcase 'b':\n\t    blockfn = strdup(optarg);\n\t    break;\n\tcase 'g':\n\t    maxgapf = atof(optarg);\n\t    break;\n\tcase '?':\n\t    exit(-1);\n\t}\n\n    if (optind >= argc)\n\tfail(\"Usage: psicov [options] alnfile\\n\\nOptions:\\n-a\\t: use approximate Lasso algorithm\\n-n\\t: don't pre-shrink the sample covariance matrix\\n-p\\t: output PPV estimates rather than raw scores\\n-l\\t: don't apply APC to Lasso output\\n-r nnn\\t: set initial rho parameter\\n-d nnn\\t: set target precision matrix sparsity (default 0 = not specified)\\n-t nnn\\t: set Lasso convergence threshold (default 1e-4)\\n-i nnn\\t: select BLOSUM weighting with given identity threshold (default selects threshold automatically)\\n-c nnn\\t: set pseudocount value (default 1)\\n-j nnn\\t: set minimum sequence separation (default 5)\\n-g nnn\\t: maximum fraction of gaps (default 0.9)\\n-b file\\t: read rho parameter file\\n\");\n\n    ifp = fopen(argv[optind], \"r\");\n    if (!ifp)\n\tfail(\"Unable to open alignment file!\");\n\n    for (nseqs=0;; nseqs++)\n\tif (!fgets(seq, MAXSEQLEN, ifp))\n\t    break;\n\n    aln = allocvec(nseqs, sizeof(char *));\n    \n    weight = allocvec(nseqs, sizeof(float));\n\n    wtcount = allocvec(nseqs, sizeof(unsigned int));\n    \n    rewind(ifp);\n    \n    if (!fgets(seq, MAXSEQLEN, ifp))\n\tfail(\"Bad alignment file!\");\n    \n    seqlen = strlen(seq)-1;\n\n    if (nseqs < MINSEQS)\n\tfail(\"Alignment too small - not enough homologous sequences to proceed (or change MINSEQS at your own risk!)\");\n\n    if (!(aln[0] = malloc(seqlen)))\n\tfail(\"Out of memory!\");\n\n    for (j=0; j<seqlen; j++)\n\taln[0][j] = aanum(seq[j]);\n    \n    for (i=1; i<nseqs; i++)\n    {\n\tif (!fgets(seq, MAXSEQLEN, ifp))\n\t    break;\n\t\n\tif (seqlen != strlen(seq)-1)\n\t    fail(\"Length mismatch in alignment file!\");\n\t\n\tif (!(aln[i] = malloc(seqlen)))\n\t    fail(\"Out of memory!\");\n\t\n\tfor (j=0; j<seqlen; j++)\n\t    aln[i][j] = aanum(seq[j]);\n    }\n\n\n    /* Calculate sequence weights */\n\n    if (idthresh < 0.0)\n    {\n\tdouble meanfracid = 0.0;\n\t\n\tfor (i=0; i<nseqs; i++)\n\t    for (j=i+1; j<nseqs; j++)\n\t    {\n\t\tint nids;\n\t\tfloat fracid;\n\t\t\n\t\tfor (nids=k=0; k<seqlen; k++)\n\t\t    if (aln[i][k] == aln[j][k])\n\t\t\tnids++;\n\t\t\n\t\tfracid = (float)nids / seqlen;\n\t\t\n\t\tmeanfracid += fracid;\n\t    }\n\t\n\tmeanfracid /= 0.5 * nseqs * (nseqs - 1.0);\n\n\tidthresh = 0.38 * 0.32 / meanfracid;\n    }\n\n    for (i=0; i<nseqs; i++)\n\tfor (j=i+1; j<nseqs; j++)\n\t{\n\t    int nthresh = seqlen * idthresh;\n\n\t    for (k=0; nthresh > 0 && k<seqlen; k++)\n\t\tif (aln[i][k] != aln[j][k])\n\t\t    nthresh--;\n\t    \n\t    if (nthresh > 0)\n\t    {\n\t\twtcount[i]++;\n\t\twtcount[j]++;\n\t    }\n\t}\n\n    for (wtsum=i=0; i<nseqs; i++)\n\twtsum += (weight[i] = 1.0 / (1 + wtcount[i]));\n\n    if (wtsum < MINEFSEQS)\n\tputs(\"\\n*** WARNING - not enough sequence variation - or change MINEFSEQS at your own risk! ***\\n\");\n\n    pa = allocmat(seqlen, 21, sizeof(double));\n    pab = allocmat(seqlen, seqlen, 21*21*sizeof(double));\n\n    /* Calculate singlet frequencies with pseudocount */\n    for (i=0; i<seqlen; i++)\n    {\n\tfor (a=0; a<21; a++)\n\t    pa[i][a] = pseudoc;\n\t\n\tfor (k=0; k<nseqs; k++)\n\t{\n\t    a = aln[k][i];\n\t    if (a < 21)\n\t\tpa[i][a] += weight[k];\n\t}\n\t\n\tfor (a=0; a<21; a++)\n\t    pa[i][a] /= pseudoc * 21.0 + wtsum;\n    }\n\n    /* Calculate pair frequencies with pseudocount */\n    for (i=0; i<seqlen; i++)\n    {\n\tfor (j=i+1; j<seqlen; j++)\n\t{\n\t    for (a=0; a<21; a++)\n\t\tfor (b=0; b<21; b++)\n\t\t    pab[i][j][a][b] = pseudoc / 21.0;\n\n\t    for (k=0; k<nseqs; k++)\n\t    {\n\t\ta = aln[k][i];\n\t\tb = aln[k][j];\n\t\tif (a < 21 && b < 21)\n\t\t    pab[i][j][a][b] += weight[k];\n\t    }\n\t    \n\t    for (a=0; a<21; a++)\n\t\tfor (b=0; b<21; b++)\n\t\t{\n\t\t    pab[i][j][a][b] /= pseudoc * 21.0 + wtsum;\n\t\t    pab[j][i][b][a] = pab[i][j][a][b];\n\n//\t\t    printf(\"%d/%d %d/%d %f %f %f %f\\n\", i+1, a, j+1, b, pab[i][j][a][b], pa[i][a] , pa[j][b], pab[i][j][a][b] - pa[i][a] * pa[j][b]);\n\t\t}\n\t}\n    }\n\n    for (i=0; i<seqlen; i++)\n\tfor (a=0; a<21; a++)\n\t    for (b=0; b<21; b++)\n\t\tpab[i][i][a][b] = (a == b) ? pa[i][a] : 0.0;\n\n    gsl_matrix *cmat, *rho, *ww, *wwi, *tempmat;\n\n    ndim = seqlen * 21;\n\n    cmat = gsl_matrix_calloc(ndim, ndim);\n\n    /* Form the covariance matrix */\n    for (i=0; i<seqlen; i++)\n\tfor (j=0; j<seqlen; j++)\n\t    for (a=0; a<21; a++)\n\t\tfor (b=0; b<21; b++)\n\t\t    if (i != j)\n\t\t\tgsl_matrix_set(cmat, i*21+a, j*21+b, pab[i][j][a][b] - pa[i][a] * pa[j][b]);\n\t\t    else if (a == b)\n\t\t\tgsl_matrix_set(cmat, i*21+a, j*21+b, pab[i][j][a][b] - pa[i][a] * pa[j][b]);\n\n    freemat(pab);\n\n    /* Shrink sample covariance matrix towards shrinkage target F = Diag(1,1,1,...,1) * smean */\n\n    if (shrinkflg)\n    {\n\tfor (smean=i=0; i<ndim; i++)\n\t    smean += gsl_matrix_get(cmat, i, i);\n\t\n\tsmean /= (float)ndim;\n\tlambda = 0.1;\n\n//\tsmean = 1;\n\n\ttempmat = gsl_matrix_calloc(ndim, ndim);\n\n\tgsl_set_error_handler_off();\n\t\n\tfor (;;)\n\t{\n\t    gsl_matrix_memcpy(tempmat, cmat);\n\t    \n\t    /* Test if positive definite using Cholesky decomposition */\n\t    if (!gsl_linalg_cholesky_decomp(tempmat))\n\t\tbreak;\n\t    \n\t    for (i=0; i<seqlen; i++)\n\t\tfor (j=0; j<seqlen; j++)\n\t\t    for (a=0; a<21; a++)\n\t\t\tfor (b=0; b<21; b++)\n\t\t\t    if (i != j)\n\t\t\t\tgsl_matrix_set(cmat, i*21+a, j*21+b, (1.0 - lambda) * gsl_matrix_get(cmat, i*21+a, j*21+b));\n\t\t\t    else if (a == b)\n\t\t\t\tgsl_matrix_set(cmat, i*21+a, j*21+b, smean * lambda + (1.0 - lambda) * gsl_matrix_get(cmat, i*21+a, j*21+b));\n\t}\n\n\tgsl_matrix_free(tempmat);\n    }\n\n    rho = gsl_matrix_alloc(ndim, ndim);\n    ww = gsl_matrix_alloc(ndim, ndim);\n    wwi = gsl_matrix_alloc(ndim, ndim);\n\n    lastfnzero=0.0;\n\n    /* Guess at a reasonable starting rho value if undefined */\n    if (rhodefault < 0.0)\n\ttrialrho = MAX(0.001, 1.0 / wtsum);\n    else\n\ttrialrho = rhodefault;\n\n    rfact = 0.0;\n\n    for (;;)\n    {\n\tif (trialrho <= 0.0 || trialrho >= 1.0)\n\t    fail(\"Sorry - failed to find suitable value for rho (0 < rho < 1)!\");\n\n\tgsl_matrix_set_all(rho, trialrho);\n\n\tfor (i=0; i<seqlen; i++)\n\t    for (j=0; j<seqlen; j++)\n\t\tfor (a=0; a<21; a++)\n\t\t    for (b=0; b<21; b++)\n\t\t\tif ((a != b && i == j) || pa[i][20] > maxgapf || pa[j][20] > maxgapf)\n\t\t\t    gsl_matrix_set(rho, i*21+a, j*21+b, 1e9);\n\t\n\t/* Mask out regions if block-out list provided */\n\tif (blockfn != NULL)\n\t{\n\t    ifp = fopen(blockfn, \"r\");\n\t    \n\t    for (;;)\n\t    {\n\t\tif (fscanf(ifp, \"%d %d %lf\", &i, &j, &score) != 3)\n\t\t    break;\n\t\t\n\t\tfor (a=0; a<21; a++)\n\t\t    for (b=0; b<21; b++)\n\t\t    {\n\t\t\tgsl_matrix_set(rho, (i-1)*21+a, (j-1)*21+b, score);\n\t\t\tgsl_matrix_set(rho, (j-1)*21+b, (i-1)*21+a, score);\n\t\t    }\n\t    }\n\t    \n\t    fclose(ifp);\n\t}\n    \n\t/* All matrices are symmetric so no need to transpose before/after calling Fortran code */\n\n\tglasso_(&ndim, cmat->data, rho->data, &approxflg, &initflg, &debugflg, &diagpenflg, &thresh, &maxit, ww->data, wwi->data, &niter, &del, &jerr);\n\n\tif (targfnzero <= 0.0)\n\t    break;\n\t\n\tfor (npair=nnzero=i=0; i<ndim; i++)\n\t    for (j=i+1; j<ndim; j++,npair++)\n\t\tif (gsl_matrix_get(wwi, i, j) != 0.0)\n\t\t    nnzero++;\n\n\tfnzero = (double) nnzero / npair;\n\n//      printf(\"rho=%f fnzero = %f\\n\", trialrho, fnzero);\n\n\t/* Stop iterating if we have achieved the target sparsity level */\n\tif (fabs(fnzero - targfnzero)/targfnzero < 0.01)\n\t    break;\n\t\n\tif (fnzero == 0.0)\n\t{\n\t    /* As we have guessed far too high, halve rho and try again */\n\t    trialrho *= 0.5;\n\t    continue;\n\t}\n\t\n\tif (lastfnzero > 0.0 && fnzero != lastfnzero)\n\t{\n//\t    printf(\"fnzero=%f lastfnzero=%f trialrho=%f oldtrialrho=%f\\n\", fnzero, lastfnzero, trialrho, trialrho/rfact);\n\t    \n\t    rfact = pow(rfact, log(targfnzero / fnzero) / log(fnzero / lastfnzero));\n\n//\t    printf(\"New rfact = %f\\n\", rfact);\n\t}\n\n\tlastfnzero = fnzero;\n\n\t/* Make a small trial step in the appropriate direction */\n\n\tif (rfact == 0.0)\n\t    rfact = (fnzero < targfnzero) ? 0.9 : 1.1;\n\t\n\ttrialrho *= rfact;\n    }\n\n    gsl_matrix_free(rho);\n    gsl_matrix_free(ww);\n\n    /* Calculate background corrected scores using average product correction */\n\n    pcmat = allocmat(seqlen, seqlen, sizeof(double));\n    pcsum = allocvec(seqlen, sizeof(double));\n    \n    pcmean = 0.0;\n    \n    for (i=0; i<seqlen; i++)\n\tfor (j=i+1; j<seqlen; j++)\n\t{\t\n\t    for (pc=a=0; a<20; a++)\n\t\tfor (b=0; b<20; b++)\n\t\t    pc += fabs(gsl_matrix_get(wwi, i*21+a, j*21+b));\n\n\t    pcmat[i][j] = pcmat[j][i] = pc;\n\t    pcsum[i] += pc;\n\t    pcsum[j] += pc;\n\n\t    pcmean += pc;\n\t}\n\n    pcmean /= seqlen * (seqlen - 1) * 0.5;\n\n    /* Build final list of predicted contacts */\n\n    sclist = allocvec(seqlen * (seqlen - 1) / 2, sizeof(struct sc_entry));\n\n    for (scsum=scsumsq=ncon=i=0; i<seqlen; i++)\n\tfor (j=i+minseqsep; j<seqlen; j++)\n\t    if (pcmat[i][j] > 0.0)\n\t    {\n\t\t/* Calculate APC score */\n\t\tif (apcflg)\n\t\t    sclist[ncon].sc = pcmat[i][j] - pcsum[i] * pcsum[j] / SQR(seqlen - 1.0) / pcmean;\n\t\telse\n\t\t    sclist[ncon].sc = pcmat[i][j];\n\t\tscsum += sclist[ncon].sc;\n\t\tscsumsq += SQR(sclist[ncon].sc);\n\t\tsclist[ncon].i = i;\n\t\tsclist[ncon++].j = j;\n\t    }\n\n    qsort(sclist, ncon, sizeof(struct sc_entry), cmpfn);\n\n    mean = scsum / ncon;\n    sd = sqrt(scsumsq / ncon - SQR(mean));\n\n    /* Print output in CASP RR format with optional PPV estimated from final Z-score */\n    if (rawscflg)\n\tfor (i=0; i<ncon; i++)\n\t    printf(\"%d %d 0 8 %f\\n\", sclist[i].i+1, sclist[i].j+1, sclist[i].sc);\n    else\n\tfor (i=0; i<ncon; i++)\n\t{\n\t    zscore = (sclist[i].sc - mean) / sd;\n\t    ppv = 0.904 / (1.0 + 16.61 * exp(-0.8105 * zscore));\n\t    printf(\"%d %d 0 8 %f\\n\", sclist[i].i+1, sclist[i].j+1, ppv);\n\t}\n    \n    return 0;\n}\n", "meta": {"hexsha": "757fb164a19794ee936ae2e048330ad224a72cb3", "size": 13006, "ext": "c", "lang": "C", "max_stars_repo_path": "COEVOLUTION_METHODS/FUNCTIONS/PSICOV/psicov_unlimited.c", "max_stars_repo_name": "dgattiwsu/MSAVOLVE_v3.0a", "max_stars_repo_head_hexsha": "daea50468c712bd7cc65e2078cdc3af4d55a5941", "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": "COEVOLUTION_METHODS/FUNCTIONS/PSICOV/psicov_unlimited.c", "max_issues_repo_name": "dgattiwsu/MSAVOLVE_v3.0a", "max_issues_repo_head_hexsha": "daea50468c712bd7cc65e2078cdc3af4d55a5941", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "COEVOLUTION_METHODS/FUNCTIONS/PSICOV/psicov_unlimited.c", "max_forks_repo_name": "dgattiwsu/MSAVOLVE_v3.0a", "max_forks_repo_head_hexsha": "daea50468c712bd7cc65e2078cdc3af4d55a5941", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-05T02:43:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-05T02:43:44.000Z", "avg_line_length": 24.0851851852, "max_line_length": 701, "alphanum_fraction": 0.5508226972, "num_tokens": 4731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872019117029, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3657668423221027}}
{"text": "/**\n *\n * @file core_cpltmg.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Ichitaro Yamazaki\n * @author Julien Herrmann\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated c Tue Jan  7 11:44:47 2014\n *\n **/\n\n#include <math.h>\n#include <lapacke.h>\n#include \"common.h\"\n\n#define pi (3.1415926535897932384626433832795028841971693992)\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex32_t\n *\n *  CORE_cpltmg initialize a tile of a random matrix from the MatLab\n *  gallery configured with the default parameters, and a few other\n *  specific matrices.\n *\n *******************************************************************************\n *\n * @param[in] mtxtype\n *          Possible types are: PlasmaMatrixRandom, PlasmaMatrixHadamard,\n *          PlasmaMatrixParter, PlasmaMatrixRis, PlasmaMatrixKms,\n *          PlasmaMatrixMoler, PlasmaMatrixCompan, PlasmaMatrixRiemann,\n *          PlasmaMatrixLehmer, PlasmaMatrixMinij, PlasmaMatrixDorr,\n *          PlasmaMatrixDemmel, PlasmaMatrixInvhess, PlasmaMatrixCauchy,\n *          PlasmaMatrixHilb, PlasmaMatrixLotkin, PlasmaMatrixOrthog,\n *          PlasmaMatrixWilkinson, PlasmaMatrixFoster, PlasmaMatrixWright,\n *          PlasmaMatrixLangou\n *          (See further in the code for more details)\n *\n * @param[in] M\n *         The number of rows of the tile A. M >= 0.\n *\n * @param[in] N\n *         The number of columns of the tile A. N >= 0.\n *\n * @param[in,out] A\n *         On entry, the M-by-N tile to be initialized.\n *         On exit, the tile initialized in the mtxtype format.\n *\n * @param[in] LDA\n *         The leading dimension of the tile A. LDA >= max(1,M).\n *\n * @param[in] gM\n *         The global number of rows of the full matrix, A is belonging to. gM >= (m0+M).\n *\n * @param[in] gN\n *         The global number of columns of the full matrix, A is belonging to. gN >= (n0+gN).\n *\n * @param[in] m0\n *         The index of the first row of tile A in the full matrix. m0 >= 0.\n *\n * @param[in] n0\n *         The index of the first column of tile A in the full matrix. n0 >= 0.\n *\n * @param[in] seed\n *         The seed used for random generation. Must be the same for\n *         all tiles initialized with this routine.\n *\n *******************************************************************************\n *\n * @return\n *         \\retval PLASMA_SUCCESS successful exit\n *         \\retval <0 if INFO = -k, the k-th argument had an illegal value\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_cpltmg = PCORE_cpltmg\n#define CORE_cpltmg PCORE_cpltmg\n#define CORE_cplrnt  PCORE_cplrnt\nvoid\nCORE_cplrnt( int M, int N, PLASMA_Complex32_t *A, int LDA,\n             int gM, int m0, int n0,\n             unsigned long long int seed );\n#endif\nint CORE_cpltmg( PLASMA_enum mtxtype,\n                  int M, int N, PLASMA_Complex32_t *A, int LDA,\n                  int gM, int gN, int m0, int n0,\n                  unsigned long long int seed )\n{\n    int i, j;\n\n    /* Check input arguments */\n    if (M < 0) {\n        coreblas_error(2, \"Illegal value of M\");\n        return -3;\n    }\n    if (N < 0) {\n        coreblas_error(3, \"Illegal value of N\");\n        return -3;\n    }\n    if ((LDA < max(1,M)) && (M > 0)) {\n        coreblas_error(5, \"Illegal value of LDA\");\n        return -5;\n    }\n    if (m0 < 0) {\n        coreblas_error(8, \"Illegal value of m0\");\n        return -8;\n    }\n    if (n0 < 0) {\n        coreblas_error(9, \"Illegal value of n0\");\n        return -9;\n    }\n    if (gM < m0+M) {\n        coreblas_error(6, \"Illegal value of gM\");\n        return -6;\n    }\n    if (gN < n0+N) {\n        coreblas_error(7, \"Illegal value of gN\");\n        return -7;\n    }\n\n    /* Quick return */\n    if ((M == 0) || (N == 0))\n        return PLASMA_SUCCESS;\n\n    switch( mtxtype ) {\n    case PlasmaMatrixRandom:\n    {\n        CORE_cplrnt( M, N, A, LDA, gM, m0, n0, seed );\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/hadamard.html\n     *\n     * Initialize the tile A to create the Hadamard matrix of order gN.\n     *\n     * Hadamard matrices are matrices of 1's and -1's whose columns are orthogonal,\n     *\n     *   H'*H = gN*I\n     *\n     *   where [gN gN]=size(H) and I = eye(gN,gN) ,.\n     *\n     *  They have applications in several different areas, including\n     *  combinatorics, signal processing, and numerical analysis.\n     *\n     *  An n-by-n Hadamard matrix with n > 2 exists only if rem(n,4) =\n     *  0. This function handles only the cases where n is a power of\n     *  2.\n     */\n    case PlasmaMatrixHadamard:\n    {\n        int tmp, nbone;\n\n        /* Extra parameters check */\n        if (gM != gN) {\n            coreblas_error(6, \"Illegal value of gM (Matrix must be square)\");\n            return -6;\n        }\n\n        tmp = gM;\n        while ( tmp > 1 ) {\n            if( tmp % 2 != 0 ) {\n                coreblas_error(6, \"Illegal value of gM (Matrix dimension must be a power of 2)\");\n                return -6;\n            }\n            tmp /= 2;\n        }\n\n        for (j=0; j<N; j++) {\n            for (i=0; i<M; i++) {\n                tmp = ((m0 + i) & (n0 + j));\n                nbone = 0;\n                while ( tmp != 0 )\n                {\n                    nbone += ( tmp & 1 );\n                    tmp >>= 1;\n                }\n                A[j*LDA+i] = (PLASMA_Complex32_t)(1. - 2. * ( nbone % 2 ));\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1000116\n     *\n     * Toeplitz matrix with singular values near pi.\n     * Returns the tile A, such that the elment of the matrix are 1/(i-j+0.5).\n     *\n     * C is a Cauchy matrix and a Toeplitz matrix. Most of the\n     * singular values of C are very close to pi.\n     *\n     */\n    case PlasmaMatrixParter:\n    {\n        PLASMA_Complex32_t tmp;\n\n        if (gM != gN) {\n            coreblas_error(6, \"Illegal value of gM (Matrix must be square for Parter)\");\n            return -6;\n        }\n\n        tmp = (PLASMA_Complex32_t)( .5 + m0 - n0 );\n        for (j=0; j<N; j++) {\n            for (i=0; i<M; i++) {\n                A[j*LDA+i] = (PLASMA_Complex32_t)1. / (PLASMA_Complex32_t)( tmp + i - j );\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1000243\n     *\n     * Symmetric Hankel matrix\n     * Returns a symmetric gN-by-gN Hankel matrix with elements.\n     *\n     *     A(i,j) = 0.5/(n-i-j+1.5)\n     *\n     * The eigenvalues of A cluster around \u03c0/2 and \u2013\u03c0/2. This matrix\n     * was invented by F.N. Ris.\n     *\n     */\n     case PlasmaMatrixRis:\n    {\n        PLASMA_Complex32_t tmp;\n\n        if (gM != gN) {\n            coreblas_error(6, \"Illegal value of gM (Matrix must be square for RIS)\");\n            return -6;\n        }\n\n        tmp = (PLASMA_Complex32_t)( gM - m0 - n0 - 0.5 );\n        for (j=0; j<N; j++) {\n            for (i=0; i<M; i++) {\n                A[j*LDA+i] = (PLASMA_Complex32_t).5 / (PLASMA_Complex32_t)( tmp - i - j );\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1000026\n     *\n     * Kac-Murdock-Szego Toeplitz matrix\n     *\n     * Returns the n-by-n Kac-Murdock-Szego Toeplitz matrix such that\n     * A(i,j) = rho^(abs(i-j)), for real rho.\n     *\n     * For complex rho, the same formula holds except that elements\n     * below the diagonal are conjfugated. rho defaults to 0.5.\n     *\n     * The KMS matrix A has these properties:\n     *     - An LDL' factorization with L inv(gallery('triw',n,-rho,1))',\n     *       and D(i,i) (1-abs(rho)^2)*eye(n), except D(1,1) = 1.\n     *     - Positive definite if and only if 0 < abs(rho) < 1.\n     *     - The inverse inv(A) is tridiagonal.Symmetric Hankel matrix\n     *\n     * In this function, rho is set to 0.5 and cannot be changed.\n     */\n    case PlasmaMatrixKms:\n    {\n        PLASMA_Complex32_t rho;\n\n        if (gM != gN) {\n            coreblas_error(6, \"Illegal value of gM (Matrix must be square for KMS)\");\n            return -6;\n        }\n\n        rho = .5;\n        for (j=0; j<N; j++) {\n            for (i=0; i<M; i++) {\n                A[j*LDA+i] = (PLASMA_Complex32_t)( cpowf( rho, fabs( (float)( m0 + i - n0 - j ) ) ) );\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1000074\n     *\n     * Symmetric positive definite matrix\n     *\n     * Returns the symmetric positive definite n-by-n matrix U'*U,\n     * where U = gallery('triw',n,alpha).\n     *\n     * For the default alpha = -1, A(i,j) = min(i,j)-2, and A(i,i) =\n     * i. One of the eigenvalues of A is small.\n     *\n     */\n    case PlasmaMatrixMoler:\n    {\n        int ii, jj;\n        for (j=0,jj=n0; j<N; j++,jj++) {\n            for (i=0,ii=m0; i<M; i++,ii++) {\n                if ( ii == jj ) {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)( ii + 1. );\n                } else {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)( min( ii, jj ) - 1. );\n                }\n            }\n        }\n    }\n    break;\n\n    /*\n     *  See http://www.mathworks.fr/fr/help/matlab/ref/compan.html\n     *\n     *  Companion matrix\n     *\n     *  A = compan(u) returns the corresponding companion matrix whose first row is\n     *  -u(2:n)/u(1), where u is a vector of polynomial coefficients. The\n     *  eigenvalues of compan(u) are the roots of the polynomial.\n     *\n     */\n    case PlasmaMatrixCompan:\n    {\n        int jj;\n\n        LAPACKE_claset_work(LAPACK_COL_MAJOR, 'A', M, N, 0., 0., A, LDA);\n\n        /* First row */\n        if ( m0 == 0 ) {\n            PLASMA_Complex32_t v0;\n            /* Get V0 */\n            CORE_cplrnt( 1, 1, &v0, 1, 1, 1, 0, seed );\n            v0 = 1. / v0 ;\n\n            /* Initialize random vector */\n            CORE_cplrnt( 1, N, A, LDA, 1, 1, n0, seed );\n            cblas_cscal( N, CBLAS_SADDR(v0), A, LDA);\n\n            /* Restore A(0,0) */\n            if ( n0 == 0 )\n                A[0] = 0.;\n        }\n\n        /* Sub diagonal*/\n        for (j=0,jj=n0; j<N; j++,jj++)\n        {\n            i = jj + 1 - m0;\n            if ( ( i > 0 ) && (i < M) )\n            {\n                A[j*LDA+i] = 1.;\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1000232\n     *\n     * Matrix associated with the Riemann hypothesis\n     *\n     * Returns an n-by-n matrix for which the Riemann hypothesis is\n     * true if and only if for every eps > 0.\n     *\n     * The Riemann matrix is defined by:\n     *\n     *    A = B(2:n+1,2:n+1)\n     *\n     *    where B(i,j) = i-1 if i divides j, and B(i,j) = -1 otherwise.\n     *\n     * The Riemann matrix has these properties:\n     *     - Each eigenvalue e(i) satisfies abs(e(i)) <= m-1/m, where m = n+1.\n     *     - i <= e(i) <= i+1 with at most m-sqrt(m) exceptions.\n     *     - All integers in the interval (m/3, m/2] are eigenvalues.\n     *\n     */\n    case PlasmaMatrixRiemann:\n    {\n        int ii, jj;\n        for (j=0,jj=n0+2; j<N; j++,jj++) {\n            for (i=0,ii=m0+2; i<M; i++,ii++) {\n                if ( jj%ii == 0 ) {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)( ii - 1. );\n                } else {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)( -1. );\n                }\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1000049\n     *\n     * Symmetric positive definite matrix\n     *\n     * Returns the symmetric positive definite n-by-n matrix such that\n     * A(i,j) = i/j for j >= i.\n     *\n     * The Lehmer matrix A has these properties:\n     *     - A is totally nonnegative.\n     *     - The inverse inv(A) is tridiagonal and explicitly known.\n     *     - The order n <= cond(A) <= 4*n*n.Matrix associated with the\n     *       Riemann hypothesis\n     *\n     */\n     case PlasmaMatrixLehmer:\n    {\n        int ii, jj;\n        for (j=0,jj=n0+1; j<N; j++,jj++) {\n            for (i=0,ii=m0+1; i<M; i++,ii++) {\n                if ( jj >= ii ) {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)( ii ) / (PLASMA_Complex32_t)( jj );\n                } else {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)( jj ) / (PLASMA_Complex32_t)( ii );\n                }\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1000066\n     *\n     * Symmetric positive definite matrix\n     *\n     * Returns the n-by-n symmetric positive definite matrix with\n     * A(i,j) = min(i,j).\n     *\n     * The minij matrix has these properties:\n     *     - The inverse inv(A) is tridiagonal and equal to -1 times the\n     *       second difference matrix, except its (n,n) element is 1.\n     *     - Givens' matrix, 2*A-ones(size(A)), has tridiagonal inverse\n     *       and eigenvalues 0.5*sec((2*r-1)*pi/(4*n))^2, where r=1:n.\n     *     - (n+1)*ones(size(A))-A has elements that are max(i,j) and a\n     *       tridiagonal inverse.\n     *\n     */\n    case PlasmaMatrixMinij:\n    {\n        int ii, jj;\n        for (j=0,jj=n0+1; j<N; j++,jj++) {\n            for (i=0,ii=m0+1; i<M; i++,ii++) {\n                A[j*LDA+i] = (PLASMA_Complex32_t) min( ii, jj );\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-999936\n     *\n     * Diagonally dominant, ill-conditioned, tridiagonal matrix\n     *\n     * Returns the n-by-n matrix, row diagonally dominant, tridiagonal\n     * matrix that is ill-conditioned for small nonnegative values of\n     * theta. The default value of theta is 0.01. The Dorr matrix\n     * itself is the same as gallery('tridiag',c,d,e).\n     *\n     */\n    case PlasmaMatrixDorr:\n    {\n        PLASMA_Complex32_t theta = 0.01;\n        PLASMA_Complex32_t h     = 1. / ( gN + 1. );\n        PLASMA_Complex32_t term  = theta / ( h * h );\n        int jj;\n        int half = (gN+1) / 2;\n\n        LAPACKE_claset_work(LAPACK_COL_MAJOR, 'A', M, N, 0., 0., A, LDA);\n\n        /* First half */\n        for (j=0, jj=n0; (j<N) && (jj<half); j++, jj++) {\n            i = jj - m0;\n            if ( ( i < -1 ) || (i > M) )\n                continue;\n\n            /* Over the diagonal */\n            if (i > 0)\n                A[j*LDA + i-1] = - term - (0.5 - jj*h)/h;\n\n            /* Diagonal */\n            if ( i >= M )\n                return PLASMA_SUCCESS;\n\n            if ( i >=0 )\n                A[j*LDA + i] = 2. * term + (0.5 - (jj+1) * h) / h;\n\n            /* Below the diagonal */\n            if (i+1 < M) {\n                if (jj+1 == half)\n                    A[j*LDA + i+1] = - term + (0.5 - (jj+2)*h)/h;\n                else\n                    A[j*LDA + i+1] = - term;\n            }\n        }\n\n        /* Second half */\n        for (; j<N; j++,jj++) {\n            i = jj - m0;\n            if ( ( i < -1 ) || (i > M))\n                continue;\n\n            if (i > 0) {\n                if (jj == half)\n                    A[j*LDA + i-1] = - term - (0.5 - jj*h)/h;\n                else\n                    A[j*LDA + i-1] = - term;\n            }\n\n            if ((i >=0) && (i < M))\n                A[j*LDA + i] = 2. * term - (0.5 - (jj+1)*h)/h;\n\n            if (i+1 < M)\n                A[j*LDA + i+1] = - term + (0.5 - (jj+2)*h)/h;\n        }\n    }\n    break;\n\n    /*\n     * See [1] J. Demmel, Applied Numerical Linear Algebra, SIAM,\n     *         Philadelphia, 1997\n     *\n     * Returns a matrix defined by:\n     *    A = D * ( I + 1e-7* rand(n)), where D = diag(10^{14*(0:n-1)/n})\n     *\n     */\n    case PlasmaMatrixDemmel:\n    {\n        PLASMA_Complex32_t dii;\n        int ii, jj;\n\n        /* Randomize the matrix */\n        CORE_cplrnt( M, N, A, LDA, gM, m0, n0, seed );\n\n\n        for (j=0,jj=n0; j<N; j++,jj++) {\n            for (i=0,ii=m0; i<M; i++,ii++) {\n                dii = cpowf( 10. , 14. * ii / gM );\n                A[j*LDA+i] *= dii * ( (jj == ii) ? 1. : 1.e-7 );\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1000000\n     *\n     * Inverse of an upper Hessenberg matrix\n     *\n     * A = gallery('invhess',x,y), where x is a length n vector and y\n     * is a length n-1 vector, returns the matrix whose lower triangle\n     * agrees with that of ones(n,1)*x' and whose strict upper\n     * triangle agrees with that of [1 y]*ones(1,n).\n     *\n     * The matrix is nonsingular if x(1) ~= 0 and x(i+1) ~= y(i) for\n     * all i, and its inverse is an upper Hessenberg matrix. Argument\n     * y defaults to -x(1:n-1).\n     *\n     * If x is a scalar, invhess(x) is the same as invhess(1:x).\n     *\n     * Here: gallery('invhess', gM)\n     */\n    case PlasmaMatrixInvhess:\n    {\n        int ii, jj;\n        for (j=0,jj=n0+1; j<N; j++,jj++) {\n            for (i=0,ii=m0+1; i<M; i++,ii++) {\n                if ( jj <= ii ) {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)( jj );\n                } else {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)( -ii );\n                }\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1019317\n     *\n     * Cauchy matrix\n     *\n     * Returns an n-by-n matrix C such that, C(i,j) = 1/(i + j).\n     *\n     */\n    case PlasmaMatrixCauchy:\n    {\n        int ii, jj;\n        for (j=0,jj=n0+1; j<N; j++,jj++) {\n            for (i=0,ii=m0+1; i<M; i++,ii++) {\n                A[j*LDA+i] = (PLASMA_Complex32_t)( 1. ) / (PLASMA_Complex32_t)( ii+jj );\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/hilb.html\n     *\n     * Hilbert Matrix\n     *\n     * The Hilbert matrix is a notable example of a poorly conditioned\n     * matrix. The elements of the Hilbert matrices are:\n     *   H(i,j) = 1/(i * + j \u2013 1).\n     *\n     */\n    case PlasmaMatrixHilb:\n    {\n        PLASMA_Complex32_t tmp = (PLASMA_Complex32_t)( m0 + n0 + 1. );\n        for (j=0; j<N; j++) {\n            for (i=0; i<M; i++) {\n                A[j*LDA+i] = (PLASMA_Complex32_t)1. / (PLASMA_Complex32_t)( tmp + i + j );\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1000062\n     *\n     * Lotkin matrix\n     *\n     * Returns the Hilbert matrix with its first row altered to all\n     * ones. The Lotkin matrix A is nonsymmetric, ill-conditioned, and\n     * has many negative eigenvalues of small magnitude. Its inverse\n     * has integer entries and is known explicitly.\n     *\n     */\n    case PlasmaMatrixLotkin:\n    {\n        PLASMA_Complex32_t tmp = (PLASMA_Complex32_t)( m0 + n0 + 1. );\n        if (m0 == 0) {\n            for (j=0; j<N; j++) {\n                A[j*LDA] = (PLASMA_Complex32_t)1.;\n                for (i=1; i<M; i++) {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)1. / (PLASMA_Complex32_t)( tmp + i + j );\n                }\n            }\n        } else {\n            for (j=0; j<N; j++) {\n                for (i=0; i<M; i++) {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)1. / (PLASMA_Complex32_t)( tmp + i + j );\n                }\n            }\n        }\n    }\n    break;\n\n    /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-1000083\n     *\n     * Orthogonal and nearly orthogonal matrices\n     *\n     * Returns the matrix Q of order n, such that:\n     *    Q(i,j) = sqrt(2/(n+1)) * sin(i*j*pi/(n+1))\n     *\n     * Symmetric eigenvector matrix for second difference matrix.\n     *\n     */\n    case PlasmaMatrixOrthog: /* Default: k=1 */\n    {\n        PLASMA_Complex32_t sqrtn = (PLASMA_Complex32_t) sqrt( 2. / (gN+1.) );\n        float scale = pi / (float)(gN+1.);\n\n        int ii, jj;\n        for (j=0,jj=n0+1; j<N; j++,jj++) {\n            for (i=0,ii=m0+1; i<M; i++,ii++) {\n                A[j*LDA+i] = sqrtn * (PLASMA_Complex32_t) sin( (float)ii * (float)jj * scale );\n            }\n        }\n    }\n    break;\n\n     /*\n     * See http://www.mathworks.fr/fr/help/matlab/ref/wilkinson.html\n     *\n     * Wilkinson's eigenvalue test matrix\n     *\n     * Returns one of J. H. Wilkinson's eigenvalue test matrices. It\n     * is a symmetric, tridiagonal matrix with pairs of nearly, but\n     * not exactly, equal eigenvalues.\n     *\n     */\n   case PlasmaMatrixWilkinson:\n    {\n        if (gM != gN) {\n            coreblas_error(6, \"Illegal value of gM (Matrix must be square for Wilkinson)\");\n            return -6;\n        }\n\n        int ii, jj;\n        for (j=0,jj=n0; j<N; j++,jj++) {\n            for (i=0,ii=m0; i<M; i++,ii++) {\n                if (ii == jj) {\n                    PLASMA_Complex32_t tmp = (PLASMA_Complex32_t)(( (gN - 1 - ii) < ii ) ? gN - 1 - ii : ii );\n                     A[j*LDA+i] = (PLASMA_Complex32_t)(gN - 2. * tmp - 1.) / 2.;\n                }\n                else if ( (ii == jj+1) || (ii == jj-1) ) {\n                     A[j*LDA+i] = (PLASMA_Complex32_t)1.;\n                }\n                else {\n                     A[j*LDA+i] = (PLASMA_Complex32_t)0.;\n                }\n           }\n       }\n    }\n    break;\n\n    /*\n     * See [1] L. V. Foster, Gaussian Elimination with Partial\n     *         Pivoting Can Fail in Practice, SIAM J. Matrix\n     *         Anal. Appl., 15 (1994), pp. 1354-1362.\n     *\n     *     [2] L. V. Foster, The growth factor and efficiency of\n     *         Gaussian elimination with rook pivoting,\n     *         J. Comput. Appl. Math., 86 (1997), pp. 177-194\n     *\n     * A pathological case for LU with gaussian elimination.\n     *\n     */\n    case PlasmaMatrixFoster: /* Default: k=h=c=1 */\n    {\n        float k=1., h=1., c=1.;\n\n        int ii, jj;\n        for (j=0,jj=n0; j<N; j++,jj++) {\n            for (i=0,ii=m0; i<M; i++,ii++) {\n\n                if (ii == jj) {\n                    if (jj == 0)\n                        A[j*LDA+i] = (PLASMA_Complex32_t)1.;\n                    else if (jj == gN-1)\n                        A[j*LDA+i] = (PLASMA_Complex32_t)(1. - (1. / c) - (k*h)/2. );\n                    else\n                        A[j*LDA+i] = (PLASMA_Complex32_t)(1. - (k*h)/2. );\n                }\n                else if (jj == 0) {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)(-k*h/2.);\n                }\n                else if (jj == gN-1) {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)(-1./c);\n                }\n                else if (ii > jj) {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)(-k*h);\n                }\n                else {\n                    A[j*LDA+i] = (PLASMA_Complex32_t)0.;\n                }\n            }\n        }\n    }\n    break;\n\n    /*\n     * See [3] S. J. Wright, A collection of problems for which\n     *         Gaussian elimination with partial pivoting is unstable,\n     *         SIAM J. SCI. STATIST. COMPUT., 14 (1993), pp. 231-238.\n     *\n     * A pathological case for LU with gaussian elimination.\n     *\n     */\n    /*\n     * Default: h=0.01, M=[-10 -19, 19 30]. Then,\n     *   exp(h*M)=[0.9048 0.8270, 1.2092 1.3499]\n     */\n    case PlasmaMatrixWright:\n    {\n        int ii, jj;\n        for (j=0,jj=n0; j<N; j++,jj++) {\n            for (i=0,ii=m0; i<M; i++,ii++) {\n\n                if (ii == jj)\n                    A[j*LDA+i] = (PLASMA_Complex32_t)1.;\n                else if ((ii == jj + 2) && (jj % 2 == 0))\n                    A[j*LDA+i] = (PLASMA_Complex32_t)(-0.9048);\n                else if ((ii == jj + 3) && (jj % 2 == 0))\n                    A[j*LDA+i] = (PLASMA_Complex32_t)(-1.2092);\n                else if ((ii == jj + 2) && (jj % 2 == 1))\n                    A[j*LDA+i] = (PLASMA_Complex32_t)(-0.8270);\n                else if ((ii == jj + 3) && (jj % 2 == 1))\n                    A[j*LDA+i] = (PLASMA_Complex32_t)(-1.3499);\n                else if ((jj == gM-2) && (ii == 0))\n                    A[j*LDA+i] = (PLASMA_Complex32_t)1.;\n                else if ((jj == gM-1) && (ii == 1))\n                    A[j*LDA+i] = (PLASMA_Complex32_t)1.;\n                else\n                    A[j*LDA+i] = (PLASMA_Complex32_t)0.;\n            }\n        }\n    }\n    break;\n\n    /*\n     * Generates a pathological case for LU with gaussian elimination.\n     *\n     * Returns a random matrix on which, the columns from N/4 to N/2\n     * are scaled down by eps.\n     * These matrices fails on LU with partial pivoting, but Hybrid\n     * LU-QR algorithms manage to recover the scaled down columns.\n     *\n     */\n    case PlasmaMatrixLangou:\n    {\n        PLASMA_Complex32_t eps = (PLASMA_Complex32_t) LAPACKE_slamch_work( 'e' );\n        int ii, jj, mm, minMN;\n        int firstcol, lastcol;\n\n         /* Create random tile */\n         CORE_cplrnt( M, N, A, LDA, gM, m0, n0, seed );\n\n         /* Scale down the columns gN/4 to gN/2 below the diagonal */\n         minMN = min( gM, gN );\n         firstcol = minMN / 4;\n         lastcol  = minMN / 2;\n\n         if ( (m0 >= n0) && ((n0+N) >= firstcol ) && (n0 < lastcol) ) {\n\n             jj = max( n0, firstcol );\n             j = jj - n0;\n\n             for (; j<N && jj < lastcol; j++,jj++) {\n\n                 ii = max( m0, jj );\n                 i  = ii - m0;\n                 mm = M - i;\n                 cblas_cscal( mm, CBLAS_SADDR(eps), A + j*LDA + i, 1);\n             }\n         }\n    }\n    break;\n\n    default:\n        coreblas_error(1, \"Illegal value of mtxtype\");\n        return -1;\n    }\n\n    return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "e9021a081235b88f13f23169119c023c6c09a4f7", "size": 25590, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_cpltmg.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_cpltmg.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_cpltmg.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.5369928401, "max_line_length": 110, "alphanum_fraction": 0.4742868308, "num_tokens": 7819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3656996158242104}}
{"text": "#ifndef CONSTITUTIVE_DF_H\n#define CONSTITUTIVE_DF_H\n\n#include <algorithm>\n#include <numeric>\n#include \"SIMD_BDB_Integrator.h\"\n\n#ifdef HAS_MKL\n#include <mkl.h>\n#else\n#include <cblas.h>\n#endif\n\n\ninline void GetTotalTraction_(Real *TotalTraction, const Real *CauchyStressTensor, int ndim) {\n    if (ndim==3) {\n        TotalTraction[0] = CauchyStressTensor[0];\n        TotalTraction[1] = CauchyStressTensor[4];\n        TotalTraction[2] = CauchyStressTensor[8];\n        TotalTraction[3] = CauchyStressTensor[1];\n        TotalTraction[4] = CauchyStressTensor[2];\n        TotalTraction[5] = CauchyStressTensor[5];\n    }\n    else if (ndim == 2) {\n        TotalTraction[0] = CauchyStressTensor[0];\n        TotalTraction[1] = CauchyStressTensor[3];\n        TotalTraction[2] = CauchyStressTensor[1];\n    }\n}\n\n\ninline void FillConstitutiveB_(Real *B, const Real* SpatialGradient,\n                     int ndim, int nvar, int rows, int cols) {\n    int i = 0;\n\n    if (ndim == 3) {\n\n        for (; i<rows; ++i) {\n\n            // Store in registers\n            const Real a0 = SpatialGradient[i*ndim];\n            const Real a1 = SpatialGradient[i*ndim+1];\n            const Real a2 = SpatialGradient[i*ndim+2];\n\n            // MECHANICAL TERMS\n            B[i*cols*nvar]              = a0;\n            B[i*cols*nvar+cols+1]       = a1;\n            B[i*cols*nvar+2*(cols+1)]   = a2;\n\n            B[i*cols*nvar+cols+5]       = a2;\n            B[i*cols*nvar+2*cols+5]     = a1;\n\n            B[i*cols*nvar+4]            = a2;\n            B[i*cols*nvar+2*cols+4]     = a0;\n\n            B[i*cols*nvar+3]            = a1;\n            B[i*cols*nvar+cols+3]       = a0;\n        }\n    }\n\n    else if (ndim == 2) {\n\n        for (; i<rows; ++i) {\n\n            // Store in registers\n            const Real a0 = SpatialGradient[i*ndim];\n            const Real a1 = SpatialGradient[i*ndim+1];\n\n            // MECHANICAL TERMS\n            B[i*cols*nvar]              = a0;\n            B[i*cols*nvar+cols+1]       = a1;\n\n            B[i*cols*nvar+2]            = a1;\n            B[i*cols*nvar+cols+2]       = a0;\n        }\n    }\n}\n\n\n\n\n\ninline void _ConstitutiveStiffnessIntegrandDF_Filler_(\n    Real *stiffness,\n    Real *traction,\n    const Real* SpatialGradient,\n    const Real* CauchyStressTensor,\n    const Real* H_Voigt,\n    const Real* detJ,\n    int ngauss,\n    int noderpelem,\n    int ndim,\n    int nvar,\n    int H_VoigtSize,\n    int requires_geometry_update) {\n\n    int local_size = nvar*noderpelem;\n\n    Real *t;\n    if (ndim==3) { t = allocate<Real>(6);}\n    else if (ndim==2) { t =  allocate<Real>(3);}\n\n    Real *B = allocate<Real>(H_VoigtSize*local_size);\n    Real *HBT = allocate<Real>(H_VoigtSize*local_size);\n    Real *BDB_1 = allocate<Real>(local_size*local_size);\n\n    std::fill(B,B+H_VoigtSize*local_size,0.);\n\n    for (int igauss = 0; igauss < ngauss; ++igauss) {\n\n        FillConstitutiveB_(B,&SpatialGradient[igauss*ndim*noderpelem],ndim,nvar,noderpelem,H_VoigtSize);\n        // if (ndim == 3) {\n            cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans,\n                H_VoigtSize, local_size, H_VoigtSize, 1.0, &H_Voigt[igauss*H_VoigtSize*H_VoigtSize], H_VoigtSize, B, H_VoigtSize, 0.0, HBT, local_size);\n\n            cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n                local_size, local_size, H_VoigtSize, 1.0, B, H_VoigtSize, HBT, local_size, 0.0, BDB_1, local_size);\n        // }\n        // else\n        // {\n        //     _SIMD_BDB_Integrator_DF_2D_(\n        //         HBT,\n        //         BDB_1,\n        //         &SpatialGradient[igauss*ndim*noderpelem],\n        //         &H_Voigt[igauss*H_VoigtSize*H_VoigtSize],\n        //         noderpelem\n        //         );\n        // }\n\n        // Multiply stiffness with detJ\n        const Real detJ_igauss = detJ[igauss];\n        for (int i=0; i<local_size*local_size; ++i) {\n            stiffness[i] += BDB_1[i]*detJ_igauss;\n        }\n\n        if (requires_geometry_update==1) {\n            // Compute tractions\n            GetTotalTraction_(t, &CauchyStressTensor[igauss*ndim*ndim], ndim);\n\n            // Multiply B with traction - for loop is okay\n            for (int i=0; i<local_size; ++i) {\n                Real tmp = 0;\n                for (int j=0; j<H_VoigtSize; ++j) {\n                    tmp += B[i*H_VoigtSize+j]*t[j];\n                }\n                // local_traction[i] = tmp;\n                traction[i] += tmp*detJ_igauss;\n            }\n        }\n    }\n\n    deallocate(t);\n    deallocate(B);\n    deallocate(HBT);\n    deallocate(BDB_1);\n}\n\n#endif", "meta": {"hexsha": "b52d830ff2fbe337ad42165d66ec1dfe9d75b736", "size": 4543, "ext": "h", "lang": "C", "max_stars_repo_path": "Florence/VariationalPrinciple/_ConstitutiveStiffness_/_ConstitutiveStiffnessDF_.h", "max_stars_repo_name": "jdlaubrie/florence", "max_stars_repo_head_hexsha": "830dca4a34be00d6e53cbec3007c10d438b27f57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65.0, "max_stars_repo_stars_event_min_datetime": "2017-08-04T10:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:45:09.000Z", "max_issues_repo_path": "Florence/VariationalPrinciple/_ConstitutiveStiffness_/_ConstitutiveStiffnessDF_.h", "max_issues_repo_name": "jdlaubrie/florence", "max_issues_repo_head_hexsha": "830dca4a34be00d6e53cbec3007c10d438b27f57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-06-03T02:29:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T02:30:22.000Z", "max_forks_repo_path": "Florence/VariationalPrinciple/_ConstitutiveStiffness_/_ConstitutiveStiffnessDF_.h", "max_forks_repo_name": "jdlaubrie/florence", "max_forks_repo_head_hexsha": "830dca4a34be00d6e53cbec3007c10d438b27f57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-05-30T09:44:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T08:06:51.000Z", "avg_line_length": 28.753164557, "max_line_length": 152, "alphanum_fraction": 0.5443539511, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.36558438600827536}}
{"text": "/* specfunc/coupling.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include \"gsl_sf_gamma.h\"\n#include \"gsl_sf_coupling.h\"\n\n#include \"error.h\"\n\ninline\nstatic\nint locMax3(const int a, const int b, const int c)\n{\n  int d = GSL_MAX(a, b);\n  return GSL_MAX(d, c);\n}\n\ninline\nstatic\nint locMin3(const int a, const int b, const int c)\n{\n  int d = GSL_MIN(a, b);\n  return GSL_MIN(d, c);\n}\n\ninline\nstatic\nint locMin5(const int a, const int b, const int c, const int d, const int e)\n{\n  int f = GSL_MIN(a, b);\n  int g = GSL_MIN(c, d);\n  int h = GSL_MIN(f, g);\n  return GSL_MIN(e, h);\n}\n\n\n/* See: [Thompson, Atlas for Computing Mathematical Functions] */\n\nstatic\nint\ndelta(int ta, int tb, int tc, gsl_sf_result * d)\n{\n  gsl_sf_result f1, f2, f3, f4;\n  int status = 0;\n  status += gsl_sf_fact_e((ta + tb - tc)/2, &f1);\n  status += gsl_sf_fact_e((ta + tc - tb)/2, &f2);\n  status += gsl_sf_fact_e((tb + tc - ta)/2, &f3);\n  status += gsl_sf_fact_e((ta + tb + tc)/2 + 1, &f4);\n  if(status != 0) {\n    OVERFLOW_ERROR(d);\n  }\n  d->val = f1.val * f2.val * f3.val / f4.val;\n  d->err = 4.0 * GSL_DBL_EPSILON * fabs(d->val);\n  return GSL_SUCCESS;\n}\n\n\nstatic\nint\ntriangle_selection_fails(int two_ja, int two_jb, int two_jc)\n{\n  return ((two_jb < abs(two_ja - two_jc)) || (two_jb > two_ja + two_jc));\n}\n\n\nstatic\nint\nm_selection_fails(int two_ja, int two_jb, int two_jc,\n                  int two_ma, int two_mb, int two_mc)\n{\n  return (   abs(two_ma) > two_ja \n          || abs(two_mb) > two_jb\n\t  || abs(two_mc) > two_jc\n\t  || GSL_IS_ODD(two_ja + two_ma)\n\t  || GSL_IS_ODD(two_jb + two_mb)\n\t  || GSL_IS_ODD(two_jc + two_mc)\n          || (two_ma + two_mb + two_mc) != 0\n\t  );\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_coupling_3j_e(int two_ja, int two_jb, int two_jc,\n                        int two_ma, int two_mb, int two_mc,\n\t\t\tgsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(two_ja < 0 || two_jb < 0 || two_jc < 0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(   triangle_selection_fails(two_ja, two_jb, two_jc)\n          || m_selection_fails(two_ja, two_jb, two_jc, two_ma, two_mb, two_mc)\n     ) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    gsl_sf_result n1_a, n1_b, n3_a, n3_b;\n    gsl_sf_result d1_a, d1_b, d2_a, d2_b, d3_a, d3_b;\n    gsl_sf_result n1, n2, n3;\n    gsl_sf_result d1, d2, d3;\n    double norm;\n    double sign = (GSL_IS_ODD((two_ja - two_jb - two_mc)/2) ? -1.0 : 1.0);\n    int tk, tkmin, tkmax;\n    double sum_pos = 0.0;\n    double sum_neg = 0.0;\n    double phase;\n    int status = 0;\n    status += gsl_sf_fact_e((two_jc + two_ja - two_jb)/2, &n1_a);\n    status += gsl_sf_fact_e((two_jc - two_ja + two_jb)/2, &n1_b);\n    status += gsl_sf_fact_e((two_ja + two_jb - two_jc)/2, &n2);\n    status += gsl_sf_fact_e((two_jc - two_mc)/2, &n3_a);\n    status += gsl_sf_fact_e((two_jc + two_mc)/2, &n3_b);\n    status += gsl_sf_fact_e((two_ja + two_jb + two_jc)/2 + 1, &d1);\n    status += gsl_sf_fact_e((two_ja - two_ma)/2, &d2_a);\n    status += gsl_sf_fact_e((two_ja + two_ma)/2, &d2_b);\n    status += gsl_sf_fact_e((two_jb - two_mb)/2, &d3_a);\n    status += gsl_sf_fact_e((two_jb + two_mb)/2, &d3_b);\n\n    if(status != 0) {\n      OVERFLOW_ERROR(result);\n    }\n\n    n1.val = n1_a.val * n1_b.val;\n    n3.val = n3_a.val * n3_b.val;\n    d2.val = d2_a.val * d2_b.val;\n    d3.val = d3_a.val * d3_b.val;\n\n    norm = sign * sqrt(n1.val*n2.val*n3.val)/sqrt(d1.val*d2.val*d3.val);\n\n    tkmin = GSL_MAX(0, two_jb - two_ja - two_mc);\n    tkmax = GSL_MIN(two_jc - two_ja + two_jb, two_jc - two_mc);\n    \n    phase = GSL_IS_ODD((tkmin + two_jb + two_mb)/2) ? -1.0 : 1.0;\n\n    for(tk=tkmin; tk<=tkmax; tk += 2) {\n      double term;\n\n      status = 0;\n      status += gsl_sf_fact_e((two_jb + two_jc + two_ma - tk)/2, &n1);\n      status += gsl_sf_fact_e((two_ja - two_ma + tk)/2, &n2);\n      status += gsl_sf_fact_e(tk/2, &d1_a);\n      status += gsl_sf_fact_e((two_jc - two_ja + two_jb - tk)/2, &d1_b);\n      status += gsl_sf_fact_e((two_jc - two_mc - tk)/2, &d2);\n      status += gsl_sf_fact_e((two_ja - two_jb + two_mc + tk)/2, &d3);\n\n      if(status != 0) {\n        OVERFLOW_ERROR(result);\n      }\n\n      d1.val = d1_a.val * d1_b.val;\n\n      term = phase * n1.val * n2.val / (d1.val * d2.val * d3.val);\n      phase = -phase;\n\n      if(norm*term >= 0.0) {\n        sum_pos += norm*term;\n      }\n      else {\n        sum_neg -= norm*term;\n      }\n    }\n\n    result->val  = sum_pos - sum_neg;\n    result->err  = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);\n    result->err += 2.0 * GSL_DBL_EPSILON * (tkmax - tkmin) * fabs(result->val);\n\n    return GSL_SUCCESS;\n  }\n}\n\n\nint\ngsl_sf_coupling_6j_e(int two_ja, int two_jb, int two_jc,\n                        int two_jd, int two_je, int two_jf,\n\t\t\tgsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(   two_ja < 0 || two_jb < 0 || two_jc < 0\n     || two_jd < 0 || two_je < 0 || two_je < 0\n     ) {\n    DOMAIN_ERROR(result);\n  }\n  else if(   triangle_selection_fails(two_ja, two_jb, two_je)\n          || triangle_selection_fails(two_ja, two_jc, two_jf)\n          || triangle_selection_fails(two_jb, two_jd, two_jf)\n          || triangle_selection_fails(two_jc, two_jd, two_je)\n     ) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    gsl_sf_result n1;\n    gsl_sf_result d1, d2, d3, d4, d5, d6;\n    double norm;\n    int tk, tkmin, tkmax;\n    double phase;\n    double sum_pos = 0.0;\n    double sum_neg = 0.0;\n    double sumsq_err = 0.0;\n    int status = 0;\n    status += delta(two_ja, two_jb, two_je, &d1);\n    status += delta(two_ja, two_jc, two_jf, &d2);\n    status += delta(two_jb, two_jd, two_jf, &d3);\n    status += delta(two_jc, two_jd, two_je, &d4);\n    if(status != GSL_SUCCESS) {\n      OVERFLOW_ERROR(result);\n    }\n    norm = sqrt(d1.val) * sqrt(d2.val) * sqrt(d3.val) * sqrt(d4.val);\n    \n    tkmin = locMax3(0,\n                   two_ja + two_jd - two_je - two_jf,\n                   two_jb + two_jc - two_je - two_jf);\n\n    tkmax = locMin5(two_ja + two_jb + two_jc + two_jd + 2,\n                    two_ja + two_jb - two_je,\n\t\t    two_jc + two_jd - two_je,\n\t\t    two_ja + two_jc - two_jf,\n\t\t    two_jb + two_jd - two_jf);\n\n    phase = GSL_IS_ODD((two_ja + two_jb + two_jc + two_jd + tkmin)/2)\n            ? -1.0\n\t    :  1.0;\n\n    for(tk=tkmin; tk<=tkmax; tk += 2) {\n      double term;\n      double term_err;\n      gsl_sf_result den_1, den_2;\n      gsl_sf_result d1_a, d1_b;\n      status = 0;\n      \n      status += gsl_sf_fact_e((two_ja + two_jb + two_jc + two_jd - tk)/2 + 1, &n1);\n      status += gsl_sf_fact_e(tk/2, &d1_a);\n      status += gsl_sf_fact_e((two_je + two_jf - two_ja - two_jd + tk)/2, &d1_b);\n      status += gsl_sf_fact_e((two_je + two_jf - two_jb - two_jc + tk)/2, &d2);\n      status += gsl_sf_fact_e((two_ja + two_jb - two_je - tk)/2, &d3);\n      status += gsl_sf_fact_e((two_jc + two_jd - two_je - tk)/2, &d4);\n      status += gsl_sf_fact_e((two_ja + two_jc - two_jf - tk)/2, &d5);\n      status += gsl_sf_fact_e((two_jb + two_jd - two_jf - tk)/2, &d6);\n      \n      if(status != GSL_SUCCESS) {\n        OVERFLOW_ERROR(result);\n      }\n\n      d1.val = d1_a.val * d1_b.val;\n      d1.err = d1_a.err * fabs(d1_b.val) + fabs(d1_a.val) * d1_b.err;\n\n      den_1.val  = d1.val*d2.val*d3.val;\n      den_1.err  = d1.err * fabs(d2.val*d3.val);\n      den_1.err += d2.err * fabs(d1.val*d3.val);\n      den_1.err += d3.err * fabs(d1.val*d2.val);\n\n      den_2.val  = d4.val*d5.val*d6.val;\n      den_2.err  = d4.err * fabs(d5.val*d6.val);\n      den_2.err += d5.err * fabs(d4.val*d6.val);\n      den_2.err += d6.err * fabs(d4.val*d5.val);\n\n      term  = phase * n1.val / den_1.val / den_2.val;\n      phase = -phase;\n      term_err  = n1.err / fabs(den_1.val) / fabs(den_2.val);\n      term_err += fabs(term / den_1.val) * den_1.err;\n      term_err += fabs(term / den_2.val) * den_2.err;\n\n      if(term >= 0.0) {\n        sum_pos += norm*term;\n      }\n      else {\n        sum_neg -= norm*term;\n      }\n\n      sumsq_err += norm*norm * term_err*term_err;\n    }\n\n    result->val  = sum_pos - sum_neg;\n    result->err  = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);\n    result->err += sqrt(sumsq_err / (0.5*(tkmax-tkmin)+1.0));\n    result->err += 2.0 * GSL_DBL_EPSILON * (tkmax - tkmin + 2.0) * fabs(result->val);\n\n    return GSL_SUCCESS;\n  }\n}\n\n\nint\ngsl_sf_coupling_9j_e(int two_ja, int two_jb, int two_jc,\n                        int two_jd, int two_je, int two_jf,\n\t\t\tint two_jg, int two_jh, int two_ji,\n\t\t\tgsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(   two_ja < 0 || two_jb < 0 || two_jc < 0\n     || two_jd < 0 || two_je < 0 || two_jf < 0\n     || two_jg < 0 || two_jh < 0 || two_ji < 0\n     ) {\n    DOMAIN_ERROR(result);\n  }\n  else if(   triangle_selection_fails(two_ja, two_jb, two_jc)\n          || triangle_selection_fails(two_jd, two_je, two_jf)\n          || triangle_selection_fails(two_jg, two_jh, two_ji)\n          || triangle_selection_fails(two_ja, two_jd, two_jg)\n          || triangle_selection_fails(two_jb, two_je, two_jh)\n          || triangle_selection_fails(two_jc, two_jf, two_ji)\n     ) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    int tk;\n    int tkmin = locMax3(abs(two_ja-two_ji), abs(two_jh-two_jd), abs(two_jb-two_jf));\n    int tkmax = locMin3(two_ja + two_ji, two_jh + two_jd, two_jb + two_jf);\n    double sum_pos = 0.0;\n    double sum_neg = 0.0;\n    double sumsq_err = 0.0;\n    double phase;\n    for(tk=tkmin; tk<=tkmax; tk += 2) {\n      gsl_sf_result s1, s2, s3;\n      double term;\n      double term_err;\n      int status = 0;\n      status += gsl_sf_coupling_6j_e(two_ja, two_ji, two_jd,  two_jh, tk, two_jg,  &s1);\n      status += gsl_sf_coupling_6j_e(two_jb, two_jf, two_jh,  two_jd, tk, two_je,  &s2);\n      status += gsl_sf_coupling_6j_e(two_ja, two_ji, two_jb,  two_jf, tk, two_jc,  &s3);\n      if(status != GSL_SUCCESS) {\n        OVERFLOW_ERROR(result);\n      }\n      term = s1.val * s2.val * s3.val;\n      term_err  = s1.err * fabs(s2.val*s3.val);\n      term_err += s2.err * fabs(s1.val*s3.val);\n      term_err += s3.err * fabs(s1.val*s2.val);\n\n      if(term >= 0.0) {\n        sum_pos += (tk + 1) * term;\n      }\n      else {\n        sum_neg -= (tk + 1) * term;\n      }\n\n      sumsq_err += ((tk+1) * term_err) * ((tk+1) * term_err);\n    }\n\n    phase = GSL_IS_ODD(tkmin) ? -1.0 : 1.0;\n\n    result->val  = phase * (sum_pos - sum_neg);\n    result->err  = 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);\n    result->err += sqrt(sumsq_err / (0.5*(tkmax-tkmin)+1.0));\n    result->err += 2.0 * GSL_DBL_EPSILON * (tkmax-tkmin + 2.0) * fabs(result->val);\n\n    return GSL_SUCCESS;\n  }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_coupling_3j(int two_ja, int two_jb, int two_jc,\n                          int two_ma, int two_mb, int two_mc)\n{\n  EVAL_RESULT(gsl_sf_coupling_3j_e(two_ja, two_jb, two_jc,\n                                   two_ma, two_mb, two_mc,\n                                   &result));\n}\n\n\ndouble gsl_sf_coupling_6j(int two_ja, int two_jb, int two_jc,\n                          int two_jd, int two_je, int two_jf)\n{\n  EVAL_RESULT(gsl_sf_coupling_6j_e(two_ja, two_jb, two_jc,\n                                   two_jd, two_je, two_jf,\n                                   &result));\n}\n\n\ndouble gsl_sf_coupling_9j(int two_ja, int two_jb, int two_jc,\n                          int two_jd, int two_je, int two_jf,\n                          int two_jg, int two_jh, int two_ji)\n{\n  EVAL_RESULT(gsl_sf_coupling_9j_e(two_ja, two_jb, two_jc,\n                                   two_jd, two_je, two_jf,\n                                   two_jg, two_jh, two_ji,\n                                   &result));\n}\n", "meta": {"hexsha": "d5799933f6a0a0d650d8779d408afe140c328903", "size": 12593, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/coupling.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/coupling.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/specfunc/coupling.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 30.4915254237, "max_line_length": 88, "alphanum_fraction": 0.5827046772, "num_tokens": 4418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239131, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3652415691845505}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_cblas.h\"\n\n#include \"tests.h\"\n\nvoid\ntest_amax (void) {\n  {\n   int N = 1;\n   float X[] = { -0.388f };\n   int incX = -1;\n   int expected = 0;\n   int k;\n   k = cblas_isamax(N, X, incX);\n   gsl_test_int(k, expected, \"samax(case 52)\");\n  };\n\n\n  {\n   int N = 1;\n   double X[] = { 0.247 };\n   int incX = -1;\n   int expected = 0;\n   int k;\n   k = cblas_idamax(N, X, incX);\n   gsl_test_int(k, expected, \"damax(case 53)\");\n  };\n\n\n  {\n   int N = 1;\n   float X[] = { 0.704f, 0.665f };\n   int incX = -1;\n   int expected = 0;\n   int k;\n   k = cblas_icamax(N, X, incX);\n   gsl_test_int(k, expected, \"camax(case 54)\");\n  };\n\n\n  {\n   int N = 1;\n   double X[] = { -0.599, -0.758 };\n   int incX = -1;\n   int expected = 0;\n   int k;\n   k = cblas_izamax(N, X, incX);\n   gsl_test_int(k, expected, \"zamax(case 55)\");\n  };\n\n\n  {\n   int N = 2;\n   float X[] = { 0.909f, 0.037f };\n   int incX = 1;\n   int expected = 0;\n   int k;\n   k = cblas_isamax(N, X, incX);\n   gsl_test_int(k, expected, \"samax(case 56)\");\n  };\n\n\n  {\n   int N = 2;\n   double X[] = { 0.271, -0.426 };\n   int incX = 1;\n   int expected = 1;\n   int k;\n   k = cblas_idamax(N, X, incX);\n   gsl_test_int(k, expected, \"damax(case 57)\");\n  };\n\n\n  {\n   int N = 2;\n   float X[] = { -0.648f, 0.317f, 0.62f, 0.392f };\n   int incX = 1;\n   int expected = 1;\n   int k;\n   k = cblas_icamax(N, X, incX);\n   gsl_test_int(k, expected, \"camax(case 58)\");\n  };\n\n\n  {\n   int N = 2;\n   double X[] = { -0.789, 0.352, 0.562, 0.697 };\n   int incX = 1;\n   int expected = 1;\n   int k;\n   k = cblas_izamax(N, X, incX);\n   gsl_test_int(k, expected, \"zamax(case 59)\");\n  };\n\n\n  {\n   int N = 2;\n   float X[] = { 0.487f, 0.918f };\n   int incX = -1;\n   int expected = 0;\n   int k;\n   k = cblas_isamax(N, X, incX);\n   gsl_test_int(k, expected, \"samax(case 60)\");\n  };\n\n\n  {\n   int N = 2;\n   double X[] = { 0.537, 0.826 };\n   int incX = -1;\n   int expected = 0;\n   int k;\n   k = cblas_idamax(N, X, incX);\n   gsl_test_int(k, expected, \"damax(case 61)\");\n  };\n\n\n  {\n   int N = 2;\n   float X[] = { 0.993f, 0.172f, -0.825f, 0.873f };\n   int incX = -1;\n   int expected = 0;\n   int k;\n   k = cblas_icamax(N, X, incX);\n   gsl_test_int(k, expected, \"camax(case 62)\");\n  };\n\n\n  {\n   int N = 2;\n   double X[] = { 0.913, -0.436, -0.134, 0.129 };\n   int incX = -1;\n   int expected = 0;\n   int k;\n   k = cblas_izamax(N, X, incX);\n   gsl_test_int(k, expected, \"zamax(case 63)\");\n  };\n\n\n}\n", "meta": {"hexsha": "1eb228cd22cb78690f4d686ec45df629e647217b", "size": 2477, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_amax.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_amax.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/cblas/test_amax.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 17.3216783217, "max_line_length": 51, "alphanum_fraction": 0.5175615664, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.3649841907808625}}
{"text": "/***************************************************************************\n *   Copyright (C) 2008 by Regis Behmo,,,   *\n *   regis.behmo@ecp.fr   *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n ***************************************************************************/\n\n#ifndef _MPLSH_FIT_TUNE_H_INCLUDED_\n#define _MPLSH_FIT_TUNE_H_INCLUDED_\n\n#include <lshkit.h>\n#include <lshkit/matrix.h>\n#include <lshkit/tune.h>\n\n#include <cstdlib>\n#include <gsl/gsl_multifit.h>\n#include <boost/program_options.hpp>\n#include <boost/progress.hpp>\n\nbool is_good_value (double v);\nbool constraint (const lshkit::tune::Input &x);\n\ndouble mplsh_tune(const double& param_M, const double& param_G, \n                  const double& param_a_M, const double& param_b_M, const double& param_c_M, \n                  const double& param_a_G, const double& param_b_G, const double& param_c_G, \n                  int N, int K, int L, int T, int& M, float& W, float R );\n\ntemplate<class DATA, class METRIC> \nvoid mplsh_fit( const DATA& data, const METRIC& metric, int NN, double& param_M, double& param_G, \n                double& param_a_M, double& param_b_M, double& param_c_M, \n                double& param_a_G, double& param_b_G, double& param_c_G )\n{\n\t// Parameters\n\tunsigned N, P, Q, K, F;\n\tN = 0;// # points\n\tP = 50000;// number of pairs to sample\n\tQ = 1000;// number of queries to sample\n\tK = NN;// search for K nearest neighbors\n\tF = 10;// divide the sample to F folds\n\t\n\tstd::vector<unsigned> idx(data.getSize());\n\tfor (unsigned i = 0; i < idx.size(); ++i) idx[i] = i;\n\trandom_shuffle(idx.begin(), idx.end());\n\n\tif (N > 0 && N < data.getSize()) idx.resize(N);\n\n\tlshkit::DefaultRng rng;\n\trng.seed(0);//plant the same seed, always\n\tboost::variate_generator<lshkit::DefaultRng &, lshkit::UniformUnsigned> gen(rng, lshkit::UniformUnsigned(0, idx.size()-1));\n    \n\tdouble gM = 0.0;\n\tdouble gG = 0.0;\n\t{\n\t\t// sample P pairs of points\n\t\tfor (unsigned k = 0; k < P; ++k)\n\t\t{\n\t\t\tdouble dist, logdist;\n\t\t\tfor (;;)\n\t\t\t{\n\t\t\t\tunsigned i = gen();\n\t\t\t\tunsigned j = gen();\n\t\t\t\tif (i == j) continue;\n\t\t\t\tdist = metric( data[idx[i]], data[idx[j]] );\n\t\t\t\tlogdist = log(dist);\n\t\t\t\tif (is_good_value(logdist)) break;\n\t\t\t}\n\t\t\tgM += dist;\n\t\t\tgG += logdist;\n\t\t}\n\t\tgM /= P;\n\t\tgG /= P;\n\t\tgG = exp(gG);\n\t}\n    \n  // TODO check that\n\t// Custom\n\tQ = (idx.size() > 1000)? 1000 : idx.size();// Added\n\t\n\t// TODO check that \n  // Supprime\n  //if (Q > idx.size()) Q = idx.size();\n  //if (K > idx.size() - Q) K = idx.size() - Q;\n\t\n\t/* sample query */\n\tstd::vector<unsigned> qry(Q);\n    \n\tlshkit::SampleQueries(&qry, idx.size(), rng);\n\n\t/* do the queries */\n\tstd::vector<lshkit::Topk<unsigned> > topks(Q);\n\tfor (unsigned i = 0; i < Q; ++i) topks[i].reset(K);\n    \n\t/* ... */\n\tgsl_matrix *X = gsl_matrix_alloc(F * K, 3);\n\tgsl_vector *yM = gsl_vector_alloc(F * K);\n\tgsl_vector *yG = gsl_vector_alloc(F * K);\n\tgsl_vector *pM = gsl_vector_alloc(3);\n\tgsl_vector *pG = gsl_vector_alloc(3);\n\tgsl_matrix *cov = gsl_matrix_alloc(3,3);\n\n\tstd::vector<double> M(K);\n\tstd::vector<double> G(K);\n    \n\tboost::progress_display progress(F, std::cerr);\n\tunsigned m = 0;\n\tfor (unsigned l = 0; l < F; l++)\n\t{\n\t\t// Scan\n\t\tfor (unsigned i = l; i< idx.size(); i += F)\n\t\t{\n\t\t\tfor (unsigned j = 0; j < Q; j++) \n\t\t\t{\n\t\t\t\tint id = qry[j];\n\t\t\t\tif (i != id) \n\t\t\t\t{\n\t\t\t\t\tfloat d = metric( data[idx[id]], data[idx[i]] );\n\t\t\t\t\tif (is_good_value(log(double(d)))) topks[j] << lshkit::Topk<unsigned>::Element(i, d);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstd::fill(M.begin(), M.end(), 0.0);\n\t\tstd::fill(G.begin(), G.end(), 0.0);\n\n\t\tfor (unsigned i = 0; i < Q; i++)\n\t\t{\n\t\t\tfor (unsigned k = 0; k < K; k++)\n\t\t\t{\n\t\t\t\tM[k] += topks[i][k].dist;\n\t\t\t\tG[k] += log(topks[i][k].dist);\n\t\t\t}\n\t\t}\n\n\t\tfor (unsigned k = 0; k < K; k++)\n\t\t{\n\t\t\tM[k] = log(M[k]/Q);\n\t\t\tG[k] /= Q;\n\t\t\tgsl_matrix_set(X, m, 0, 1.0);\n\t\t\tgsl_matrix_set(X, m, 1, log(double(data.getSize() * (l + 1)) / double(F)));\n\t\t\tgsl_matrix_set(X, m, 2, log(double(k + 1)));\n\t\t\tgsl_vector_set(yM, m, M[k]);\n\t\t\tgsl_vector_set(yG, m, G[k]);\n\t\t\t++m;\n\t\t}\n        ++progress;\n\t}\n\n\tgsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(F * K, 3);\n\n\tdouble chisq;\n\n\tgsl_multifit_linear(X, yM, pM, cov, &chisq, work);\n\tgsl_multifit_linear(X, yG, pG, cov, &chisq, work);\n\t\n\tparam_M = gM;\n\tparam_G = gG;\n\tparam_a_M = gsl_vector_get(pM, 0);\n\tparam_b_M = gsl_vector_get(pM, 1);\n\tparam_c_M = gsl_vector_get(pM, 2);\n\tparam_a_G = gsl_vector_get(pG, 0);\n\tparam_b_G = gsl_vector_get(pG, 1);\n\tparam_c_G = gsl_vector_get(pG, 2);\n\t\n\tgsl_matrix_free(X);\n\tgsl_matrix_free(cov);\n\tgsl_vector_free(pM);\n\tgsl_vector_free(pG);\n\tgsl_vector_free(yM);\n\tgsl_vector_free(yG);\n}\n\ntemplate<class DATA, class METRIC> \ndouble mplsh_fit_tune( const DATA& data, const METRIC& metric, const int& L, const int& T, int& M, float& W, float R = 0.8, int K = 1 )\n{\n\t\n\t/** ***************************/\n\t/** ********** FIT  ***********/\n\t/** ***************************/\n  std::cout << \"Fitting...\" << std::endl;\n\tdouble param_M, param_G, param_a_M, param_b_M, param_c_M, param_a_G, param_b_G, param_c_G;\n\tmplsh_fit( data, metric, K, param_M, param_G, param_a_M, param_b_M, param_c_M, param_a_G, param_b_G, param_c_G );\n\t\n  std::cout << param_M << \"    \" << param_G << std::endl;\n  std::cout << param_a_M << \"    \" << param_b_M << \"    \" << param_c_M << std::endl;\n  std::cout << param_a_G << \"    \" << param_b_G << \"    \" << param_c_G << std::endl;\n\t\n\t/** ***************************/\n\t/** ********** TUNE ***********/\n\t/** ***************************/\n  std::cout << \"Tuning...\" << std::endl;\n\tdouble cost = mplsh_tune(param_M, param_G, param_a_M, param_b_M, param_c_M, param_a_G, param_b_G, param_c_G, \n                    data.getSize(), K, L, T, M, W, R );\n  std::cout << \"L = \" << L;\n  std::cout << \"    \" << \"T = \" << T;\n  std::cout << \"    \" << \"M = \" << M;\n  std::cout << \"    \" << \"W = \" << W;\n  std::cout << \"    \" << \"R = \" << R;\n  std::cout << \"    \" << \"M = \" << M;\n  std::cout << std::endl;\n\n  return cost;\n}\n\n#endif\n\n", "meta": {"hexsha": "f148348df34e5c2f2be8e9d2144330627aa35de4", "size": 6277, "ext": "h", "lang": "C", "max_stars_repo_path": "lshkit/mplsh-fit-tune.h", "max_stars_repo_name": "ocallaco/LuaSHkit", "max_stars_repo_head_hexsha": "c77186ef123505c7e2065dcde05d8b699d6a93d9", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-10-02T21:07:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-09T21:48:38.000Z", "max_issues_repo_path": "lshkit/mplsh-fit-tune.h", "max_issues_repo_name": "ocallaco/LuaSHkit", "max_issues_repo_head_hexsha": "c77186ef123505c7e2065dcde05d8b699d6a93d9", "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": "lshkit/mplsh-fit-tune.h", "max_forks_repo_name": "ocallaco/LuaSHkit", "max_forks_repo_head_hexsha": "c77186ef123505c7e2065dcde05d8b699d6a93d9", "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": 30.033492823, "max_line_length": 135, "alphanum_fraction": 0.5537677234, "num_tokens": 1992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.36497933765773755}}
{"text": "/* specfunc/test_gamma.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_test.h>\n#include <gsl/gsl_sf.h>\n#include \"test_sf.h\"\n\n\nint test_gamma(void)\n{\n  gsl_sf_result r;\n  gsl_sf_result r1, r2;\n  double sgn;\n  int s = 0;\n\n  TEST_SF(s,  gsl_sf_lngamma_e, (-0.1, &r), 2.368961332728788655 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lngamma_e, (-1.0/256.0, &r), 5.547444766967471595  , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lngamma_e, (1.0e-08, &r), 18.420680738180208905 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lngamma_e, (0.1, &r), 2.252712651734205 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lngamma_e, (1.0 + 1.0/256.0, &r), -0.0022422226599611501448 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lngamma_e, (2.0 + 1.0/256.0, &r), 0.0016564177556961728692 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lngamma_e, (100.0, &r), 359.1342053695753 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lngamma_e, (-1.0-1.0/65536.0, &r), 11.090348438090047844 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lngamma_e, (-1.0-1.0/268435456.0, &r), 19.408121054103474300 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lngamma_e, (-100.5, &r), -364.9009683094273518 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lngamma_e, (-100-1.0/65536.0, &r), -352.6490910117097874 , TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (0.7, &r, &sgn), 0.26086724653166651439, TEST_TOL1, 1.0, GSL_SUCCESS);\n  TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (0.1, &r, &sgn), 2.2527126517342059599, TEST_TOL0, 1.0, GSL_SUCCESS);\n  TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-0.1, &r, &sgn), 2.368961332728788655, TEST_TOL0, -1.0, GSL_SUCCESS);\n  TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-1.0-1.0/65536.0, &r, &sgn), 11.090348438090047844, TEST_TOL0, 1.0, GSL_SUCCESS);\n  TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-2.0-1.0/256.0, &r, &sgn), 4.848447725860607213, TEST_TOL0, -1.0, GSL_SUCCESS);\n  TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-2.0-1.0/65536.0, &r, &sgn), 10.397193628164674967, TEST_TOL0, -1.0, GSL_SUCCESS);\n  TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-3.0-1.0/8.0, &r, &sgn), 0.15431112768404182427, TEST_TOL2, 1.0, GSL_SUCCESS);\n  TEST_SF_SGN(s, gsl_sf_lngamma_sgn_e, (-100.5, &r, &sgn), -364.9009683094273518, TEST_TOL0, -1.0, GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_gamma_e, (1.0 + 1.0/4096.0, &r), 0.9998591371459403421 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gamma_e, (1.0 + 1.0/32.0, &r), 0.9829010992836269148 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gamma_e, (2.0 + 1.0/256.0, &r), 1.0016577903733583299 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gamma_e, (9.0, &r), 40320.0                   , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gamma_e, (10.0, &r), 362880.0                  , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gamma_e, (100.0, &r), 9.332621544394415268e+155 , TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gamma_e, (170.0, &r), 4.269068009004705275e+304 , TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gamma_e, (-10.5, &r), -2.640121820547716316e-07  , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gamma_e, (-11.25, &r), 6.027393816261931672e-08  , TEST_TOL0, GSL_SUCCESS); /* exp()... not my fault */\n  TEST_SF(s,  gsl_sf_gamma_e, (-1.0+1.0/65536.0, &r), -65536.42280587818970 , TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_gammastar_e, (1.0e-08, &r), 3989.423555759890865  , TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammastar_e, (1.0e-05, &r), 126.17168469882690233 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammastar_e, (0.001, &r), 12.708492464364073506 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammastar_e, (1.5, &r), 1.0563442442685598666 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammastar_e, (3.0, &r), 1.0280645179187893045 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammastar_e, (9.0, &r), 1.0092984264218189715 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammastar_e, (11.0, &r), 1.0076024283104962850 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammastar_e, (100.0, &r), 1.0008336778720121418 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammastar_e, (1.0e+05, &r), 1.0000008333336805529 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammastar_e, (1.0e+20, &r), 1.0 , TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_gammainv_e, (10.0, &r), 1.0/362880.0, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammainv_e, (100.0, &r), 1.0715102881254669232e-156, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammainv_e, (-10.5, &r), -1.0/2.640121820547716316e-07, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammainv_e, (-11.25, &r), 1.0/6.027393816261931672e-08, TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_gammainv_e, (-1.0+1.0/65536.0, &r), -1.0/65536.42280587818970 , TEST_TOL1, GSL_SUCCESS);\n\n  TEST_SF_2(s, gsl_sf_lngamma_complex_e, (5.0, 2.0, &r1, &r2),\n            2.7487017561338026749, TEST_TOL0,\n\t    3.0738434100497007915, TEST_TOL0,\n            GSL_SUCCESS);\n\t    \n  TEST_SF_2(s, gsl_sf_lngamma_complex_e, (100.0, 100.0, &r1, &r2),\n            315.07804459949331323, TEST_TOL1,\n\t    2.0821801804113110099, TEST_TOL3,\n            GSL_SUCCESS);\n\n  TEST_SF_2(s, gsl_sf_lngamma_complex_e, (100.0, -1000.0, &r1, &r2),\n            -882.3920483010362817000, TEST_TOL1,\n\t    -2.1169293725678813270, TEST_TOL3,\n            GSL_SUCCESS);\n\n  TEST_SF_2(s, gsl_sf_lngamma_complex_e, (-100.0, -1.0, &r1, &r2),\n            -365.0362469529239516000, TEST_TOL1,\n            -3.0393820262864361140, TEST_TOL1,\n            GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_taylorcoeff_e, (10,   1.0/1048576.0, &r), 1.7148961854776073928e-67  , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_taylorcoeff_e, (10,   1.0/1024.0, &r), 2.1738891788497900281e-37  , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_taylorcoeff_e, (10,   1.0, &r), 2.7557319223985890653e-07  , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_taylorcoeff_e, (10,   5.0, &r), 2.6911444554673721340      , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_taylorcoeff_e, (10,   500.0, &r), 2.6911444554673721340e+20  , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_taylorcoeff_e, (100,  100.0, &r), 1.0715102881254669232e+42  , TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_taylorcoeff_e, (1000, 200.0, &r), 2.6628790558154746898e-267 , TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_taylorcoeff_e, (1000, 500.0, &r), 2.3193170139740855074e+131 , TEST_TOL1, GSL_SUCCESS);\n\n  TEST_SF(s,   gsl_sf_fact_e, (0, &r), 1.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,   gsl_sf_fact_e, (1, &r), 1.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,   gsl_sf_fact_e, (7, &r), 5040.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_fact_e, (33, &r), 8.683317618811886496e+36 , TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF(s,   gsl_sf_doublefact_e, (0, &r), 1.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,   gsl_sf_doublefact_e, (1, &r), 1.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,   gsl_sf_doublefact_e, (7, &r), 105.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_doublefact_e, (33, &r), 6.332659870762850625e+18 , TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_lnfact_e, (0, &r), 0.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lnfact_e, (1, &r), 0.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lnfact_e, (7, &r), 8.525161361065414300 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lnfact_e, (33, &r), 85.05446701758151741 , TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_lndoublefact_e, (0, &r), 0.0  , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lndoublefact_e, (7, &r), 4.653960350157523371  , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lndoublefact_e, (33, &r), 43.292252022541719660 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lndoublefact_e, (34, &r), 45.288575519655959140 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lndoublefact_e, (1034, &r), 3075.6383796271197707 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lndoublefact_e, (1035, &r), 3078.8839081731809169 , TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_lnchoose_e, (7,3, &r), 3.555348061489413680 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lnchoose_e, (5,2, &r), 2.302585092994045684 , TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_choose_e, (7,3, &r), 35.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_choose_e, (5,2, &r), 10.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_choose_e, (500,200, &r), 5.054949849935532221e+144 , TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_lnpoch_e, (5, 1.0/65536.0, &r), 0.000022981557571259389129, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lnpoch_e, (5, 1.0/256.0, &r),   0.005884960217985189004,    TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lnpoch_e, (7,3, &r), 6.222576268071368616, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_lnpoch_e, (5,2, &r), 3.401197381662155375, TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF_SGN(s, gsl_sf_lnpoch_sgn_e, (-4.5, 0.25, &r, &sgn), 0.7430116475119920117, TEST_TOL1, 1.0, GSL_SUCCESS);\n  TEST_SF_SGN(s, gsl_sf_lnpoch_sgn_e, (-4.5, 1.25, &r, &sgn), 2.1899306304483174731, TEST_TOL1, -1.0, GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_poch_e, (7,3, &r), 504.0 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_poch_e, (5,2, &r), 30.0  , TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_poch_e, (5,1.0/256.0, &r), 1.0059023106151364982 , TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF(s,  gsl_sf_pochrel_e, (7,3, &r), 503.0/3.0, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_pochrel_e, (5,2, &r), 29.0/2.0, TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_pochrel_e, (5,0.01, &r), 1.5186393661368275330, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_pochrel_e, (-5.5,0.01, &r), 1.8584945633829063516, TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_pochrel_e, (-5.5,-1.0/8.0, &r), 1.0883319303552135488, TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_pochrel_e, (-5.5,-1.0/256.0, &r), 1.7678268037726177453, TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_pochrel_e, (-5.5,-11.0, &r), 0.09090909090939652475, TEST_TOL0, GSL_SUCCESS);\n\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (0.001, 0.001, &r), 0.9936876467088602902, TEST_TOL0, GSL_SUCCESS) ;\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (0.001, 1.0, &r), 0.9997803916424144436, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (0.001, 10.0, &r), 0.9999999958306921828, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (1.0, 0.001, &r), 0.0009995001666250083319, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (1.0, 1.01, &r), 0.6357810204284766802, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (1.0, 10.0, &r), 0.9999546000702375151, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (10.0, 10.01, &r), 0.5433207586693410570, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (10.0, 20.0, &r), 0.9950045876916924128, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (1000.0, 1000.1, &r), 0.5054666401440661753, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (1000.0, 2000.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS);\n  \n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (0.001, 0.001, &r), 0.006312353291139709793, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (0.001, 1.0, &r), 0.00021960835758555639171, TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (0.001, 2.0, &r), 0.00004897691783098147880, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (0.001, 5.0, &r), 1.1509813397308608541e-06, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1.0, 0.001, &r), 0.9990004998333749917, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1.0, 1.01, &r), 0.3642189795715233198, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1.0, 10.0, &r), 0.00004539992976248485154, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (10.0, 10.01, &r), 0.4566792413306589430, TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (10.0, 100.0, &r), 1.1253473960842733885e-31, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1000.0, 1000.1, &r), 0.4945333598559338247, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (1000.0, 2000.0, &r), 6.847349459614753180e-136, TEST_TOL2, GSL_SUCCESS);\n\n  /* designed to trap the a-x=1 problem */\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (100,  99.0, &r), 0.5266956696005394, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_Q_e, (200, 199.0, &r), 0.5188414119121281, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (100,  99.0, &r), 0.4733043303994607, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_gamma_inc_P_e, (200, 199.0, &r), 0.4811585880878718, TEST_TOL2, GSL_SUCCESS);\n\n\n  TEST_SF(s, gsl_sf_lnbeta_e, (1.0e-8, 1.0e-8, &r),  19.113827924512310617 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (1.0e-8, 0.01, &r),  18.420681743788563403 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (1.0e-8, 1.0, &r),  18.420680743952365472 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (1.0e-8, 10.0, &r),  18.420680715662683009 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (1.0e-8, 1000.0, &r),  18.420680669107656949 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (0.1, 0.1, &r), 2.9813614810376273949 , TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (0.1, 1.0, &r),  2.3025850929940456840 , TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (0.1, 100.0, &r),  1.7926462324527931217 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (0.1, 1000, &r),  1.5619821298353164928 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (1.0, 1.00025, &r),  -0.0002499687552073570, TEST_TOL4, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (1.0, 1.01, &r),  -0.009950330853168082848 , TEST_TOL3, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (1.0, 1000.0, &r),  -6.907755278982137052 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (100.0, 100.0, &r),  -139.66525908670663927 , TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (100.0, 1000.0, &r),  -336.4348576477366051 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s, gsl_sf_lnbeta_e, (100.0, 1.0e+8, &r),  -1482.9339185256447309 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_e, (1.0,   1.0, &r), 1.0                   , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_e, (1.0, 1.001, &r), 0.9990009990009990010 , TEST_TOL0, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_e, (1.0,   5.0, &r), 0.2                   , TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_e, (1.0,  100.0, &r), 0.01                  , TEST_TOL1, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_e, (10.0, 100.0, &r), 2.3455339739604649879e-15 , TEST_TOL2, GSL_SUCCESS);\n\n\n  TEST_SF(s,  gsl_sf_beta_inc_e, (1.0, 1.0, 0.0, &r), 0.0, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, (1.0, 1.0, 1.0, &r), 1.0, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, (0.1, 0.1, 1.0, &r), 1.0, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, ( 1.0,  1.0, 0.5, &r), 0.5, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, ( 0.1,  1.0, 0.5, &r), 0.9330329915368074160, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, (10.0,  1.0, 0.5, &r), 0.0009765625000000000000, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, (50.0,  1.0, 0.5, &r), 8.881784197001252323e-16, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, ( 1.0,  0.1, 0.5, &r), 0.06696700846319258402, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, ( 1.0, 10.0, 0.5, &r), 0.99902343750000000000, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, ( 1.0, 50.0, 0.5, &r), 0.99999999999999911180, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, ( 1.0,  1.0, 0.1, &r), 0.10, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, ( 1.0,  2.0, 0.1, &r), 0.19, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, ( 1.0,  2.0, 0.9, &r), 0.99, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, (50.0, 60.0, 0.5, &r), 0.8309072939016694143, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, (90.0, 90.0, 0.5, &r), 0.5, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, ( 500.0,  500.0, 0.6, &r), 0.9999999999157549630, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, (5000.0, 5000.0, 0.4, &r), 4.518543727260666383e-91, TEST_TOL5, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, (5000.0, 5000.0, 0.6, &r), 1.0, TEST_TOL2, GSL_SUCCESS);\n  TEST_SF(s,  gsl_sf_beta_inc_e, (5000.0, 2000.0, 0.6, &r), 8.445388773903332659e-89, TEST_TOL5, GSL_SUCCESS);\n\n\n  return s;\n}\n", "meta": {"hexsha": "a6d819ba627ed3b68e656e6b438bf80b768e2930", "size": 17004, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/test_gamma.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/test_gamma.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/specfunc/test_gamma.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 71.746835443, "max_line_length": 124, "alphanum_fraction": 0.7035403434, "num_tokens": 7360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.36491075203131107}}
{"text": "/* interpolation/accel.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman\n */\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_interp.h>\n\ngsl_interp_accel *\ngsl_interp_accel_alloc (void)\n{\n  gsl_interp_accel *a = (gsl_interp_accel *) malloc (sizeof (gsl_interp_accel));\n  if (a == 0)\n    {\n      GSL_ERROR_NULL(\"could not allocate space for gsl_interp_accel\", GSL_ENOMEM);\n    }\n\n  a->cache = 0;\n  a->hit_count = 0;\n  a->miss_count = 0;\n\n  return a;\n}\n\nint\ngsl_interp_accel_reset (gsl_interp_accel * a)\n{\n  a->cache = 0;\n  a->hit_count = 0;\n  a->miss_count = 0;\n\n  return GSL_SUCCESS;\n}\n\n#ifndef HIDE_INLINE_STATIC\nsize_t\ngsl_interp_accel_find (gsl_interp_accel * a, const double xa[], size_t len, double x)\n{\n  size_t x_index = a->cache;\n\n  if (x < xa[x_index])\n    {\n      a->miss_count++;\n      a->cache = gsl_interp_bsearch (xa, x, 0, x_index);\n    }\n  else if (x > xa[x_index + 1])\n    {\n      a->miss_count++;\n      a->cache = gsl_interp_bsearch (xa, x, x_index, len - 1);\n    }\n  else\n    {\n      a->hit_count++;\n    }\n\n  return a->cache;\n}\n#endif\n\nvoid\ngsl_interp_accel_free (gsl_interp_accel * a)\n{\n  free (a);\n}\n", "meta": {"hexsha": "72d9345971c111ef580c8e3d60e68b1e930ed9c7", "size": 1926, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/interpolation/accel.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/interpolation/accel.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/interpolation/accel.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 23.2048192771, "max_line_length": 85, "alphanum_fraction": 0.6765316719, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.3646433588425346}}
{"text": "#ifndef INCLUDED_BLAS_DETAIL_H\n#define INCLUDED_BLAS_DETAIL_H\n\n#include <cblas.h>\n#include \"telepath/blas/traits.h\"\n\nnamespace blas{\n\n    namespace matrix{\n\n        namespace matrix_detail{\n\n            template< typename T, bool = BlasCast<T>::value >\n            struct BlasMatImpl { };\n\n            template< typename T >\n            struct BlasMatImpl< T, true >{\n                using mat_t = decltype( BlasCast<T>::blas_cast(\n                    std::declval<T>() ) );\n                mat_t mat;\n                constexpr BlasMatImpl( const T& m )\n                    : mat( BlasCast<T>::blas_cast( m ) ) { }\n                operator mat_t&() { return mat; }\n                operator const mat_t&() const{ return mat; }\n            };\n\n            template< typename T >\n            struct BlasMatImpl< T, false >{\n                using mat_t = T;\n                mat_t& mat;\n                constexpr BlasMatImpl( T& m ) : mat( m ) { }\n                operator mat_t&() { return mat; }\n                operator const mat_t&() const{ return mat; }\n            };\n            \n            template< typename T, bool = BlasCast<T>::value >\n            struct ConstBlasMatImpl { };\n\n            template< typename T >\n            struct ConstBlasMatImpl< T, true >{\n                using mat_t = decltype( BlasCast<T>::blas_cast(\n                    std::declval<T>() ) );\n                mat_t mat;\n                constexpr ConstBlasMatImpl( const T& m )\n                    : mat( BlasCast<T>::blas_cast( m ) ) { }\n                operator const mat_t&() const{ return mat; }\n            };\n\n            template< typename T >\n            struct ConstBlasMatImpl< T, false >{\n                using mat_t = T;\n                const mat_t& mat;\n                constexpr ConstBlasMatImpl( const T& m ) : mat( m ) { }\n                operator const mat_t&() const{ return mat; }\n            };\n\n        } //namespace matrix_detail\n\n        template< typename T >\n        struct Mat : public matrix_detail::BlasMatImpl<T> {\n            using impl = typename matrix_detail::BlasMatImpl<T>; \n            using impl::impl;\n        };\n\n        template< typename T >\n        struct ConstMat : public matrix_detail::ConstBlasMatImpl<T>{\n            using impl = typename matrix_detail::ConstBlasMatImpl<T>; \n            using impl::impl;\n        };\n\n        template< typename T >\n        using scalar_t = typename MatrixTraits<T>::scalar_t;\n\n        template< typename T >\n        constexpr CBLAS_ORDER layout( const T& x ){\n            return MatrixTraits<T>::layout( x );\n        }\n        \n        template< typename T >\n        constexpr CBLAS_TRANSPOSE trans( const T& x ){\n            return MatrixTraits<T>::trans( x );\n        }\n        \n        template< typename T >\n        constexpr CBLAS_UPLO uplo( const T& x ){\n            return MatrixTraits<T>::uplo( x );\n        }\n        \n        template< typename T >\n        constexpr std::size_t nrows( const T& x ){\n            return MatrixTraits<T>::nrows( x );\n        }\n        \n        template< typename T >\n        constexpr std::size_t ncols( const T& x ){\n            return MatrixTraits<T>::ncols( x );\n        }\n        \n        template< typename T >\n        constexpr std::size_t ld( const T& x ){\n            return MatrixTraits<T>::ld( x );\n        }\n        \n        template< typename T >\n        constexpr auto array( T& x ){\n            return MatrixTraits<T>::array( x );\n        }\n        \n        template< typename T >\n        constexpr auto array( const T& x ){\n            return MatrixTraits<T>::array( x );\n        }\n\n    } //namespace matrix\n\n    template< typename T >\n    inline auto blas_matrix( T& x ){\n        return matrix::Mat<T>( x );\n    }\n\n    template< typename T >\n    inline auto blas_matrix( const T& x ){\n        return matrix::ConstMat<T>( x );\n    }\n\n    template< typename T >\n    struct MatrixTraits< matrix::Mat<T> >\n        : public MatrixTraits< typename matrix::Mat<T>::mat_t > { };\n    \n    template< typename T >\n    struct MatrixTraits< matrix::ConstMat<T> >\n        : public MatrixTraits< typename matrix::ConstMat<T>::mat_t > { };\n\n    namespace vector{\n\n        namespace vector_detail{\n\n            template< typename T, bool = BlasCast<T>::value >\n            struct BlasVecImpl { };\n\n            template< typename T >\n            struct BlasVecImpl< T, true >{\n                using vec_t = decltype( BlasCast<T>::blas_cast(\n                    std::declval<T>() ) );\n                vec_t vec;\n                constexpr BlasVecImpl( const T& v )\n                    : vec( BlasCast<T>::blas_cast( v ) ) { }\n                operator vec_t&() { return vec; }\n                operator const vec_t&() const{ return vec; }\n            };\n\n            template< typename T >\n            struct BlasVecImpl< T, false >{\n                using vec_t = T;\n                vec_t& vec;\n                BlasVecImpl( const T& v ) : vec( v ) { }\n                operator vec_t&() { return vec; }\n                operator const vec_t&() const{ return vec; }\n            };\n\n        } //namespace vector_detail\n\n        template< typename T >\n        struct Vec : public vector_detail::BlasVecImpl<T> {\n            using impl = typename vector_detail::BlasVecImpl<T>; \n            using impl::impl;\n        };\n\n        template< typename T >\n        using scalar_t = typename VectorTraits<T>::scalar_t;\n\n        template< typename T >\n        constexpr auto length( const T& x ){\n            return VectorTraits<T>::length( x );\n        }\n\n        template< typename T >\n        constexpr auto inc( const T& x ){\n            return VectorTraits<T>::inc( x );\n        }\n\n        template< typename T >\n        constexpr auto array( T& x ){\n            return VectorTraits<T>::array( x );\n        }\n        \n        template< typename T >\n        constexpr auto array( const T& x ){\n            return VectorTraits<T>::array( x );\n        }\n\n    } //namespace vector\n\n    template< typename T >\n    struct VectorTraits< vector::Vec<T> >\n        : public VectorTraits< typename vector::Vec<T>::vec_t > { };\n\n} //namespace blas\n\n#endif\n", "meta": {"hexsha": "132500f2ccb7ddba7f177426d5e7864ca14cd8c5", "size": 6133, "ext": "h", "lang": "C", "max_stars_repo_path": "include/telepath/blas/detail.h", "max_stars_repo_name": "tbepler/telepath", "max_stars_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/telepath/blas/detail.h", "max_issues_repo_name": "tbepler/telepath", "max_issues_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/telepath/blas/detail.h", "max_forks_repo_name": "tbepler/telepath", "max_forks_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c", "max_forks_repo_licenses": ["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.5124378109, "max_line_length": 73, "alphanum_fraction": 0.5072558291, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.36445961820348877}}
{"text": "/**\n * @file batchv_zgemv.c\n *\n * Part of API test for Batched BLAS routines.\n *\n * @author Samuel D. Relton\n * @author Pedro   V. Lara\n * @author Mawussi Zounon\n * @date 2016-06-01\n *\n * @precisions normal z -> c d s\n *\n **/\n\n#include <cblas.h>\n#include \"bblas.h\"\n\n#define COMPLEX\nvoid batchv_zgemv(\n\tconst enum BBLAS_TRANS *trans,\n\tconst int *m, const int *n,\n\tconst BBLAS_Complex64_t *alpha,\n\tconst BBLAS_Complex64_t **arrayA, const int *lda,\n\tconst BBLAS_Complex64_t **arrayx, const int *incx,\n\tconst BBLAS_Complex64_t *beta,\n\tBBLAS_Complex64_t **arrayy, const int *incy,\n\tconst int batch_count, int* info)\n{\n\t/* Local variables */\n//\tint first_index = 0;\n\tint batch_iter = 0;\n\tchar func_name[15] = \"batchv_zgemv\";\n\n\tif (batch_count < 0)\n\t{\n\t\txerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1);\n\t}\n\n\tfor (batch_iter = 0; batch_iter < batch_count; batch_iter++)\n\t{\n\t\t/* Check input arguments */\n\t\tif ((trans[batch_iter] != BblasTrans) &&\n\t\t\t(trans[batch_iter] != BblasNoTrans) &&\n\t\t\t(trans[batch_iter] != BblasConjTrans))\n\t\t{\n\t\t\txerbla_batch(func_name, BBLAS_ERR_TRANS, batch_iter);\n\t\t\tinfo[batch_iter] = BBLAS_ERR_TRANS;\n\t\t}\n\n\t\tif (m[batch_iter] < 0)\n\t\t{\n\t\t\txerbla_batch(func_name, BBLAS_ERR_M, batch_iter);\n\t\t\tinfo[batch_iter] = BBLAS_ERR_M;\n\t\t}\n\n\t\tif (n[batch_iter] < 0)\n\t\t{\n\t\t\txerbla_batch(func_name, BBLAS_ERR_N, batch_iter);\n\t\t\tinfo[batch_iter] = BBLAS_ERR_N;\n\t\t}\n\n\t\t/* Column major */\n\t\tif ((lda[batch_iter] < 1) && (lda[batch_iter] < m[batch_iter]))\n\t\t{\n\t\t\txerbla_batch(func_name, BBLAS_ERR_LDA, batch_iter);\n\t\t\tinfo[batch_iter] = BBLAS_ERR_LDA;\n\t\t}\n\n\t\tif (incx[batch_iter] < 1)\n\t\t{\n\t\t\txerbla_batch(func_name, BBLAS_ERR_INCX, batch_iter);\n\t\t\tinfo[batch_iter] = BBLAS_ERR_INCX;\n\t\t}\n\n\t\tif (incy[batch_iter] < 1)\n\t\t{\n\t\t\txerbla_batch(func_name, BBLAS_ERR_INCY, batch_iter);\n\t\t\tinfo[batch_iter] = BBLAS_ERR_INCY;\n\t\t}\n\n\t\t/* Call CBLAS */\n\t\tcblas_zgemv(\n\t\t\tBblasColMajor,\n\t\t\ttrans[batch_iter],\n\t\t\tm[batch_iter], n[batch_iter],\n\t\t\tCBLAS_SADDR( alpha[batch_iter] ),\n\t\t\tarrayA[batch_iter], lda[batch_iter],\n\t\t\tarrayx[batch_iter], incx[batch_iter],\n\t\t\tCBLAS_SADDR( beta[batch_iter] ),\n\t\t\tarrayy[batch_iter], incy[batch_iter]);\n\t\t/* Successful */\n\t\tinfo[batch_iter] = BBLAS_SUCCESS;\n\t} /* End variable size for loop */\n}\n#undef COMPLEX\n", "meta": {"hexsha": "101f80764377ee4cb3805b5ae4d81565e4ff09f7", "size": 2235, "ext": "c", "lang": "C", "max_stars_repo_path": "src/batchv_zgemv.c", "max_stars_repo_name": "mawussi/BBLAS-group", "max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z", "max_issues_repo_path": "src/batchv_zgemv.c", "max_issues_repo_name": "sdrelton/bblas_api_test", "max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/batchv_zgemv.c", "max_forks_repo_name": "sdrelton/bblas_api_test", "max_forks_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.28125, "max_line_length": 65, "alphanum_fraction": 0.6814317673, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3644596035150616}}
{"text": "/* interpolation/interp2d.c\n * \n * Copyright 2012 David Zaslavsky\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_interp.h>\n#include <gsl/gsl_interp2d.h>\n\n/**\n * Triggers a GSL error if the argument is not equal to GSL_SUCCESS.\n * If the argument is GSL_SUCCESS, this does nothing.\n */\n#define DISCARD_STATUS(s) if ((s) != GSL_SUCCESS) { GSL_ERROR_VAL(\"interpolation error\", (s),  GSL_NAN); }\n\n#define IDX2D(i, j, w) ((j) * ((w)->xsize) + (i))\n\ngsl_interp2d *\ngsl_interp2d_alloc(const gsl_interp2d_type * T, const size_t xsize,\n                   const size_t ysize)\n{\n  gsl_interp2d * interp;\n\n  if (xsize < T->min_size || ysize < T->min_size)\n    {\n      GSL_ERROR_NULL (\"insufficient number of points for interpolation type\",\n                      GSL_EINVAL);\n    }\n\n  interp = (gsl_interp2d *) calloc(1, sizeof(gsl_interp2d));\n  if (interp == NULL)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for gsl_interp2d struct\",\n                      GSL_ENOMEM);\n    }\n\n  interp->type = T;\n  interp->xsize = xsize;\n  interp->ysize = ysize;\n\n  if (interp->type->alloc == NULL)\n    {\n      interp->state = NULL;\n      return interp;\n    }\n\n  interp->state = interp->type->alloc(xsize, ysize);\n  if (interp->state == NULL)\n    {\n      free(interp);\n      GSL_ERROR_NULL (\"failed to allocate space for gsl_interp2d state\",\n                      GSL_ENOMEM);\n    }\n\n  return interp;\n} /* gsl_interp2d_alloc() */\n\nvoid\ngsl_interp2d_free (gsl_interp2d * interp)\n{\n  RETURN_IF_NULL(interp);\n\n  if (interp->type->free)\n    interp->type->free(interp->state);\n\n  free(interp);\n} /* gsl_interp2d_free() */\n\nint\ngsl_interp2d_init (gsl_interp2d * interp, const double xarr[], const double yarr[],\n                   const double zarr[], const size_t xsize, const size_t ysize)\n{\n  size_t i;\n\n  if (xsize != interp->xsize || ysize != interp->ysize)\n    {\n      GSL_ERROR(\"data must match size of interpolation object\", GSL_EINVAL);\n    }\n\n  for (i = 1; i < xsize; i++)\n    {\n      if (xarr[i-1] >= xarr[i])\n        {\n          GSL_ERROR(\"x values must be strictly increasing\", GSL_EINVAL);\n        }\n    }\n\n  for (i = 1; i < ysize; i++)\n    {\n      if (yarr[i-1] >= yarr[i])\n        {\n          GSL_ERROR(\"y values must be strictly increasing\", GSL_EINVAL);\n        }\n    }\n\n  interp->xmin = xarr[0];\n  interp->xmax = xarr[xsize - 1];\n  interp->ymin = yarr[0];\n  interp->ymax = yarr[ysize - 1];\n\n  {\n    int status = interp->type->init(interp->state, xarr, yarr, zarr,\n                                    xsize, ysize);\n    return status;\n  }\n} /* gsl_interp2d_init() */\n\n/*\n * A wrapper function that checks boundary conditions, calls an evaluator\n * which implements the actual calculation of the function value or \n * derivative etc., and checks the return status.\n */\nstatic int\ninterp2d_eval(int (*evaluator)(const void *, const double xa[], const double ya[],\n                               const double za[], size_t xsize, size_t ysize,\n                               double x, double y, gsl_interp_accel *,\n                               gsl_interp_accel *, double * z),\n              const gsl_interp2d * interp, const double xarr[],\n              const double yarr[], const double zarr[],\n              const double x, const double y,\n              gsl_interp_accel * xa, gsl_interp_accel * ya,\n              double * result)\n{\n  if (x < interp->xmin || x > interp->xmax)\n    {\n      GSL_ERROR (\"interpolation x value out of range\", GSL_EDOM);\n    }\n  else if (y < interp->ymin || y > interp->ymax)\n    {\n      GSL_ERROR (\"interpolation y value out of range\", GSL_EDOM);\n    }\n\n  return evaluator(interp->state, xarr, yarr, zarr,\n                   interp->xsize, interp->ysize,\n                   x, y, xa, ya, result);\n}\n\n/*\n * Another wrapper function that serves as a drop-in replacement for\n * interp2d_eval but does not check the bounds. This can be used\n * for extrapolation.\n */\nstatic int\ninterp2d_eval_extrap(int (*evaluator)(const void *, const double xa[],\n                                      const double ya[], const double za[],\n                                      size_t xsize, size_t ysize,\n                                      double x, double y,\n                                      gsl_interp_accel *,\n                                      gsl_interp_accel *, double * z),\n                     const gsl_interp2d * interp, const double xarr[],\n                     const double yarr[], const double zarr[],\n                     const double x, const double y,\n                     gsl_interp_accel * xa, gsl_interp_accel * ya,\n                     double * result)\n{\n  return evaluator(interp->state, xarr, yarr, zarr,\n                   interp->xsize, interp->ysize, x, y, xa, ya, result);\n}\n\ndouble\ngsl_interp2d_eval (const gsl_interp2d * interp, const double xarr[],\n                   const double yarr[], const double zarr[],\n                   const double x, const double y,\n                   gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  double z;\n  int status = gsl_interp2d_eval_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);\n  DISCARD_STATUS(status)\n  return z;\n} /* gsl_interp2d_eval() */\n\ndouble\ngsl_interp2d_eval_extrap (const gsl_interp2d * interp,\n                          const double xarr[],\n                          const double yarr[],\n                          const double zarr[],\n                          const double x,\n                          const double y,\n                          gsl_interp_accel * xa,\n                          gsl_interp_accel * ya)\n{\n  double z;\n  int status =\n    interp2d_eval_extrap(interp->type->eval, interp,\n                         xarr, yarr, zarr, x, y, xa, ya, &z);\n  DISCARD_STATUS(status)\n  return z;\n}\n\nint\ngsl_interp2d_eval_e (const gsl_interp2d * interp, const double xarr[],\n                     const double yarr[], const double zarr[],\n                     const double x, const double y,\n                     gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)\n{\n  return interp2d_eval(interp->type->eval, interp,\n                       xarr, yarr, zarr, x, y, xa, ya, z);\n} /* gsl_interp2d_eval_e() */\n\nint\ngsl_interp2d_eval_e_extrap (const gsl_interp2d * interp,\n                            const double xarr[], const double yarr[],\n                            const double zarr[], const double x,\n                            const double y, gsl_interp_accel * xa,\n                            gsl_interp_accel * ya, double * z)\n{\n  return interp2d_eval_extrap(interp->type->eval, interp,\n                              xarr, yarr, zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_interp2d_eval_deriv_x (const gsl_interp2d * interp, const double xarr[],\n                           const double yarr[], const double zarr[],\n                           const double x, const double y,\n                           gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  double z;\n  int status = gsl_interp2d_eval_deriv_x_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);\n  DISCARD_STATUS(status)\n  return z;\n}\n\nint\ngsl_interp2d_eval_deriv_x_e (const gsl_interp2d * interp, const double xarr[],\n                             const double yarr[], const double zarr[],\n                             const double x, const double y,\n                             gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)\n{\n  return interp2d_eval(interp->type->eval_deriv_x, interp,\n                       xarr, yarr, zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_interp2d_eval_deriv_y (const gsl_interp2d * interp, const double xarr[],\n                           const double yarr[], const double zarr[],\n                           const double x, const double y,\n                           gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  double z;\n  int status = gsl_interp2d_eval_deriv_y_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);\n  DISCARD_STATUS(status)\n  return z;\n}\n\nint\ngsl_interp2d_eval_deriv_y_e (const gsl_interp2d * interp, const double xarr[],\n                             const double yarr[], const double zarr[],\n                             const double x, const double y,\n                             gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)\n{\n  return interp2d_eval(interp->type->eval_deriv_y, interp,\n                       xarr, yarr, zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_interp2d_eval_deriv_xx (const gsl_interp2d * interp, const double xarr[],\n                            const double yarr[], const double zarr[],\n                            const double x, const double y,\n                            gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  double z;\n  int status = gsl_interp2d_eval_deriv_xx_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);\n  DISCARD_STATUS(status)\n  return z;\n}\n\nint\ngsl_interp2d_eval_deriv_xx_e (const gsl_interp2d * interp, const double xarr[],\n                              const double yarr[], const double zarr[],\n                              const double x, const double y,\n                              gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)\n{\n  return interp2d_eval(interp->type->eval_deriv_xx, interp,\n                       xarr, yarr, zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_interp2d_eval_deriv_yy (const gsl_interp2d * interp, const double xarr[],\n                            const double yarr[], const double zarr[],\n                            const double x, const double y,\n                            gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  double z;\n  int status = gsl_interp2d_eval_deriv_yy_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);\n  DISCARD_STATUS(status)\n  return z;\n}\n\nint\ngsl_interp2d_eval_deriv_yy_e (const gsl_interp2d * interp, const double xarr[],\n                              const double yarr[], const double zarr[],\n                              const double x, const double y,\n                              gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)\n{\n  return interp2d_eval(interp->type->eval_deriv_yy, interp,\n                       xarr, yarr, zarr, x, y, xa, ya, z);\n}\n\ndouble\ngsl_interp2d_eval_deriv_xy (const gsl_interp2d * interp, const double xarr[],\n                            const double yarr[], const double zarr[],\n                            const double x, const double y,\n                            gsl_interp_accel * xa, gsl_interp_accel * ya)\n{\n  double z;\n  int status = gsl_interp2d_eval_deriv_xy_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z);\n  DISCARD_STATUS(status)\n  return z;\n}\n\nint\ngsl_interp2d_eval_deriv_xy_e (const gsl_interp2d * interp, const double xarr[],\n                              const double yarr[], const double zarr[],\n                              const double x, const double y,\n                              gsl_interp_accel * xa, gsl_interp_accel * ya, double * z)\n{\n  return interp2d_eval(interp->type->eval_deriv_xy, interp,\n                       xarr, yarr, zarr, x, y, xa, ya, z);\n}\n\nsize_t\ngsl_interp2d_type_min_size(const gsl_interp2d_type * T)\n{\n  return T->min_size;\n}\n\nsize_t\ngsl_interp2d_min_size(const gsl_interp2d * interp)\n{\n  return interp->type->min_size;\n}\n\nconst char *\ngsl_interp2d_name(const gsl_interp2d * interp)\n{\n  return interp->type->name;\n}\n\nsize_t\ngsl_interp2d_idx(const gsl_interp2d * interp,\n                 const size_t i, const size_t j)\n{\n  if (i >= interp->xsize)\n    {\n      GSL_ERROR_VAL (\"x index out of range\", GSL_ERANGE, 0);\n    }\n  else if (j >= interp->ysize)\n    {\n      GSL_ERROR_VAL (\"y index out of range\", GSL_ERANGE, 0);\n    }\n  else\n    {\n      return IDX2D(i, j, interp);\n    }\n} /* gsl_interp2d_idx() */\n\nint\ngsl_interp2d_set(const gsl_interp2d * interp, double zarr[],\n                 const size_t i, const size_t j, const double z)\n{\n  if (i >= interp->xsize)\n    {\n      GSL_ERROR (\"x index out of range\", GSL_ERANGE);\n    }\n  else if (j >= interp->ysize)\n    {\n      GSL_ERROR (\"y index out of range\", GSL_ERANGE);\n    }\n  else\n    {\n      zarr[IDX2D(i, j, interp)] = z;\n      return GSL_SUCCESS;\n    }\n} /* gsl_interp2d_set() */\n\ndouble\ngsl_interp2d_get(const gsl_interp2d * interp, const double zarr[],\n                 const size_t i, const size_t j)\n{\n  if (i >= interp->xsize)\n    {\n      GSL_ERROR_VAL (\"x index out of range\", GSL_ERANGE, 0);\n    }\n  else if (j >= interp->ysize)\n    {\n      GSL_ERROR_VAL (\"y index out of range\", GSL_ERANGE, 0);\n    }\n  else\n    {\n      return zarr[IDX2D(i, j, interp)];\n    }\n} /* gsl_interp2d_get() */\n\n#undef IDX2D\n", "meta": {"hexsha": "6389ebf0e833f5407ee2a9be6bb1098ce80187fa", "size": 13179, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/interpolation/interp2d.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/interp2d.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "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/BaselineMethods/MNE/C++/gsl-2.4/interpolation/interp2d.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.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.9878640777, "max_line_length": 106, "alphanum_fraction": 0.5778131876, "num_tokens": 3305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3643930717635579}}
{"text": "// 02.05.2021 - Colloid in a fluctuating scalar field\n// Davide Venturelli & Benjamin Walter\n// Last update 08.11.21\n\n/* COMMENTS:\n- Stochastic Runge-Kutta II for colloid evolution, Euler-Maruyama for field evolution (can be enhanced, but the price is O(N) at least. We could even think of anisotropic resolution, i.e. better around the colloid).\n- No boundary conditions on the colloid displacement; they only get enforced when locating the nearest site.\n- Space is measured in units of the lattice spacing.\n- I am saving X(t) in colloid_pos and Y(t) in colloid_msd. Printing only X(t) at the moment.\n- Finite size colloid, Gaussian interaction potential.\n- Zero set in correspondence of trap center when printing out colloid data.\n- Random inizialitazion of the field in Fourier space\n- There is no limit on the size of R (other than physical, L/2)\n- Compile as $ gcc -o colloid colloid_RF.c -lm -lgsl -lfftw3 -O3 -Wall -Wextra -O3\n*/\n\n// LIBRARIES, TYPES, DEFINITIONS\n\n#include <stdio.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_sf.h>\n#include <time.h>\n#include <unistd.h>\n#include <fftw3.h>\n\n#define ALLOC(p,n) (p)=malloc( (n) * sizeof(*(p))); if( (p) == NULL){printf(\"Allocation of '%s' failed. Terminate. \\n\", #p); exit(2); } \n#define CALLOC(p,n) (p)=calloc( (n) , sizeof(*(p))); if( (p) == NULL){printf(\"Allocation of '%s' failed. Terminate. \\n\", #p); exit(2); } \n//#define long unsigned long\t\t\t\t\t\t \t\t\t\t\t// This is to make long hold twice as much\n#define DD printf(\"# Debug: line %d \\n\",__LINE__);\n#define DEBUG (1)\n#define EPS 0.0000000001\t\t\t\t\t\t\t\t\t\t\t\t// Used to compare non-integer variables to 0\n\n// Data types\ntypedef struct{\n\tdouble mass;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Mass of the field\n\tdouble lambda;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Field-colloid coupling strength\n\tdouble quartic_u;\t\t\t\t\t\t\t\t\t\t\t\t\t// Self-interaction coupling strength\n\tdouble temperature;\t\t\t\t\t\t\t\t\t\t\t\t\t// Temperature of the common bath\n\tdouble relativeD;\t\t\t\t\t\t\t\t\t\t\t\t\t// Ratio of colloid to field mobility (it's basically \\nu of the particle)\n\tdouble trap_strength;\t\t\t\t\t\t\t\t\t\t\t\t// Stiffness of the harmonic trap\n\tint rng_seed;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Seed for random number generator\n\tint system_size;\t\t\t\t\t\t\t\t\t\t\t\t\t// Side of the DIM-dimensional lattice\n\tdouble delta_t;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Time-discretization step\n\tlong n_timestep;\t\t\t\t\t\t\t\t\t\t\t\t\t// Number of timesteps\n\tint mc_runs;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Number of Monte Carlo iterations\n\tdouble R;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Size of colloid in lattice units\n\tdouble X0;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Initial displacement of the colloid\n} parameter;\n\ntypedef struct{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// This structure bundles all observables \n\tdouble** field_average;\t\t\t\t\t\t\t\t\t\t\t\t// Saves the measured field-average <phi[i]> for certain subset of i's (eg along an axis) AND at all writing times\n\tdouble** field_correlation;\t\t\t\t\t\t\t\t\t\t\t// Saves the measured field-correlator < phi[0] phi[i]> for certain subset of i's (eg along an axis) AND at all writing times\n\tdouble* colloid_pos;\t\t\t\t\t\t\t\t\t\t\t\t// Saves the measured displacement of the colloid at all writing times\n\tdouble* colloid_msd;\t\t\t\t\t\t\t\t\t\t\t\t// Saves the measured mean square displacement of the colloid at all writing times\n\tdouble write_time_delta;\t\t\t\t\t\t\t\t\t\t\t// This is the gap between writing times (at the moment linear, maybe later exponential writing times?) \n\tint write_count;\n//\tdouble* colloid_fpt_distribution;\t\t\t\t\t\t\t\t\t// Saves the first-passage time distribution of the colloid\n} observables;\n\n// Global variables\nint DIM = 1;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Physical dimensions\nint MOD = 2;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// 0 for Model A, 2 for Model B\nint top;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Actual number of sites within 5R around a single site\ndouble gauss_norm;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Normalization constant of Gaussian functions\nconst gsl_rng_type *T;\t\t\t\t\t\t\t\t\t\t\t\t\t// GSL RNG (it turns out Ziggurat is faster than Box-Muller)\ngsl_rng *seed;\n\n\n// FUNCTION PROTOTYPES\n\nvoid default_parameters(parameter*);\nvoid initialise(long***, parameter*, long***);\nvoid initialise_observable(observables*, parameter*);\nvoid wipe(double**, double**, parameter*);\nvoid prethermalize(double**, parameter*);\nvoid field_prepare(double**, parameter*);\nvoid evolveB(double**, double**, long**, parameter*, observables*, long**);\nvoid evolveA(double**, double**, long**, parameter*, observables*, long**);\nvoid laplacian(double**, double*, long**, long);\nvoid laplacian_of_cube(double**, double*, long**, long);\nvoid generate_noise_field(double**, long, parameter*);\nvoid gradient_field(double**, double*, long**, long);\nvoid phi_evolveB(double**, double*, double*, double*, double*, long, parameter*, double*, long**);\nvoid phi_evolveA(double**, double*, double*, long, parameter*, double*, long**);\nvoid measure(double**, double**, long, parameter*, observables*);\nvoid print_observables(observables*, parameter*);\nvoid print_trajectory(observables*, parameter*);\nvoid print_params(parameter*);\nvoid printhelp(parameter*);\nvoid print_source(void);\nvoid neighborhood(long***, int);\nint ind2coord(int, int, int);\nint vec2ind(int*, int);\nvoid ind2vecROW(int**, int, int, int);\nint closest_site(double*, int);\ndouble distance(double*, int, int);\nunsigned modulo(int, unsigned);\ndouble modular(double, double, double);\nint factorial(int);\nint double_factorial(int);\nint intpow(int, int);\ndouble floatpow(double, int);\nvoid print_lookup(long **, int, int);\ndouble gaussian(double, double);\ndouble laplacian_gaussian(double, double);\nvoid evolve_quenched(double**, double**, parameter*, observables*, long**);\n\n\n// MAIN BODY\n\nint main(int argc, char *argv[]){\n\tsetlinebuf(stdout);\n\t\n\t// INPUT PARAMETERS\n\tparameter params;\n\tdefault_parameters(&params);\n\n\topterr = 0;\n\tint c = 0;\n\t// ./colloid -r 2 -L 23 (order doesn't count)\n    while( (c = getopt (argc, argv, \"L:r:l:u:T:d:k:S:t:N:M:n:m:R:X:hP\") ) != -1){\n    \tswitch(c){\n\t\t\tcase 'L':\n\t\t\t\tparams.system_size = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'r':\n\t\t\t\tparams.mass = atof(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'l':\n\t\t\t\tparams.lambda = atof(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'u':\n\t\t\t\tparams.quartic_u = atof(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'T':\n\t\t\t\tparams.temperature = atof(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'n':\n\t\t\t\tparams.relativeD = atof(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'k':\n\t\t\t\tparams.trap_strength = atof(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'S':\n\t\t\t\tparams.rng_seed = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\tparams.delta_t = atof(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'N':\n\t\t\t\tparams.n_timestep = atol(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'M':\n\t\t\t\tparams.mc_runs = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tDIM = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tMOD = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'R':\n\t\t\t\tparams.R = atof(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'X':\n\t\t\t\tparams.X0 = atof(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'P':\n\t\t\t\tprint_source();\n\t\t\t\texit(2);\n\t\t\tcase 'h':\n\t\t\t\tprinthelp(&params);\n\t\t\t\texit(2);\n\t\t\tdefault:\n\t\t\t\tprinthelp(&params);\n                exit(EXIT_FAILURE);\n       }\n\t}\n\t\n\t// VARIABLES, ALLOCATION\n\tint i, j;\n\tlong L = params.system_size;\n\tlong n_sites = intpow(L, DIM);\n\tint max_within_5R;\n\tdouble prefactor[3] = {2,M_PI,4.0/3*M_PI};\n\tif(DIM<4) max_within_5R = (int) ceil( prefactor[DIM-1]*floatpow(ceil(5*params.R), DIM) ) + 2;\n\telse max_within_5R=10000;\t\t\t\t\t\t\t\t\t\t\t// Overkill, maybe I'll generalize it one day\n\t\n\tdouble* phi; \t\t\t\t\t\t\t\t\t\t\t\t\t\t// Field on lattice NxNxN\n\tdouble* y_colloid; \t\t\t\t\t\t\t\t\t\t\t\t\t// Colloid position (DIM real numbers)\n\tlong** neighbours; \t\t\t\t\t\t\t\t\t\t\t\t\t// i x j - table with j neighbours of site i\n\tlong** mosaic;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Table with neighbours of site i with distance < 4R\n\t\n\tALLOC(phi, n_sites);\n\tCALLOC(y_colloid, DIM);\n\tALLOC(neighbours, n_sites);\n\tALLOC(mosaic, n_sites);\n\t\n\tfor(i = 0; i < n_sites; i++){\n\t\tneighbours[i]=calloc( 2 * DIM , sizeof(long)); \t\t\t\t\t// At each index there are 2*D neighbours\n\t\tif( neighbours[i] == NULL){printf(\"Allocation of neighbour list failed. Terminate. \\n\"); exit(2);}\n\t\tmosaic[i]=calloc( max_within_5R , sizeof(long)); \t\t\t\t// At each index, all the sites within 5R\n\t\tif( mosaic[i] == NULL){printf(\"Allocation of mosaic list failed. Terminate. \\n\"); exit(2);}\n\t}\t\t\n\n\t// INITIALIZATION\n\tinitialise(&neighbours, &params, &mosaic);\t\t\t\t\t\t\t// Random function, nearest neighbours list, mosaic\n\tobservables obvs;\t\t\t\t\t\t\t\t\t\t\t\t\t// Creates a pointer to an observables structure\n\tinitialise_observable(&obvs, &params);\t\t\t\t\t\t\t\t// Initialise observables\n\tprint_params(&params);   \t\t\t\t\t\t\t\t\t\t\t// Print header with all parameters\n\tgauss_norm = 1/(pow(2*M_PI,DIM*0.5) * floatpow(params.R,DIM));\t\t// Normalization for Gaussian functions\n\n\tprintf(\"# Max within 5R: %d\\n\", max_within_5R);\n\tprintf(\"# Actual within 5R: %d\\n\", top);\n\t//print_lookup(neighbours, n_sites, 2*DIM);\t\t\t\t\t\t\t// Prints nearest-neighbours list\n\t//print_lookup(mosaic, n_sites, top);\t\t\t\t\t\t\t\t// Prints cell-list\n\n\t// MC ITERATION\n\tint mc_counter, flag;\t\n\tprintf(\"\\n# MC ITERATION BEGINS\\n\");\n\t\t\n\tfor(mc_counter = 0; mc_counter < params.mc_runs; mc_counter++){\n\t\t//wipe(&phi, &y_colloid, &params); \t\t\t\t\t\t\t\t// Reset field and colloid to initial conditions\n\t\tprethermalize(&phi, &params);\t\t\t\t\t\t\t\t\t// Pre-thermalization cycle\n\t\t//field_prepare(&phi, &params);\t\n\t\tfor(j=0; j<DIM; j++) y_colloid[j] = L/2;\t\t\t\t\t\t// Colloid initially in the middle of the trap\n\t\ty_colloid[0] = (L/2)+params.X0;\t\t\t\t\t\t\t\t\t// Add initial displacement in one direction\t\t\t\t\n\t\t\n\t\t// Numerical integration of the dynamics\n\n\t\tif(MOD==0){\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Model A\n\t\t\tevolveA(&phi, &y_colloid, neighbours, &params, &obvs, mosaic);\n\t\t} else if(MOD==2){\t\t\t\t\t\t\t\t\t\t\t\t// Model B\n\t\t\tevolveB(&phi, &y_colloid, neighbours, &params, &obvs, mosaic);\n\t\t} else if(MOD==1){\t\t\t\t\t\t\t\t\t\t\t\t// Evolution in a quenched potential\n\t\t\tevolve_quenched(&phi, &y_colloid, &params, &obvs, mosaic);\n\t\t} else {\n\t\t\tprinthelp(&params);\n            exit(EXIT_FAILURE);\n\t\t}\n\t\t\n\t\tflag = params.mc_runs/10;\t\t\t\t\t\t\t\t\t\t// Prints completing percentage\n\t\tif( flag !=0 && ((mc_counter +1)%flag) == 0 ) printf(\"# MC PROGRESS %d%%\\n\", (mc_counter +1)/flag*10);\n\t}\n\t\n\t//print_observables(&obvs, &params);\n\tprint_trajectory(&obvs, &params);\n\t\n\t// Free memory and exit\n\tfree(phi);\n\tfree(y_colloid);\n\tfor(i=0; i<n_sites; i++) free(neighbours[i]);\n\tfor(i=0; i<n_sites; i++) free(mosaic[i]);\n\tfree(obvs.colloid_pos);\t\t\t\t\t\t\t\t\t\t\t\t// Add any other observable you are storing\n\treturn 0;\n}\n\n\n// DEFINITION OF FUNCTIONS\n\n// Default parameters\nvoid default_parameters(parameter* params){\n\tparams->mass = 0.0;\n\tparams->lambda = 0.25;\n\tparams->quartic_u = 0.0;\n\tparams->temperature = 0.001;\n\tparams->relativeD = 1.0;\n\tparams->trap_strength = 0.1;\n\tparams->rng_seed = -1; \t\t\t\t\t\t\t\t\t\t\t\t// if seed is -1 (not given by user), it will be picked randomly\n\tparams->system_size = 128;\n\tparams->delta_t = 0.01;\n\tparams->n_timestep = 100000;\n\tparams->mc_runs = 10000;\n\tparams->R = 1;\n\tparams->X0 = 2;\n}\n\n// All that needs to be done once\nvoid initialise(long*** neighbours, parameter* params, long*** mosaic){\n\t// i) GSL random number generator setup\n\tgsl_rng_env_setup();\n    T = gsl_rng_default;\n    seed = gsl_rng_alloc (T);\t\t\t\t\t\t\t\t\t\t\t// This is probably not really a seed, but sticazzi\n    time_t t;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// If no seed provided, draw a random one\n    if(params->rng_seed==-1) params->rng_seed = (unsigned) time(&t) % 100000; \n    gsl_rng_set(seed, params->rng_seed);\n\t\n\t// ii) What are each position's neighbours?\n\tlong L = params->system_size;\n\tneighborhood(neighbours, L);\n\t\n\t// iii) Initialize the mosaic\n\tdouble dist;\n\tlong n_sites = intpow(L, DIM);\n\tint i, j, d;\n\tfor(i=0; i<n_sites; i++){\n\t\ttop=0;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Number of sites within 5R around a given site (global variable)\n\t\tfor(j=0; j<n_sites; j++){\n\t\t\tdist=0;\n\t\t\tfor(d=0; d<DIM; d++) dist += floatpow( modular( ind2coord(d,i,L), ind2coord(d,j,L), L) , 2);\n\t\t\tdist = sqrt(dist);\n\t\t\tif(dist < ceil(5*params->R) + EPS ){\n\t\t\t\t(*mosaic)[i][top]=j;\n\t\t\t\ttop++;\n\t\t\t}\n\t\t}\n\t}\t\t\t\t\t\t\t\t\n}\n\n// Reset field and colloid to initial conditions\nvoid wipe(double** phi, double** y_colloid, parameter* params)\n{\n\tint n_sites, i;\n\tn_sites = intpow(params->system_size, DIM);\n\tfor(i = 0; i < n_sites; i++){ \n\t\t //(*phi)[i] = gsl_ran_gaussian_ziggurat(seed,1.0);\t\t\t\t// Infinite temperature state\n\t\t (*phi)[i] = 0;\t\t\t\t\t\t\t\t\t\t\t\t\t// Initially flat field - default after calloc()\n\t\t //(*phi)[i] = (i % 2 ? 1 : -1);\t\t\t\t\t\t\t\t// Staggered\n\t}\n\t\n\t// y - colloid (initially in the middle of the lattice, where the harmonic well stands)\n\tlong L = params->system_size;\n\tfor(i=0; i<DIM; i++) (*y_colloid)[i] = L/2;\n}\n\n// This initialises the observables structure later containing the measurements\nvoid initialise_observable(observables* obvs, parameter* params)\n{\n\tobvs->write_time_delta = 0.2; \t\t\t\t\t\t\t\t\t\t// This is in physical time units, so writing occurs every (write_time_delta / n_timestep) integration step\n\t\n\t// This counts how many writing events will occur in time (including t=0, thus + 1). If you choose exp distributed measurements, it still works (but it's overestimated).\n\tint writing_times = (int)(1 + (((params->n_timestep)*params->delta_t)/obvs->write_time_delta)); \n\n\t//CALLOC(obvs->colloid_msd, writing_times); \t\t\t\t\t\t// Save MSD vs time\n\tCALLOC(obvs->colloid_pos, writing_times); \t\t\t\t\t\t\t// Save position vs time\n\t\n\t/*\n\t// FIELD MEASUREMENTS ONLY\n\tCALLOC(obvs->field_average, writing_times); \t\t\t\t\t\t// Prepare writing_times many arrays to store averages\n\t//CALLOC(obvs->field_correlation, writing_times); \t\t\t\t\t// Prepare writing_times many arrays to store correlations\n\tint i;\n\tfor(i = 0; i < writing_times; i++)\n\t{\n\t\t//obvs->field_correlation[i] = calloc( params->system_size , sizeof(double) );\n\t\t//if( (obvs->field_correlation[i]) == NULL){printf(\"Allocation of '(obvs->field_correlation[%i])'  failed. Terminate. \\n\", i); exit(2);} \n\t\tobvs->field_average[i] = calloc( params->system_size , sizeof(double) );\n\t\tif( (obvs->field_average[i]) == NULL){\n\t\t\tprintf(\"Allocation of '(obvs->field_average[%i])'  failed. Terminate. \\n\", i); \n\t\t\texit(2);\n\t\t} \n\t}\n\t*/\n}\n\n// Perform measurements and print them out\nvoid measure(double** phi, double** y_colloid, long tstep, parameter* params, observables* obvs){\n\tlong i;\n\tprintf(\"%g\\t\", tstep*params->delta_t);\n\tfor(i = 0; i < params->system_size; i++){\n\t\tobvs->field_average[obvs->write_count][i] += (*phi)[i];\n\t\tobvs->field_correlation[obvs->write_count][i] += ((*phi)[0] * (*phi)[i]);\n\t}\t\n\t\n\tlong n_sites = intpow(params->system_size , DIM);\n\tfor(i = 0; i < DIM; i++){\n\t\tobvs->colloid_msd[obvs->write_count] += ((*y_colloid)[i] - ind2coord(i, n_sites/2 , params->system_size))*((*y_colloid)[i] - ind2coord(i, n_sites/2 , params->system_size));\n\t}\n\t//printf(\"\\n\");\n}\n\n// Creates list of nearest neighbours in DIM dimensions\nvoid neighborhood(long*** list, int L){\n\tint k,d;\n\tint vec[DIM], neigh[DIM];\n\n\tfor(k=0; k<intpow(L,DIM); k++){\t\t\t\t\t\t\t\t\t\t// Cycles over lattice sites\n\t\tfor(d=0; d<DIM; d++){\t\t\t\t\t\t\t\t\t\t\t// Finds the DIM coordinates of the current site\n\t\t\tvec[d] = ind2coord(d,k,L);\n\t\t\tneigh[d] = vec[d];\n\t\t}\n\t\tfor(d=0; d<DIM; d++){\n\t\t\tneigh[d] = (vec[d]+1)%L;\t\t\t\t\t\t\t\t\t// Finds right neighbour\n\t\t\t(*list)[k][2*d] = vec2ind(neigh,L);\t\t\t\t\t\t\t// Stores it in the neighbour list\n\t\t\tneigh[d] = (vec[d]+L-1)%L;\t\t\t\t\t\t\t\t\t// Finds left neighbour\n\t\t\t(*list)[k][2*d+1] = vec2ind(neigh,L);\t\t\t\t\t\t// Stores it in the neighbour list\n\t\t\tneigh[d] = vec[d];\t\t\t\t\t\t\t\t\t\t\t// Restores local copy (prepares for next dimension)\n\t\t}\n\t}\n}\n\n// Pre-thermalization of the field\nvoid prethermalize(double** phi, parameter* params){\n\t// Benjamin: 20/08/21, spectral thermalisation\n\t// \\phi_k are complex normal random variables with <\\phi_k> = 0, < |\\phi_k|^2> = k_B T*(k^2+r)^-1, and \\phi_k = \\phi^*_{-k}\n\t// Using FFTW library, -lfftw3\n\tfftw_complex *phi_fourier;\n\tfftw_plan p;\n\n\tint n_sites = intpow(params->system_size, DIM);\n\tint i, j;\n\t\n\tphi_fourier = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (n_sites/2 + 1)); // complex Hermitian array\n\tint *vec = malloc(DIM * sizeof(int));\n\t/* fill with random data */\n\tdouble inverse_variance, variance;\n\tdouble inv_L_square = (39.438/pow(((double) params->system_size), 2)); //(2\\pi /L)^2\n\tdouble radius;\n\tdouble polar_angle;\n\n\tint centre = (n_sites/2);\n\tfor(i = centre; i >=0 ; i--) // Fill half the reciprocal lattice without the zero mode first. The first entry is at the centre of the reciprocal lattice and therefore the zero mode (~ k_BT/r)\n\t{\n\t\t// What's the L2 norm of the reciprocal vector?\n\t\tinverse_variance = params->mass;\n\t\tind2vecROW(&vec, i, DIM, params->system_size);\n\t\tfor(j = 0; j < DIM; j++)\n\t\t{\n\t\t\tinverse_variance += inv_L_square*(vec[j]*vec[j]);\n\t\t}\n\t\tvariance = (params->temperature/inverse_variance); // k_B T /(q^2 + r)\n\n\t\tif(inverse_variance > 0){\n\t\t\tradius = gsl_ran_gaussian_ziggurat(seed, sqrt(variance)); \n\t\t\tpolar_angle =  gsl_ran_flat(seed, 0, 6.2831); // pick random angle\n\t\t\n\t\t\tphi_fourier[centre-i][0] = radius*cos(polar_angle);\n\t\t\tphi_fourier[centre-i][1] = radius*sin(polar_angle);\n\t\t}\n\t\telse{ // Critical mode is force set to zero\n\t\t\tphi_fourier[centre-i][0] = 0.0;\n\t\t\tphi_fourier[centre-i][1] = 0.0;\n\t\t}\n\t}\n\t\n\t// _c2r transforms a half-complex array into real fft http://www.fftw.org/fftw3_doc/Real_002ddata-DFTs.html\n\tint lattice_dimensions[DIM];\n\tfor(i = 0; i < DIM; i++){lattice_dimensions[i] = ((int) params->system_size);} //It's a cube\n\t\n\tdouble* phi_real;\n \tphi_real = (double*)fftw_malloc(n_sites * sizeof(double));\n\n\t// http://www.fftw.org/fftw3_doc/Real_002ddata-DFTs.html\n\t//fftw_plan fftw_plan_dft_c2r(int rank, const int *n, fftw_complex *in, double *out, unsigned flags);\n\tp = fftw_plan_dft_c2r(DIM, lattice_dimensions, phi_fourier, phi_real,  FFTW_ESTIMATE);\n\tif(p == NULL){printf(\"fftw plan didn't work\\n\");}\n\tfftw_execute(p); \n\t\n\t// normalising inverse transform with V^(-d/2), ass fftw3 doesn't do that.\n\tdouble normalising_volume = (1.0/(((double) n_sites))); \n\n\t// Now transform rowmajor phi_real into col_major *phi -> matrix transpose\n\t/* Only for D > 1\n\t * int row_maj_index, col_maj_index, dir;\n\tfor(row_maj_index = 0; row_maj_index < n_sites; row_maj_index++)\n\t{\n\t\tfor(dir = 0; dir < DIM; dir++)\n\t\t{\n\t\t\tvec[dir] = ((int) (row_maj_index / intpow(params->system_size, (DIM - dir -1))) % params->system_size);\n\t\t}\n\t       \tcol_maj_index = vec2ind(vec, params->system_size);\n\t\tif(row_maj_ind\n\t\tprintf(\"RM %i CM %i | phi_real: %g\\n\", row_maj_index, col_maj_index, phi_real[row_maj_index]);\n\t\t(*phi)[col_maj_index] = phi_real[row_maj_index]; \n\t}*/\n\n\t// For D = 1\n\t// Shift origin to centre\n\tfor(i = 0; i <= centre; i++) (*phi)[i] = normalising_volume*phi_real[centre-i];\n\tfor(i = centre+1; i < n_sites; i++) (*phi)[i] = normalising_volume*phi_real[n_sites+centre-i];\n\t\n    fftw_free(phi_fourier); \n    fftw_free(phi_real); \n\tfftw_destroy_plan(p);\n}\n\n\n// Preparation of the field in equilibrium at T=0 around X0 \n// 1d only at the moment. It can probably be generalized to finite T by adding noise later on.\nvoid field_prepare(double** phi, parameter* params){\n\t// Spectral initialization using FFTW library, -lfftw3\n\t// \\phi_k are complex normal random variables with <\\phi_k> = 0, < |\\phi_k|^2> = k_B T*(k^2+r)^-1, and \\phi_k = \\phi^*_{-k}\n\tfftw_complex *phi_fourier;\n\tfftw_plan p;\n\n\tint n_sites = intpow(params->system_size, DIM);\n\tint i, j;\n\t\n\tphi_fourier = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (n_sites/2 + 1)); // complex Hermitian array\n\tint *vec = malloc(DIM * sizeof(int));\n\t/* fill with random data */\n\t//double inverse_variance, variance;\n\tdouble inverse_variance;\n\tdouble inv_L = 6.28318530718/params->system_size;\t\t\t\t\t\t\t\t\t// 2pi/L\t\t\t\n\tdouble inv_L_square = (39.438/intpow(params->system_size, 2)); \t\t\t\t\t\t// (2\\pi /L)^2\n\tdouble radius;\n\tdouble polar_angle;\n\n\tint centre = (n_sites/2);\n\tfor(i = centre; i >=0 ; i--) // Fill half the reciprocal lattice without the zero mode first. The first entry is at the centre of the reciprocal lattice and therefore the zero mode (~ k_BT/r)\n\t{\n\t\t// What's the L2 norm of the reciprocal vector?\n\t\tinverse_variance = params->mass;\n\t\tind2vecROW(&vec, i, DIM, params->system_size);\n\t\tfor(j = 0; j < DIM; j++)\n\t\t{\n\t\t\tinverse_variance += inv_L_square*(vec[j]*vec[j]);\n\t\t}\n\t\t//variance = (params->temperature/inverse_variance); // k_B T /(q^2 + r)\n\t\tradius = params->lambda * exp(- floatpow(params->R,2)*(inverse_variance - params->mass)/2) /inverse_variance ; // l* exp(-q^2 R^2/2) / (q^2 + r)\n\n\t\tif(inverse_variance > 0){\n\t\t\t//radius = gsl_ran_gaussian_ziggurat(seed, sqrt(variance)); \n\t\t\t//polar_angle =  gsl_ran_flat(seed, 0, 6.2831); \t\t\t\t\t\t\t// pick random angle\n\t\t\tpolar_angle = - inv_L * vec[j] * (params->system_size/2+params->X0);\t\t// Careful if you ever generalize to higher dimensions\n\t\t\n\t\t\tphi_fourier[centre-i][0] = radius*cos(polar_angle);\n\t\t\tphi_fourier[centre-i][1] = radius*sin(polar_angle);\n\t\t}\n\t\telse{ // Critical mode is force set to zero\n\t\t\tphi_fourier[centre-i][0] = 0.0;\n\t\t\tphi_fourier[centre-i][1] = 0.0;\n\t\t}\n\t}\n\n\t// _c2r transforms a half-complex array into real fft http://www.fftw.org/fftw3_doc/Real_002ddata-DFTs.html\n\tint lattice_dimensions[DIM];\n\tfor(i = 0; i < DIM; i++){lattice_dimensions[i] = ((int) params->system_size);} //It's a cube\n\t\n\tdouble* phi_real;\n \tphi_real = (double*)fftw_malloc(n_sites * sizeof(double));\n\n\t// http://www.fftw.org/fftw3_doc/Real_002ddata-DFTs.html\n\t//fftw_plan fftw_plan_dft_c2r(int rank, const int *n, fftw_complex *in, double *out, unsigned flags);\n\tp = fftw_plan_dft_c2r(DIM, lattice_dimensions, phi_fourier, phi_real,  FFTW_ESTIMATE);\n\tif(p == NULL){printf(\"fftw plan didn't work\\n\");}\n\tfftw_execute(p); \n\t\n\t// normalising inverse transform with V^(-d/2), ass fftw3 doesn't do that.\n\tdouble normalising_volume = (1.0/(((double) n_sites))); \n\n\t// Now transform rowmajor phi_real into col_major *phi -> matrix transpose\n\t/* Only for D > 1\n\t * int row_maj_index, col_maj_index, dir;\n\tfor(row_maj_index = 0; row_maj_index < n_sites; row_maj_index++)\n\t{\n\t\tfor(dir = 0; dir < DIM; dir++)\n\t\t{\n\t\t\tvec[dir] = ((int) (row_maj_index / intpow(params->system_size, (DIM - dir -1))) % params->system_size);\n\t\t}\n\t       \tcol_maj_index = vec2ind(vec, params->system_size);\n\t\tif(row_maj_ind\n\t\tprintf(\"RM %i CM %i | phi_real: %g\\n\", row_maj_index, col_maj_index, phi_real[row_maj_index]);\n\t\t(*phi)[col_maj_index] = phi_real[row_maj_index]; \n\t}*/\n\n\t// For D = 1\n\t// Shift origin to centre\n\tfor(i = 0; i <= centre; i++) (*phi)[i] = normalising_volume*phi_real[centre-i];\n\tfor(i = centre+1; i < n_sites; i++) (*phi)[i] = normalising_volume*phi_real[n_sites+centre-i];\n\n    fftw_free(phi_fourier); \n    fftw_free(phi_real); \n\tfftw_destroy_plan(p);\n}\n\n// Evolution - colloid only (quenched potential)\nvoid evolve_quenched(double** phi, double** y_colloid, parameter* params, observables* obvs, long** mosaic){\n\t// Preparing variables for field evolution (Euler-Maruyama)\n\tlong tstep, n_timestep;\n\tn_timestep = params->n_timestep;\n\t\n\t// Preparing variables for colloid evolution (Stochastic Runge-Kutta II)\n\tint i, j, y_site;\n\tdouble grad, noise, F2, r, weight;\t\n\tdouble w[DIM], F1[DIM], Y[DIM];\n\tlong L = params->system_size;\n\tdouble noise_intensity = sqrt(2.0 * params->temperature * params->relativeD * params->delta_t);\n\tfor(j=0; j<DIM; j++) w[j] = L/2;\t\t\t\t\t\t\t\t\t\t\t\t// Finds position of the harmonic well\n\t\n\t// Preparing measurement process\n\tint write_time_delta_step = (int) ((obvs->write_time_delta)/(params->delta_t));\n\tint next_writing_step = 0;\n\tobvs->write_count = 0;\n\t\n\tfor(tstep = 0; tstep < n_timestep; tstep++){\t\t\t\t\t\t\t\t\t// Time evolution\n\t\n\t\t// MEASUREMENT\n\t\tif(tstep == next_writing_step){\n\t\t\tobvs->colloid_pos[obvs->write_count] += (*y_colloid)[0];\t\t\t\t// Save colloid position\n\t\t\t//obvs->colloid_msd[obvs->write_count] += (*y_colloid)[1];\t\t\t\t// Save colloid position of 2nd coordinate\n\t\t\tnext_writing_step += write_time_delta_step;\t\t\t\t\t\t\t\t// Linearly distributed\n\t\t\tobvs->write_count++;\n\t\t}\n\t\t\n\t\t// EVOLUTION\n\n\t\t// i) Create local copy of the colloid variable\n\t\tfor(i=0; i<DIM; i++) Y[i] = (*y_colloid)[i];\t\n\t\t\n\t\t// ii) Prediction step for the colloid\n\t\ty_site = closest_site(Y,L);\t\t\t\t\t\t\t\t\t\t\t\t\t// Finds the lattice site closest to Y\n\t\t\n\t\tfor(i=0; i<DIM; i++){ \t\t\t\t\t\t\t\t\t\t\t\t\t\t// Evolves each of the components separately\n\t\t\t// Compute gradient of the field under the colloid\n\t\t\tgrad = 0;\n\t\t\tfor(j=0; j<top; j++){\n\t\t\t\tr = distance(Y, mosaic[y_site][j], L);\n\t\t\t\tweight = gaussian(r,params->R);\n\t\t\t\tgrad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;\n\t\t\t}\n\t\t\t\n\t\t\t// Compute temporary position\n\t\t\tnoise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);\n\t\t\tF1[i] =  params->relativeD * (params->lambda*grad -params->trap_strength*( Y[i]-w[i] ));\n\t\t\t(*y_colloid)[i] += params->delta_t * F1[i] + noise;\n\t\t}\n\n\t\t// iv) Correction step for the colloid (with the evolved field)\n\t\ty_site = closest_site(*y_colloid,L);\t\t\t\t\t\t\t\t\t\t// Compute new site of the colloid\n\t\t\n\t\tfor(i=0; i< DIM; i++){\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Evolve each of the components separately\n\t\t\t// Compute new gradient\n\t\t\tgrad = 0;\n\t\t\tfor(j=0; j<top; j++){\n\t\t\t\tr = distance(*y_colloid, mosaic[y_site][j], L);\n\t\t\t\tweight = gaussian(r,params->R);\n\t\t\t\tgrad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;\n\t\t\t}\n\t\t\t\n\t\t\t// Compute corrected contribution\n\t\t\tF2 = params->relativeD * ( params->lambda*grad -params->trap_strength*( (*y_colloid)[i]-w[i] ) );\n\t\t\t\n\t\t\t// Sum the two contributions: y_n+1 = y_n + 1/2(F1+F2)*dt + noise\n\t\t\tnoise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);\n\t\t\t(*y_colloid)[i] = Y[i] + 0.5*(F1[i]+F2)*params->delta_t + noise;\n\t\t}\n\t}\n}\n\n// Model B evolution\nvoid evolveB(double** phi, double** y_colloid, long** neighbours, parameter* params, observables* obvs, long** mosaic){\n\t// Preparing variables for field evolution (Euler-Maruyama)\n\tlong tstep, n_sites, n_timestep;\n\tn_sites = intpow(params->system_size, DIM);\n\tn_timestep = params->n_timestep;\n\t\n\t// TODO it's a terrible idea to allocate memory here, because this function is called M times\n\tdouble* laplacian_phi;\n\tALLOC(laplacian_phi, n_sites);\n\tdouble* laplacian_square_phi;\n\tALLOC(laplacian_square_phi, n_sites);\n\tdouble* laplacian_phi_cubed;\n\tCALLOC(laplacian_phi_cubed, n_sites);\n\tdouble* noise_field;\n\tCALLOC(noise_field, DIM * n_sites);\n\tdouble* noise_gradient;\n\tCALLOC(noise_gradient, n_sites);\n\t\n\t// Preparing variables for colloid evolution (Stochastic Runge-Kutta II)\n\tint i, j, y_site;\n\tdouble grad, noise, F2, r, weight;\t\n\tdouble w[DIM], F1[DIM], Y[DIM];\n\tlong L = params->system_size;\n\tdouble noise_intensity = sqrt(2.0 * params->temperature * params->relativeD * params->delta_t);\n\tfor(j=0; j<DIM; j++) w[j] = L/2;\t\t\t\t\t\t\t\t\t\t\t\t// Finds position of the harmonic well\n\t\n\t// Preparing measurement process\n\tint write_time_delta_step = (int) ((obvs->write_time_delta)/(params->delta_t));\n\tint next_writing_step = 0;\n\tobvs->write_count = 0;\n\t\n\tfor(tstep = 0; tstep < n_timestep; tstep++){\t\t\t\t\t\t\t\t\t// Time evolution\n\t\n\t\t// MEASUREMENT\n\t\t\n\t\tif(tstep == next_writing_step){\n\t\t\t//measure(phi, y_colloid, tstep, params, obvs); \t\t\t\t\t\t// Evaluate all sorts of correlators etc. here\n\t\t\t//for(i = 0; i < params->system_size; i++) obvs->field_average[obvs->write_count][i] += (*phi)[i]; // Save field average\n\t\t\tobvs->colloid_pos[obvs->write_count] += (*y_colloid)[0];\t\t\t\t// Save colloid position\n\t\t\t//obvs->colloid_msd[obvs->write_count] += (*y_colloid)[1];\t\t\t\t// Save colloid position of 2nd coordinate\n\t\t\tnext_writing_step += write_time_delta_step;\t\t\t\t\t\t\t\t// Linearly distributed\n\t\t\tobvs->write_count++;\n\t\t}\n\t\t\n\t\t// EVOLUTION\n\n\t\t// i) Create local copy of the colloid variable\n\t\tfor(i=0; i<DIM; i++) Y[i] = (*y_colloid)[i];\t\n\t\t\n\t\t// ii) Prediction step for the colloid\n\t\ty_site = closest_site(Y,L);\t\t\t\t\t\t\t\t\t\t\t\t\t// Finds the lattice site closest to Y\n\t\t\n\t\tfor(i=0; i<DIM; i++){ \t\t\t\t\t\t\t\t\t\t\t\t\t\t// Evolves each of the components separately\n\t\t\t// Compute gradient of the field under the colloid\n\t\t\tgrad = 0;\n\t\t\tfor(j=0; j<top; j++){\n\t\t\t\tr = distance(Y, mosaic[y_site][j], L);\n\t\t\t\tweight = gaussian(r,params->R);\n\t\t\t\tgrad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;\n\t\t\t}\n\t\t\t\n\t\t\t// Compute temporary position\n\t\t\tnoise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);\n\t\t\tF1[i] =  params->relativeD * (params->lambda*grad -params->trap_strength*( Y[i]-w[i] ));\n\t\t\t(*y_colloid)[i] += params->delta_t * F1[i] + noise;\n\t\t}\n\t\t\n\t\t// iii) Evolve the field with the local copy of the colloid position\n\t\tlaplacian(&laplacian_phi, *phi, neighbours, n_sites);\t\t\t\t\t\t// Write Laplacian of phi into laplacian_phi\n\t\tlaplacian(&laplacian_square_phi, laplacian_phi, neighbours, n_sites);\t\t// Write (D^2)^2 phi into laplacian_square_phi\n\t\tif(params->quartic_u > EPS){\n\t\t\tlaplacian_of_cube(&laplacian_phi_cubed, *phi, neighbours, n_sites);\t\t// Write D2 [phi(x)^3] into laplacian_phi_cubed\n\t\t}\n\t\tif(params->temperature > EPS){\n\t\t\tgenerate_noise_field(&noise_field, DIM*n_sites, params);\t\t\t\t// Fill \\vec{Lambda} with randomness\n\t\t\tgradient_field(&noise_gradient, noise_field, neighbours, n_sites);\t\t// Compute gradient noise term\n\t\t}\t\n\n\t\t// Add together to new step d/dt phi = -a * D2 phi - b D4 phi - u D2 (phi^3) + D * noise (D is nabla)\n\t\tphi_evolveB(phi, laplacian_phi, laplacian_square_phi, laplacian_phi_cubed, noise_gradient, n_sites, params, Y, mosaic);\n\n\t\t// iv) Correction step for the colloid (with the evolved field)\n\t\ty_site = closest_site(*y_colloid,L);\t\t\t\t\t\t\t\t\t\t// Compute new site of the colloid\n\t\t\n\t\tfor(i=0; i< DIM; i++){\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Evolve each of the components separately\n\t\t\t// Compute new gradient\n\t\t\tgrad = 0;\n\t\t\tfor(j=0; j<top; j++){\n\t\t\t\tr = distance(*y_colloid, mosaic[y_site][j], L);\n\t\t\t\tweight = gaussian(r,params->R);\n\t\t\t\tgrad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;\n\t\t\t}\n\t\t\t\n\t\t\t// Compute corrected contribution\n\t\t\tF2 = params->relativeD * ( params->lambda*grad -params->trap_strength*( (*y_colloid)[i]-w[i] ) );\n\t\t\t\n\t\t\t// Sum the two contributions: y_n+1 = y_n + 1/2(F1+F2)*dt + noise\n\t\t\tnoise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);\n\t\t\t(*y_colloid)[i] = Y[i] + 0.5*(F1[i]+F2)*params->delta_t + noise;\n\t\t}\n\t}\n\t\n\t// Free memory\n\tfree(laplacian_phi);\n\tfree(laplacian_square_phi);\n\tfree(laplacian_phi_cubed);\n\tfree(noise_field);\n\tfree(noise_gradient);\n}\n\n// Model A evolution\nvoid evolveA(double** phi, double** y_colloid, long** neighbours, parameter* params, observables* obvs, long** mosaic){\n\t// Preparing variables for field evolution (Euler-Maruyama)\n\tlong tstep, n_sites, n_timestep;\n\tn_sites = intpow(params->system_size, DIM);\n\tn_timestep = params->n_timestep;\n\t\n\tdouble* laplacian_phi;\n\tALLOC(laplacian_phi, n_sites);\n\tdouble* noise_field;\n\tCALLOC(noise_field, n_sites);\n\n\tint i, j, y_site;\n\tdouble grad, noise, F2, r, weight;\n\tdouble w[DIM], F1[DIM], Y[DIM];\n\tlong L = params->system_size;\n\tdouble noise_intensity = sqrt(2.0 * params->temperature * params->relativeD * params->delta_t);\n\t\n\tfor(i=0; i<DIM; i++) w[i] = L/2;\t\t\t\t\t\t\t\t\t\t\t\t// Finds position of the harmonic well\n\t\n\t// Preparing measurement process\n\tint write_time_delta_step = (int) ((obvs->write_time_delta)/(params->delta_t));\n\tint next_writing_step = 0;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Linearly distributed writing times\n\t//int next_writing_step = write_time_delta_step;\t\t\t\t\t\t\t\t// Exponentially distributed writing times TODO\n\tobvs->write_count = 0;\n\t\n\tfor(tstep = 0; tstep < n_timestep; tstep++){\t\t\t\t\t\t\t\t\t// Time evolution\n\t\n\t\t// MEASUREMENT\n\t\t\n\t\tif(tstep == next_writing_step){\n\t\t\t//measure(phi, y_colloid, tstep, params, obvs); \t\t\t\t\t\t// Evaluate all sorts of correlators etc. here\n\t\t\tobvs->colloid_pos[obvs->write_count] += (*y_colloid)[0];\t\t\t\t// Save colloid position\n\t\t\t//for(i = 0; i < params->system_size; i++) obvs->field_average[obvs->write_count][i] += (*phi)[i]; // Save field average\n\t\t\t//obvs->colloid_msd[obvs->write_count] += (*y_colloid)[1];\t\t\t\t// Save colloid position of 2nd coordinate\n\t\t\tnext_writing_step += write_time_delta_step;\t\t\t\t\t\t\t\t// Linearly distributed\n\t\t\t//next_writing_step = (int)(next_writing_step * exp( write_time_delta_step));\t// Exponentially distributed TODO\n\t\t\tobvs->write_count++;\n\t\t}\n\t\t\n\t\t// EVOLUTION\n\t\t\t\t\t\t\t\t\t\n\t\t// i) Create local copy of the colloid variable\n\t\tfor(i=0; i<DIM; i++) Y[i] = (*y_colloid)[i];\t\n\t\t\n\t\t// ii) Prediction step for the colloid\n\t\ty_site = closest_site(Y,L);\t\t\t\t\t\t\t\t\t\t\t\t\t// Finds the lattice site closest to Y\n\t\t\n\t\tfor(i=0; i<DIM; i++){ \t\t\t\t\t\t\t\t\t\t\t\t\t\t// Evolve each of the components separately\n\t\t\t// Compute gradient of the field under the colloid\n\t\t\tgrad = 0;\n\t\t\tfor(j=0; j<top; j++){\n\t\t\t\tr = distance(Y, mosaic[y_site][j], L);\n\t\t\t\tweight = gaussian(r,params->R);\n\t\t\t\tgrad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;\n\t\t\t}\n\t\t\t\n\t\t\t// Compute temporary position\n\t\t\tnoise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);\n\t\t\tF1[i] =  params->relativeD * (params->lambda*grad -params->trap_strength*( Y[i]-w[i] ));\n\t\t\t(*y_colloid)[i] += params->delta_t * F1[i] + noise;\n\t\t}\n\t\n\t\t// iii) Evolve the field with the local copy of the colloid position\t\n\t\tlaplacian(&laplacian_phi, *phi, neighbours, n_sites);\t\t\t\t\t\t// Write Laplacian of phi into laplacian_phi\n\t\tif(params->temperature > EPS){\n\t\t\tgenerate_noise_field(&noise_field, n_sites, params);\t\t\t\t\t// Fill Lambda with randomness\n\t\t}\n\t\t\t\t\n\t\t// Add together to new step d/dt phi = -r * phi + \\nabla^2 phi - u * (phi^3) + l * V(x-Y) + noise\n\t\tphi_evolveA(phi, laplacian_phi, noise_field, n_sites, params, Y, mosaic);\n\t\t\n\t\t// iv) Correction step for the colloid (with the evolved field)\n\t\ty_site = closest_site(*y_colloid,L);\t\t\t\t\t\t\t\t\t\t// Compute new site of the colloid\n\t\t \t\n\t\tfor(i=0; i< DIM; i++){\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Evolve each of the components separately\n\t\t\t// Compute new gradient\n\t\t\tgrad = 0;\n\t\t\tfor(j=0; j<top; j++){\n\t\t\t\tr = distance(*y_colloid, mosaic[y_site][j], L);\n\t\t\t\tweight = gaussian(r,params->R);\n\t\t\t\tgrad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t// Compute corrected contribution\n\t\t\tF2 = params->relativeD * (params->lambda*grad -params->trap_strength*( (*y_colloid)[i]-w[i] ));\n\t\t\t\n\t\t\t// Sum the two contributions: y_n+1 = y_n + 1/2(F1+F2)*dt + noise\n\t\t\tnoise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);\n\t\t\t(*y_colloid)[i] = Y[i] + 0.5*(F1[i]+F2)*params->delta_t + noise;\n\t\t}\n\t}\n\t\n\t// Free memory\n\tfree(laplacian_phi);\n\tfree(noise_field);\n}\n\n// Field evolution - Model B\nvoid phi_evolveB(double** phi, double* laplacian_phi, double* laplacian_square_phi, double* laplacian_phi_cubed, double* noise_gradient, long n_sites, parameter* params, double* Y, long** mosaic){\n\tlong i;\n\tlong L = params->system_size;\n\tdouble delta_t = params->delta_t;\n\tdouble r, weight;\n\n\tfor(i = 0; i < n_sites; i++){\n\t\t(*phi)[i] += (delta_t*( -laplacian_square_phi[i] + params->mass*laplacian_phi[i] + params->quartic_u * laplacian_phi_cubed[i]) + noise_gradient[i]);\n\t}\n\t\n\t// Interaction with the colloid\n\tint y_site = closest_site(Y,L);\t\t\t\t\t\t\t\t\t\t\t\t\t// Finds the lattice site closest to Y, the colloid\n\tfor(i=0; i<top; i++){\n\t\tr = distance(Y, mosaic[y_site][i], L);\n\t\tweight = laplacian_gaussian(r,params->R);\n\t\t(*phi)[mosaic[y_site][i]] -= delta_t * params->lambda * weight;\n\t}\n}\n\n// Field evolution - Model A\nvoid phi_evolveA(double** phi, double* laplacian_phi, double* noise_field, long n_sites, parameter* params, double* Y, long** mosaic){\n\tlong i;\n\tdouble delta_t = params->delta_t;\n\tlong L = params->system_size;\n\tdouble r, weight;\n\t\n\tfor(i = 0; i < n_sites; i++){\t\t\t\t\t\t\t\t\t\t\t\t\t// Notice noise_field contains delta_t in its variance\n\t\t(*phi)[i] += delta_t*(- params->mass*(*phi)[i] + laplacian_phi[i] - params->quartic_u * floatpow((*phi)[i],3) ) + noise_field[i];\n\t}\n\t\n\t// Interaction with the colloid\n\tint y_site = closest_site(Y,L);\t\t\t\t\t\t\t\t\t\t\t\t\t// Finds the lattice site closest to Y, the colloid\n\tfor(i=0; i<top; i++){\n\t\tr = distance(Y, mosaic[y_site][i], L);\n\t\tweight = gaussian(r,params->R);\n\t\t(*phi)[mosaic[y_site][i]] += delta_t * params->lambda * weight;\n\t}\n}\n\n// Returns Laplacian as calculated from cubic neighbour cells in DIM dimensions\nvoid laplacian(double** laplacian,  double* field, long** neighbours, long n_sites){\n\tdouble buffer;\n\tlong pos, i;\n\tfor(pos = 0; pos < n_sites; pos++){\n\t\tbuffer = 0;\n\t\tfor(i = 0; i < 2*DIM; i++) {buffer += field[neighbours[pos][i]]; }\n\t\tbuffer -= (2*DIM*field[pos]);\n\t\t(*laplacian)[pos] = buffer;\n\t}\n}\n\n// Returns the Laplacian of field^3\nvoid laplacian_of_cube(double** laplacian,  double* field, long** neighbours, long n_sites){\n\tdouble buffer;\n\tlong pos, i;\n\tfor(pos = 0; pos < n_sites; pos++){\n\t\tbuffer = 0;\n\t\tfor(i = 0; i < 2*DIM; i++){\n\t\t\tbuffer += pow( (field[neighbours[pos][i]]), 3); \n\t\t}\n\t\tbuffer -= (2*DIM*field[pos]*field[pos]*field[pos]);\n\t\t(*laplacian)[pos] = buffer;\n\t}\n}\n\n// This function generates a completely uncorrelated random field on a line\nvoid generate_noise_field(double** noise_field, long length, parameter* params){\n\tlong i;\n\tdouble noise_intensity = sqrt(2.0 * params->temperature * params->delta_t);\n\tfor(i = 0; i < length; i++){\n\t\t(*noise_field)[i] = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);\n\t}\n}\n\n// Computes the gradient of a (noisy) field\nvoid gradient_field(double** grad_noise, double* noise, long** neighbours, long n_sites){\n\tlong i;\n\tint j; // neighbour of i\n\tdouble buffer;\n\tfor(i = 0; i < n_sites; i++){\n\t\tbuffer = 0;\n\t\tfor(j = 0; j < DIM; j++){\n\t\t\tbuffer += noise[neighbours[i][2*j]];\n\t\t\tbuffer -= noise[neighbours[i][2*j+1]];\n\t\t}\n\t\t(*grad_noise)[i] = 0.5*buffer;\n\t}\n}\n\n// Returns the value of a Gaussian of variance R evaluated at r\ndouble gaussian(double r, double R){\n\treturn gauss_norm * exp(-r*r/(2*R*R));\n}\n\n// Returns the value of the laplacian of a Gaussian of variance R evaluated at r\ndouble laplacian_gaussian(double r, double R){\n\treturn gauss_norm * exp(-r*r/(2*R*R)) * (r*r - DIM*R*R) / floatpow(R,4);\n}\n\n// Translate from a list index (k) to d-th lattice index, and viceversa.\ninline int ind2coord(int d, int k, int L) {return ( (int)( k/intpow(L,d) ) )%L ;}\nint vec2ind(int *vec, int L){\n\tint i, res=0;\n\tfor(i=0; i<DIM; i++) res += vec[i] * intpow(L,i);\n\treturn res;\n}\n\nvoid ind2vecROW(int** vec, int ind, int dim, int L)\n{\t\n\t// Places origin in the middle, row-major format.\n\tint dir;\n\tint offset = (int) ((L-1)/2.0); // So if L = 7 then the middle is at ___3___ \n\tfor(dir = 0; dir < dim; dir++)\n\t{\n\t\t(*vec)[dir] = (((int) (ind / intpow(L, (dim - dir -1))) % L) - offset) ; // row format, last index is fastest moving\n\t}\n}\n\n// Finds index of closest lattice site to the vector \"vec\" \n// I'm using a special modulo function to avoid getting negative return values, eg -3 % 10 = -3, but modulo(-3,10) = 7.\nint closest_site(double *vec, int L){\n\tint i, site=0;\n\tfor(i=0; i<DIM; i++){\t\n\t\tsite += (int)(modulo( round(vec[i])  , L) * intpow(L,i)); \n\t}\n\treturn site;\n}\n\n// According to https://stackoverflow.com/questions/14997165/fastest-way-to-get-a-positive-modulo-in-c-c this is still fast\nunsigned modulo( int value, unsigned m) {\n    int mod = value % (int)m;\n    if (mod < 0) {\n        mod += m;\n    }\n    return mod;\n}\n\n// Return the distance mod(L)\ndouble modular(double a, double b, double L){\n    return fabs(L/2 - fmod(3*L/2 + a - b, L));\n}\n\n// Returns the distance between the position vector and a given site (in a lattice of side L)\ndouble distance(double* pos, int site, int L){\n\tint d;\n\tdouble dist=0;\n\t//for(d=0; d<DIM; d++) dist += floatpow( pos[d] - ind2coord(d,site,L) ,2);\n\tfor(d=0; d<DIM; d++) dist += floatpow( modular(pos[d], ind2coord(d,site,L), L) , 2);\n\tdist = sqrt(dist);\n\treturn dist;\n}\n\n// Factorial of a number\nint factorial(int n){\n    if (n == 0) return 1;\n    return n * factorial(n - 1);\n}\n\n// Double factorial of a number\nint double_factorial(int n){\n    if (n <= 1) return 1;\n    return n * factorial(n - 2);\n}\n\n// The usual pow(a,b)=exp(log(a) * b) is slow AF\nint intpow(int a, int b){\n\tint i, res=1;\n\tfor(i=0; i<b; i++) res *= a;\n\treturn res;\n} \n\n// The usual pow(a,b)=exp(log(a) * b) is slow AF\ndouble floatpow(double a, int b){\n\tint i;\n\tdouble res=1;\n\tfor(i=0; i<b; i++) res *= a;\n\treturn res;\n}\n\n// Prints observables including field\nvoid print_observables(observables* obvs, parameter* params){\n\tint i,j;\n\tint system_size = params->system_size;\n\tint write_count = obvs->write_count;\n\tdouble weight = 1/((double) params->mc_runs);\n\n\tfor(i = 0; i < write_count; i ++){\n\t\tprintf(\"#FIELDAVG %g\", i * (obvs->write_time_delta));\n\t\tfor(j = 0; j < system_size; j++){\n\t\t\tprintf(\"\\t%g\", weight*(obvs->field_average[i][j]));\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\t/*\n\tfor(i = 0; i < write_count; i ++){\n\t\tprintf(\"#FIELDCORR %g\", i * (obvs->write_time_delta));\n\t\tfor(j = 0; j < system_size; j++){\n\t\t\tprintf(\"\\t%g\", weight*(obvs->field_correlation[i][j]- (obvs->field_average[i][0] * obvs->field_average[i][j]) ));\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\t// Output MSD of colloid\n\tfor(i = 0; i < write_count; i++){\n\t\tprintf(\"# COLLOIDMSD %g\", i * (obvs->write_time_delta));\n\t\tprintf(\"\\t%.3f\",weight*(obvs->colloid_msd[i]));\n\t\tprintf(\"\\n\");\n\t}\n\t*/\n\t\n\t// Output trajectory of colloid\n\tfor(i = 0; i < write_count; i++){\n\t\tprintf(\"#COLLOID_X %g\", i * (obvs->write_time_delta));\n\t\t//printf(\"%.4f\", i * (obvs->write_time_delta));\n\t\tprintf(\"\\t%.15f\",weight*obvs->colloid_pos[i]- params->system_size/2);\n\t\t//printf(\"\\t%.12f\",weight*(obvs->colloid_msd[i]));\n\t\tprintf(\"\\n\");\n\t}\n}\n\n// Prints colloid-related observables only\nvoid print_trajectory(observables* obvs, parameter* params)\n{\n\tint i;\n\tint write_count = obvs->write_count;\n\tdouble weight = 1/((double) params->mc_runs);\n\n\t// Output trajectory of colloid\n\tfor(i = 0; i < write_count; i++){\n\t\t//printf(\"#COLLOID_X %g\", i * (obvs->write_time_delta));\n\t\tprintf(\"%.4f\", i * (obvs->write_time_delta));\n\t\tprintf(\"\\t%.15f\", weight*obvs->colloid_pos[i]- params->system_size/2);\n\t\t//printf(\"\\t%.12f\",weight*(obvs->colloid_msd[i]));\n\t\tprintf(\"\\n\");\n\t}\n}\n\n// Prints out simulation parameters\nvoid print_params(parameter* params){\nprintf(\"# Parameters\\n\\\n# MASS %g\\n\\\n# LAMBDA (field-colloid-coupling) %g\\n\\\n# U (quartic coupling) %g\\n\\\n# TEMPERATURE %g\\n\\\n# RELATIVE MOTILITY D %g\\n\\\n# TRAP STRENGTH %g\\n\\\n# RNG SEED %u\\n\\\n# L (System Size) %i\\n\\\n# DIM %i\\n\\\n# RADIUS %g\\n\\\n# INITIAL DISPLACEMENT %g\\n\\\n# DELTA T %g\\n\\\n# TIMESTEPS %lu\\n\\\n# MONTE CARLO RUNS %i\\n\",\nparams->mass, params->lambda, params->quartic_u, params->temperature, params->relativeD, params->trap_strength, params->rng_seed, params->system_size, DIM, params->R, params->X0, params->delta_t, params->n_timestep, params->mc_runs);\n\t\t\n\tif(MOD==0) printf(\"# MODEL A\\n\");\n\tif(MOD==2) printf(\"# MODEL B\\n\");\n}\n\n// Prints out the instructions\nvoid printhelp(parameter* params){\n\tprintf(\"# Colloid in Gaussian Field\\n# '%s' built %s\\n\\\n# Use with options flags\\n\\\n# -L Length of d-dimensional lattice (default %i)\\n\\\n# -r Mass of Gaussian field (default %g)\\n\\\n# -l Coupling strength between colloid and field (default %g)\\n\\\n# -u Quartic coupling strength (default %g)\\n\\\n# -T Temperature of bath (default %g)\\n\\\n# -n Relative motility colloid/field (default %g)\\n\\\n# -k Strength of harmonic trap (default %g)\\n\\\n# -S Seed for RNG (default random)\\n\\\n# -t Integration timestep (default %g)\\n\\\n# -d Dimension (default %i)\\n\\\n# -N Number of timesteps (default %lu)\\n\\\n# -M Number of Monte Carlo samples (default %i)\\n\\\n# -R Radius of the colloid (default %g)\\n\\\n# -X Initial displacement of the colloid (default %g)\\n\\\n# -m Field dynamics (model A -> 0, model B -> 2, quenched -> 1, default %i)\\n\\\n# -h To see this helpscreen\\n\\\n# -P Output source code\\n\",__FILE__,__DATE__, params->system_size, params->mass, params->lambda, params->quartic_u, params->temperature, params->relativeD, params->trap_strength, params->delta_t, DIM, params->n_timestep, params->mc_runs, params->R, params->X0, MOD);\n}\n\n// Prints out the nearest-neighbour list\n// For neighbour list, size1=n_sites and size2=2*DIM. For mosaic, size1=n_sites and size2=top.\nvoid print_lookup(long ** list, int size1, int size2){\n\tint i,j;\n\tfor(i=0; i<size1; i++){\n\t\tprintf(\"# Around site %d : \\t\",i);\n\t\tfor(j=0; j<size2; j++) printf(\"%li\\t\", list[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n}\n\n// Prints out this whole code\nvoid print_source(){\n    printf(\"/* Source Code %s, created %s */\\n\",__FILE__,__DATE__);\n    FILE *fp;\n    int c;\n   \n    fp = fopen(__FILE__,\"r\");\n\n    do {\n     c = getc(fp); \n \t putchar(c);\n \t}\n \twhile(c != EOF);     \n    fclose(fp);\n}", "meta": {"hexsha": "f7a42ccdce37cea24d4bc7c4758395b9e29b8d9b", "size": 44122, "ext": "c", "lang": "C", "max_stars_repo_path": "colloid_field.c", "max_stars_repo_name": "sonarventu/field_and_particle", "max_stars_repo_head_hexsha": "9a41efd53c0bfd2ae73677f394a2101450a3d81f", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-30T14:53:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:53:37.000Z", "max_issues_repo_path": "colloid_field.c", "max_issues_repo_name": "sonarventu/field_and_particle", "max_issues_repo_head_hexsha": "9a41efd53c0bfd2ae73677f394a2101450a3d81f", "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": "colloid_field.c", "max_forks_repo_name": "sonarventu/field_and_particle", "max_forks_repo_head_hexsha": "9a41efd53c0bfd2ae73677f394a2101450a3d81f", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0034453058, "max_line_length": 266, "alphanum_fraction": 0.6554553284, "num_tokens": 13481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3643050450022372}}
{"text": "/* specfunc/airy_der.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_exp.h>\n#include <gsl/gsl_sf_airy.h>\n\n#include \"error.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval_mode.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n\n/* based on SLATEC aide.f, bide.f, aid.f, bid.f, r9admp.f */\n \n/* \n series for aif on the interval -1.00000e+00 to  1.00000e+00\n                                        with weighted error   5.22e-18\n                                         log weighted error  17.28\n                               significant figures required  16.01\n                                    decimal places required  17.73\n*/\nstatic double aif_data[8] = {\n   0.10527461226531408809,\n   0.01183613628152997844,\n   0.00012328104173225664,\n   0.00000062261225638140,\n   0.00000000185298887844,\n   0.00000000000363328873,\n   0.00000000000000504622,\n   0.00000000000000000522\n};\nstatic cheb_series aif_cs = {\n  aif_data,\n  7,\n  -1, 1,\n  7\n};\n\n/*\n series for aig on the interval -1.00000e+00 to  1.00000e+00\n                                        with weighted error   3.14e-19\n                                         log weighted error  18.50\n                               significant figures required  17.44\n                                    decimal places required  18.98\n*/\nstatic double aig_data[9] = {\n   0.021233878150918666852,\n   0.086315930335214406752,\n   0.001797594720383231358,\n   0.000014265499875550693,\n   0.000000059437995283683,\n   0.000000000152403366479,\n   0.000000000000264587660,\n   0.000000000000000331562,\n   0.000000000000000000314\n};\nstatic cheb_series aig_cs = {\n  aig_data,\n  8,\n  -1, 1,\n  8\n};\n\n/*\n series for aip2 on the interval  0.00000e+00 to  1.25000e-01\n                                        with weighted error   2.15e-17\n                                         log weighted error  16.67\n                               significant figures required  14.27\n                                    decimal places required  17.26\n*/\nstatic double aip2_data[15] = {\n    0.0065457691989713757,\n    0.0023833724120774592,\n   -0.0000430700770220586,\n    0.0000015629125858629,\n   -0.0000000815417186163,\n    0.0000000054103738057,\n   -0.0000000004284130883,\n    0.0000000000389497963,\n   -0.0000000000039623161,\n    0.0000000000004428184,\n   -0.0000000000000536297,\n    0.0000000000000069650,\n   -0.0000000000000009620,\n    0.0000000000000001403,\n   -0.0000000000000000215\n};\nstatic cheb_series aip2_cs = {\n  aip2_data,\n  14,\n  -1, 1,\n  9\n};\n\n/*\n series for aip1 on the interval  1.25000e-01 to  1.00000e+00\n                                        with weighted error   2.60e-17\n                                         log weighted error  16.58\n                               significant figures required  14.91\n                                    decimal places required  17.28\n*/\nstatic double aip1_data[25] = {\n    0.0358865097808301538,\n    0.0114668575627764899,\n   -0.0007592073583861400,\n    0.0000869517610893841,\n   -0.0000128237294298592,\n    0.0000022062695681038,\n   -0.0000004222295185921,\n    0.0000000874686415726,\n   -0.0000000192773588418,\n    0.0000000044668460054,\n   -0.0000000010790108052,\n    0.0000000002700029447,\n   -0.0000000000696480108,\n    0.0000000000184489907,\n   -0.0000000000050027817,\n    0.0000000000013852243,\n   -0.0000000000003908218,\n    0.0000000000001121536,\n   -0.0000000000000326862,\n    0.0000000000000096619,\n   -0.0000000000000028935,\n    0.0000000000000008770,\n   -0.0000000000000002688,\n    0.0000000000000000832,\n   -0.0000000000000000260\n};\nstatic cheb_series aip1_cs = {\n  aip1_data,\n  24,\n  -1, 1,\n  14\n};\n\n\n/*\n series for bif on the interval -1.00000e+00 to  1.00000e+00\n                                        with weighted error   9.05e-18\n                                         log weighted error  17.04\n                               significant figures required  15.83\n                                    decimal places required  17.49\n*/\nstatic double bif_data[8] = {\n   0.1153536790828570243,\n   0.0205007894049192875,\n   0.0002135290278902876,\n   0.0000010783960614677,\n   0.0000000032094708833,\n   0.0000000000062930407,\n   0.0000000000000087403,\n   0.0000000000000000090\n};\nstatic cheb_series bif_cs = {\n  bif_data,\n  7,\n  -1, 1,\n  7\n};\n\n/*\n series for big on the interval -1.00000e+00 to  1.00000e+00\n                                        with weighted error   5.44e-19\n                                         log weighted error  18.26\n                               significant figures required  17.46\n                                    decimal places required  18.74\n*/\nstatic double big_data[9] = {\n   -0.097196440416443537390,\n    0.149503576843167066571,\n    0.003113525387121326042,\n    0.000024708570579821297,\n    0.000000102949627731379,\n    0.000000000263970373987,\n    0.000000000000458279271,\n    0.000000000000000574283,\n    0.000000000000000000544\n};\nstatic cheb_series big_cs = {\n  big_data,\n  8,\n  -1, 1,\n  8\n};\n\n/*\n series for bif2 on the interval  1.00000e+00 to  8.00000e+00\n                                        with weighted error   3.82e-19\n                                         log weighted error  18.42\n                               significant figures required  17.68\n                                    decimal places required  18.92\n*/\nstatic double bif2_data[10] = {\n   0.323493987603522033521,\n   0.086297871535563559139,\n   0.002994025552655397426,\n   0.000051430528364661637,\n   0.000000525840250036811,\n   0.000000003561751373958,\n   0.000000000017146864007,\n   0.000000000000061663520,\n   0.000000000000000171911,\n   0.000000000000000000382\n};\nstatic cheb_series bif2_cs = {\n  bif2_data,\n  9,\n  -1, 1,\n  9\n};\n\n/*\n series for big2 on the interval  1.00000e+00 to  8.00000e+00\n                                        with weighted error   3.35e-17\n                                         log weighted error  16.48\n                               significant figures required  16.52\n                                    decimal places required  16.98\n*/\nstatic double big2_data[10] = {\n   1.6062999463621294578,\n   0.7449088819876088652,\n   0.0470138738610277380,\n   0.0012284422062548239,\n   0.0000173222412256624,\n   0.0000001521901652368,\n   0.0000000009113560249,\n   0.0000000000039547918,\n   0.0000000000000130017,\n   0.0000000000000000335\n};\nstatic cheb_series big2_cs = {\n  big2_data,\n  9,\n  -1, 1,\n  9\n};\n\n/*\n series for bip2 on the interval  0.00000e+00 to  1.25000e-01\n                                        with weighted error   2.07e-18\n                                         log weighted error  17.69\n                               significant figures required  16.51\n                                    decimal places required  18.42\n*/\nstatic double bip2_data[29] = {\n    -0.13269705443526630495,\n    -0.00568443626045977481,\n    -0.00015643601119611610,\n    -0.00001136737203679562,\n    -0.00000143464350991284,\n    -0.00000018098531185164,\n     0.00000000926177343611,\n     0.00000001710005490721,\n     0.00000000476698163504,\n    -0.00000000035195022023,\n    -0.00000000058890614316,\n    -0.00000000006678499608,\n     0.00000000006395565102,\n     0.00000000001554529427,\n    -0.00000000000792397000,\n    -0.00000000000258326243,\n     0.00000000000121655048,\n     0.00000000000038707207,\n    -0.00000000000022487045,\n    -0.00000000000004953477,\n     0.00000000000004563782,\n     0.00000000000000332998,\n    -0.00000000000000921750,\n     0.00000000000000094157,\n     0.00000000000000167154,\n    -0.00000000000000055134,\n    -0.00000000000000022369,\n     0.00000000000000017487,\n     0.00000000000000000207\n};\nstatic cheb_series bip2_cs = {\n  bip2_data,\n  28,\n  -1, 1,\n  14\n};\n\n/*\n series for bip1 on the interval  1.25000e-01 to  3.53553e-01\n                                        with weighted error   1.86e-17\n                                         log weighted error  16.73\n                               significant figures required  15.67\n                                    decimal places required  17.42\n*/\nstatic double bip1_data[24] = {\n   -0.1729187351079553719,\n   -0.0149358492984694364,\n   -0.0005471104951678566,\n    0.0001537966292958408,\n    0.0000154353476192179,\n   -0.0000065434113851906,\n    0.0000003728082407879,\n    0.0000002072078388189,\n   -0.0000000658173336470,\n    0.0000000074926746354,\n    0.0000000011101336884,\n   -0.0000000007265140553,\n    0.0000000001782723560,\n   -0.0000000000217346352,\n   -0.0000000000020302035,\n    0.0000000000019311827,\n   -0.0000000000006044953,\n    0.0000000000001209450,\n   -0.0000000000000125109,\n   -0.0000000000000019917,\n    0.0000000000000015154,\n   -0.0000000000000004977,\n    0.0000000000000001155,\n   -0.0000000000000000186\n};\nstatic cheb_series bip1_cs = {\n  bip1_data,\n  23,\n  -1, 1,\n  13\n};\n\n/*\n series for an22 on the interval -1.00000e+00 to -1.25000e-01\n                                        with weighted error   3.30e-17\n                                         log weighted error  16.48\n                               significant figures required  14.95\n                                    decimal places required  17.24\n*/\nstatic double an22_data[33] = {\n    0.0537418629629794329,\n   -0.0126661435859883193,\n   -0.0011924334106593007,\n   -0.0002032327627275655,\n   -0.0000446468963075164,\n   -0.0000113359036053123,\n   -0.0000031641352378546,\n   -0.0000009446708886149,\n   -0.0000002966562236472,\n   -0.0000000969118892024,\n   -0.0000000326822538653,\n   -0.0000000113144618964,\n   -0.0000000040042691002,\n   -0.0000000014440333684,\n   -0.0000000005292853746,\n   -0.0000000001967763374,\n   -0.0000000000740800096,\n   -0.0000000000282016314,\n   -0.0000000000108440066,\n   -0.0000000000042074801,\n   -0.0000000000016459150,\n   -0.0000000000006486827,\n   -0.0000000000002574095,\n   -0.0000000000001027889,\n   -0.0000000000000412846,\n   -0.0000000000000166711,\n   -0.0000000000000067657,\n   -0.0000000000000027585,\n   -0.0000000000000011296,\n   -0.0000000000000004645,\n   -0.0000000000000001917,\n   -0.0000000000000000794,\n   -0.0000000000000000330\n};\nstatic cheb_series an22_cs = {\n  an22_data,\n  32,\n  -1, 1,\n  18\n};\n\n/*\n series for an21 on the interval -1.25000e-01 to -1.56250e-02\n                                        with weighted error   3.43e-17\n                                         log weighted error  16.47\n                               significant figures required  14.48\n                                    decimal places required  17.16\n*/\nstatic double an21_data[24] = {\n    0.0198313155263169394,\n   -0.0029376249067087533,\n   -0.0001136260695958196,\n   -0.0000100554451087156,\n   -0.0000013048787116563,\n   -0.0000002123881993151,\n   -0.0000000402270833384,\n   -0.0000000084996745953,\n   -0.0000000019514839426,\n   -0.0000000004783865344,\n   -0.0000000001236733992,\n   -0.0000000000334137486,\n   -0.0000000000093702824,\n   -0.0000000000027130128,\n   -0.0000000000008075954,\n   -0.0000000000002463214,\n   -0.0000000000000767656,\n   -0.0000000000000243883,\n   -0.0000000000000078831,\n   -0.0000000000000025882,\n   -0.0000000000000008619,\n   -0.0000000000000002908,\n   -0.0000000000000000993,\n   -0.0000000000000000343\n};\nstatic cheb_series an21_cs = {\n  an21_data,\n  23,\n  -1, 1,\n  12\n};\n\n/*\n series for an20 on the interval -1.56250e-02 to  0.00000e+00\n                                        with weighted error   4.41e-17\n                                         log weighted error  16.36\n                               significant figures required  14.16\n                                    decimal places required  16.96\n*/\nstatic double an20_data[16] = {\n    0.0126732217145738027,\n   -0.0005212847072615621,\n   -0.0000052672111140370,\n   -0.0000001628202185026,\n   -0.0000000090991442687,\n   -0.0000000007438647126,\n   -0.0000000000795494752,\n   -0.0000000000104050944,\n   -0.0000000000015932426,\n   -0.0000000000002770648,\n   -0.0000000000000535343,\n   -0.0000000000000113062,\n   -0.0000000000000025772,\n   -0.0000000000000006278,\n   -0.0000000000000001621,\n   -0.0000000000000000441\n};\nstatic cheb_series an20_cs = {\n  an20_data,\n  15,\n  -1, 1,\n  8\n};\n\n/*\n series for aph2 on the interval -1.00000e+00 to -1.25000e-01\n                                        with weighted error   2.94e-17\n                                         log weighted error  16.53\n                               significant figures required  15.58\n                                    decimal places required  17.28\n*/\nstatic double aph2_data[32] = {\n   -0.2057088719781465107,\n    0.0422196961357771922,\n    0.0020482560511207275,\n    0.0002607800735165006,\n    0.0000474824268004729,\n    0.0000105102756431612,\n    0.0000026353534014668,\n    0.0000007208824863499,\n    0.0000002103236664473,\n    0.0000000644975634555,\n    0.0000000205802377264,\n    0.0000000067836273921,\n    0.0000000022974015284,\n    0.0000000007961306765,\n    0.0000000002813860610,\n    0.0000000001011749057,\n    0.0000000000369306738,\n    0.0000000000136615066,\n    0.0000000000051142751,\n    0.0000000000019351689,\n    0.0000000000007393607,\n    0.0000000000002849792,\n    0.0000000000001107281,\n    0.0000000000000433412,\n    0.0000000000000170801,\n    0.0000000000000067733,\n    0.0000000000000027017,\n    0.0000000000000010835,\n    0.0000000000000004367,\n    0.0000000000000001769,\n    0.0000000000000000719,\n    0.0000000000000000294\n};\nstatic cheb_series aph2_cs = {\n  aph2_data,\n  31,\n  -1, 1,\n  16\n};\n\n/*\n series for aph1 on the interval -1.25000e-01 to -1.56250e-02\n                                        with weighted error   6.38e-17\n                                         log weighted error  16.20\n                               significant figures required  14.91\n                                    decimal places required  16.87\n*/\nstatic double aph1_data[22] = {\n  -0.1024172908077571694,\n   0.0071697275146591248,\n   0.0001209959363122329,\n   0.0000073361512841220,\n   0.0000007535382954272,\n   0.0000001041478171741,\n   0.0000000174358728519,\n   0.0000000033399795033,\n   0.0000000007073075174,\n   0.0000000001619187515,\n   0.0000000000394539982,\n   0.0000000000101192282,\n   0.0000000000027092778,\n   0.0000000000007523806,\n   0.0000000000002156369,\n   0.0000000000000635283,\n   0.0000000000000191757,\n   0.0000000000000059143,\n   0.0000000000000018597,\n   0.0000000000000005950,\n   0.0000000000000001934,\n   0.0000000000000000638\n};\nstatic cheb_series aph1_cs = {\n  aph1_data,\n  21,\n  -1, 1,\n  10\n};\n\n/*\n series for aph0 on the interval -1.56250e-02 to  0.00000e+00\n                                        with weighted error   2.29e-17\n                                         log weighted error  16.64\n                               significant figures required  15.27\n                                    decimal places required  17.23\n*/\nstatic double aph0_data[15] = {\n -0.0855849241130933257,\n  0.0011214378867065261,\n  0.0000042721029353664,\n  0.0000000817607381483,\n  0.0000000033907645000,\n  0.0000000002253264423,\n  0.0000000000206284209,\n  0.0000000000023858763,\n  0.0000000000003301618,\n  0.0000000000000527010,\n  0.0000000000000094555,\n  0.0000000000000018709,\n  0.0000000000000004024,\n  0.0000000000000000930,\n  0.0000000000000000229\n};\nstatic cheb_series aph0_cs = {\n  aph0_data,\n  14,\n  -1, 1,\n  7\n};\n\n\nstatic\nint\nairy_deriv_mod_phase(const double x, gsl_mode_t mode,\n                     gsl_sf_result * ampl, gsl_sf_result * phi)\n{\n  const double pi34 = 2.356194490192344928847;\n  gsl_sf_result result_a;\n  gsl_sf_result result_p;\n  double a, p;\n  double sqx;\n\n  if(x <= -4.0) {\n    double z = 128.0/(x*x*x) + 1.0;\n    cheb_eval_mode_e(&an20_cs, z, mode, &result_a);\n    cheb_eval_mode_e(&aph0_cs, z, mode, &result_p);\n  }\n  else if(x <= -2.0) {\n    double z = (128.0/(x*x*x) + 9.0) / 7.0;\n    cheb_eval_mode_e(&an21_cs, z, mode, &result_a);\n    cheb_eval_mode_e(&aph1_cs, z, mode, &result_p);\n  }\n  else if(x <= -1.0) {\n    double z = (16.0/(x*x*x) + 9.0) / 7.0;\n    cheb_eval_mode_e(&an22_cs, z, mode, &result_a);\n    cheb_eval_mode_e(&aph2_cs, z, mode, &result_p);\n  }\n  else {\n    ampl->val = 0.0;\n    ampl->err = 0.0;\n    phi->val  = 0.0;\n    phi->err  = 0.0;\n    GSL_ERROR (\"x is greater than 1.0\", GSL_EDOM);\n  }\n\n  a =  0.3125 + result_a.val;\n  p = -0.625  + result_p.val;\n \n  sqx = sqrt(-x);\n\n  ampl->val = sqrt(a * sqx);\n  ampl->err = fabs(ampl->val) * (GSL_DBL_EPSILON + fabs(result_a.err/result_a.val));\n  phi->val  = pi34 - x * sqx * p;\n  phi->err = fabs(phi->val) * (GSL_DBL_EPSILON + fabs(result_p.err/result_p.val));\n\n  return GSL_SUCCESS;\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_airy_Ai_deriv_scaled_e(const double x, gsl_mode_t mode, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x < -1.0) {\n    gsl_sf_result a;\n    gsl_sf_result p;\n    int status_ap = airy_deriv_mod_phase(x, mode, &a, &p);\n    double c    = cos(p.val);\n    result->val  = a.val * c;\n    result->err  = fabs(result->val * p.err) + fabs(c * a.err);\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return status_ap;\n  }\n  else if(x <= 1.0) {\n    const double x3 = x*x*x;\n    const double x2 = x*x;\n    gsl_sf_result result_c0;\n    gsl_sf_result result_c1;\n    cheb_eval_mode_e(&aif_cs, x3, mode, &result_c0);\n    cheb_eval_mode_e(&aig_cs, x3, mode, &result_c1);\n\n    result->val  = (x2*(0.125 + result_c0.val) - result_c1.val) - 0.25;\n    result->err  = fabs(x2*result_c0.val) + result_c1.err;\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n\n    if(x > GSL_ROOT3_DBL_EPSILON*GSL_ROOT3_DBL_EPSILON) {\n      /* scale only if x is positive */\n      double s = exp(2.0*x*sqrt(x)/3.0);\n      result->val *= s;\n      result->err *= s;\n    }\n\n    return GSL_SUCCESS;\n  }\n  else if(x <= 4.0) {\n    const double sqrtx = sqrt(x);\n    const double z = (16.0/(x*sqrtx) - 9.0)/7.0;\n    const double s = sqrt(sqrtx);\n    gsl_sf_result result_c0;\n    cheb_eval_mode_e(&aip1_cs, z, mode, &result_c0);\n    result->val  = -(0.28125 + result_c0.val) * s;\n    result->err  = result_c0.err * s;\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    const double sqrtx = sqrt(x);\n    const double z = 16.0/(x*sqrtx) - 1.0;\n    const double s = sqrt(sqrtx);\n    gsl_sf_result result_c0;\n    cheb_eval_mode_e(&aip2_cs, z, mode, &result_c0);\n    result->val  = -(0.28125 + result_c0.val) * s;\n    result->err  = result_c0.err * s;\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n}\n\n\nint\ngsl_sf_airy_Ai_deriv_e(const double x, gsl_mode_t mode, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x < -1.0) {\n    gsl_sf_result a;\n    gsl_sf_result p;\n    int status_ap = airy_deriv_mod_phase(x, mode, &a, &p);\n    double c    = cos(p.val);\n    result->val  = a.val * c;\n    result->err  = fabs(result->val * p.err) + fabs(c * a.err);\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return status_ap;\n  }\n  else if(x < 1.0) {\n    const double x3 = x*x*x;\n    gsl_sf_result result_c1;\n    gsl_sf_result result_c2;\n    cheb_eval_mode_e(&aif_cs, x3, mode, &result_c1);\n    cheb_eval_mode_e(&aig_cs, x3, mode, &result_c2);\n    result->val  = (x*x*(0.125 + result_c1.val) - result_c2.val) - 0.25;\n    result->err  = fabs(x*x*result_c1.err) + result_c2.err;\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x*x*x < 9.0/4.0 * GSL_LOG_DBL_MIN*GSL_LOG_DBL_MIN) {\n    gsl_sf_result result_aps;\n    const double arg = -2.0*x*sqrt(x)/3.0;\n    const int stat_a = gsl_sf_airy_Ai_deriv_scaled_e(x, mode, &result_aps);\n    const int stat_e = gsl_sf_exp_mult_err_e(arg, 1.5*fabs(arg*GSL_DBL_EPSILON),\n                                                result_aps.val, result_aps.err,\n                                                result);\n    return GSL_ERROR_SELECT_2(stat_e, stat_a);\n  }\n  else {\n    UNDERFLOW_ERROR(result);\n  }\n}\n\n\nint\ngsl_sf_airy_Bi_deriv_scaled_e(const double x, gsl_mode_t mode, gsl_sf_result * result)\n{\n  const double atr =  8.7506905708484345;   /* 16./(sqrt(8)-1) */\n  const double btr = -2.0938363213560543;   /* -(sqrt(8)+1)/(sqrt(8)-1) */\n\n  /* CHECK_POINTER(result) */\n\n  if(x < -1.0) {\n    gsl_sf_result a;\n    gsl_sf_result p;\n    int status_ap = airy_deriv_mod_phase(x, mode, &a, &p);\n    double s     = sin(p.val);\n    result->val  = a.val * s;\n    result->err  = fabs(result->val * p.err) + fabs(s * a.err);\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return status_ap;\n  }\n  else if(x < 1.0) {\n    const double x3 = x*x*x;\n    const double x2 = x*x;\n    gsl_sf_result result_c1;\n    gsl_sf_result result_c2;\n    cheb_eval_mode_e(&bif_cs, x3, mode, &result_c1);\n    cheb_eval_mode_e(&big_cs, x3, mode, &result_c2);\n    result->val  = x2 * (result_c1.val + 0.25) + result_c2.val + 0.5;\n    result->err  = x2 * result_c1.err + result_c2.err;\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n\n    if(x > GSL_ROOT3_DBL_EPSILON*GSL_ROOT3_DBL_EPSILON) {\n      /* scale only if x is positive */\n      const double s = exp(-2.0*x*sqrt(x)/3.0);\n      result->val *= s;\n      result->err *= s;\n    }\n\n    return GSL_SUCCESS;\n  }\n  else if(x < 2.0) {\n    const double z = (2.0*x*x*x - 9.0) / 7.0;\n    const double s = exp(-2.0*x*sqrt(x)/3.0);\n    gsl_sf_result result_c0;\n    gsl_sf_result result_c1;\n    cheb_eval_mode_e(&bif2_cs, z, mode, &result_c0);\n    cheb_eval_mode_e(&big2_cs, z, mode, &result_c1);\n    result->val  = s * (x*x * (0.25 + result_c0.val) + 0.5 + result_c1.val);\n    result->err  = s * (x*x * result_c0.err + result_c1.err);\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x < 4.0) {\n    const double sqrtx = sqrt(x);\n    const double z = atr/(x*sqrtx) + btr;\n    const double s = sqrt(sqrtx);\n    gsl_sf_result result_c0;\n    cheb_eval_mode_e(&bip1_cs, z, mode, &result_c0);\n    result->val  = s * (0.625 + result_c0.val);\n    result->err  = s * result_c0.err;\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    const double sqrtx = sqrt(x);\n    const double z = 16.0/(x*sqrtx) - 1.0;\n    const double s = sqrt(sqrtx);\n    gsl_sf_result result_c0;\n    cheb_eval_mode_e(&bip2_cs, z, mode, &result_c0);\n    result->val  = s * (0.625 + result_c0.val);\n    result->err  = s * result_c0.err;\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n}\n\n\nint\ngsl_sf_airy_Bi_deriv_e(const double x, gsl_mode_t mode, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x < -1.0) {\n    gsl_sf_result a;\n    gsl_sf_result p;\n    int status_ap = airy_deriv_mod_phase(x, mode, &a, &p);\n    double s    = sin(p.val);\n    result->val  = a.val * s;\n    result->err  = fabs(result->val * p.err) + fabs(s * a.err);\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return status_ap;\n  }\n  else if(x < 1.0) {\n    const double x3 = x*x*x;\n    const double x2 = x*x;\n    gsl_sf_result result_c1;\n    gsl_sf_result result_c2;\n    cheb_eval_mode_e(&bif_cs, x3, mode, &result_c1);\n    cheb_eval_mode_e(&big_cs, x3, mode, &result_c2);\n    result->val  = x2 * (result_c1.val + 0.25) + result_c2.val + 0.5;\n    result->err  = x2 * result_c1.err + result_c2.err;\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x < 2.0) {\n    const double z = (2.0*x*x*x - 9.0) / 7.0;\n    gsl_sf_result result_c1;\n    gsl_sf_result result_c2;\n    cheb_eval_mode_e(&bif2_cs, z, mode, &result_c1);\n    cheb_eval_mode_e(&big2_cs, z, mode, &result_c2);\n    result->val  = x*x * (result_c1.val + 0.25) + result_c2.val + 0.5;\n    result->err  = x*x * result_c1.err + result_c2.err;\n    result->err += GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else if(x < GSL_ROOT3_DBL_MAX*GSL_ROOT3_DBL_MAX) {\n    gsl_sf_result result_bps;\n    const double arg = 2.0*(x*sqrt(x)/3.0);\n    int stat_b = gsl_sf_airy_Bi_deriv_scaled_e(x, mode, &result_bps);\n    int stat_e = gsl_sf_exp_mult_err_e(arg, 1.5*fabs(arg*GSL_DBL_EPSILON),\n                                          result_bps.val, result_bps.err,\n                                          result);\n    return GSL_ERROR_SELECT_2(stat_e, stat_b);\n  }\n  else {\n    OVERFLOW_ERROR(result);\n  }\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_airy_Ai_deriv_scaled(const double x, gsl_mode_t mode)\n{\n  EVAL_RESULT(gsl_sf_airy_Ai_deriv_scaled_e(x, mode, &result));\n}\n\ndouble gsl_sf_airy_Ai_deriv(const double x, gsl_mode_t mode)\n{\n  EVAL_RESULT(gsl_sf_airy_Ai_deriv_e(x, mode, &result));\n}\n\ndouble gsl_sf_airy_Bi_deriv_scaled(const double x, gsl_mode_t mode)\n{\n  EVAL_RESULT(gsl_sf_airy_Bi_deriv_scaled_e(x, mode, &result));\n}\n\ndouble gsl_sf_airy_Bi_deriv(const double x, gsl_mode_t mode)\n{\n  EVAL_RESULT(gsl_sf_airy_Bi_deriv_e(x, mode, &result));\n}\n", "meta": {"hexsha": "45a1c1b7e453c864a2b6af3b2601ccc8ebdc7bc3", "size": 25598, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/airy_der.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/airy_der.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/airy_der.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 28.8590755355, "max_line_length": 86, "alphanum_fraction": 0.6191499336, "num_tokens": 8842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3643050393603126}}
{"text": "/**\n *\n * @file testing_cgetri.c\n *\n *  PLASMA testing routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @date 2010-11-15\n * @generated c Tue Jan  7 11:45:17 2014\n *\n **/\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#include <plasma.h>\n#include <cblas.h>\n#include <lapacke.h>\n#include <core_blas.h>\n#include \"testing_cmain.h\"\n\nstatic int check_factorization(int, PLASMA_Complex32_t*, PLASMA_Complex32_t*, int, int*, float);\nstatic int check_inverse(int, PLASMA_Complex32_t *, PLASMA_Complex32_t *, int, int*, float);\n\nint testing_cgetri(int argc, char **argv)\n{\n\n    /* Check for number of arguments*/\n    if (argc != 2){\n        USAGE(\"GETRI\", \"N LDA\",\n              \"   - N    : the size of the matrix\\n\"\n              \"   - LDA  : leading dimension of the matrix A\\n\");\n        return -1;\n    }\n\n    int N     = atoi(argv[0]);\n    int LDA   = atoi(argv[1]);\n    float eps;\n    int info_inverse, info_factorization;\n    int i, j;\n\n    PLASMA_Complex32_t *A1   = (PLASMA_Complex32_t *)malloc(LDA*N*sizeof(PLASMA_Complex32_t));\n    PLASMA_Complex32_t *A2   = (PLASMA_Complex32_t *)malloc(LDA*N*sizeof(PLASMA_Complex32_t));\n    PLASMA_Complex32_t *WORK = (PLASMA_Complex32_t *)malloc(2*LDA*sizeof(PLASMA_Complex32_t));\n    float *D                = (float *)malloc(LDA*sizeof(float));\n    int *IPIV = (int *)malloc(N*sizeof(int));\n\n    /* Check if unable to allocate memory */\n    if ( (!A1) || (!A2) || (!IPIV) ){\n        printf(\"Out of Memory \\n \");\n        return -2;\n    }\n\n    eps = LAPACKE_slamch_work('e');\n\n    /*-------------------------------------------------------------\n    *  TESTING CGETRI\n    */\n\n    /* Initialize A1 and A2 Matrix */\n    PLASMA_cplrnt(N, N, A1, LDA, 3453);\n    for ( i = 0; i < N; i++)\n        for (  j = 0; j < N; j++)\n            A2[LDA*j+i] = A1[LDA*j+i];\n\n    printf(\"\\n\");\n    printf(\"------ TESTS FOR PLASMA CGETRI ROUTINE -------  \\n\");\n    printf(\"            Size of the Matrix %d by %d\\n\", N, N);\n    printf(\"\\n\");\n    printf(\" The matrix A is randomly generated for each test.\\n\");\n    printf(\"============\\n\");\n    printf(\" The relative machine precision (eps) is to be %e \\n\", eps);\n    printf(\" Computational tests pass if scaled residuals are less than 60.\\n\");\n\n    /* PLASMA CGETRF */\n    PLASMA_cgetrf(N, N, A2, LDA, IPIV);\n\n    /* Check the factorization */\n    info_factorization = check_factorization( N, A1, A2, LDA, IPIV, eps);\n\n    /* PLASMA CGETRI */\n    PLASMA_cgetri(N, A2, LDA, IPIV);\n\n    /* Check the inverse */\n    info_inverse = check_inverse(N, A1, A2, LDA, IPIV, eps);\n\n    if ( (info_inverse == 0) && (info_factorization == 0) ) {\n        printf(\"***************************************************\\n\");\n        printf(\" ---- TESTING CGETRI ..................... PASSED !\\n\");\n        printf(\"***************************************************\\n\");\n    }\n    else {\n        printf(\"***************************************************\\n\");\n        printf(\" - TESTING CGETRI ... FAILED !\\n\");\n        printf(\"***************************************************\\n\");\n    }\n\n    free(A1); free(A2); free(IPIV); free(WORK); free(D);\n\n    return 0;\n}\n\n\n/*------------------------------------------------------------------------\n *  Check the factorization of the matrix A2\n */\nstatic int check_factorization(int N, PLASMA_Complex32_t *A1, PLASMA_Complex32_t *A2, int LDA, int *IPIV, float eps)\n{\n    int info_factorization;\n    float Rnorm, Anorm, Xnorm, Bnorm, result;\n    PLASMA_Complex32_t alpha, beta;\n\n    alpha = 1.0;\n    beta  = -1.0;\n\n    PLASMA_Complex32_t *b  = (PLASMA_Complex32_t *)malloc(LDA*sizeof(PLASMA_Complex32_t));\n    PLASMA_Complex32_t *x  = (PLASMA_Complex32_t *)malloc(LDA*sizeof(PLASMA_Complex32_t));\n\n    LAPACKE_clarnv_work(1, ISEED, LDA, x);\n    LAPACKE_clacpy_work(LAPACK_COL_MAJOR, 'A', N, 1, x, LDA, b, LDA);\n\n    PLASMA_cgetrs( PlasmaNoTrans, N, 1, A2, LDA, IPIV, x, LDA );\n\n    Xnorm = PLASMA_clange(PlasmaInfNorm, N, 1, x,  LDA);\n    Anorm = PLASMA_clange(PlasmaInfNorm, N, N, A1, LDA);\n    Bnorm = PLASMA_clange(PlasmaInfNorm, N, 1, b,  LDA);\n\n    PLASMA_cgemm( PlasmaNoTrans, PlasmaNoTrans, N, 1, N, \n                  alpha, A1, LDA, x, LDA, beta, b, LDA);\n    \n    Rnorm = PLASMA_clange(PlasmaInfNorm, N, 1, b, LDA);\n\n    if (getenv(\"PLASMA_TESTING_VERBOSE\"))\n      printf( \"||A||_oo=%f\\n||X||_oo=%f\\n||B||_oo=%f\\n||A X - B||_oo=%e\\n\", Anorm, Xnorm, Bnorm, Rnorm );\n\n    result = Rnorm / ( (Anorm*Xnorm+Bnorm)*N*eps ) ;\n    printf(\"============\\n\");\n    printf(\"Checking the Residual of the solution \\n\");\n    printf(\"-- ||Ax-B||_oo/((||A||_oo||x||_oo+||B||_oo).N.eps) = %e \\n\", result);\n\n    if (  isnan(Xnorm) || isinf(Xnorm) || isnan(result) || isinf(result) || (result > 60.0) ) {\n        printf(\"-- The factorization is suspicious ! \\n\");\n        info_factorization = 1;\n     }\n    else{\n        printf(\"-- The factorization is CORRECT ! \\n\");\n        info_factorization = 0;\n    }\n    free(x); free(b);\n\n    return info_factorization;\n}\n\n\n/*------------------------------------------------------------------------\n *  Check the accuracy of the computed inverse\n */\n\nstatic int check_inverse(int N, PLASMA_Complex32_t *A1, PLASMA_Complex32_t *A2, int LDA, int *IPIV, float eps )\n{\n    int info_inverse;\n    int i;\n    float Rnorm, Anorm, Ainvnorm, result;\n    PLASMA_Complex32_t alpha, beta, zone;\n    PLASMA_Complex32_t *work = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t));\n\n    alpha = -1.0;\n    beta  = 0.0;\n    zone = 1.0;\n\n    PLASMA_cgemm( PlasmaNoTrans, PlasmaNoTrans, N, N, N, alpha, A2, LDA, A1, LDA, beta, work, N);\n\n    /* Add the identity matrix to work */\n    for(i=0; i<N; i++)\n        *(work+i+i*N) = *(work+i+i*N) + zone;\n\n    Rnorm    = PLASMA_clange(PlasmaInfNorm, N, N, work, N);\n    Anorm    = PLASMA_clange(PlasmaInfNorm, N, N, A1,   LDA);\n    Ainvnorm = PLASMA_clange(PlasmaInfNorm, N, N, A2,   LDA);\n\n    if (getenv(\"PLASMA_TESTING_VERBOSE\"))\n      printf( \"||A||_1=%f\\n||Ainv||_1=%f\\n||Id - A*Ainv||_1=%e\\n\", Anorm, Ainvnorm, Rnorm );\n\n    result = Rnorm / ( (Anorm*Ainvnorm)*N*eps ) ;\n    printf(\"============\\n\");\n    printf(\"Checking the Residual of the inverse \\n\");\n    printf(\"-- ||Id - A*Ainv||_1/((||A||_1||Ainv||_1).N.eps) = %e \\n\", result);\n\n    if (  isnan(Ainvnorm) || isinf(Ainvnorm) || isnan(result) || isinf(result) || (result > 60.0) ) {\n        printf(\"-- The inverse is suspicious ! \\n\");\n        info_inverse = 1;\n     }\n    else{\n        printf(\"-- The inverse is CORRECT ! \\n\");\n        info_inverse = 0;\n    }\n\n    free(work);\n\n    return info_inverse;\n}\n", "meta": {"hexsha": "c4b0388aff715bada41a65b25fff54f0f0076ffc", "size": 6689, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/testing_cgetri.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/testing_cgetri.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/testing_cgetri.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.4708737864, "max_line_length": 116, "alphanum_fraction": 0.553445956, "num_tokens": 2143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.36422578108397413}}
{"text": "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <php.h>\n#include <cblas.h>\n#include <lapacke.h>\n#include \"kernel/operators.h\"\n\n/**\n * Matrix-matrix multiplication i.e. linear transformation of matrices A and B.\n * \n * @param return_value\n * @param a\n * @param b\n */\nvoid tensor_matmul(zval * return_value, zval * a, zval * b)\n{\n    unsigned int i, j;\n    Bucket * row;\n    zval rowC, c;\n\n    zend_array * aa = Z_ARR_P(a);\n    zend_array * ab = Z_ARR_P(b);\n\n    Bucket * ba = aa->arData;\n    Bucket * bb = ab->arData;\n\n    unsigned int m = zend_array_count(aa);\n    unsigned int p = zend_array_count(ab);\n    unsigned int n = zend_array_count(Z_ARR(bb[0].val));\n\n    double * va = emalloc(m * p * sizeof(double));\n    double * vb = emalloc(n * p * sizeof(double));\n    double * vc = emalloc(m * n * sizeof(double));\n\n    for (i = 0; i < m; ++i) {\n        row = Z_ARR(ba[i].val)->arData;\n\n        for (j = 0; j < p; ++j) {\n            va[i * p + j] = zephir_get_doubleval(&row[j].val);\n        }\n    }\n\n    for (i = 0; i < p; ++i) {\n        row = Z_ARR(bb[i].val)->arData;\n\n        for (j = 0; j < n; ++j) {\n            vb[i * n + j] = zephir_get_doubleval(&row[j].val);\n        }\n    }\n\n    cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, p, 1.0, va, p, vb, n, 0.0, vc, n);\n\n    array_init_size(&c, m);\n\n    for (i = 0; i < m; ++i) {\n        array_init_size(&rowC, n);\n\n        for (j = 0; j < n; ++j) {\n            add_next_index_double(&rowC, vc[i * n + j]);\n        }\n\n        add_next_index_zval(&c, &rowC);\n    }\n\n    RETVAL_ARR(Z_ARR(c));\n\n    efree(va);\n    efree(vb);\n    efree(vc);\n}\n\n/**\n * Dot product between vectors A and B.\n * \n * @param return_value\n * @param a\n * @param b\n */\nvoid tensor_dot(zval * return_value, zval * a, zval * b)\n{\n    unsigned int i;\n\n    zend_array * aa = Z_ARR_P(a);\n    zend_array * ab = Z_ARR_P(b);\n\n    Bucket * ba = aa->arData;\n    Bucket * bb = ab->arData;\n\n    unsigned int n = zend_array_count(aa);\n\n    double sigma = 0.0;\n\n    for (i = 0; i < n; ++i) {\n        sigma += zephir_get_doubleval(&ba[i].val) * zephir_get_doubleval(&bb[i].val);\n    }\n\n    RETVAL_DOUBLE(sigma);\n}\n\n/**\n * Return the multiplicative inverse of a square matrix A.\n * \n * @param return_value\n * @param a\n */\nvoid tensor_inverse(zval * return_value, zval * a)\n{\n    unsigned int i, j;\n    Bucket * row;\n    zval rowB, b;\n\n    zend_array * aa = Z_ARR_P(a);\n\n    Bucket * ba = aa->arData;\n\n    unsigned int n = zend_array_count(aa);\n\n    double * va = emalloc(n * n * sizeof(double));\n    int * pivots = emalloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        row = Z_ARR(ba[i].val)->arData;\n\n        for (j = 0; j < n; ++j) {\n            va[i * n + j] = zephir_get_doubleval(&row[j].val);\n        }\n    }\n\n    lapack_int status;\n\n    status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, va, n, pivots);\n\n    if (status != 0) {\n        RETURN_NULL();\n    }\n    \n    status = LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, va, n, pivots);\n\n    if (status != 0) {\n        RETURN_NULL();\n    }\n\n    array_init_size(&b, n);\n\n    for (i = 0; i < n; ++i) {\n        array_init_size(&rowB, n);\n\n        for (j = 0; j < n; ++j) {\n            add_next_index_double(&rowB, va[i * n + j]);\n        }\n\n        add_next_index_zval(&b, &rowB);\n    }\n\n    RETVAL_ARR(Z_ARR(b));\n\n    efree(va);\n    efree(pivots);\n}\n\n/**\n * Return the (Moore-Penrose) pseudoinverse of a general matrix A.\n * \n * @param return_value\n * @param a\n */\nvoid tensor_pseudoinverse(zval * return_value, zval * a)\n{\n    unsigned int i, j;\n    Bucket * row;\n    zval b, rowB;\n\n    zend_array * aa = Z_ARR_P(a);\n\n    Bucket * ba = aa->arData;\n\n    unsigned int m = zend_array_count(aa);\n    unsigned int n = zend_array_count(Z_ARR(ba[0].val));\n    unsigned int k = MIN(m, n);\n\n    double * va = emalloc(m * n * sizeof(double));\n    double * vu = emalloc(m * m * sizeof(double));\n    double * vs = emalloc(k * sizeof(double));\n    double * vvt = emalloc(n * n * sizeof(double));\n    double * vb = emalloc(n * m * sizeof(double));\n\n    for (i = 0; i < m; ++i) {\n        row = Z_ARR(ba[i].val)->arData;\n\n        for (j = 0; j < n; ++j) {\n            va[i * n + j] = zephir_get_doubleval(&row[j].val);\n        }\n    }\n\n    lapack_int status = LAPACKE_dgesdd(LAPACK_ROW_MAJOR, 'A', m, n, va, n, vs, vu, m, vvt, n);\n\n    if (status != 0) {\n        RETURN_NULL();\n    }\n\n    for (i = 0; i < k; ++i) {\n        cblas_dscal(m, 1.0 / vs[i], &vu[i], m);\n    }\n\n    cblas_dgemm(CblasRowMajor, CblasTrans, CblasTrans, n, m, m, 1.0, vvt, n, vu, m, 0.0, vb, m);\n\n    array_init_size(&b, n);\n\n    for (i = 0; i < n; ++i) {\n        array_init_size(&rowB, m);\n\n        for (j = 0; j < m; ++j) {\n            add_next_index_double(&rowB, vb[i * m + j]);\n        }\n\n        add_next_index_zval(&b, &rowB);\n    }\n\n    RETVAL_ARR(Z_ARR(b));\n\n    efree(va);\n    efree(vu);\n    efree(vs);\n    efree(vvt);\n    efree(vb);\n}\n\n/**\n * Return the row echelon form of matrix A.\n * \n * @param return_value\n * @param a\n */\nvoid tensor_ref(zval * return_value, zval * a)\n{\n    unsigned int i, j;\n    Bucket * row;\n    zval rowB, b;\n    zval tuple;\n\n    zend_array * aa = Z_ARR_P(a);\n\n    Bucket * ba = aa->arData;\n\n    unsigned int m = zend_array_count(aa);\n    unsigned int n = zend_array_count(Z_ARR(ba[0].val));\n\n    double * va = emalloc(m * n * sizeof(double));\n    int * pivots = emalloc(MIN(m, n) * sizeof(int));\n\n    for (i = 0; i < m; ++i) {\n        row = Z_ARR(ba[i].val)->arData;\n\n        for (j = 0; j < n; ++j) {\n            va[i * n + j] = zephir_get_doubleval(&row[j].val);\n        }\n    }\n\n    lapack_int status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, m, n, va, n, pivots);\n\n    if (status != 0) {\n        RETURN_NULL();\n    }\n    \n    array_init_size(&b, m);\n\n    long swaps = 0;\n\n    for (i = 0; i < m; ++i) {\n        array_init_size(&rowB, n);\n\n        for (j = 0; j < i; ++j) {\n            add_next_index_double(&rowB, 0.0);\n        }\n\n        for (j = i; j < n; ++j) {\n            add_next_index_double(&rowB, va[i * n + j]);\n        }\n\n        add_next_index_zval(&b, &rowB);\n\n        if (i + 1 != pivots[i]) {\n            ++swaps;\n        }\n    }\n\n    array_init_size(&tuple, 2);\n    \n    add_next_index_zval(&tuple, &b);\n    add_next_index_long(&tuple, swaps);\n\n    RETVAL_ARR(Z_ARR(tuple));\n\n    efree(va);\n    efree(pivots);\n}\n\n/**\n * Compute the Cholesky decomposition of matrix A and return the lower triangular matrix.\n * \n * @param return_value\n * @param a\n */\nvoid tensor_cholesky(zval * return_value, zval * a)\n{\n    unsigned int i, j;\n    Bucket * row;\n    zval rowB, b;\n\n    zend_array * aa = Z_ARR_P(a);\n\n    Bucket * ba = aa->arData;\n\n    unsigned int n = zend_array_count(aa);\n\n    double * va = emalloc(n * n * sizeof(double));\n\n    for (i = 0; i < n; ++i) {\n        row = Z_ARR(ba[i].val)->arData;\n\n        for (j = 0; j < n; ++j) {\n            va[i * n + j] = zephir_get_doubleval(&row[j].val);\n        }\n    }\n\n    lapack_int status = LAPACKE_dpotrf(LAPACK_ROW_MAJOR, 'L', n, va, n);\n\n    if (status != 0) {\n        RETURN_NULL();\n    }\n    \n    array_init_size(&b, n);\n\n    for (i = 0; i < n; ++i) {\n        array_init_size(&rowB, n);\n\n        for (j = 0; j <= i; ++j) {\n            add_next_index_double(&rowB, va[i * n + j]);\n        }\n\n        for (j = i + 1; j < n; ++j) {\n            add_next_index_double(&rowB, 0.0);\n        }\n\n        add_next_index_zval(&b, &rowB);\n    }\n\n    RETVAL_ARR(Z_ARR(b));\n\n    efree(va);\n}\n\n/**\n * Compute the LU factorization of matrix A and return a tuple with lower, upper, and permutation matrices.\n * \n * @param return_value\n * @param a\n */\nvoid tensor_lu(zval * return_value, zval * a)\n{\n    unsigned int i, j;\n    Bucket * row;\n    zval rowL, l, rowU, u, rowP, p;\n    zval tuple;\n\n    zend_array * aa = Z_ARR_P(a);\n\n    Bucket * ba = aa->arData;\n\n    unsigned int n = zend_array_count(aa);\n\n    double * va = emalloc(n * n * sizeof(double));\n    int * pivots = emalloc(n * sizeof(int));\n\n    for (i = 0; i < n; ++i) {\n        row = Z_ARR(ba[i].val)->arData;\n\n        for (j = 0; j < n; ++j) {\n            va[i * n + j] = zephir_get_doubleval(&row[j].val);\n        }\n    }\n\n    lapack_int status = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, va, n, pivots);\n\n    if (status != 0) {\n        RETURN_NULL();\n    }\n    \n    array_init_size(&l, n);\n    array_init_size(&u, n);\n    array_init_size(&p, n);\n\n    for (i = 0; i < n; ++i) {\n        array_init_size(&rowL, n);\n\n        for (j = 0; j < i; ++j) {\n            add_next_index_double(&rowL, va[i * n + j]);\n        }\n\n        add_next_index_double(&rowL, 1.0);\n\n        for (j = i + 1; j < n; ++j) {\n            add_next_index_double(&rowL, 0.0);\n        }\n\n        add_next_index_zval(&l, &rowL);\n    }\n\n    for (i = 0; i < n; ++i) {\n        array_init_size(&rowU, n);\n\n        for (j = 0; j < i; ++j) {\n            add_next_index_double(&rowU, 0.0);\n        }\n\n        for (j = i; j < n; ++j) {\n            add_next_index_double(&rowU, va[i * n + j]);\n        }\n\n        add_next_index_zval(&u, &rowU);\n    }\n\n    for (i = 0; i < n; ++i) {\n        array_init_size(&rowP, n);\n\n        for (j = 0; j < n; ++j) {\n            if (j == pivots[i] - 1) {\n                add_next_index_long(&rowP, 1);\n            } else {\n                add_next_index_long(&rowP, 0);\n            }\n        }\n\n        add_next_index_zval(&p, &rowP);\n    }\n\n    array_init_size(&tuple, 3);\n    \n    add_next_index_zval(&tuple, &l);\n    add_next_index_zval(&tuple, &u);\n    add_next_index_zval(&tuple, &p);\n\n    RETVAL_ARR(Z_ARR(tuple));\n\n    efree(va);\n    efree(pivots); \n}\n\n/**\n * Compute the eigendecomposition of a general matrix A and return the eigenvalues and eigenvectors in a tuple.\n * \n * @param return_value\n * @param a\n */\nvoid tensor_eig(zval * return_value, zval * a)\n{\n    unsigned int i, j;\n    Bucket * row;\n    zval eigenvalues;\n    zval eigenvectors;\n    zval eigenvector;\n    zval tuple;\n\n    zend_array * aa = Z_ARR_P(a);\n\n    Bucket * ba = aa->arData;\n\n    unsigned int n = zend_array_count(aa);\n\n    double * va = emalloc(n * n * sizeof(double));\n    double * wr = emalloc(n * sizeof(double));\n    double * wi = emalloc(n * sizeof(double));\n    double * vr = emalloc(n * n * sizeof(double));\n\n    for (i = 0; i < n; ++i) {\n        row = Z_ARR(ba[i].val)->arData;\n\n        for (j = 0; j < n; ++j) {\n            va[i * n + j] = zephir_get_doubleval(&row[j].val);\n        }\n    }\n\n    lapack_int status = LAPACKE_dgeev(LAPACK_ROW_MAJOR, 'N', 'V', n, va, n, wr, wi, NULL, n, vr, n);\n\n    if (status != 0) {\n        RETURN_NULL();\n    }\n\n    array_init_size(&eigenvalues, n);\n    array_init_size(&eigenvectors, n);\n\n    for (i = 0; i < n; ++i) {\n        add_next_index_double(&eigenvalues, wr[i]);\n\n        array_init_size(&eigenvector, n);\n\n        for (j = 0; j < n; ++j) {\n            add_next_index_double(&eigenvector, vr[i * n + j]);\n        }\n\n        add_next_index_zval(&eigenvectors, &eigenvector);\n    }\n\n    array_init_size(&tuple, 2);\n    \n    add_next_index_zval(&tuple, &eigenvalues);\n    add_next_index_zval(&tuple, &eigenvectors);\n\n    RETVAL_ARR(Z_ARR(tuple));\n\n    efree(va);\n    efree(wr);\n    efree(wi);\n    efree(vr);\n}\n\n/**\n * Compute the eigendecomposition of a symmetric matrix A and return the eigenvalues and eigenvectors in a tuple.\n * \n * @param return_value\n * @param a\n */\nvoid tensor_eig_symmetric(zval * return_value, zval * a)\n{\n    unsigned int i, j;\n    Bucket * row;\n    zval eigenvalues;\n    zval eigenvectors;\n    zval eigenvector;\n    zval tuple;\n\n    zend_array * aa = Z_ARR_P(a);\n\n    Bucket * ba = aa->arData;\n\n    unsigned int n = zend_array_count(aa);\n\n    double * va = emalloc(n * n * sizeof(double));\n    double * wr = emalloc(n * sizeof(double));\n\n    for (i = 0; i < n; ++i) {\n        row = Z_ARR(ba[i].val)->arData;\n\n        for (j = 0; j < n; ++j) {\n            va[i * n + j] = zephir_get_doubleval(&row[j].val);\n        }\n    }\n\n    lapack_int status = LAPACKE_dsyev(LAPACK_ROW_MAJOR, 'V', 'U', n, va, n, wr);\n\n    if (status != 0) {\n        RETURN_NULL();\n    }\n\n    array_init_size(&eigenvalues, n);\n    array_init_size(&eigenvectors, n);\n\n    for (i = 0; i < n; ++i) {\n        add_next_index_double(&eigenvalues, wr[i]);\n\n        array_init_size(&eigenvector, n);\n\n        for (j = 0; j < n; ++j) {\n            add_next_index_double(&eigenvector, va[i * n + j]);\n        }\n\n        add_next_index_zval(&eigenvectors, &eigenvector);\n    }\n\n    array_init_size(&tuple, 2);\n    \n    add_next_index_zval(&tuple, &eigenvalues);\n    add_next_index_zval(&tuple, &eigenvectors);\n\n    RETVAL_ARR(Z_ARR(tuple));\n\n    efree(va);\n    efree(wr);\n}\n\n/**\n * Compute the singular value decomposition of a matrix A and return the singular values, and unitary matrices U and VT in a tuple.\n * \n * @param return_value\n * @param a\n */\nvoid tensor_svd(zval * return_value, zval * a)\n{\n    unsigned int i, j;\n    Bucket * row;\n    zval u, rowU;\n    zval s;\n    zval vt, rowVt;\n    zval tuple;\n\n    zend_array * aa = Z_ARR_P(a);\n\n    Bucket * ba = aa->arData;\n\n    unsigned int m = zend_array_count(aa);\n    unsigned int n = zend_array_count(Z_ARR(ba[0].val));\n    unsigned int k = MIN(m, n);\n\n    double * va = emalloc(m * n * sizeof(double));\n    double * vu = emalloc(m * m * sizeof(double));\n    double * vs = emalloc(k * sizeof(double));\n    double * vvt = emalloc(n * n * sizeof(double));\n\n    for (i = 0; i < m; ++i) {\n        row = Z_ARR(ba[i].val)->arData;\n\n        for (j = 0; j < n; ++j) {\n            va[i * n + j] = zephir_get_doubleval(&row[j].val);\n        }\n    }\n\n    lapack_int status = LAPACKE_dgesdd(LAPACK_ROW_MAJOR, 'A', m, n, va, n, vs, vu, m, vvt, n);\n\n    if (status != 0) {\n        RETURN_NULL();\n    }\n\n    array_init_size(&u, m);\n    array_init_size(&s, k);\n    array_init_size(&vt, n);\n\n    for (i = 0; i < m; ++i) {\n        array_init_size(&rowU, m);\n\n        for (j = 0; j < m; ++j) {\n            add_next_index_double(&rowU, vu[i * m + j]);\n        }\n\n        add_next_index_zval(&u, &rowU);\n    }\n    \n    for (i = 0; i < k; ++i) {\n        add_next_index_double(&s, vs[i]);\n    }\n\n    for (i = 0; i < n; ++i) {\n        array_init_size(&rowVt, n);\n\n        for (j = 0; j < n; ++j) {\n            add_next_index_double(&rowVt, vvt[i * n + j]);\n        }\n\n        add_next_index_zval(&vt, &rowVt);\n    }\n\n    array_init_size(&tuple, 3);\n    \n    add_next_index_zval(&tuple, &u);\n    add_next_index_zval(&tuple, &s);\n    add_next_index_zval(&tuple, &vt);\n\n    RETVAL_ARR(Z_ARR(tuple));\n\n    efree(va);\n    efree(vu);\n    efree(vs);\n    efree(vvt);\n}\n", "meta": {"hexsha": "a551923dcc5ad00a6fc78c69c1d1e0c86d7437f1", "size": 14486, "ext": "c", "lang": "C", "max_stars_repo_path": "src/vendor/rubix/tensor/ext/include/linear_algebra.c", "max_stars_repo_name": "asdrenxhafa/mood_detection", "max_stars_repo_head_hexsha": "cf6f57a4b88e2954c00c2598ea37e6246567d215", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-06T19:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-06T19:09:18.000Z", "max_issues_repo_path": "src/vendor/rubix/tensor/ext/include/linear_algebra.c", "max_issues_repo_name": "asdrenxhafa/mood_detection", "max_issues_repo_head_hexsha": "cf6f57a4b88e2954c00c2598ea37e6246567d215", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vendor/rubix/tensor/ext/include/linear_algebra.c", "max_forks_repo_name": "asdrenxhafa/mood_detection", "max_forks_repo_head_hexsha": "cf6f57a4b88e2954c00c2598ea37e6246567d215", "max_forks_repo_licenses": ["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.7507507508, "max_line_length": 131, "alphanum_fraction": 0.5321689907, "num_tokens": 4684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.36422578108397413}}
{"text": "/* specfunc/legendre_con.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\n * Copyright (C) 2010 Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_poly.h>\n#include <gsl/gsl_sf_exp.h>\n#include <gsl/gsl_sf_trig.h>\n#include <gsl/gsl_sf_gamma.h>\n#include <gsl/gsl_sf_ellint.h>\n#include <gsl/gsl_sf_pow_int.h>\n#include <gsl/gsl_sf_bessel.h>\n#include <gsl/gsl_sf_hyperg.h>\n#include <gsl/gsl_sf_legendre.h>\n\n#include \"error.h\"\n#include \"legendre.h\"\n\n#define Root_2OverPi_  0.797884560802865355879892\n#define locEPS         (1000.0*GSL_DBL_EPSILON)\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n\n#define RECURSE_LARGE  (1.0e-5*GSL_DBL_MAX)\n#define RECURSE_SMALL  (1.0e+5*GSL_DBL_MIN)\n\n\n/* Continued fraction for f_{ell+1}/f_ell\n * f_ell := P^{-mu-ell}_{-1/2 + I tau}(x),  x < 1.0\n *\n * Uses standard CF method from Temme's book.\n */\nstatic\nint\nconicalP_negmu_xlt1_CF1(const double mu, const int ell, const double tau,\n                        const double x, gsl_sf_result * result)\n{\n  const double RECUR_BIG = GSL_SQRT_DBL_MAX;\n  const int maxiter = 5000;\n  int n = 1;\n  double xi = x/(sqrt(1.0-x)*sqrt(1.0+x));\n  double Anm2 = 1.0;\n  double Bnm2 = 0.0;\n  double Anm1 = 0.0;\n  double Bnm1 = 1.0;\n  double a1 = 1.0;\n  double b1 = 2.0*(mu + ell + 1.0) * xi;\n  double An = b1*Anm1 + a1*Anm2;\n  double Bn = b1*Bnm1 + a1*Bnm2;\n  double an, bn;\n  double fn = An/Bn;\n\n  while(n < maxiter) {\n    double old_fn;\n    double del;\n    n++;\n    Anm2 = Anm1;\n    Bnm2 = Bnm1;\n    Anm1 = An;\n    Bnm1 = Bn;\n    an = tau*tau + (mu - 0.5 + ell + n)*(mu - 0.5 + ell + n);\n    bn = 2.0*(ell + mu + n) * xi;\n    An = bn*Anm1 + an*Anm2;\n    Bn = bn*Bnm1 + an*Bnm2;\n\n    if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) {\n      An /= RECUR_BIG;\n      Bn /= RECUR_BIG;\n      Anm1 /= RECUR_BIG;\n      Bnm1 /= RECUR_BIG;\n      Anm2 /= RECUR_BIG;\n      Bnm2 /= RECUR_BIG;\n    }\n\n    old_fn = fn;\n    fn = An/Bn;\n    del = old_fn/fn;\n    \n    if(fabs(del - 1.0) < 2.0*GSL_DBL_EPSILON) break;\n  }\n\n  result->val = fn;\n  result->err = 4.0 * GSL_DBL_EPSILON * (sqrt(n) + 1.0) * fabs(fn);\n\n  if(n >= maxiter)\n    GSL_ERROR (\"error\", GSL_EMAXITER);\n  else\n    return GSL_SUCCESS;\n}\n\n\n/* Continued fraction for f_{ell+1}/f_ell\n * f_ell := P^{-mu-ell}_{-1/2 + I tau}(x),  x >= 1.0\n *\n * Uses Gautschi (Euler) equivalent series.\n */\nstatic\nint\nconicalP_negmu_xgt1_CF1(const double mu, const int ell, const double tau,\n                        const double x, gsl_sf_result * result)\n{ \n  const int maxk = 20000;\n  const double gamma = 1.0-1.0/(x*x);\n  const double pre = sqrt(x-1.0)*sqrt(x+1.0) / (x*(2.0*(ell+mu+1.0)));\n  double tk   = 1.0;\n  double sum  = 1.0;\n  double rhok = 0.0;\n  int k;\n \n  for(k=1; k<maxk; k++) {\n    double tlk = 2.0*(ell + mu + k);\n    double l1k = (ell + mu - 0.5 + 1.0 + k);\n    double ak = -(tau*tau + l1k*l1k)/(tlk*(tlk+2.0)) * gamma;\n    rhok = -ak*(1.0 + rhok)/(1.0 + ak*(1.0 + rhok));\n    tk  *= rhok;\n    sum += tk;\n    if(fabs(tk/sum) < GSL_DBL_EPSILON) break;\n  }\n\n  result->val  = pre * sum;\n  result->err  = fabs(pre * tk);\n  result->err += 2.0 * GSL_DBL_EPSILON * (sqrt(k) + 1.0) * fabs(pre*sum);\n\n  if(k >= maxk)\n    GSL_ERROR (\"error\", GSL_EMAXITER);\n  else\n    return GSL_SUCCESS;\n}\n\n\n/* Implementation of large negative mu asymptotic\n * [Dunster, Proc. Roy. Soc. Edinburgh 119A, 311 (1991), p. 326]\n */\n\ninline\nstatic double olver_U1(double beta2, double p)\n{\n  return (p-1.0)/(24.0*(1.0+beta2)) * (3.0 + beta2*(2.0 + 5.0*p*(1.0+p)));\n}\n\ninline\nstatic double olver_U2(double beta2, double p)\n{\n  double beta4 = beta2*beta2;\n  double p2    = p*p;\n  double poly1 =  4.0*beta4 + 84.0*beta2 - 63.0;\n  double poly2 = 16.0*beta4 + 90.0*beta2 - 81.0;\n  double poly3 = beta2*p2*(97.0*beta2 - 432.0 + 77.0*p*(beta2-6.0) - 385.0*beta2*p2*(1.0 + p));\n  return (1.0-p)/(1152.0*(1.0+beta2)) * (poly1 + poly2 + poly3);\n}\n\nstatic const double U3c1[] = {   -1307.0,   -1647.0,    3375.0,    3675.0 };\nstatic const double U3c2[] = {   29366.0,   35835.0, -252360.0, -272630.0,\n                                276810.0,  290499.0 };\nstatic const double U3c3[] = {  -29748.0,   -8840.0, 1725295.0, 1767025.0,\n                              -7313470.0, -754778.0, 6309875.0, 6480045.0 };\nstatic const double U3c4[] = {    2696.0,    -16740.0,   -524250.0,  -183975.0,\n                              14670540.0,  14172939.0, -48206730.0, -48461985.0,\n                              36756720.0,  37182145.0 };\nstatic const double U3c5[] = {       9136.0,      22480.0,     12760.0,\n                                  -252480.0,   -4662165.0,   -1705341.0,\n                                 92370135.0,   86244015.0, -263678415.0,\n                               -260275015.0, 185910725.0,  185910725.0 };\n\n#if 0\nstatic double olver_U3(double beta2, double p)\n{\n  double beta4 = beta2*beta2;\n  double beta6 = beta4*beta2;\n  double opb2s = (1.0+beta2)*(1.0+beta2);\n  double den   = 39813120.0 * opb2s*opb2s;\n  double poly1 = gsl_poly_eval(U3c1, 4, p);\n  double poly2 = gsl_poly_eval(U3c2, 6, p);\n  double poly3 = gsl_poly_eval(U3c3, 8, p);\n  double poly4 = gsl_poly_eval(U3c4, 10, p);\n  double poly5 = gsl_poly_eval(U3c5, 12, p);\n  \n  return (p-1.0)*(     1215.0*poly1 + 324.0*beta2*poly2\n                 + 54.0*beta4*poly3 +  12.0*beta6*poly4\n                 + beta4*beta4*poly5\n                 ) / den;\n}\n#endif /* 0 */\n\n\n/* Large negative mu asymptotic\n * P^{-mu}_{-1/2 + I tau}, mu -> Inf\n * |x| < 1\n *\n * [Dunster, Proc. Roy. Soc. Edinburgh 119A, 311 (1991), p. 326]\n */\nint\ngsl_sf_conicalP_xlt1_large_neg_mu_e(double mu, double tau, double x,\n                                       gsl_sf_result * result, double * ln_multiplier)\n{\n  double beta  = tau/mu;\n  double beta2 = beta*beta;\n  double S     = beta * acos((1.0-beta2)/(1.0+beta2));\n  double p     = x/sqrt(beta2*(1.0-x*x) + 1.0);\n  gsl_sf_result lg_mup1;\n  int lg_stat = gsl_sf_lngamma_e(mu+1.0, &lg_mup1);\n  double ln_pre_1 =  0.5*mu*(S - log(1.0+beta2) + log((1.0-p)/(1.0+p))) - lg_mup1.val;\n  double ln_pre_2 = -0.25 * log(1.0 + beta2*(1.0-x));\n  double ln_pre_3 = -tau * atan(p*beta);\n  double ln_pre = ln_pre_1 + ln_pre_2 + ln_pre_3;\n  double sum   = 1.0 - olver_U1(beta2, p)/mu + olver_U2(beta2, p)/(mu*mu);\n\n  if(sum == 0.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    *ln_multiplier = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    int stat_e = gsl_sf_exp_mult_e(ln_pre, sum, result);\n    if(stat_e != GSL_SUCCESS) {\n      result->val = sum;\n      result->err = 2.0 * GSL_DBL_EPSILON * fabs(sum);\n      *ln_multiplier = ln_pre;\n    }\n    else {\n      *ln_multiplier = 0.0;\n    }\n    return lg_stat;\n  }\n}\n\n\n/* Implementation of large tau asymptotic\n *\n * A_n^{-mu}, B_n^{-mu}  [Olver, p.465, 469]\n */\n\ninline\nstatic double olver_B0_xi(double mu, double xi)\n{\n  return (1.0 - 4.0*mu*mu)/(8.0*xi) * (1.0/tanh(xi) - 1.0/xi);\n}\n\nstatic double olver_A1_xi(double mu, double xi, double x)\n{\n  double B = olver_B0_xi(mu, xi);\n  double psi;\n  if(fabs(x - 1.0) < GSL_ROOT4_DBL_EPSILON) {\n    double y = x - 1.0;\n    double s = -1.0/3.0 + y*(2.0/15.0 - y *(61.0/945.0 - 452.0/14175.0*y));\n    psi = (4.0*mu*mu - 1.0)/16.0 * s;\n  }\n  else {\n    psi = (4.0*mu*mu - 1.0)/16.0 * (1.0/(x*x-1.0) - 1.0/(xi*xi));\n  }\n  return 0.5*xi*xi*B*B + (mu+0.5)*B - psi + mu/6.0*(0.25 - mu*mu);\n}\n\ninline\nstatic double olver_B0_th(double mu, double theta)\n{\n  return -(1.0 - 4.0*mu*mu)/(8.0*theta) * (1.0/tan(theta) - 1.0/theta);\n}\n\nstatic double olver_A1_th(double mu, double theta, double x)\n{\n  double B = olver_B0_th(mu, theta);\n  double psi;\n  if(fabs(x - 1.0) < GSL_ROOT4_DBL_EPSILON) {\n    double y = 1.0 - x;\n    double s = -1.0/3.0 + y*(2.0/15.0 - y *(61.0/945.0 - 452.0/14175.0*y));\n    psi = (4.0*mu*mu - 1.0)/16.0 * s;\n  }\n  else {\n    psi = (4.0*mu*mu - 1.0)/16.0 * (1.0/(x*x-1.0) + 1.0/(theta*theta));\n  }\n  return -0.5*theta*theta*B*B + (mu+0.5)*B - psi + mu/6.0*(0.25 - mu*mu);\n}\n\n\n/* Large tau uniform asymptotics\n * P^{-mu}_{-1/2 + I tau}\n * 1 < x\n * tau -> Inf \n * [Olver, p. 469]\n */\nint\ngsl_sf_conicalP_xgt1_neg_mu_largetau_e(const double mu, const double tau,\n                                          const double x, double acosh_x,\n                                          gsl_sf_result * result, double * ln_multiplier)\n{\n  double xi = acosh_x;\n  double ln_xi_pre;\n  double ln_pre;\n  double sumA, sumB, sum;\n  double arg;\n  gsl_sf_result J_mup1;\n  gsl_sf_result J_mu;\n  double J_mum1;\n\n  if(xi < GSL_ROOT4_DBL_EPSILON) {\n    ln_xi_pre = -xi*xi/6.0;           /* log(1.0 - xi*xi/6.0) */\n  }\n  else {\n    gsl_sf_result lnshxi;\n    gsl_sf_lnsinh_e(xi, &lnshxi);\n    ln_xi_pre = log(xi) - lnshxi.val;     /* log(xi/sinh(xi) */\n  }\n\n  ln_pre = 0.5*ln_xi_pre - mu*log(tau);\n\n  arg = tau*xi;\n\n  gsl_sf_bessel_Jnu_e(mu + 1.0,   arg, &J_mup1);\n  gsl_sf_bessel_Jnu_e(mu,         arg, &J_mu);\n  J_mum1 = -J_mup1.val + 2.0*mu/arg*J_mu.val;      /* careful of mu < 1 */\n\n  sumA = 1.0 - olver_A1_xi(-mu, xi, x)/(tau*tau);\n  sumB = olver_B0_xi(-mu, xi);\n  sum  = J_mu.val * sumA - xi/tau * J_mum1 * sumB;\n\n  if(sum == 0.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    *ln_multiplier = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    int stat_e = gsl_sf_exp_mult_e(ln_pre, sum, result);\n    if(stat_e != GSL_SUCCESS) {\n      result->val = sum;\n      result->err = 2.0 * GSL_DBL_EPSILON * fabs(sum);\n      *ln_multiplier = ln_pre;\n    }\n    else {\n      *ln_multiplier = 0.0;\n    }\n    return GSL_SUCCESS;\n  }\n}\n\n\n/* Large tau uniform asymptotics\n * P^{-mu}_{-1/2 + I tau}\n * -1 < x < 1\n * tau -> Inf \n * [Olver, p. 473]\n */\nint\ngsl_sf_conicalP_xlt1_neg_mu_largetau_e(const double mu, const double tau,\n                                          const double x, const double acos_x,\n                                          gsl_sf_result * result, double * ln_multiplier)\n{\n  double theta = acos_x;\n  double ln_th_pre;\n  double ln_pre;\n  double sumA, sumB, sum, sumerr;\n  double arg;\n  gsl_sf_result I_mup1, I_mu;\n  double I_mum1;\n\n  if(theta < GSL_ROOT4_DBL_EPSILON) {\n    ln_th_pre = theta*theta/6.0;   /* log(1.0 + theta*theta/6.0) */\n  }\n  else {\n    ln_th_pre = log(theta/sin(theta));\n  }\n\n  ln_pre = 0.5 * ln_th_pre - mu * log(tau);\n\n  arg = tau*theta;\n  gsl_sf_bessel_Inu_e(mu + 1.0,   arg, &I_mup1);\n  gsl_sf_bessel_Inu_e(mu,         arg, &I_mu);\n  I_mum1 = I_mup1.val + 2.0*mu/arg * I_mu.val; /* careful of mu < 1 */\n\n  sumA = 1.0 - olver_A1_th(-mu, theta, x)/(tau*tau);\n  sumB = olver_B0_th(-mu, theta);\n  sum  = I_mu.val * sumA - theta/tau * I_mum1 * sumB;\n  sumerr  = fabs(I_mu.err * sumA);\n  sumerr += fabs(I_mup1.err * theta/tau * sumB);\n  sumerr += fabs(I_mu.err   * theta/tau * sumB * 2.0 * mu/arg);\n\n  if(sum == 0.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    *ln_multiplier = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    int stat_e = gsl_sf_exp_mult_e(ln_pre, sum, result);\n    if(stat_e != GSL_SUCCESS) {\n      result->val  = sum;\n      result->err  = sumerr;\n      result->err += GSL_DBL_EPSILON * fabs(sum);\n      *ln_multiplier = ln_pre;\n    }\n    else {\n      *ln_multiplier = 0.0;\n    }\n    return GSL_SUCCESS;\n  }\n}\n\n\n/* Hypergeometric function which appears in the\n * large x expansion below:\n *\n *   2F1(1/4 - mu/2 - I tau/2, 3/4 - mu/2 - I tau/2, 1 - I tau, y)\n *\n * Note that for the usage below y = 1/x^2;\n */\nstatic\nint\nconicalP_hyperg_large_x(const double mu, const double tau, const double y,\n                        double * reF, double * imF)\n{\n  const int kmax = 1000;\n  const double re_a = 0.25 - 0.5*mu;\n  const double re_b = 0.75 - 0.5*mu;\n  const double re_c = 1.0;\n  const double im_a = -0.5*tau;\n  const double im_b = -0.5*tau;\n  const double im_c = -tau;\n\n  double re_sum = 1.0;\n  double im_sum = 0.0;\n  double re_term = 1.0;\n  double im_term = 0.0;\n  int k;\n\n  for(k=1; k<=kmax; k++) {\n    double re_ak = re_a + k - 1.0;\n    double re_bk = re_b + k - 1.0;\n    double re_ck = re_c + k - 1.0;\n    double im_ak = im_a;\n    double im_bk = im_b;\n    double im_ck = im_c;\n    double den = re_ck*re_ck + im_ck*im_ck;\n    double re_multiplier = ((re_ak*re_bk - im_ak*im_bk)*re_ck + im_ck*(im_ak*re_bk + re_ak*im_bk)) / den;\n    double im_multiplier = ((im_ak*re_bk + re_ak*im_bk)*re_ck - im_ck*(re_ak*re_bk - im_ak*im_bk)) / den;\n    double re_tmp = re_multiplier*re_term - im_multiplier*im_term;\n    double im_tmp = im_multiplier*re_term + re_multiplier*im_term;\n    double asum = fabs(re_sum) + fabs(im_sum);\n    re_term = y/k * re_tmp;\n    im_term = y/k * im_tmp;\n    if(fabs(re_term/asum) < GSL_DBL_EPSILON && fabs(im_term/asum) < GSL_DBL_EPSILON) break;\n    re_sum += re_term;\n    im_sum += im_term;\n  }\n\n  *reF = re_sum;\n  *imF = im_sum;\n\n  if(k == kmax)\n    GSL_ERROR (\"error\", GSL_EMAXITER);\n  else  \n    return GSL_SUCCESS;\n}\n\n\n/* P^{mu}_{-1/2 + I tau}\n * x->Inf\n */\nint\ngsl_sf_conicalP_large_x_e(const double mu, const double tau, const double x,\n                             gsl_sf_result * result, double * ln_multiplier)\n{\n  /* 2F1 term\n   */\n  double y = ( x < 0.5*GSL_SQRT_DBL_MAX ? 1.0/(x*x) : 0.0 );\n  double reF, imF;\n  int stat_F = conicalP_hyperg_large_x(mu, tau, y, &reF, &imF);\n\n  /* f = Gamma(+i tau)/Gamma(1/2 - mu + i tau)\n   * FIXME: shift so it's better for tau-> 0\n   */\n  gsl_sf_result lgr_num, lgth_num;\n  gsl_sf_result lgr_den, lgth_den;\n  int stat_gn = gsl_sf_lngamma_complex_e(0.0,tau,&lgr_num,&lgth_num);\n  int stat_gd = gsl_sf_lngamma_complex_e(0.5-mu,tau,&lgr_den,&lgth_den);\n\n  double angle = lgth_num.val - lgth_den.val + atan2(imF,reF);\n\n  double lnx   = log(x);\n  double lnxp1 = log(x+1.0);\n  double lnxm1 = log(x-1.0);\n  double lnpre_const = 0.5*M_LN2 - 0.5*M_LNPI;\n  double lnpre_comm = (mu-0.5)*lnx - 0.5*mu*(lnxp1 + lnxm1);\n  double lnpre_err  =   GSL_DBL_EPSILON * (0.5*M_LN2 + 0.5*M_LNPI)\n                      + GSL_DBL_EPSILON * fabs((mu-0.5)*lnx)\n                      + GSL_DBL_EPSILON * fabs(0.5*mu)*(fabs(lnxp1)+fabs(lnxm1));\n\n  /*  result = pre*|F|*|f| * cos(angle - tau * (log(x)+M_LN2))\n   */\n  gsl_sf_result cos_result;\n  int stat_cos = gsl_sf_cos_e(angle + tau*(log(x) + M_LN2), &cos_result);\n  int status = GSL_ERROR_SELECT_4(stat_cos, stat_gd, stat_gn, stat_F);\n  if(cos_result.val == 0.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return status;\n  }\n  else {\n    double lnFf_val = 0.5*log(reF*reF+imF*imF) + lgr_num.val - lgr_den.val;\n    double lnFf_err = lgr_num.err + lgr_den.err + GSL_DBL_EPSILON * fabs(lnFf_val);\n    double lnnoc_val = lnpre_const + lnpre_comm + lnFf_val;\n    double lnnoc_err = lnpre_err + lnFf_err + GSL_DBL_EPSILON * fabs(lnnoc_val);\n    int stat_e = gsl_sf_exp_mult_err_e(lnnoc_val, lnnoc_err,\n                                          cos_result.val, cos_result.err,\n                                          result);\n    if(stat_e == GSL_SUCCESS) {\n      *ln_multiplier = 0.0;\n    }\n    else {\n      result->val  = cos_result.val;\n      result->err  = cos_result.err;\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      *ln_multiplier = lnnoc_val;\n    }\n    return status;\n  }\n}\n\n\n/* P^{mu}_{-1/2 + I tau}  first hypergeometric representation\n * -1 < x < 1\n * This is more effective for |x| small, however it will work w/o\n * reservation for any x < 0 because everything is positive\n * definite in that case.\n *\n * [Kolbig,   (3)] (note typo in args of gamma functions)\n * [Bateman, (22)] (correct form)\n */\nstatic\nint\nconicalP_xlt1_hyperg_A(double mu, double tau, double x, gsl_sf_result * result)\n{\n  double x2 = x*x;\n  double err_amp = 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-fabs(x)));\n  double pre_val = M_SQRTPI / pow(0.5*sqrt(1-x2), mu);\n  double pre_err = err_amp * GSL_DBL_EPSILON * (fabs(mu)+1.0) * fabs(pre_val) ;\n  gsl_sf_result ln_g1, ln_g2, arg_g1, arg_g2;\n  gsl_sf_result F1, F2;\n  gsl_sf_result pre1, pre2;\n  double t1_val, t1_err;\n  double t2_val, t2_err;\n\n  int stat_F1 = gsl_sf_hyperg_2F1_conj_e(0.25 - 0.5*mu, 0.5*tau, 0.5, x2, &F1);\n  int stat_F2 = gsl_sf_hyperg_2F1_conj_e(0.75 - 0.5*mu, 0.5*tau, 1.5, x2, &F2);\n  int status = GSL_ERROR_SELECT_2(stat_F1, stat_F2);\n\n  gsl_sf_lngamma_complex_e(0.75 - 0.5*mu, -0.5*tau, &ln_g1, &arg_g1);\n  gsl_sf_lngamma_complex_e(0.25 - 0.5*mu, -0.5*tau, &ln_g2, &arg_g2);\n\n  gsl_sf_exp_err_e(-2.0*ln_g1.val, 2.0*ln_g1.err, &pre1);\n  gsl_sf_exp_err_e(-2.0*ln_g2.val, 2.0*ln_g2.err, &pre2);\n  pre2.val *= -2.0*x;\n  pre2.err *=  2.0*fabs(x);\n  pre2.err +=  GSL_DBL_EPSILON * fabs(pre2.val);\n\n  t1_val = pre1.val * F1.val;\n  t1_err = fabs(pre1.val) * F1.err + pre1.err * fabs(F1.val);\n  t2_val = pre2.val * F2.val;\n  t2_err = fabs(pre2.val) * F2.err + pre2.err * fabs(F2.val);\n\n  result->val  = pre_val * (t1_val + t2_val);\n  result->err  = pre_val * (t1_err + t2_err);\n  result->err += pre_err * fabs(t1_val + t2_val);\n  result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n  return status;\n}\n\n\n/* P^{mu}_{-1/2 + I tau}\n * defining hypergeometric representation\n * [Abramowitz+Stegun, 8.1.2]\n * 1 < x < 3\n * effective for x near 1\n *\n */\n#if 0\nstatic\nint\nconicalP_def_hyperg(double mu, double tau, double x, double * result)\n{\n  double F;\n  int stat_F = gsl_sf_hyperg_2F1_conj_renorm_e(0.5, tau, 1.0-mu, 0.5*(1.0-x), &F);\n  *result = pow((x+1.0)/(x-1.0), 0.5*mu) * F;\n  return stat_F;\n}\n#endif /* 0 */\n\n\n/* P^{mu}_{-1/2 + I tau}  second hypergeometric representation\n * [Zhurina+Karmazina, (3.1)] \n * -1 < x < 3\n * effective for x near 1\n *\n */\n#if 0\nstatic\nint\nconicalP_xnear1_hyperg_C(double mu, double tau, double x, double * result)\n{\n  double ln_pre, arg_pre;\n  double ln_g1, arg_g1;\n  double ln_g2, arg_g2;\n  double F;\n\n  int stat_F = gsl_sf_hyperg_2F1_conj_renorm_e(0.5+mu, tau, 1.0+mu, 0.5*(1.0-x), &F);\n\n  gsl_sf_lngamma_complex_e(0.5+mu, tau, &ln_g1, &arg_g1);\n  gsl_sf_lngamma_complex_e(0.5-mu, tau, &ln_g2, &arg_g2);\n\n  ln_pre  = mu*M_LN2 - 0.5*mu*log(fabs(x*x-1.0)) + ln_g1 - ln_g2;\n  arg_pre = arg_g1 - arg_g2;\n\n  *result = exp(ln_pre) * F;\n  return stat_F;\n}\n#endif /* 0 */\n\n\n/* V0, V1 from Kolbig, m = 0\n */\nstatic\nint\nconicalP_0_V(const double t, const double f, const double tau, const double sgn,\n             double * V0, double * V1)\n{\n  double C[8];\n  double T[8];\n  double H[8];\n  double V[12];\n  int i;\n  T[0] = 1.0;\n  H[0] = 1.0;\n  V[0] = 1.0;\n  for(i=1; i<=7; i++) {\n    T[i] = T[i-1] * t;\n    H[i] = H[i-1] * (t*f);\n  }\n  for(i=1; i<=11; i++) {\n    V[i] = V[i-1] * tau;\n  }\n\n  C[0] = 1.0;\n  C[1] = (H[1]-1.0)/(8.0*T[1]);\n  C[2] = (9.0*H[2] + 6.0*H[1] - 15.0 - sgn*8.0*T[2])/(128.0*T[2]);\n  C[3] = 5.0*(15.0*H[3] + 27.0*H[2] + 21.0*H[1] - 63.0 - sgn*T[2]*(16.0*H[1]+24.0))/(1024.0*T[3]);\n  C[4] = 7.0*(525.0*H[4] + 1500.0*H[3] + 2430.0*H[2] + 1980.0*H[1] - 6435.0\n              + 192.0*T[4] - sgn*T[2]*(720.0*H[2]+1600.0*H[1]+2160.0)\n              ) / (32768.0*T[4]);\n  C[5] = 21.0*(2835.0*H[5] + 11025.0*H[4] + 24750.0*H[3] + 38610.0*H[2]\n               + 32175.0*H[1] - 109395.0 + T[4]*(1984.0*H[1]+4032.0)\n               - sgn*T[2]*(4800.0*H[3]+15120.0*H[2]+26400.0*H[1]+34320.0)\n               ) / (262144.0*T[5]);\n  C[6] = 11.0*(218295.0*H[6] + 1071630.0*H[5] + 3009825.0*H[4] + 6142500.0*H[3]\n               + 9398025.0*H[2] + 7936110.0*H[1] - 27776385.0\n               + T[4]*(254016.0*H[2]+749952.0*H[1]+1100736.0)\n               - sgn*T[2]*(441000.0*H[4] + 1814400.0*H[3] + 4127760.0*H[2]\n                         + 6552000.0*H[1] + 8353800.0 + 31232.0*T[4]\n                         )\n               ) / (4194304.0*T[6]);\n\n  *V0 = C[0] + (-4.0*C[3]/T[1]+C[4])/V[4]\n             + (-192.0*C[5]/T[3]+144.0*C[6]/T[2])/V[8]\n             + sgn * (-C[2]/V[2]\n                      + (-24.0*C[4]/T[2]+12.0*C[5]/T[1]-C[6])/V[6] \n                      + (-1920.0*C[6]/T[4])/V[10]\n                      );\n  *V1 = C[1]/V[1] + (8.0*(C[3]/T[2]-C[4]/T[1])+C[5])/V[5]\n                  + (384.0*C[5]/T[4] - 768.0*C[6]/T[3])/V[9]\n                  + sgn * ((2.0*C[2]/T[1]-C[3])/V[3]\n                           + (48.0*C[4]/T[3]-72.0*C[5]/T[2] + 18.0*C[6]/T[1])/V[7]\n                           + (3840.0*C[6]/T[5])/V[11]\n                           );\n\n  return GSL_SUCCESS;\n}\n\n\n/* V0, V1 from Kolbig, m = 1\n */\nstatic\nint\nconicalP_1_V(const double t, const double f, const double tau, const double sgn,\n             double * V0, double * V1)\n{\n  double Cm1;\n  double C[8];\n  double T[8];\n  double H[8];\n  double V[12];\n  int i;\n  T[0] = 1.0;\n  H[0] = 1.0;\n  V[0] = 1.0;\n  for(i=1; i<=7; i++) {\n    T[i] = T[i-1] * t;\n    H[i] = H[i-1] * (t*f);\n  }\n  for(i=1; i<=11; i++) {\n    V[i] = V[i-1] * tau;\n  }\n\n  Cm1  = -1.0;\n  C[0] = 3.0*(1.0-H[1])/(8.0*T[1]);\n  C[1] = (-15.0*H[2]+6.0*H[1]+9.0+sgn*8.0*T[2])/(128.0*T[2]);\n  C[2] = 3.0*(-35.0*H[3] - 15.0*H[2] + 15.0*H[1] + 35.0 + sgn*T[2]*(32.0*H[1]+8.0))/(1024.0*T[3]);\n  C[3] = (-4725.0*H[4] - 6300.0*H[3] - 3150.0*H[2] + 3780.0*H[1] + 10395.0\n          -1216.0*T[4] + sgn*T[2]*(6000.0*H[2]+5760.0*H[1]+1680.0)) / (32768.0*T[4]);\n  C[4] = 7.0*(-10395.0*H[5] - 23625.0*H[4] - 28350.0*H[3] - 14850.0*H[2]\n              +19305.0*H[1] + 57915.0 - T[4]*(6336.0*H[1]+6080.0)\n              + sgn*T[2]*(16800.0*H[3] + 30000.0*H[2] + 25920.0*H[1] + 7920.0)\n              ) / (262144.0*T[5]);\n  C[5] = (-2837835.0*H[6] - 9168390.0*H[5] - 16372125.0*H[4] - 18918900*H[3]\n          -10135125.0*H[2] + 13783770.0*H[1] + 43648605.0\n          -T[4]*(3044160.0*H[2] + 5588352.0*H[1] + 4213440.0)\n          +sgn*T[2]*(5556600.0*H[4] + 14817600.0*H[3] + 20790000.0*H[2]\n                     + 17297280.0*H[1] + 5405400.0 + 323072.0*T[4]\n                     )\n          ) / (4194304.0*T[6]);\n  C[6] = 0.0;\n\n  *V0 = C[0] + (-4.0*C[3]/T[1]+C[4])/V[4]\n             + (-192.0*C[5]/T[3]+144.0*C[6]/T[2])/V[8]\n             + sgn * (-C[2]/V[2]\n                      + (-24.0*C[4]/T[2]+12.0*C[5]/T[1]-C[6])/V[6] \n                      );\n  *V1 = C[1]/V[1] + (8.0*(C[3]/T[2]-C[4]/T[1])+C[5])/V[5]\n                  + (384.0*C[5]/T[4] - 768.0*C[6]/T[3])/V[9]\n                  + sgn * (Cm1*V[1] + (2.0*C[2]/T[1]-C[3])/V[3]\n                           + (48.0*C[4]/T[3]-72.0*C[5]/T[2] + 18.0*C[6]/T[1])/V[7]\n                           );\n\n  return GSL_SUCCESS;\n}\n\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\n/* P^0_{-1/2 + I lambda}\n */\nint\ngsl_sf_conicalP_0_e(const double lambda, const double x, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= -1.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x == 1.0) {\n    result->val = 1.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(lambda == 0.0) {\n    gsl_sf_result K;\n    int stat_K;\n    if(x < 1.0) {\n      const double th = acos(x);\n      const double s  = sin(0.5*th);\n      stat_K = gsl_sf_ellint_Kcomp_e(s, GSL_MODE_DEFAULT, &K);\n      result->val  = 2.0/M_PI * K.val;\n      result->err  = 2.0/M_PI * K.err;\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      return stat_K;\n    }\n    else {\n      const double xi = acosh(x);\n      const double c  = cosh(0.5*xi);\n      const double t  = tanh(0.5*xi);\n      stat_K = gsl_sf_ellint_Kcomp_e(t, GSL_MODE_DEFAULT, &K);\n      result->val  = 2.0/M_PI / c * K.val;\n      result->err  = 2.0/M_PI / c * K.err;\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      return stat_K;\n    }\n  }\n  else if(   (x <= 0.0 && lambda < 1000.0)\n          || (x <  0.1 && lambda < 17.0)\n          || (x <  0.2 && lambda < 5.0 )\n    ) {\n    return conicalP_xlt1_hyperg_A(0.0, lambda, x, result);\n  }\n  else if(   (x <= 0.2 && lambda < 17.0)\n          || (x <= 1.5 && lambda < 20.0)\n    ) {\n    return gsl_sf_hyperg_2F1_conj_e(0.5, lambda, 1.0, (1.0-x)/2, result);\n  }\n  else if(1.5 < x && lambda < GSL_MAX(x,20.0)) {\n    gsl_sf_result P;\n    double lm;\n    int stat_P = gsl_sf_conicalP_large_x_e(0.0, lambda, x,\n                                              &P, &lm\n                                              );\n    int stat_e = gsl_sf_exp_mult_err_e(lm, 2.0*GSL_DBL_EPSILON * fabs(lm),\n                                          P.val, P.err,\n                                          result);\n    return GSL_ERROR_SELECT_2(stat_e, stat_P);\n  }\n  else {\n    double V0, V1;\n    if(x < 1.0) {\n      double th  = acos(x);\n      double sth = sqrt(1.0-x*x);  /* sin(th) */\n      gsl_sf_result I0, I1;\n      int stat_I0 = gsl_sf_bessel_I0_scaled_e(th * lambda, &I0);\n      int stat_I1 = gsl_sf_bessel_I1_scaled_e(th * lambda, &I1);\n      int stat_I  = GSL_ERROR_SELECT_2(stat_I0, stat_I1);\n      int stat_V  = conicalP_0_V(th, x/sth, lambda, -1.0, &V0, &V1);\n      double bessterm = V0 * I0.val + V1 * I1.val;\n      double besserr  = fabs(V0) * I0.err + fabs(V1) * I1.err;\n      double arg1 = th*lambda;\n      double sqts = sqrt(th/sth);\n      int stat_e = gsl_sf_exp_mult_err_e(arg1, 4.0 * GSL_DBL_EPSILON * fabs(arg1),\n                                            sqts * bessterm, sqts * besserr,\n                                            result);\n      return GSL_ERROR_SELECT_3(stat_e, stat_V, stat_I);\n    }\n    else {\n      double sh = sqrt(x-1.0)*sqrt(x+1.0);  /* sinh(xi)      */\n      double xi = log(x + sh);              /* xi = acosh(x) */\n      gsl_sf_result J0, J1;\n      int stat_J0 = gsl_sf_bessel_J0_e(xi * lambda, &J0);\n      int stat_J1 = gsl_sf_bessel_J1_e(xi * lambda, &J1);\n      int stat_J  = GSL_ERROR_SELECT_2(stat_J0, stat_J1);\n      int stat_V  = conicalP_0_V(xi, x/sh, lambda, 1.0, &V0, &V1);\n      double bessterm = V0 * J0.val + V1 * J1.val;\n      double besserr  = fabs(V0) * J0.err + fabs(V1) * J1.err;\n      double pre_val = sqrt(xi/sh);\n      double pre_err = 2.0 * fabs(pre_val);\n      result->val  = pre_val * bessterm;\n      result->err  = pre_val * besserr;\n      result->err += pre_err * fabs(bessterm);\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      return GSL_ERROR_SELECT_2(stat_V, stat_J);\n    }\n  }\n}\n\n\n/* P^1_{-1/2 + I lambda}\n */\nint\ngsl_sf_conicalP_1_e(const double lambda, const double x, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= -1.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(lambda == 0.0) {\n    gsl_sf_result K, E;\n    int stat_K, stat_E;\n    if(x == 1.0) {\n      result->val = 0.0;\n      result->err = 0.0;\n      return GSL_SUCCESS;\n    }\n    else if(x < 1.0) {\n      if(1.0-x < GSL_SQRT_DBL_EPSILON) {\n        double err_amp = GSL_MAX_DBL(1.0, 1.0/(GSL_DBL_EPSILON + fabs(1.0-x)));\n        result->val = 0.25/M_SQRT2 * sqrt(1.0-x) * (1.0 + 5.0/16.0 * (1.0-x));\n        result->err = err_amp * 3.0 * GSL_DBL_EPSILON * fabs(result->val);\n        return GSL_SUCCESS;\n      }\n      else {\n        const double th = acos(x);\n        const double s  = sin(0.5*th);\n        const double c2 = 1.0 - s*s;\n        const double sth = sin(th);\n        const double pre = 2.0/(M_PI*sth);\n        stat_K = gsl_sf_ellint_Kcomp_e(s, GSL_MODE_DEFAULT, &K);\n        stat_E = gsl_sf_ellint_Ecomp_e(s, GSL_MODE_DEFAULT, &E);\n        result->val  = pre * (E.val - c2 * K.val);\n        result->err  = pre * (E.err + fabs(c2) * K.err);\n        result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n        return GSL_ERROR_SELECT_2(stat_K, stat_E);\n      }\n    }\n    else {\n      if(x-1.0 < GSL_SQRT_DBL_EPSILON) {\n        double err_amp = GSL_MAX_DBL(1.0, 1.0/(GSL_DBL_EPSILON + fabs(1.0-x)));\n        result->val = -0.25/M_SQRT2 * sqrt(x-1.0) * (1.0 - 5.0/16.0 * (x-1.0));\n        result->err = err_amp * 3.0 * GSL_DBL_EPSILON * fabs(result->val);\n        return GSL_SUCCESS;\n      }\n      else {\n        const double xi = acosh(x);\n        const double c  = cosh(0.5*xi);\n        const double t  = tanh(0.5*xi);\n        const double sxi = sinh(xi);\n        const double pre = 2.0/(M_PI*sxi) * c;\n        stat_K = gsl_sf_ellint_Kcomp_e(t, GSL_MODE_DEFAULT, &K);\n        stat_E = gsl_sf_ellint_Ecomp_e(t, GSL_MODE_DEFAULT, &E);\n        result->val  = pre * (E.val - K.val);\n        result->err  = pre * (E.err + K.err);\n        result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n        return GSL_ERROR_SELECT_2(stat_K, stat_E);\n      }\n    }\n  }\n  else if(   (x <= 0.0 && lambda < 1000.0)\n          || (x <  0.1 && lambda < 17.0)\n          || (x <  0.2 && lambda < 5.0 )\n    ) {\n    return conicalP_xlt1_hyperg_A(1.0, lambda, x, result);\n  }\n  else if(   (x <= 0.2 && lambda < 17.0)\n          || (x <  1.5 && lambda < 20.0)\n    ) {\n    const double arg = fabs(x*x - 1.0);\n    const double sgn = GSL_SIGN(1.0 - x);\n    const double pre = 0.5*(lambda*lambda + 0.25) * sgn * sqrt(arg);\n    gsl_sf_result F;\n    int stat_F = gsl_sf_hyperg_2F1_conj_e(1.5, lambda, 2.0, (1.0-x)/2, &F);\n    result->val  = pre * F.val;\n    result->err  = fabs(pre) * F.err;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return stat_F;\n  }\n  else if(1.5 <= x && lambda < GSL_MAX(x,20.0)) {\n    gsl_sf_result P;\n    double lm;\n    int stat_P = gsl_sf_conicalP_large_x_e(1.0, lambda, x,\n                                              &P, &lm\n                                              );\n    int stat_e = gsl_sf_exp_mult_err_e(lm, 2.0 * GSL_DBL_EPSILON * fabs(lm),\n                                          P.val, P.err,\n                                          result);\n    return GSL_ERROR_SELECT_2(stat_e, stat_P);\n  }\n  else {\n    double V0, V1;\n    if(x < 1.0) {\n      const double sqrt_1mx = sqrt(1.0 - x);\n      const double sqrt_1px = sqrt(1.0 + x);\n      const double th  = acos(x);\n      const double sth = sqrt_1mx * sqrt_1px;  /* sin(th) */\n      gsl_sf_result I0, I1;\n      int stat_I0 = gsl_sf_bessel_I0_scaled_e(th * lambda, &I0);\n      int stat_I1 = gsl_sf_bessel_I1_scaled_e(th * lambda, &I1);\n      int stat_I  = GSL_ERROR_SELECT_2(stat_I0, stat_I1);\n      int stat_V  = conicalP_1_V(th, x/sth, lambda, -1.0, &V0, &V1);\n      double bessterm = V0 * I0.val + V1 * I1.val;\n      double besserr  =  fabs(V0) * I0.err + fabs(V1) * I1.err\n                       + 2.0 * GSL_DBL_EPSILON * fabs(V0 * I0.val)\n                       + 2.0 * GSL_DBL_EPSILON * fabs(V1 * I1.val);\n      double arg1 = th * lambda;\n      double sqts = sqrt(th/sth);\n      int stat_e = gsl_sf_exp_mult_err_e(arg1, 2.0 * GSL_DBL_EPSILON * fabs(arg1),\n                                            sqts * bessterm, sqts * besserr,\n                                            result);\n      result->err *= 1.0/sqrt_1mx;\n      return GSL_ERROR_SELECT_3(stat_e, stat_V, stat_I);\n    }\n    else {\n      const double sqrt_xm1 = sqrt(x - 1.0);\n      const double sqrt_xp1 = sqrt(x + 1.0);\n      const double sh = sqrt_xm1 * sqrt_xp1;  /* sinh(xi)      */\n      const double xi = log(x + sh);          /* xi = acosh(x) */\n      const double xi_lam = xi * lambda;\n      gsl_sf_result J0, J1;\n      const int stat_J0 = gsl_sf_bessel_J0_e(xi_lam, &J0);\n      const int stat_J1 = gsl_sf_bessel_J1_e(xi_lam, &J1);\n      const int stat_J  = GSL_ERROR_SELECT_2(stat_J0, stat_J1);\n      const int stat_V  = conicalP_1_V(xi, x/sh, lambda, 1.0, &V0, &V1);\n      const double bessterm = V0 * J0.val + V1 * J1.val;\n      const double besserr  = fabs(V0) * J0.err + fabs(V1) * J1.err\n                       + 512.0 * 2.0 * GSL_DBL_EPSILON * fabs(V0 * J0.val)\n                       + 512.0 * 2.0 * GSL_DBL_EPSILON * fabs(V1 * J1.val)\n                       + GSL_DBL_EPSILON * fabs(xi_lam * V0 * J1.val)\n                       + GSL_DBL_EPSILON * fabs(xi_lam * V1 * J0.val);\n      const double pre = sqrt(xi/sh);\n      result->val  = pre * bessterm;\n      result->err  = pre * besserr * sqrt_xp1 / sqrt_xm1;\n      result->err += 4.0 * GSL_DBL_EPSILON * fabs(result->val);\n      return GSL_ERROR_SELECT_2(stat_V, stat_J);\n    }\n  }\n}\n\n\n/* P^{1/2}_{-1/2 + I lambda} (x)\n * [Abramowitz+Stegun 8.6.8, 8.6.12]\n * checked OK [GJ] Fri May  8 12:24:36 MDT 1998 \n */\nint gsl_sf_conicalP_half_e(const double lambda, const double x,\n                              gsl_sf_result * result\n                              )\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= -1.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x < 1.0) {\n    double err_amp = 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-fabs(x)));\n    double ac  = acos(x);\n    double den = sqrt(sqrt(1.0-x)*sqrt(1.0+x));\n    result->val  = Root_2OverPi_ / den * cosh(ac * lambda);\n    result->err  = err_amp * 3.0 * GSL_DBL_EPSILON * fabs(result->val);\n    result->err *= fabs(ac * lambda) + 1.0;\n    return GSL_SUCCESS;\n  }\n  else if(x == 1.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    /* x > 1 */\n    double err_amp = 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-fabs(x)));\n    double sq_term = sqrt(x-1.0)*sqrt(x+1.0);\n    double ln_term = log(x + sq_term);\n    double den = sqrt(sq_term);\n    double carg_val = lambda * ln_term;\n    double carg_err = 2.0 * GSL_DBL_EPSILON * fabs(carg_val);\n    gsl_sf_result cos_result;\n    int stat_cos = gsl_sf_cos_err_e(carg_val, carg_err, &cos_result);\n    result->val  = Root_2OverPi_ / den * cos_result.val;\n    result->err  = err_amp * Root_2OverPi_ / den * cos_result.err;\n    result->err += 4.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return stat_cos;\n  }\n}\n\n\n/* P^{-1/2}_{-1/2 + I lambda} (x)\n * [Abramowitz+Stegun 8.6.9, 8.6.14]\n * checked OK [GJ] Fri May  8 12:24:43 MDT 1998 \n */\nint gsl_sf_conicalP_mhalf_e(const double lambda, const double x, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= -1.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x < 1.0) {\n    double ac  = acos(x);\n    double den = sqrt(sqrt(1.0-x)*sqrt(1.0+x));\n    double arg = ac * lambda;\n    double err_amp = 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-fabs(x)));\n    if(fabs(arg) < GSL_SQRT_DBL_EPSILON) {\n      result->val  = Root_2OverPi_ / den * ac;\n      result->err  = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      result->err *= err_amp;\n    }\n    else {\n      result->val  = Root_2OverPi_ / (den*lambda) * sinh(arg);\n      result->err  = GSL_DBL_EPSILON * (fabs(arg)+1.0) * fabs(result->val);\n      result->err *= err_amp;\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    }\n    return GSL_SUCCESS;\n  }\n  else if(x == 1.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    /* x > 1 */\n    double sq_term = sqrt(x-1.0)*sqrt(x+1.0);\n    double ln_term = log(x + sq_term);\n    double den = sqrt(sq_term);\n    double arg_val = lambda * ln_term;\n    double arg_err = 2.0 * GSL_DBL_EPSILON * fabs(arg_val);\n    if(arg_val < GSL_SQRT_DBL_EPSILON) {\n      result->val = Root_2OverPi_ / den * ln_term;\n      result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      return GSL_SUCCESS;\n    }\n    else {\n      gsl_sf_result sin_result;\n      int stat_sin = gsl_sf_sin_err_e(arg_val, arg_err, &sin_result);\n      result->val  = Root_2OverPi_ / (den*lambda) * sin_result.val;\n      result->err  = Root_2OverPi_ / fabs(den*lambda) * sin_result.err;\n      result->err += 3.0 * GSL_DBL_EPSILON * fabs(result->val);\n      return stat_sin;\n    }\n  }\n}\n\n\nint gsl_sf_conicalP_sph_reg_e(const int l, const double lambda,\n                                 const double x,\n                                 gsl_sf_result * result\n                                 )\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= -1.0 || l < -1) {\n    DOMAIN_ERROR(result);\n  }\n  else if(l == -1) {\n    return gsl_sf_conicalP_half_e(lambda, x, result);\n  }\n  else if(l == 0) {\n    return gsl_sf_conicalP_mhalf_e(lambda, x, result);\n  }\n  else if(x == 1.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(x < 0.0) {\n    double c = 1.0/sqrt(1.0-x*x);\n    gsl_sf_result r_Pellm1;\n    gsl_sf_result r_Pell;\n    int stat_0 = gsl_sf_conicalP_half_e(lambda, x, &r_Pellm1);  /* P^( 1/2) */\n    int stat_1 = gsl_sf_conicalP_mhalf_e(lambda, x, &r_Pell);   /* P^(-1/2) */\n    int stat_P = GSL_ERROR_SELECT_2(stat_0, stat_1);\n    double Pellm1 = r_Pellm1.val;\n    double Pell   = r_Pell.val;\n    double Pellp1;\n    int ell;\n\n    for(ell=0; ell<l; ell++) {\n      double d = (ell+1.0)*(ell+1.0) + lambda*lambda;\n      Pellp1 = (Pellm1 - (2.0*ell+1.0)*c*x * Pell) / d;\n      Pellm1 = Pell;\n      Pell   = Pellp1;\n    }\n\n    result->val  = Pell;\n    result->err  = (0.5*l + 1.0) * GSL_DBL_EPSILON * fabs(Pell);\n    result->err += GSL_DBL_EPSILON * l * fabs(result->val);\n    return stat_P;\n  }\n  else if(x < 1.0) {\n    const double xi = x/(sqrt(1.0-x)*sqrt(1.0+x));\n    gsl_sf_result rat;\n    gsl_sf_result Phf;\n    int stat_CF1 = conicalP_negmu_xlt1_CF1(0.5, l, lambda, x, &rat);\n    int stat_Phf = gsl_sf_conicalP_half_e(lambda, x, &Phf);\n    double Pellp1 = rat.val * GSL_SQRT_DBL_MIN;\n    double Pell   = GSL_SQRT_DBL_MIN;\n    double Pellm1;\n    int ell;\n\n    for(ell=l; ell>=0; ell--) {\n      double d = (ell+1.0)*(ell+1.0) + lambda*lambda;\n      Pellm1 = (2.0*ell+1.0)*xi * Pell + d * Pellp1;\n      Pellp1 = Pell;\n      Pell   = Pellm1;\n    }\n\n    result->val  = GSL_SQRT_DBL_MIN * Phf.val / Pell;\n    result->err  = GSL_SQRT_DBL_MIN * Phf.err / fabs(Pell);\n    result->err += fabs(rat.err/rat.val) * (l + 1.0) * fabs(result->val);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n    return GSL_ERROR_SELECT_2(stat_Phf, stat_CF1);\n  }\n  else if(x == 1.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    /* x > 1.0 */\n\n    const double xi = x/sqrt((x-1.0)*(x+1.0));\n    gsl_sf_result rat;\n    int stat_CF1 = conicalP_negmu_xgt1_CF1(0.5, l, lambda, x, &rat);\n    int stat_P;\n    double Pellp1 = rat.val * GSL_SQRT_DBL_MIN;\n    double Pell   = GSL_SQRT_DBL_MIN;\n    double Pellm1;\n    int ell;\n\n    for(ell=l; ell>=0; ell--) {\n      double d = (ell+1.0)*(ell+1.0) + lambda*lambda;\n      Pellm1 = (2.0*ell+1.0)*xi * Pell - d * Pellp1;\n      Pellp1 = Pell;\n      Pell   = Pellm1;\n    }\n\n    if(fabs(Pell) > fabs(Pellp1)){\n      gsl_sf_result Phf;\n      stat_P = gsl_sf_conicalP_half_e(lambda, x, &Phf);\n      result->val  =       GSL_SQRT_DBL_MIN * Phf.val / Pell;\n      result->err  = 2.0 * GSL_SQRT_DBL_MIN * Phf.err / fabs(Pell);\n      result->err += 2.0 * fabs(rat.err/rat.val) * (l + 1.0) * fabs(result->val);\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    }\n    else {\n      gsl_sf_result Pmhf;\n      stat_P = gsl_sf_conicalP_mhalf_e(lambda, x, &Pmhf);\n      result->val  =       GSL_SQRT_DBL_MIN * Pmhf.val / Pellp1;\n      result->err  = 2.0 * GSL_SQRT_DBL_MIN * Pmhf.err / fabs(Pellp1);\n      result->err += 2.0 * fabs(rat.err/rat.val) * (l + 1.0) * fabs(result->val);\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    }\n\n    return GSL_ERROR_SELECT_2(stat_P, stat_CF1);\n  }\n}\n\n\nint gsl_sf_conicalP_cyl_reg_e(const int m, const double lambda,\n                                 const double x,\n                                 gsl_sf_result * result\n                                 )\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= -1.0 || m < -1) {\n    DOMAIN_ERROR(result);\n  }\n  else if(m == -1) {\n    return gsl_sf_conicalP_1_e(lambda, x, result);\n  }\n  else if(m == 0) {\n    return gsl_sf_conicalP_0_e(lambda, x, result);\n  }\n  else if(x == 1.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(x < 0.0) {\n    double c = 1.0/sqrt(1.0-x*x);\n    gsl_sf_result r_Pkm1;\n    gsl_sf_result r_Pk;\n    int stat_0 = gsl_sf_conicalP_1_e(lambda, x, &r_Pkm1);  /* P^1 */\n    int stat_1 = gsl_sf_conicalP_0_e(lambda, x, &r_Pk);    /* P^0 */\n    int stat_P = GSL_ERROR_SELECT_2(stat_0, stat_1);\n    double Pkm1 = r_Pkm1.val;\n    double Pk   = r_Pk.val;\n    double Pkp1;\n    int k;\n\n    for(k=0; k<m; k++) {\n      double d = (k+0.5)*(k+0.5) + lambda*lambda;\n      Pkp1 = (Pkm1 - 2.0*k*c*x * Pk) / d;\n      Pkm1 = Pk;\n      Pk   = Pkp1;\n    }\n\n    result->val  = Pk;\n    result->err  = (m + 2.0) * GSL_DBL_EPSILON * fabs(Pk);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n    return stat_P;\n  }\n  else if(x < 1.0) {\n    const double xi = x/(sqrt(1.0-x)*sqrt(1.0+x));\n    gsl_sf_result rat;\n    gsl_sf_result P0;\n    int stat_CF1 = conicalP_negmu_xlt1_CF1(0.0, m, lambda, x, &rat);\n    int stat_P0  = gsl_sf_conicalP_0_e(lambda, x, &P0);\n    double Pkp1 = rat.val * GSL_SQRT_DBL_MIN;\n    double Pk   = GSL_SQRT_DBL_MIN;\n    double Pkm1;\n    int k;\n\n    for(k=m; k>0; k--) {\n      double d = (k+0.5)*(k+0.5) + lambda*lambda;\n      Pkm1 = 2.0*k*xi * Pk + d * Pkp1;\n      Pkp1 = Pk;\n      Pk   = Pkm1;\n    }\n\n    result->val  = GSL_SQRT_DBL_MIN * P0.val / Pk;\n    result->err  = 2.0 * GSL_SQRT_DBL_MIN * P0.err / fabs(Pk);\n    result->err += 2.0 * fabs(rat.err/rat.val) * (m + 1.0) * fabs(result->val);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n\n    return GSL_ERROR_SELECT_2(stat_P0, stat_CF1);\n  }\n  else if(x == 1.0) {\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else {\n    /* x > 1.0 */\n\n    const double xi = x/sqrt((x-1.0)*(x+1.0));\n    gsl_sf_result rat;\n    int stat_CF1 = conicalP_negmu_xgt1_CF1(0.0, m, lambda, x, &rat);\n    int stat_P;\n    double Pkp1 = rat.val * GSL_SQRT_DBL_MIN;\n    double Pk   = GSL_SQRT_DBL_MIN;\n    double Pkm1;\n    int k;\n\n    for(k=m; k>-1; k--) {\n      double d = (k+0.5)*(k+0.5) + lambda*lambda;\n      Pkm1 = 2.0*k*xi * Pk - d * Pkp1;\n      Pkp1 = Pk;\n      Pk   = Pkm1;\n    }\n\n    if(fabs(Pk) > fabs(Pkp1)){\n      gsl_sf_result P1;\n      stat_P = gsl_sf_conicalP_1_e(lambda, x, &P1);\n      result->val  = GSL_SQRT_DBL_MIN * P1.val / Pk;\n      result->err  = 2.0 * GSL_SQRT_DBL_MIN * P1.err / fabs(Pk);\n      result->err += 2.0 * fabs(rat.err/rat.val) * (m+2.0) * fabs(result->val);\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    }\n    else {\n      gsl_sf_result P0;\n      stat_P = gsl_sf_conicalP_0_e(lambda, x, &P0);\n      result->val  = GSL_SQRT_DBL_MIN * P0.val / Pkp1;\n      result->err  = 2.0 * GSL_SQRT_DBL_MIN * P0.err / fabs(Pkp1);\n      result->err += 2.0 * fabs(rat.err/rat.val) * (m+2.0) * fabs(result->val);\n      result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    }\n\n    return GSL_ERROR_SELECT_2(stat_P, stat_CF1);\n  }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_conicalP_0(const double lambda, const double x)\n{\n  EVAL_RESULT(gsl_sf_conicalP_0_e(lambda, x, &result));\n}\n\ndouble gsl_sf_conicalP_1(const double lambda, const double x)\n{\n  EVAL_RESULT(gsl_sf_conicalP_1_e(lambda, x, &result));\n}\n\ndouble gsl_sf_conicalP_half(const double lambda, const double x)\n{\n  EVAL_RESULT(gsl_sf_conicalP_half_e(lambda, x, &result));\n}\n\ndouble gsl_sf_conicalP_mhalf(const double lambda, const double x)\n{\n  EVAL_RESULT(gsl_sf_conicalP_mhalf_e(lambda, x, &result));\n}\n\ndouble gsl_sf_conicalP_sph_reg(const int l, const double lambda, const double x)\n{\n  EVAL_RESULT(gsl_sf_conicalP_sph_reg_e(l, lambda, x, &result));\n}\n\ndouble gsl_sf_conicalP_cyl_reg(const int m, const double lambda, const double x)\n{\n  EVAL_RESULT(gsl_sf_conicalP_cyl_reg_e(m, lambda, x, &result));\n}\n", "meta": {"hexsha": "85dee57b788bfbd917d825cdde5b1b33998ba8b3", "size": 43329, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/legendre_con.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/legendre_con.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/legendre_con.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 31.512, "max_line_length": 105, "alphanum_fraction": 0.5596251933, "num_tokens": 16442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3641921673892915}}
{"text": "#ifndef TETRA_DOS_DOS_VALUES_H\n#define TETRA_DOS_DOS_VALUES_H\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_sort_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_eigen.h>\n#include \"ctetra/dos.h\"\n#include \"elHamiltonian.h\"\n#include \"environment.h\"\n\ngsl_matrix* cubicRecipLat(double a);\n\ndouble* DosValues(Environment *env, int n, double *Es, double num_dos);\n\n#endif // TETRA_DOS_DOS_VALUES_H\n", "meta": {"hexsha": "ec88f7fa7d6637b5e9cdb9d07ebf02cf0a22eb4c", "size": 426, "ext": "h", "lang": "C", "max_stars_repo_path": "tetra_dos/DosValues.h", "max_stars_repo_name": "tflovorn/vo2mft", "max_stars_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tetra_dos/DosValues.h", "max_issues_repo_name": "tflovorn/vo2mft", "max_issues_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tetra_dos/DosValues.h", "max_forks_repo_name": "tflovorn/vo2mft", "max_forks_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T15:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T15:11:23.000Z", "avg_line_length": 23.6666666667, "max_line_length": 71, "alphanum_fraction": 0.7769953052, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.364176935448373}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C header for functions windowing and computing FFT/IFFT of time/frequency series.\n *\n */\n\n#ifndef __GENERATEWAVEFORM_H__\n#define __GENERATEWAVEFORM_H__ 1\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#define _XOPEN_SOURCE 500\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n#include \"struct.h\"\n#include \"waveform.h\"\n#include \"EOBNRv2HMROMstruct.h\"\n#include \"EOBNRv2HMROM.h\"\n#include \"fft.h\"\n\n/********************************** Structures ******************************************/\n\ntypedef enum GenWavetag {\n  hlm,\n  h22TD,\n  hphcFD,\n  hphcTD\n} GenWavetag;\n\n/* Parameters for the generation of a LISA waveform (in the form of a list of modes) */\ntypedef struct tagGenWaveParams {\n  double tRef;               /* reference time (s) - GPS time at the frequency representing coalescence */\n  double phiRef;             /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */\n  double fRef;               /* reference frequency at which phiRef is set (Hz, default 0 which is interpreted as Mf=0.14) */\n  double m1;                 /* mass of companion 1 (solar masses, default 2e6) */\n  double m2;                 /* mass of companion 2 (solar masses, default 1e6) */\n  double distance;           /* distance of source (Mpc, default 1e3) */\n  double inclination;        /* inclination of source (rad, default pi/3) */\n  double minf;               /* Minimal frequency, ignore if 0 (Hz, default=0) - will use first frequency covered by the ROM if higher */\n  double maxf;               /* Maximal frequency, ignore if 0 (Hz, default=0) - will use last frequency covered by the ROM if lower */\n  double deltatobs;          /* Observation duration (years, default=2) */\n  int tagextpn;              /* Tag to allow PN extension of the waveform at low frequencies */\n  double Mfmatch;            /* When PN extension allowed, geometric matching frequency: will use ROM above this value. If <=0, use ROM down to the lowest covered frequency */\n  int nbmode;                /* Number of modes to generate (starting with 22) - defaults to 1 (22 only) */\n  int taggenwave;            /* Tag selecting the desired output format */\n  double f1windowbeg;        /* If generating h22TD/hphcTD, start frequency for windowing at the beginning - set to 0 to ignore and use max(fstartobs, fLowROM, minf), where fLowROM is either the lowest frequency covered by the ROM or simply minf if PN extension is used (Hz, default=0) */\n  double f2windowbeg;        /* If generating h22TD/hphcTD, stop frequency for windowing at the beginning - set to 0 to ignore and use 1.1*f1windowbeg (Hz, default=0) */\n  double f1windowend;        /* If generating h22TD/hphcTD, start frequency for windowing at the end - set to 0 to ignore and use 0.995*f2windowend (Hz, default=0) */\n  double f2windowend;        /* If generating h22TD/hphcTD, stop frequency for windowing at the end - set to 0 to ignore and use min(maxf, fHighROM), where fHighROM is the highest frequency covered by the ROM (Hz, default=0) */\n  int tagh22fromfile;        /* Tag choosing wether to load h22 FD downsampled Amp/Phase from file (default 0) */\n  int nsamplesinfile;        /* Number of lines of inputs file */\n  int binaryin;              /* Tag for loading the data in gsl binary form instead of text (default false) */\n  char indir[256];           /* Input directory */\n  char infile[256];          /* Input file name */\n  int binaryout;             /* Tag for outputting the data in gsl binary form instead of text (default 0) */\n  char outdir[256];          /* Path for the output directory */\n  char outfile[256];         /* Path for the output file */\n} GenWaveParams;\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _GENERATEWAVEFORM_H */\n", "meta": {"hexsha": "78a4fabb92263cc8acde03f1267dfe024e219e6b", "size": 4234, "ext": "h", "lang": "C", "max_stars_repo_path": "EOBNRv2HMROM/GenerateWaveform.h", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EOBNRv2HMROM/GenerateWaveform.h", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EOBNRv2HMROM/GenerateWaveform.h", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.5730337079, "max_line_length": 288, "alphanum_fraction": 0.6669815777, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.36410404299860133}}
{"text": "\n#ifndef KGS_NULLSPACESVD_H\n#define KGS_NULLSPACESVD_H\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <string>\n\n#include \"math/SVD.h\"\n#include \"math/Nullspace.h\"\n\n/**\n * An implementation of Nullspace backed by SVD\n */\nclass NullspaceSVD: public Nullspace {\n public:\n  /** Will construct a nullspace of `matrix` using the SVD decomposition */\n  NullspaceSVD(SVD* svd);\n\n  /** Update the Nullspace (and underlying SVD) to reflect an updated state of the matrix */\n  void updateFromMatrix() override;\n\n  /** Return the SVD of the nullspace as columns of a matrix */\n  SVD *getSVD() const;\n\n  static void setSingularValueTolerance(double val);\n\nprivate:\n  SVD* m_svd;                  ///< SVD underlying this nullspace\n\n  /// These values have to be chosen according to the numerical analysis\n  static double SINGVAL_TOL;\n//  static constexpr double RIGID_TOL =   1.0e-10; //0.0000000001; //depends on molecule, but 10^-10 seems a good fit!\n\n  friend class Configuration;\n};\n\n\n#endif //KGS_nullptrSPACE_H\n", "meta": {"hexsha": "68c25a710518afde6e20461c1ecdb1a2ae6461ff", "size": 1022, "ext": "h", "lang": "C", "max_stars_repo_path": "src/math/NullspaceSVD.h", "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_issues_repo_path": "src/math/NullspaceSVD.h", "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_forks_repo_path": "src/math/NullspaceSVD.h", "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": ["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.55, "max_line_length": 118, "alphanum_fraction": 0.7201565558, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3641040377421842}}
{"text": "/* linalg/choleskyc.c\n * \n * Copyright (C) 2007 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_errno.h>\n\n/*\n * This module contains routines related to the Cholesky decomposition\n * of a complex Hermitian positive definite matrix.\n */\n\nstatic void cholesky_complex_conj_vector(gsl_vector_complex *v);\n\n/*\ngsl_linalg_complex_cholesky_decomp()\n  Perform the Cholesky decomposition on a Hermitian positive definite\nmatrix. See Golub & Van Loan, \"Matrix Computations\" (3rd ed),\nalgorithm 4.2.2.\n\nInputs: A - (input/output) complex postive definite matrix\n\nReturn: success or error\n\nThe lower triangle of A is overwritten with the Cholesky decomposition\n*/\n\nint\ngsl_linalg_complex_cholesky_decomp(gsl_matrix_complex *A)\n{\n  const size_t N = A->size1;\n  \n  if (N != A->size2)\n    {\n      GSL_ERROR(\"cholesky decomposition requires square matrix\", GSL_ENOTSQR);\n    }\n  else\n    {\n      size_t i, j;\n      gsl_complex z;\n      double ajj;\n\n      for (j = 0; j < N; ++j)\n        {\n          z = gsl_matrix_complex_get(A, j, j);\n          ajj = GSL_REAL(z);\n\n          if (j > 0)\n            {\n              gsl_vector_complex_const_view aj =\n                gsl_matrix_complex_const_subrow(A, j, 0, j);\n\n              gsl_blas_zdotc(&aj.vector, &aj.vector, &z);\n              ajj -= GSL_REAL(z);\n            }\n\n          if (ajj <= 0.0)\n            {\n              GSL_ERROR(\"matrix is not positive definite\", GSL_EDOM);\n            }\n\n          ajj = sqrt(ajj);\n          GSL_SET_COMPLEX(&z, ajj, 0.0);\n          gsl_matrix_complex_set(A, j, j, z);\n\n          if (j < N - 1)\n            {\n              gsl_vector_complex_view av =\n                gsl_matrix_complex_subcolumn(A, j, j + 1, N - j - 1);\n\n              if (j > 0)\n                {\n                  gsl_vector_complex_view aj =\n                    gsl_matrix_complex_subrow(A, j, 0, j);\n                  gsl_matrix_complex_view am =\n                    gsl_matrix_complex_submatrix(A, j + 1, 0, N - j - 1, j);\n\n                  cholesky_complex_conj_vector(&aj.vector);\n\n                  gsl_blas_zgemv(CblasNoTrans,\n                                 GSL_COMPLEX_NEGONE,\n                                 &am.matrix,\n                                 &aj.vector,\n                                 GSL_COMPLEX_ONE,\n                                 &av.vector);\n\n                  cholesky_complex_conj_vector(&aj.vector);\n                }\n\n              gsl_blas_zdscal(1.0 / ajj, &av.vector);\n            }\n        }\n\n      /* Now store L^H in upper triangle */\n      for (i = 1; i < N; ++i)\n        {\n          for (j = 0; j < i; ++j)\n            {\n              z = gsl_matrix_complex_get(A, i, j);\n              gsl_matrix_complex_set(A, j, i, gsl_complex_conjugate(z));\n            }\n        }\n\n      return GSL_SUCCESS;\n    }\n} /* gsl_linalg_complex_cholesky_decomp() */\n\n/*\ngsl_linalg_complex_cholesky_solve()\n  Solve A x = b where A is in cholesky form\n*/\n\nint\ngsl_linalg_complex_cholesky_solve (const gsl_matrix_complex * cholesky,\n                                   const gsl_vector_complex * b,\n                                   gsl_vector_complex * x)\n{\n  if (cholesky->size1 != cholesky->size2)\n    {\n      GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (cholesky->size1 != b->size)\n    {\n      GSL_ERROR (\"matrix size must match b size\", GSL_EBADLEN);\n    }\n  else if (cholesky->size2 != x->size)\n    {\n      GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n    }\n  else\n    {\n      gsl_vector_complex_memcpy (x, b);\n\n      /* solve for y using forward-substitution, L y = b */\n\n      gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasNonUnit, cholesky, x);\n\n      /* perform back-substitution, L^H x = y */\n\n      gsl_blas_ztrsv (CblasLower, CblasConjTrans, CblasNonUnit, cholesky, x);\n\n      return GSL_SUCCESS;\n    }\n} /* gsl_linalg_complex_cholesky_solve() */\n\n/*\ngsl_linalg_complex_cholesky_svx()\n  Solve A x = b in place where A is in cholesky form\n*/\n\nint\ngsl_linalg_complex_cholesky_svx (const gsl_matrix_complex * cholesky,\n                                 gsl_vector_complex * x)\n{\n  if (cholesky->size1 != cholesky->size2)\n    {\n      GSL_ERROR (\"cholesky matrix must be square\", GSL_ENOTSQR);\n    }\n  else if (cholesky->size2 != x->size)\n    {\n      GSL_ERROR (\"matrix size must match solution size\", GSL_EBADLEN);\n    }\n  else\n    {\n      /* solve for y using forward-substitution, L y = b */\n\n      gsl_blas_ztrsv (CblasLower, CblasNoTrans, CblasNonUnit, cholesky, x);\n\n      /* perform back-substitution, L^H x = y */\n\n      gsl_blas_ztrsv (CblasLower, CblasConjTrans, CblasNonUnit, cholesky, x);\n\n      return GSL_SUCCESS;\n    }\n} /* gsl_linalg_complex_cholesky_svx() */\n\n/********************************************\n *           INTERNAL ROUTINES              *\n ********************************************/\n\nstatic void\ncholesky_complex_conj_vector(gsl_vector_complex *v)\n{\n  size_t i;\n\n  for (i = 0; i < v->size; ++i)\n    {\n      gsl_complex z = gsl_vector_complex_get(v, i);\n      gsl_vector_complex_set(v, i, gsl_complex_conjugate(z));\n    }\n} /* cholesky_complex_conj_vector() */\n", "meta": {"hexsha": "1a2d464d6c7da74914792e30f83771514fdedf77", "size": 6050, "ext": "c", "lang": "C", "max_stars_repo_path": "folding_libs/gsl-1.14/linalg/choleskyc.c", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/choleskyc.c", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/choleskyc.c", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 28.2710280374, "max_line_length": 81, "alphanum_fraction": 0.5885950413, "num_tokens": 1586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.5, "lm_q1q2_score": 0.363987730354659}}
{"text": "// NIT_inspiral - code to rapidly compute extreme mass-ratio inspirals using self-force results\n// Copyright (C) 2017  Niels Warburton\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\n#ifndef __INTERPOLANT_H__\n#define __INTERPOLANT_H__\n\n#include <vector>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_interp2d.h>\n#include <gsl/gsl_spline2d.h>\n\nusing namespace std;\n\ntypedef vector<double> Vector;\n\nclass Interpolant{\n\tpublic:\n\t\t// 1D interpolation\n\t\tInterpolant(Vector x, Vector f);\n\t\tdouble eval(double x);\n\n\t\t// 2D interpolation\n\t\tInterpolant(Vector x, Vector y, Vector f);\n\t\tdouble eval(double x, double y);\n\n\t\t// Destructor\n\t\t~Interpolant();\n\n\n\tprivate:\n\t\tint interp_type;\t// Set to 1 for 1D interpolation and 2 for 2D interpolation\n\n\t\tgsl_spline *spline;\n\t\tgsl_spline2d *spline2d;\n\t\tgsl_interp_accel *xacc;\n\t\tgsl_interp_accel *yacc;\n};\n#endif // __INTERPOLANT_H__\n", "meta": {"hexsha": "c0e2aa92ad897312e17e8b0432b1274966cd563c", "size": 1471, "ext": "h", "lang": "C", "max_stars_repo_path": "FastEMRIWaveforms/include/Interpolant.h", "max_stars_repo_name": "basuparth/ICERM_Workshop", "max_stars_repo_head_hexsha": "ebabce680fc87e90ff1de30246dcda9beb384bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FastEMRIWaveforms/include/Interpolant.h", "max_issues_repo_name": "basuparth/ICERM_Workshop", "max_issues_repo_head_hexsha": "ebabce680fc87e90ff1de30246dcda9beb384bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FastEMRIWaveforms/include/Interpolant.h", "max_forks_repo_name": "basuparth/ICERM_Workshop", "max_forks_repo_head_hexsha": "ebabce680fc87e90ff1de30246dcda9beb384bb4", "max_forks_repo_licenses": ["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.2884615385, "max_line_length": 95, "alphanum_fraction": 0.7457511897, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.36380533920028246}}
{"text": "/*\n * Simultaneous ML fitting of N 3D Gaussian kernels against a volumetric image\n * MATLAB interface in df_mlfitN.c\n *\n * TODO: \n * - how to handle background, still as a constant over the\n * patch? \n * - bg not handled yet.\n *\n */\n\n#include <assert.h>\n#include <inttypes.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n\n#include <gsl/gsl_multimin.h>\n#include <gsl/gsl_statistics.h>\n\n#include \"blit3.h\"\n#include \"mlfit.h\"\n\n#ifndef verbose\n#define verbose 1\n#endif\n\n// When low on bugs, uncomment the following lines for speed\n// Try with valgrind and cmocka first ...\n//\n// replace gsl_vector_get(v,i) by v->data[i*v->stride]\n// #define GSL_RANGE_CHECK_OFF\n\n// Globals\nuint32_t maxIterations = 5000;\ndouble convCriteria = 1e-6;\n\n\n// Headers\nint    localizeDot(double *, size_t, double *,  double *);\nint    localize(double *, size_t, size_t, size_t, double *, size_t, size_t, double *);\ndouble matrix_get(double * , size_t, size_t, size_t, double *);\ndouble my_f (const gsl_vector *, void *);\nint    unit_tests(void);\n\n// Optimization constants\ntypedef struct {\n  double * V; // Volumetric image\n  double * W; // Temporary space for model during iterations\n  double * D; // dots, x,y,z, nphot, sigmax, sigmay, sigmaz\n  size_t Vm, Vn, Vp;\n  size_t Dm, Dn;\n  double * bg;\n} optParams;\n\n\ndouble my_f (const gsl_vector *v, void *params)\n  // The function to optimize. mlsimplex controls/varies the variables\n  // in v. params are to set up the context\n{\n\n  optParams *p = (optParams *) params;\n\n  // Size of volumetric image\n  const size_t Vm = p->Vm; // Size of image\n  const size_t Vn = p->Vn;\n  const size_t Vp = p->Vp;\n  const size_t Dn = p->Dn; // number of dots\n  const size_t Dm = p->Dm;  // and number of features\n  double * D = p->D;\n  const double * restrict V = p->V; // Volumetric data to fit against\n  double * W = p->W; // Pre allocated memory for the model\n  double * bg = p->bg;\n\n\n#if verbose > 0\n  printf(\"-> my_f, %d dots\\n\", (int) Dn);\n#endif\n\n  // Get the other parameters ...  \n\n  double photsum = 0;\n\n  // Copy the cordinates and nphot at the current iteration to D\n  for(size_t dd = 0; dd<Dn; dd++)\n  {\n#if verbose > 0\n    printf(\"%lu: (%.1f %.1f %.1f) %.0f (%.1f %.1f %.1f)\\n\", dd, D[Dm*dd+0],D[Dm*dd+1], D[Dm*dd+2], D[Dm*dd+3], D[Dm*dd+4], D[Dm*dd+5], D[Dm*dd+6]);        \n#endif\n    D[Dm*dd+0] = gsl_vector_get(v, 4*dd+0); // x\n    D[Dm*dd+1] = gsl_vector_get(v, 4*dd+1); // y\n    D[Dm*dd+2] = gsl_vector_get(v, 4*dd+2); // z \n    D[Dm*dd+3] = gsl_vector_get(v, 4*dd+3); // nphot\n\n#if verbose>0\n    printf(\"%lu: xyz (%.1f %.1f %.1f) %.0f (%.1f %.1f %.1f)\\n\", dd, D[Dm*dd+0],D[Dm*dd+1], D[Dm*dd+2], D[Dm*dd+3], D[Dm*dd+4], D[Dm*dd+5], D[Dm*dd+6]);        \n#endif\n    if(D[Dm*dd+3]<0)\n      return INFINITY;\n\n    photsum = photsum + D[7*dd+3];\n  }\n\n#if verbose > 0\n  printf(\"phosum of dot parameters: %f\\n\", photsum);\n#endif\n\n  // Copy background map to model\n  memcpy(W, bg, sizeof(double)*Vm*Vn*Vp); \n  //  memset(W, 0, sizeof(double)*Vm*Vn*Vp); // W = 0;\n  blit3g(W, Vm, Vn, Vp, D, Dn, mid_point,0);\n\n  // set bg as well with blit3(g)\n  for(size_t kk = 0; kk<Vn*Vm*Vp; kk++) {\n    //W[kk]++;\n  }\n\n  double vmin = 10e99;\n  double vmax = -10e99;\n  double wmin = 10e99;\n  double wmax = -10e99;\n  double diffmax = 0;\n  for(size_t kk = 0; kk<Vn*Vm*Vp; kk++)\n  {\n    vmin = GSL_MIN(vmin, V[kk]);\n    vmax = GSL_MAX(vmax, V[kk]);\n    wmin = GSL_MIN(wmin, W[kk]);\n    wmax = GSL_MAX(wmax, W[kk]);\n    diffmax = GSL_MAX(diffmax, fabs(V[kk]-W[kk]));\n  }\n#if verbose>0\n  printf(\"V -- min: %f max %f\\n\", vmin, vmax);\n  printf(\"W -- min: %f max %f\\n\", wmin, wmax);\n  printf(\"diffmax: %f\\n\", diffmax);\n#endif\n\n  /* \n   * from LL2PG.m\n   *   model = x(3)+x(4)*gaussianInt2([x(1), x(2)], x(5), (size(patch, 1)-1)/2);\n   *   mask = disk2d((size(patch,1)-1)/2);\n   *   %L = -sum(sum(-(patch-model).^2./model - .5*log(model)));\n   *   L = -sum(sum(mask.*(-(patch-model).^2./model - .5*log(model))));\n   */\n\n  double E = 0;\n  for (size_t kk=0; kk<Vm*Vn*Vp; kk++) {\n    //E+= (V[kk]-W[kk])*(V[kk]-W[kk])/V[kk] - .5*log(W[kk]);\n    E+= (V[kk]-W[kk])*(V[kk]-W[kk]);\n  }\n  //  E = -E;\n\n  /* Quadratic\n   * for (size_t kk=0; kk<Rw*Rw; kk++)\n   * E+= (GI[kk]-R[kk])*(GI[kk]-R[kk]);\n   */\n#if verbose >0\n  printf(\"E: %f\\n\", E);\n#endif \n  return E;\n} \ndouble matrix_get(double * V, size_t Vm, size_t Vn, size_t Vp, double * D)\n  // Safely get V(D), i.e. check bounds. Returns 0 if outside\n  //\n{\n\n  double x = D[0];\n  double y = D[1];\n  double z = D[2];\n\n  if(x<0)\n    return 0;\n  if(x>Vm-1)\n    return 0;\n  if(y<0)\n    return 0;\n  if(y>Vn-1)\n    return 0;\n  if(z<0)\n    return 0;\n  if(z>Vp-1)\n    return 1;\n\n  size_t pos = (size_t) nearbyint(x) + nearbyint(y)*Vm +  nearbyint(z)*Vm*Vn; \n  assert(pos<Vm*Vn*Vp);\n  return V[pos];\n}\n\nint localize(double * V, size_t Vm, size_t Vn, size_t Vp, \n    double * D, size_t Dm, size_t Dn, double * F)\n  // Localization for a dot roughly centered in V of size Vm x Vm\n  // D[0], D[1], D[3] are the global coordinates of the dot\n  // F are the fitted coordinates\n{\n\n  // avoid crashing matlab\n  gsl_set_error_handler_off();\n\n#if verbose > 0\n  printf(\"-> Localize\\n\");\n  printf(\"V: %lu %lu %lu\\n\", Vm, Vn, Vp);\n  printf(\"D: %lu %lu\\n\", Dm, Dn);\n#endif\n  assert(Dm == 7); // x y z nphot sigmax sigmay sigmaz\n\n  // Non-optimized parameters\n  optParams par;\n  par.V = V;\n  par.Vm = Vm;\n  par.Vn = Vn;\n  par.Vp = Vp;\n  par.Dn = Dn;\n  par.Dm = Dm;\n  par.W = malloc(Vm*Vn*Vp*sizeof(double));\n  assert(par.W != NULL);\n  par.D = D;\n  par.bg = malloc(Vm*Vn*Vp*sizeof(double));\n\n#if verbose > 0\n  printf(\"Estimating local background\\n\");\n#endif\n  // Estimating a constant from the surroundings of the first dot\n  // printf(\"Vm: %lu %Vn: %lu Vp: %lu, D: %f %f %f\\n\", Vm, Vn, Vp, D[0], D[1], D[2]);\n  double bg = estimateBGV(V, Vm, Vn, Vp, D);\n#if verbose>0\n  printf(\"Background estimated to %f\\n\", bg);\n#endif\n  printf(\"Background estimated to %f\\n\", bg);\n\n  for(size_t kk=0; kk<Vm*Vn*Vp; kk++)\n    par.bg[kk] = bg;\n\n  const gsl_multimin_fminimizer_type *T = \n    gsl_multimin_fminimizer_nmsimplex2;\n  gsl_multimin_fminimizer *s = NULL;\n  gsl_vector *ss, *x;\n  gsl_multimin_function minex_func;\n\n  size_t iter = 0;\n  int status;\n  double size;\n\n  /* Starting point */\n#if verbose > 0\n  printf(\"Setting up starting vector\\n\");\n#endif \n  const int nf = 4; // # of features to be optimized: x, y, z, nphot\n  int nParameters = nf*Dn;\n  x = gsl_vector_alloc (nParameters);\n  for(size_t dd = 0; dd<Dn; dd++)\n  {\n    gsl_vector_set(x, dd*nf+0, D[dd*Dm+0]); // x position\n    gsl_vector_set(x, dd*nf+1, D[dd*Dm+1]); // y position\n    gsl_vector_set(x, dd*nf+2, D[dd*Dm+2]); // z position\n    \n    // number of photons\n    // Since the blitting is scaled by the central pixel, the number\n    // of photons can be estimated as the central value of each peak -\n    // background from the surrounding\n    double nphot = gsl_max(0, matrix_get(V, Vm, Vn, Vp, D+ dd*Dm)-par.bg[0]); \n    printf(\"nphot: %f\\n\", nphot);\n    gsl_vector_set(x, dd*nf+3, nphot); \n  }\n#if verbose > 0\n  printf(\"Setting up initial step sizes\\n\");\n#endif\n  /* Set initial step sizes */\n  ss = gsl_vector_alloc(nParameters);\n  gsl_vector_set_all(ss, 0.01);\n  for(size_t dd = 0; dd<Dn; dd++)\n  {\n    gsl_vector_set(ss, dd*nf+3, 5); // Number of photons\n  }\n\n#if verbose > 0\n  printf(\"Testing the fitting with the initial data\\n\");\n#endif\n  my_f(x,(void*) &par);\n\n  /* Initialize method and iterate */\n  minex_func.n = nParameters;\n  minex_func.f = my_f;\n  minex_func.params = &par;\n#if verbose > 0\n  printf(\"Allocating for the solver\\n\");\n#endif\n  s = gsl_multimin_fminimizer_alloc (T, nParameters);\n#if verbose > 0\n  printf(\"Initializing solver\\n\");\n#endif\n  gsl_multimin_fminimizer_set (s, &minex_func, x, ss);\n\n  do\n  {\n    iter++;\n#if verbose>0\n    printf(\"----------------------------- Iteration: %lu\\n\", iter);\n#endif\n    status = gsl_multimin_fminimizer_iterate(s);\n\n    if (status) \n      break;\n\n    size = gsl_multimin_fminimizer_size(s);\n    status = gsl_multimin_test_size(size, convCriteria);\n\n    if (status == GSL_SUCCESS)\n    {\n#if verbose > 0\n      printf (\"converged to minimum at\\n\");\n      printf (\"%5lu x:%10.3e y:%10.3e z:%10.3e NP:%6.1f f() = %7.3f size = %10.3e\\n\", \n          iter,\n          gsl_vector_get (s->x, 0), \n          gsl_vector_get (s->x, 1), \n          gsl_vector_get (s->x, 2), \n          gsl_vector_get (s->x, 3), \n          s->fval, size);\n#endif\n    }\n  }\n  while (status == GSL_CONTINUE && iter < maxIterations);\n\n  for(size_t dd = 0; dd<Dn; dd++)\n  {\n    F[5*dd+0] = gsl_vector_get (s->x, nf*dd+0); // x\n    F[5*dd+1] = gsl_vector_get (s->x, nf*dd+1); // y\n    F[5*dd+2] = gsl_vector_get (s->x, nf*dd+2); // z\n    F[5*dd+3] = gsl_vector_get (s->x, nf*dd+3); // nphot\n    F[5*dd+4] = status;                            // status\n  }\n\n  gsl_vector_free(x);\n  gsl_vector_free(ss);\n  gsl_multimin_fminimizer_free (s);\n\n  free(par.W);\n  free(par.bg);\n  return status;\n}\n\n#ifndef _MAIN\n#define _MAIN\nint unit_tests(){\n  double * V; // image\n  int Vm = 102; int Vn = 107; int Vp = 60;\n  double * D; // list of dots\n  size_t Dm = 7; // number of features of the dots\n  size_t Dn = 10; // number of dots\n  double * F; // fitted dots\n\n  printf(\"Image size: %dx%dx%d\\n\", Vm, Vn, Vp);\n  printf(\"Localizing %lu dots\\n\", Dn);\n\n  V = malloc(Vm*Vn*Vp*sizeof(double));\n  D = malloc(Dm*Dn*sizeof(double));\n  F = malloc(5*Dn*sizeof(double));\n\n  // Initialize the data\n  for(int kk=0; kk<Vm*Vn*Vp; kk++)\n    V[kk] = rand_range(2,9);\n\n  for(uint32_t kk=0; kk<Dn; kk++)\n  {\n    size_t pos = kk*Dm;\n    D[pos] =   rand_range(6, Vm-7); \n    D[pos+1] = rand_range(6, Vn-7); \n    D[pos+2] = rand_range(6, Vp-7);\n    D[pos+3] = 1000;\n    D[pos+4] = 1.2;\n    D[pos+5] = 1.2;\n    D[pos+6] = 1.4;\n\n    if(D[pos] < 6)\n      D[pos] = 6;\n    if(D[pos+1] < 6)\n      D[pos+1] = 6;\n    if(D[pos+2] < 6)\n      D[pos+2] = 6;\n#if verbose > 0\n    printf(\"D %03d %f %f %f\\n\", kk, D[pos], D[pos+1], D[pos+2]);\n#endif\n  }\n\n  for(uint32_t kk=0; kk<Dn; kk++)\n  {\n    size_t pos = nearbyint(D[kk*7]) + nearbyint(D[kk*7+1])*Vm + nearbyint(D[kk*7+2])*Vm*Vn;\n    assert(pos<(size_t) Vm*Vn*Vp);\n    assert(pos>0);\n    V[pos] = 5;\n  }\n\n  // Run the optimization\n  localize(V, Vm, Vn, Vp, D, Dm, Dn, F);\n\n  // In next version, also supply clustering information\n\n#if verbose >0\n  for(size_t kk = 0; kk<Dm; kk++)\n  {\n    size_t Dpos = kk*7;\n    size_t Fpos = kk*5;\n    printf(\"%6lu (%f, %f, %f) -> (%f, %f, %f)\\n\", kk,\n        D[Dpos], D[Dpos+1], D[Dpos+2],\n        F[Fpos], F[Fpos+1], F[Fpos+2]);\n  }\n#endif \n  free(F);\n  free(D);\n  free(V);\n  return 0;  \n}\n\nint main(int argc, char ** argv)\n  // For testing, not used any more, see the MATLAB interface in\n  // df_mlfit.c\n{\n\n  printf(\"%s\\n\", argv[0]);\n\n  if(argc == 1)\n    return unit_tests();\n\n  return 0;\n}\n#endif\n\n", "meta": {"hexsha": "5b9b3227349a6f10925df2d6ae24dbdd43bdb80c", "size": 10753, "ext": "c", "lang": "C", "max_stars_repo_path": "common/mex/mlfitN.c", "max_stars_repo_name": "elgw/dotter", "max_stars_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T08:20:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T08:20:13.000Z", "max_issues_repo_path": "common/mex/mlfitN.c", "max_issues_repo_name": "elgw/dotter", "max_issues_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_issues_repo_licenses": ["MIT"], "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/mex/mlfitN.c", "max_forks_repo_name": "elgw/dotter", "max_forks_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938", "max_forks_repo_licenses": ["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.2417840376, "max_line_length": 159, "alphanum_fraction": 0.5878359528, "num_tokens": 3943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3636908551908027}}
{"text": "\n/**\n  *\n  * For reference: Pearson's rho...\n  *\n  *               sum( (x_i-E[x])(y_i-E[y]) )\n  * rho = -------------------------------------------\n  *       sqrt( sum((x_i-E[x])^2) sum((y_i-E[y])^2) )\n  */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <limits.h>\n#include <string.h>\n#include <math.h>\n#include <assert.h>\n#include <alloca.h>\n\n#include <gsl/gsl_cdf.h>\n\n#include \"stattest.h\"\n#include \"mix.h\"\n#include \"bvr.h\"\n#include \"limits.h\"\n\nstruct Pair {\n\tfloat cv; // Continuous Variable\n\tunsigned int dv; // Discrete Variable\n};\n\n\nstatic int _cmp_pair( const void *pvl, const void *pvr ) {\n\tconst struct Pair *l = (const struct Pair *)pvl;\n\tconst struct Pair *r = (const struct Pair *)pvr;\n\tconst float delta = l->cv - r->cv;\n\tif( delta == 0.0 )\n\t\treturn 0.0;\n\telse\n\t\treturn  delta < 0.0 ? -1 : +1;\n}\n\n\nstruct MixCovars {\n\n\t/**\n\t  * Maximum number of samples\n\t  */\n\tunsigned int SAMPLE_CAPACITY;\n\n\t/**\n\t  * All category labels pushed into this accumulator must\n\t  * be in [0,category_capacity).\n\t */ \n\tunsigned int CATEGORY_CAPACITY;\n\n\t/**\n\t  * Count of samples pushed since last cat_clear.\n\t  */\n\tunsigned int sample_count;\n\n\t/**\n\t  * This essentially bounds the allowed category LABELS.\n\t  * Any category label push'ed in must be in [0,expected_categories).\n\t  * Only this member, NOT category_capacity, should be used to size \n\t  * counts arrays!\n\t  */\n\tunsigned int expected_categories;\n\n\t/**\n\t  * This is an count of DISTINCT LABELS observed by push.\n\t  */\n\tunsigned int observed_categories;\n\n\t// Calculation state ///////////////////////////////////////////////////\n\n\tdouble mean_rank;  // necessarily of both covariates\n\tdouble sum_sq_dev; // used for Kruskal-Wallis and Spearman\n\n\t/**\n\t  * Following struct array is ONLY for Spearman rho calculation.\n\t  * Note that the number of non-empty categories after data entry\n\t  * says NOTHING about WHICH categories (indices) are non-zero.\n\t  * An earlier implementation was assuming category_count[0,1] > 0,\n\t  * BUT THIS NEED NOT BE TRUE! Thus, all this hack...\n\t  */\n\tstruct {\n\t\tunsigned int index;\n\t\tunsigned int count;\n\t\tunsigned int meanRank;\n\t} edge[2];\n\n\tdouble sum_dev_prod; // used only for Spearman-rho\n\n\t// Buffer //////////////////////////////////////////////////////////////\n\n\t/**\n\t  * The TOTAL amount of malloc'ed space (for the purposes\n\t  * of fast clearing with memset).\n\t  */\n\tsize_t SIZEOF_BUFFERS;\n\n\t/**\n\t  * Two buffers\n\t  */\n\tstruct Pair *samples;\n\n\t/**\n\t  * A buffer allocated once in construction and reused for \n\t  * all subsequent analyses.\n\t  * Reallocation is not currently supported.\n\t  */\n\tunsigned int *category_count;\n};\n\n\n#ifdef _UNITTEST_MIX_\nunsigned arg_min_mixb_count = 1;\n#else\nextern unsigned arg_min_mixb_count;\n#endif\n\n/**\n  * Both minCat and maxCat assume that samples is non-empty,\n  * but it's entirely possible that there were NO samples.\n  */\nstatic unsigned _minCat( struct MixCovars *co ) {\n\tunsigned int i = 0;\n\twhile( i < co->expected_categories ) {\n\t\tif( co->category_count[i] > 0 ) \n\t\t\treturn i;\n\t\ti++;\n\t}\n\treturn INT_MAX; // just to silence compiler.\n}\n\n\nstatic unsigned _maxCat( struct MixCovars *co ) {\n\n\tint i = co->expected_categories;\n\twhile( i-- > 0 ) {\n\t\tif( co->category_count[i] > 0 ) \n\t\t\treturn (unsigned int)i;\n\t}\n\treturn INT_MAX; // just to silence compiler\n}\n\n\n/**\n  * Notice that all calcuations are performed without actually requiring\n  * an array of ranks.\n  */\nstatic unsigned int _rank_sums( struct MixCovars *co,\n\tdouble *sums ) {\n\n\tconst unsigned int N = co->sample_count;\n\tconst bool PRECALC_SPEARMAN_PRODUCT\n\t\t= co->observed_categories == 2;\n\tconst unsigned UPPER\n\t\t= co->edge[1].index;\n\tunsigned int ties = 0;\n\tunsigned int until = 0;\n\tfloat rank = 0;\n\tdouble diff;\n\n\t// The default pair::operator< automatically uses the first element.\n\n\tqsort( co->samples, co->sample_count, sizeof(struct Pair), _cmp_pair );\n\n\tfor(unsigned int i = 0; i < N; i++ ) {\n\n\t\tconst unsigned int cat \n\t\t\t= co->samples[i].dv;\n\n\t\t// The rank of the current sample is i+1 UNLESS we're in\n\t\t// the midst of a run of samples with the same value in\n\t\t// which case the last computed rank (a mean) is reused.\n\n\t\tif( ! ( i < until ) ) {\n\n\t\t\tuntil = i + 1;\n\t\t\twhile( until < N \n\t\t\t\t\t&& ( co->samples[i].cv == co->samples[until].cv ) ) {\n\t\t\t\tties++;\n\t\t\t\tuntil++;\n\t\t\t}\n\n\t\t\tif( i == 0 && until == N ) {\n\t\t\t\t// degenerate case: all ties.\n\t\t\t}\n\n\t\t\t// Mean of n integers starting on r:\n\t\t\t// [ (r+0) + (r+1) + (r+2) + ... + (r+(n-1)) ] / n\n\t\t\t// ... = \\frac{nr + \\sum_{i=0}^{n-1} i}{n} \n\t\t\t// ... = r + (1/n)[ (n-1)n / 2 ]\n\t\t\t// ... = r + (n-1)/2\n\n\t\t\trank = (1.0+i) + ((until-i)-1)/2.0;\n\n\t\t\t// ...notice if the very next sample -is- different\n\t\t\t// then rank == i+1, the trivial case.\n\t\t}\n\n\t\t/**\n\t\t  * Warning: If the numeric feature is constant then rank==meanRank\n\t\t  * and diff == 0\n\t\t  */\n\t\tdiff = rank - co->mean_rank;\n\n\t\tco->sum_sq_dev += ( diff * diff );\n\n\t\tif( PRECALC_SPEARMAN_PRODUCT ) {\n\t\t\tco->sum_dev_prod += ( diff * ( co->edge[UPPER==cat?1:0].meanRank - co->mean_rank ) );\n\t\t}\n\n\t\tsums[ cat ] += rank;\n\t}\n\n\treturn ties;\n}\n\n\n#if defined(_UNITTEST_MIX_)\nstatic void dbg_dump( struct MixCovars *co, FILE *fp ) {\n\tfor(unsigned int i = 0; i < co->sample_count; i++ )\n\t\tfprintf( fp, \"%.3f\\t%d\\n\", co->samples[i].cv, co->samples[i].dv );\n}\n#endif\n\n/***************************************************************************\n  * Publics\n  */\n\nvoid mix_destroy( void *pv ) {\n\n\tif( pv ) {\n\t\tstruct MixCovars *co = (struct MixCovars *)pv;\n\t\tif( co->samples )\n\t\t\tfree( co->samples );\n\t\tfree( pv );\n\t}\n}\n\n\n/**\n  * Pre-allocate a set of working buffers large enough for all anticipated\n  * calculations (max feature length) and a struct to wrap them.\n  */\nvoid *mix_create( unsigned int sample_capacity, unsigned int category_capacity ) {\n\n\tstruct MixCovars *co\n\t\t= calloc( 1, sizeof(struct MixCovars) );\n\tif( co ) {\n\t\tco->SAMPLE_CAPACITY   = sample_capacity;\n\t\tco->CATEGORY_CAPACITY = category_capacity;\n\t\tco->SIZEOF_BUFFERS\n\t\t\t= ( sample_capacity * sizeof(struct Pair) )\n\t\t\t+ ( category_capacity * sizeof(unsigned int) );\n\n\t\t// Allocate one large buffer and partition it up.\n\t\tco->samples\n\t\t\t= calloc( co->SIZEOF_BUFFERS, sizeof(char) );\n\t\tco->category_count\n\t\t\t= (unsigned int*)(co->samples\n\t\t\t+ sample_capacity);\n\t\t// If -anything- failed clean up any successes.\n\t\tif( NULL == co->samples ) {\n\t\t\tmix_destroy( co );\n\t\t\treturn NULL;\n\t\t}\n\t\treturn co;\n\t}\n\treturn NULL;\n}\n\n\nvoid mix_clear( void *pv, unsigned expcat ) {\n\n\tstruct MixCovars *co = (struct MixCovars *)pv;\n\n\tassert( expcat <= co->CATEGORY_CAPACITY );\n\n\tco->sample_count = 0;\n\tco->expected_categories = expcat;\n\tco->observed_categories = 0;\n\tco->mean_rank    = 0.0;\n\tco->sum_sq_dev   = 0.0;\n\tco->sum_dev_prod = 0.0;\n\tmemset( co->edge, 0, sizeof(co->edge) );\n\tco->sum_dev_prod = 0.0;\n\n\tmemset( co->samples, 0, co->SIZEOF_BUFFERS );\n}\n\n\nvoid mix_push( void *pv, float num, unsigned int cat ) {\n\n\tstruct MixCovars *co = (struct MixCovars *)pv;\n\n\tassert( cat              < co->expected_categories );\n\tassert( co->sample_count < co->SAMPLE_CAPACITY     );\n\n\tif( 0 == co->category_count[ cat ] ) \n\t\tco->observed_categories++;\n\n\tco->category_count[ cat ] += 1;\n\n\t// Not updating edges in here because the number of conditionals\n\t// executed for sample counts > 32 exceeds the work to find the\n\t// edges post-sample accumulation.\n\tco->samples[ co->sample_count ].cv = num;\n\tco->samples[ co->sample_count ].dv = cat;\n\tco->sample_count++;\n}\n\n\nsize_t mix_size( void *pv ) {\n\tstruct MixCovars *co = (struct MixCovars *)pv;\n\treturn co->sample_count;\n}\n\n\n/**\n  * - Establish whether or not Spearman is even sensible (according to\n  *   whether or not the categorical variable is binary).\n  * - Compute the mean rank used throughout subsequent calcs.\n  * - Compute the mean ranks of the categorical values assuming\n  *   they -are- binary.\n  */\nbool mix_complete( void *pv ) {\n\n\tstruct MixCovars *co = (struct MixCovars *)pv;\n\tif( mix_degenerate( co ) ) return false;\n\n\tco->mean_rank = (1.0 + co->sample_count)/2.0;\n\n\tco->edge[1].index = _maxCat( co ); // ...this is used by kruskal_wallis, but\n\n\tassert( co->edge[1].index < co->expected_categories );\n\n\t// ...the remainder of the edge[] struct is only used if...\n\n\tif( co->observed_categories == 2 ) {\n\n\t\t// All the following is relevant only to Spearman rho calculation.\n\n\t\tco->edge[0].index = _minCat( co );\n\t\tassert( co->edge[0].index < co->expected_categories );\n\n\t\tco->edge[0].count = co->category_count[ co->edge[0].index ];\n\t\tco->edge[0].meanRank = MEAN_RANK_OF_TIES( 0, co->edge[0].count );\n\n\t\tco->edge[1].count = co->category_count[ co->edge[1].index ];\n\n\t\tif( co->edge[0].count < arg_min_mixb_count ||\n\t\t\tco->edge[1].count < arg_min_mixb_count )\n\t\t\treturn false; // another degeneracy class\n\n\t\tco->edge[1].meanRank = MEAN_RANK_OF_TIES( co->edge[0].count, co->sample_count );\n\n\t\tassert( (co->edge[0].count + co->edge[1].count) == co->sample_count );\n\t}\n\treturn true;\n}\n\n\nbool mix_degenerate( void *pv ) {\n\tstruct MixCovars *co = (struct MixCovars *)pv;\n\treturn co->observed_categories < 2 || co->sample_count < 2;\n}\n\n\nbool mix_categoricalIsBinary( void *pv ) {\n\tstruct MixCovars *co = (struct MixCovars *)pv;\n\treturn co->observed_categories == 2;\n}\n\n\n/**\n * Calculates the Kruskal-Wallis statistic and optionally a p-value.\n * Importantly, it does it in a one pass iteration over the data.\n */\nint mix_kruskal_wallis( void *pv, struct Statistic *result ) {\n\n\tstruct MixCovars *co = (struct MixCovars *)pv;\n\tconst unsigned int N \n\t\t= co->sample_count ;\n\tconst size_t SIZEOF_SUMS\n\t\t= co->expected_categories * sizeof(double);\n\tdouble *rank_sum\n\t\t= (double*)alloca( SIZEOF_SUMS );\n\tdouble numerator = 0.0;\n\n\tmemset( rank_sum, 0, SIZEOF_SUMS   );\n\n\tresult->extra_value[0] = _rank_sums( co, rank_sum );\n\n\tfor(unsigned int i = 0; i <= co->edge[1].index; i++ ) {\n\t\tif( co->category_count[i] > 0 ) {\n\t\t\trank_sum[i] /= co->category_count[i];\n\t\t\tdouble delta \n\t\t\t\t= rank_sum[i] - co->mean_rank;\n\t\t\tnumerator \n\t\t\t\t+= ( co->category_count[i] * delta * delta );\n\t\t}\n\t}\n\n\tresult->name\n\t\t= \"Kruskal-Wallis_K\";\n\tresult->sample_count\n\t\t= N;\n\tresult->value\n\t\t= (N-1) * ( numerator / co->sum_sq_dev );\n\tresult->probability\n\t\t= gsl_cdf_chisq_Q( result->value, co->observed_categories-1 );\n\n\treturn 0;\n}\n\n\n/**\n * P-value returned is ONE-SIDED. Double it for two-sided.\n */\n#ifdef HAVE_MANN_WHITNEY\nint mix_mann_whitney( void *pv, struct Statistic *result ) {\n\n\tstruct MixCovars *co = (struct MixCovars *)pv;\n\tconst size_t SIZEOF_SUMS\n\t\t= co->expected_categories * sizeof(double);\n\tdouble *rank_sum\n\t\t= (double*)alloca( SIZEOF_SUMS );\n\tmemset( rank_sum, 0, SIZEOF_SUMS   );\n\n\tms->ties\n\t\t= _rank_sums( co, rank_sum );\n\n\t// TODO: If too many ties, the following method of calculating U\n\t//       becomes invalid. What to do?\n\n\tconst unsigned int SQ\n\t\t= category_count[0]*category_count[1];\n\n\t// If either group count is 0 we're done...\n\n\tif( SQ ) {\n\n\t\tconst double U1\n\t\t\t= rank_sum[0] - (category_count[0]*(category_count[0]+1.0))/2.0;\n\t\tconst double U2\n\t\t\t= rank_sum[1] - (category_count[1]*(category_count[1]+1.0))/2.0;\n\n\t\tassert( U1+U2 == SQ );\n\n\t\tms->U = U1 < U2 ? U1 : U2;\n\n\t\tconst double mean_U\n\t\t\t= SQ / 2.0;\n\t\tconst double sigma_U\n\t\t\t= sqrt( SQ*( category_count[0] + category_count[1] + 1.0 ) / 12.0 );\n\n\t\tcs->P = gsl_cdf_ugaussian_P( ( ms->U - mean_U ) / sigma_U );\n\t}\n\treturn 0;\n}\n#endif\n\n/**\n  * This calculation depends on a quantities calculated within\n  * kruskal_wallis (or mann_whitney), so must be called after\n  * either of them.\n  * (This is also the only reason this method can be const.)\n  */\ndouble mix_spearman_rho( void *pv ) {\n\n\tstruct MixCovars *co = (struct MixCovars *)pv;\n\t/**\n\t  * denominator requires sum of square deviation for\n\t  * the binary variables which collapses to...\n\t  */\n\tdouble SQD0 = (co->edge[0].meanRank - co->mean_rank ); SQD0 *= SQD0;\n\tdouble SQD1 = (co->edge[1].meanRank - co->mean_rank ); SQD1 *= SQD1;\n\n\tconst double SUMSQD\n\t\t= co->edge[0].count * SQD0 + co->edge[1].count * SQD1;\n\t/**\n\t  * And the sum of squared deviation of the numeric covariate's\n\t  * ranks (sum_sq_dev) was (necessarily) calculated earlier!\n\t  */\n\treturn co->sum_dev_prod / sqrt( co->sum_sq_dev * SUMSQD );\n}\n\n\n#ifdef _UNITTEST_MIX_\n\n/**\n * This is intended to be exercised with the following R script\n * that generates a small table of grouped floating-point values\n * executes a Kruskal-Wallis test on it, and dumps the table\n * to a tab-delimited file with the test results as a comment on\n * the first line.\n *\n * x <- data.frame(\n * \t\tcat=as.integer(gl(3,4))-1, \n * \t\tnum=c( runif(4)*10, runif(4)*20, 10+runif(4)*10 ) );\n * k <- with( x, kruskal.test( num, cat ) );\n * cat( sprintf( \"# K=%f p-value=%f\\n\", k$statistic, k$p.value ), file=\"foo.tab\" );\n * write.table( x, 'foo.tab', quote=F, sep='\\t', row.names=F, col.names=F, append=TRUE );\n */\n#include <err.h>\n\nint main( int argc, char *argv[] ) {\n\n\tif( argc >= 3 ) {\n\n\t\tstruct Statistic result;\n\t\tconst int EXPCAT\n\t\t\t= atoi( argv[1] );\n\t\tstruct MixCovars *accum\n\t\t   = mix_create( atoi( argv[2] ), MAX_CATEGORY_COUNT );\n\t\tFILE *fp \n\t\t\t= argc > 3\n\t\t\t? fopen( argv[3], \"r\" )\n\t\t\t: stdin;\n\t\tchar *line = NULL;\n\t\tsize_t n = 0;\n\n\t\tmix_clear( accum, EXPCAT );\n\n\t\twhile( getline( &line, &n, fp ) > 0 ) {\n\t\t\tunsigned int cat;\n\t\t\tfloat        num;\n\t\t\tif( line[0] == '#' ) {\n\t\t\t\tfputs( line, stdout );\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif( 2 == sscanf( line, \"%d\\t%f\\n\", &cat, &num ) ) {\n\t\t\t\tmix_push( accum, num, cat );\n\t\t\t} else {\n\t\t\t\tfprintf( stderr, \"Failure parsing line: %s\", line );\n\t\t\t}\n\t\t}\n\t\tfree( line );\n\t\tfclose( fp );\n\n\t\t// Always calculate Kruskal-Wallis since it's valid for any groups\n\t\t// count >= 2...\n\n\t\tif( mix_complete( accum ) ) {\n\t\t\tmemset( &result, 0, sizeof(struct Statistic) );\n\t\t\tif( mix_kruskal_wallis( accum, &result ) == 0 ) {\n\t\t\t\tprintf( \"K=%f, p-value=%f\", result.value, result.probability );\n\t\t\t\tif( mix_categoricalIsBinary( accum ) )\n\t\t\t\t\tprintf( \", spearman=%f\\n\", mix_spearman_rho(accum) );\n\t\t\t\telse\n\t\t\t\t\tfputc( '\\n', stdout );\n\t\t\t} else {\n\t\t\t\tprintf( \"error\\n\" );\n\t\t\t}\n\t\t}\n\n#ifdef HAVE_MANN_WHITNEY\n\t\t// Do a Mann-Whitney, too, if there are only 2 groups.\n\t\tif( mix_categoricalIsBinary(accum) == 2 ) {\n\t\t}\n#endif\n\t\tmix_destroy( accum );\n\t} else\n\t\terr( -1, \"%s <categories> <sample count> [ <input file> ]\", argv[0] );\n\treturn 0;\n}\n#endif\n\n", "meta": {"hexsha": "c6be03832df5f1284062d48677396f9094ac778e", "size": 14242, "ext": "c", "lang": "C", "max_stars_repo_path": "pairwise/src/mix.c", "max_stars_repo_name": "IlyaLab/kramtools", "max_stars_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T03:07:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-30T03:07:45.000Z", "max_issues_repo_path": "pairwise/src/mix.c", "max_issues_repo_name": "IlyaLab/kramtools", "max_issues_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pairwise/src/mix.c", "max_forks_repo_name": "IlyaLab/kramtools", "max_forks_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81", "max_forks_repo_licenses": ["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.8551483421, "max_line_length": 89, "alphanum_fraction": 0.6322145766, "num_tokens": 4314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3634274616350385}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_integration.h>\n\n#include \"ccl.h\"\n\nccl_cl_tracer_collection_t *ccl_cl_tracer_collection_t_new(int *status) {\n  ccl_cl_tracer_collection_t *trc = NULL;\n  trc = malloc(sizeof(ccl_cl_tracer_collection_t));\n  if (trc == NULL)\n    *status = CCL_ERROR_MEMORY;\n\n  if (*status == 0) {\n    trc->n_tracers = 0;\n    // Currently CCL_MAX_TRACERS_PER_COLLECTION is hard-coded to 100.\n    // It should be enough for any practical application with minimal memory overhead\n    trc->ts = malloc(CCL_MAX_TRACERS_PER_COLLECTION*sizeof(ccl_cl_tracer_t *));\n    if (trc->ts == NULL) {\n      *status = CCL_ERROR_MEMORY;\n      free(trc);\n      trc = NULL;\n    }\n  }\n\n  return trc;\n}\n\nvoid ccl_cl_tracer_collection_t_free(ccl_cl_tracer_collection_t *trc) {\n  if (trc != NULL) {\n    if (trc->ts != NULL)\n      free(trc->ts);\n    free(trc);\n  }\n}\n\nvoid ccl_add_cl_tracer_to_collection(ccl_cl_tracer_collection_t *trc,\n                                     ccl_cl_tracer_t *tr, int *status) {\n  if (trc->n_tracers >= CCL_MAX_TRACERS_PER_COLLECTION) {\n    *status = CCL_ERROR_MEMORY;\n    return;\n  }\n  trc->ts[trc->n_tracers] = tr;\n  trc->n_tracers++;\n}\n\n\n// Takes an array of z-dependent numbers and the corresponding z values\n// and returns an array of a values and the corresponding a-dependent values.\n// The order of the original arrays is assumed to be ascending in z, and\n// the order of the returned arrays is swapped (so it has ascending a).\nstatic void from_z_to_a(ccl_cosmology *cosmo,\n                        int nz, double *z_arr, double *fz_arr,\n                        double **a_arr, double **fa_arr, int *status) {\n  *a_arr = NULL;\n  *fa_arr = NULL;\n  *a_arr = malloc(nz*sizeof(double));\n  *fa_arr = malloc(nz*sizeof(double));\n\n  if ((a_arr == NULL) || (fa_arr == NULL)) {\n    *status = CCL_ERROR_MEMORY;\n    free(*a_arr);\n    free(*fa_arr);\n    ccl_cosmology_set_status_message(\n      cosmo, \"ccl_tracers.c: from_z_to_a(): memory allocation error\\n\");\n  }\n\n  if (*status == 0) {\n    int ia;\n    // Populate array of scale factors in reverse order\n    for (ia=0; ia < nz; ia++) {\n      (*a_arr)[ia] = 1./(1+z_arr[nz-1-ia]);\n      (*fa_arr)[ia] = fz_arr[nz-1-ia];\n    }\n  }\n}\n\n//Integrand for N(z) integrator\nstatic double nz_integrand(double z, void *pars) {\n  ccl_f1d_t *nz_f = (ccl_f1d_t *)pars;\n\n  return ccl_f1d_t_eval(nz_f,z);\n}\n\n// Gets area of N(z) curve\nstatic double get_nz_norm(ccl_cosmology *cosmo, ccl_f1d_t *nz_f,\n                          double z0, double zf, int *status) {\n  double nz_norm = -1, nz_enorm;\n\n  // Get N(z) norm\n  gsl_function F;\n  gsl_integration_workspace *w = NULL;\n  F.function = &nz_integrand;\n  F.params = nz_f;\n\n  w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n\n  if (w == NULL) {\n    *status = CCL_ERROR_MEMORY;\n    ccl_cosmology_set_status_message(\n      cosmo, \"ccl_tracers.c: get_nz_norm(): out of memory\");\n  }\n  else {\n    int gslstatus = gsl_integration_qag(\n      &F, z0, zf, 0,\n      cosmo->gsl_params.INTEGRATION_EPSREL,\n      cosmo->gsl_params.N_ITERATION,\n      cosmo->gsl_params.INTEGRATION_GAUSS_KRONROD_POINTS,\n      w, &nz_norm, &nz_enorm);\n\n    if (gslstatus != GSL_SUCCESS) {\n      ccl_raise_gsl_warning(gslstatus, \"ccl_tracers.c: get_nz_norm():\");\n      *status = CCL_ERROR_INTEG;\n      ccl_cosmology_set_status_message(\n        cosmo,\n        \"ccl_tracers.c: get_nz_norm(): \"\n        \"integration error when normalizing N(z)\\n\");\n    }\n  }\n\n  gsl_integration_workspace_free(w);\n\n  return nz_norm;\n}\n\nstatic void from_z_to_chi(ccl_cosmology *cosmo, int nz, double *z_arr,\n                          double *chi_arr, int *status) {\n  for (int ichi=0; ichi < nz; ichi++)\n    chi_arr[ichi] = ccl_comoving_radial_distance(cosmo, 1./(1+z_arr[ichi]), status);\n}\n\nvoid ccl_get_number_counts_kernel(ccl_cosmology *cosmo,\n                                  int nz, double *z_arr, double *nz_arr,\n                                  int normalize_nz,\n                                  double *pchi_arr, int *status) {\n  // Returns dn/dchi normalized to unit area from an unnormalized dn/dz.\n  // Prepare N(z) spline\n  ccl_f1d_t *nz_f = NULL;\n\n  nz_f = ccl_f1d_t_new(nz, z_arr, nz_arr, 0, 0);\n  if (nz_f == NULL) {\n    *status = CCL_ERROR_SPLINE;\n    ccl_cosmology_set_status_message(\n      cosmo,\n      \"ccl_tracers.c: ccl_get_number_counts_kernel: \"\n      \"error initializing spline\\n\");\n  }\n\n  // Get N(z) normalization\n  double i_nz_norm = -1;\n  if (*status == 0) {\n    if (normalize_nz)\n      i_nz_norm = 1./get_nz_norm(cosmo, nz_f, z_arr[0], z_arr[nz-1], status);\n    else\n      i_nz_norm = 1;\n  }\n\n  if (*status == 0) {\n    // Populate arrays\n    for(int ichi=0; ichi < nz; ichi++) {\n      double a = 1./(1+z_arr[ichi]);\n      double h = cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/ccl_constants.CLIGHT_HMPC;\n      // H(z) * dN/dz * 1/Ngal\n      pchi_arr[ichi] = h*nz_arr[ichi]*i_nz_norm;\n    }\n  }\n\n  ccl_f1d_t_free(nz_f);\n}\n\n//3 H0^2 Omega_M / 2\nstatic double get_lensing_prefactor(ccl_cosmology *cosmo,int *status) {\n  double hub = cosmo->params.h/ccl_constants.CLIGHT_HMPC;\n  return 1.5*hub*hub*cosmo->params.Omega_m;\n}\n\ntypedef struct {\n  ccl_cosmology *cosmo;\n  double z_max;\n  double z_end;\n  double chi_end;\n  double i_nz_norm;\n  ccl_f1d_t *nz_f;\n  ccl_f1d_t *sz_f;\n  int *status;\n} integ_lensing_pars;\n\n// Integrand for lensing kernel.\n// Returns N(z) * (1 - 5*s(z)/2) * (chi(z)-chi) / chi(z)\nstatic double lensing_kernel_integrand(double z, void *pars) {\n  integ_lensing_pars *p = (integ_lensing_pars *)pars;\n  double pz = ccl_f1d_t_eval(p->nz_f, z);\n  double qz;\n  if (p->sz_f == NULL) // No magnification factor\n    qz = 1;\n  else // With magnification factor\n    qz = (1 - 2.5*ccl_f1d_t_eval(p->sz_f, z));\n\n  if (z == 0)\n    return pz * qz;\n  else {\n    double chi = ccl_comoving_radial_distance(p->cosmo, 1./(1+z), p->status);\n    return (\n      pz * qz *\n      ccl_sinn(p->cosmo, chi-p->chi_end, p->status) /\n      ccl_sinn(p->cosmo, chi, p->status));\n  }\n}\n\n// Returns\n// Integral[ p(z) * (1-5s(z)/2) * chi_end * (chi(z)-chi_end)/chi(z) , {z',z_end,z_max} ]\nstatic double lensing_kernel_integrate(ccl_cosmology *cosmo,\n                                       integ_lensing_pars *pars,\n                                       gsl_integration_workspace *w) {\n  int gslstatus = 0;\n  double result, eresult;\n  gsl_function F;\n  F.function = &lensing_kernel_integrand;\n  F.params = pars;\n  gslstatus = gsl_integration_qag(\n    &F, pars->z_end, pars->z_max, 0,\n    cosmo->gsl_params.INTEGRATION_EPSREL,\n    cosmo->gsl_params.N_ITERATION,\n    cosmo->gsl_params.INTEGRATION_GAUSS_KRONROD_POINTS,\n    w, &result, &eresult);\n\n  if ((gslstatus != GSL_SUCCESS) || (*(pars->status))) {\n    ccl_raise_gsl_warning(gslstatus, \"ccl_tracers.c: lensing_kernel_integrate():\");\n    return -1;\n  }\n\n  return result * pars->i_nz_norm * pars->chi_end;\n}\n\n//Returns number of divisions on which\n//the lensing kernel should be calculated\nint ccl_get_nchi_lensing_kernel(int nz, double *z_arr, int *status) {\n  int nchi;\n  double dz = -1, z_max = -1;\n  //Compute redshift step\n  dz = (z_arr[nz-1]-z_arr[0])/(nz-1);\n\n  //How many steps to z=0?\n  return (int)(z_arr[nz-1]/dz+0.5);\n}\n\n//Return array with the values of chi at\n//the which the lensing kernel will be\n//calculated.\nvoid ccl_get_chis_lensing_kernel(ccl_cosmology *cosmo,\n                                 int nchi, double z_max,\n                                 double *chis, int *status) {\n  double dz = z_max/nchi;\n  for(int ichi=0; ichi < nchi; ichi++) {\n    double z = dz*ichi+1E-15;\n    double a = 1./(1+z);\n    chis[ichi] = ccl_comoving_radial_distance(cosmo, a, status);\n  }\n}\n\n//Returns array with lensing kernel:\n//3 * H0^2 * Omega_M / 2 / a *\n// Integral[ p(z) * (1-5s(z)/2) * chi_end * (chi(z)-chi_end)/chi(z) ,\n//          {z',z_end,z_max} ]\nvoid ccl_get_lensing_mag_kernel(ccl_cosmology *cosmo,\n                                int nz, double *z_arr, double *nz_arr,\n                                int normalize_nz, double z_max,\n                                int nz_s, double *zs_arr, double *sz_arr,\n                                int nchi, double *chi_arr, double *wL_arr,\n                                int *status) {\n  ccl_f1d_t *nz_f = NULL;\n  ccl_f1d_t *sz_f = NULL;\n  gsl_integration_workspace *w;\n  integ_lensing_pars *ipar;\n  int local_status;\n\n  // Prepare N(z) spline\n  nz_f = ccl_f1d_t_new(nz, z_arr, nz_arr, 0, 0);\n  if (nz_f == NULL) {\n    *status = CCL_ERROR_SPLINE;\n    ccl_cosmology_set_status_message(\n      cosmo,\n      \"ccl_tracers.c: get_lensing_mag_kernel: error initializing spline\\n\");\n  }\n\n  // Get N(z) normalization\n  double i_nz_norm = -1;\n  if (*status == 0) {\n    if (normalize_nz)\n      i_nz_norm = 1./get_nz_norm(cosmo, nz_f, z_arr[0], z_arr[nz-1], status);\n    else\n      i_nz_norm = 1.;\n  }\n\n  // Prepare magnification bias spline if needed\n  if (*status == 0) {\n    if ((nz_s > 0) && (zs_arr != NULL) && (sz_arr != NULL)) {\n      sz_f = ccl_f1d_t_new(nz_s, zs_arr, sz_arr, sz_arr[0], sz_arr[nz_s-1]);\n      if (sz_f == NULL) {\n        *status = CCL_ERROR_SPLINE;\n        ccl_cosmology_set_status_message(\n          cosmo,\n          \"ccl_tracers.c: get_lensing_mag_kernel: error initializing spline\\n\");\n      }\n    }\n  }\n\n  double lens_prefac = get_lensing_prefactor(cosmo, status);\n  double chi, a, z, mgfac;\n  int ichi;\n\n  w = NULL;\n  ipar = NULL;\n  local_status = *status;\n\n  if (local_status == 0) {\n    ipar = malloc(sizeof(integ_lensing_pars));\n    w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION);\n\n    if ((ipar == NULL) || (w == NULL)) {\n      local_status = CCL_ERROR_MEMORY;\n    }\n  }\n\n  if (local_status == 0) {\n    ipar->cosmo = cosmo;\n    ipar->z_max = z_max;\n    ipar->i_nz_norm = i_nz_norm;\n    ipar->sz_f = sz_f;\n    ipar->nz_f = nz_f;\n    ipar->status = &local_status;\n  }\n\n  //Populate arrays\n  for (ichi=0; ichi < nchi; ichi++) {\n    if (local_status == 0) {\n      chi = chi_arr[ichi];\n      a = ccl_scale_factor_of_chi(cosmo, chi, &local_status);\n      z = 1./a-1;\n      // Add MG correction if needed\n      mgfac = 1.0;\n      if (fabs(cosmo->params.sigma_0))\n        mgfac += ccl_Sig_MG(cosmo, a, &local_status);\n      ipar->z_end = z;\n      ipar->chi_end = chi;\n\n      wL_arr[ichi] = lensing_kernel_integrate(cosmo, ipar, w)*(1+z)*lens_prefac*mgfac;\n    } else {\n      wL_arr[ichi] = NAN;\n    }\n  }\n\n  gsl_integration_workspace_free(w);\n  free(ipar);\n\n  if (local_status != 0) {\n    *status = CCL_ERROR_INTEG;\n  }\n\n  ccl_f1d_t_free(nz_f);\n  ccl_f1d_t_free(sz_f);\n}\n\n// Returns kernel for CMB lensing\n// 3H0^2Om/2 * chi * (chi_s - chi) / chi_s / a\nvoid ccl_get_kappa_kernel(ccl_cosmology *cosmo, double chi_source,\n                          int nchi, double *chi_arr,\n                          double *wchi, int *status) {\n  double lens_prefac = get_lensing_prefactor(cosmo, status) / ccl_sinn(cosmo, chi_source, status);\n\n  for (int ichi=0; ichi < nchi; ichi++) {\n    double chi = chi_arr[ichi];\n    double a = ccl_scale_factor_of_chi(cosmo, chi, status);\n    double mgfac = 1;\n    // Add MG correction if needed\n    if (fabs(cosmo->params.sigma_0))\n      mgfac += ccl_Sig_MG(cosmo, a, status);\n    wchi[ichi] = lens_prefac*(ccl_sinn(cosmo,chi_source-chi,status))*chi*mgfac/a;\n  }\n}\n\nccl_cl_tracer_t *ccl_cl_tracer_t_new(ccl_cosmology *cosmo,\n                                     int der_bessel,\n                                     int der_angles,\n                                     int n_w, double *chi_w, double *w_w,\n                                     int na_ka, double *a_ka,\n                                     int nk_ka, double *lk_ka,\n                                     double *fka_arr,\n                                     double *fk_arr,\n                                     double *fa_arr,\n                                     int is_fka_log,\n                                     int is_factorizable,\n                                     int extrap_order_lok,\n                                     int extrap_order_hik,\n                                     int *status) {\n  ccl_cl_tracer_t *tr = NULL;\n\n  // Check der_bessel and der_angles are sensible\n  if ((der_angles < 0) || (der_angles > 2)) {\n    *status = CCL_ERROR_INCONSISTENT;\n    ccl_cosmology_set_status_message(\n      cosmo,\n      \"ccl_tracers.c: ccl_cl_tracer_new: der_angles must be between 0 and 2\\n\");\n  }\n  if ((der_bessel < -1) || (der_bessel > 2)) {\n    *status = CCL_ERROR_INCONSISTENT;\n    ccl_cosmology_set_status_message(\n      cosmo,\n      \"ccl_tracers.c: ccl_cl_tracer_new: der_bessel must be between -1 and 2\\n\");\n  }\n\n  if (*status == 0) {\n    tr = malloc(sizeof(ccl_cl_tracer_t));\n    if (tr == NULL)\n      *status = CCL_ERROR_MEMORY;\n  }\n\n  // Initialize everythin\n  if (*status == 0) {\n    tr->der_angles = der_angles;\n    tr->der_bessel = der_bessel;\n    tr->kernel = NULL; // Initialize these to NULL\n    tr->transfer = NULL; // Initialize these to NULL\n    tr->chi_min = 0;\n    tr->chi_max = 1E15;\n  }\n\n  if (*status == 0) {\n    // Initialize radial kernel\n    if ((n_w > 0) && (chi_w != NULL) && (w_w != NULL)) {\n      tr->kernel = ccl_f1d_t_new(n_w,chi_w,w_w,0,0);\n      if (tr->kernel == NULL)\n        *status=CCL_ERROR_MEMORY;\n    }\n  }\n\n  // Find kernel edges\n  if (*status == 0) {\n    // If no radial kernel, set limits to zero and maximum distance\n    if (tr->kernel == NULL) {\n      tr->chi_min = 0;\n      tr->chi_max = ccl_comoving_radial_distance(cosmo, cosmo->spline_params.A_SPLINE_MIN, status);\n    }\n    else {\n      int ichi;\n      double w_max = fabs(w_w[0]);\n\n      // Find maximum of radial kernel\n      for (ichi=0; ichi < n_w; ichi++) {\n        if (fabs(w_w[ichi]) >= w_max)\n          w_max = fabs(w_w[ichi]);\n      }\n\n      // Multiply by fraction\n      w_max *= CCL_FRAC_RELEVANT;\n\n      // Initialize as the original edges in case we don't find an interval\n      tr->chi_min = chi_w[0];\n      tr->chi_max = chi_w[n_w-1];\n\n      // Find minimum\n      for (ichi=0; ichi < n_w; ichi++) {\n        if (fabs(w_w[ichi]) >= w_max) {\n          tr->chi_min = chi_w[ichi];\n          break;\n        }\n      }\n\n      // Find maximum\n      for (ichi=n_w-1; ichi >= 0; ichi--) {\n        if (fabs(w_w[ichi]) >= w_max) {\n          tr->chi_max = chi_w[ichi];\n          break;\n        }\n      }\n    }\n  }\n\n  if (*status == 0) {\n    if ((fka_arr != NULL) || (fk_arr != NULL) || (fa_arr != NULL)) {\n      tr->transfer = ccl_f2d_t_new(\n        na_ka,a_ka, // na, a_arr\n        nk_ka,lk_ka, // nk, lk_arr\n        fka_arr, // fka_arr\n        fk_arr, // fk_arr\n        fa_arr, // fa_arr\n        is_factorizable, // is factorizable\n        extrap_order_lok, // extrap_order_lok\n        extrap_order_hik, // extrap_order_hik\n        ccl_f2d_constantgrowth, // extrap_linear_growth\n        is_fka_log, // is_fka_log\n        NULL, // growth (function)\n        1, // growth_factor_0 -> will assume constant transfer function\n        0, // growth_exponent\n        ccl_f2d_3, // interp_type\n        status);\n      if (tr->transfer == NULL)\n        *status=CCL_ERROR_MEMORY;\n    }\n  }\n\n  return tr;\n}\n\nvoid ccl_cl_tracer_t_free(ccl_cl_tracer_t *tr) {\n  if (tr != NULL) {\n    if (tr->transfer != NULL)\n      ccl_f2d_t_free(tr->transfer);\n    if (tr->kernel != NULL)\n      ccl_f1d_t_free(tr->kernel);\n    free(tr);\n  }\n}\n\ndouble ccl_cl_tracer_t_get_f_ell(ccl_cl_tracer_t *tr, double ell, int *status) {\n  if (tr != NULL) {\n    if (tr->der_angles == 1)\n      return ell*(ell+1.);\n    else if (tr->der_angles == 2) {\n      if (ell <= 1) // This is identically 0\n        return 0;\n      else if (ell <= 10) // Use full expression in this case\n        return sqrt((ell+2)*(ell+1)*ell*(ell-1));\n      else {\n        double lp1h = ell+0.5;\n        double lp1h2 = lp1h*lp1h;\n        if (ell <= 1000)  // This is accurate to 5E-5 for l>10\n          return lp1h2*(1-1.25/lp1h2);\n        else // This is accurate to 1E-6 for l>1000\n          return lp1h2;\n      }\n    }\n    else\n      return 1;\n  }\n  else\n    return 1;\n}\n\ndouble ccl_cl_tracer_t_get_kernel(ccl_cl_tracer_t *tr, double chi, int *status) {\n  if (tr != NULL) {\n    if (tr->kernel != NULL)\n      return ccl_f1d_t_eval(tr->kernel, chi);\n    else\n      return 1;\n  }\n  else\n    return 1;\n}\n\ndouble ccl_cl_tracer_t_get_transfer(ccl_cl_tracer_t *tr,\n                                    double lk, double a, int *status) {\n  if (tr != NULL) {\n    if (tr->transfer != NULL)\n      return ccl_f2d_t_eval(tr->transfer, lk, a, NULL, status);\n    else\n      return 1;\n  }\n  else\n    return 1;\n}\n", "meta": {"hexsha": "d234499f6102a8398a4b2c53ba6891599ce67cdf", "size": 16528, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_tracers.c", "max_stars_repo_name": "benediktdiemer/CCL", "max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_tracers.c", "max_issues_repo_name": "benediktdiemer/CCL", "max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_tracers.c", "max_forks_repo_name": "benediktdiemer/CCL", "max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z", "avg_line_length": 29.304964539, "max_line_length": 99, "alphanum_fraction": 0.5942037754, "num_tokens": 5134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.36337378339089627}}
{"text": "#ifndef Two_Group_Diffusion_h\n#define Two_Group_Diffusion_h\n\n#include <vector>\n\n// Trilinos includes\n#include \"Kokkos_DefaultNode.hpp\"\n#include \"Teuchos_ParameterList.hpp\"\n#include \"Teuchos_RCP.hpp\"\n#include \"Tpetra_CrsGraph.hpp\"\n#include \"Tpetra_CrsMatrix.hpp\"\n#include \"Tpetra_MultiVector.hpp\"\n#include \"Tpetra_Operator.hpp\"\n#include \"Tpetra_RowMatrix.hpp\"\n#include \"Tpetra_Vector.hpp\"\n\n// SCALE includes\n#include \"Nemesis/comm/global.hh\"\n\n// vendored includes\n#include <gsl/gsl>\n\n// enrico includes\n#include \"Assembly_Model.h\"\n#include \"Neutronics_Solver.h\"\n#include \"Two_Group_Cross_Sections.h\"\n\nnamespace enrico {\n\n//===========================================================================//\n/*!\n * \\class Two_Group_Diffusion\n * \\brief Two-group, 3D neutron diffusion solver.\n */\n//===========================================================================//\n\nclass Two_Group_Diffusion : public Neutronics_Solver {\npublic:\n  enum BC_TYPE { VACUUM, REFLECT };\n  enum FACE { LO_X, HI_X, LO_Y, HI_Y, LO_Z, HI_Z };\n\n  //@{\n  //! Typedefs\n  using XS = Two_Group_Cross_Sections;\n  using XS_Data = XS::XS_Data;\n  using Vec_Dbl = std::vector<double>;\n  using Vec_Int = std::vector<int>;\n  using Vec_BC = std::vector<BC_TYPE>;\n  using SP_Assembly = std::shared_ptr<Assembly_Model>;\n  using Pin_Map = std::vector<Assembly_Model::PIN_TYPE>;\n  using ST = double;\n  using LO = int;\n  using GO = int;\n  using NODE = KokkosClassic::DefaultNode::DefaultNodeType;\n  using MV = Tpetra::MultiVector<ST, LO, GO, NODE>;\n  using VECTOR = Tpetra::Vector<ST, LO, GO, NODE>;\n  using OP = Tpetra::Operator<ST, LO, GO, NODE>;\n  using MAP = Tpetra::Map<LO, GO, NODE>;\n  using MATRIX = Tpetra::CrsMatrix<ST, LO, GO, NODE>;\n  using GRAPH = Tpetra::CrsGraph<LO, GO, NODE>;\n  using RCP_PL = Teuchos::RCP<Teuchos::ParameterList>;\n  //@}\n\nprivate:\n  // >>> DATA\n  SP_Assembly d_assembly;\n\n  Vec_Dbl d_dx;\n  Vec_Dbl d_dy;\n  Vec_Dbl d_dz;\n  Pin_Map d_pin_map;\n  XS d_xs;\n  size_t d_Nx, d_Ny, d_Nz, d_num_cells;\n\n  // Solver parameters\n  double d_tol;\n  int d_max_iters;\n\n  // Boundary conditions\n  Vec_BC d_bcs;\n\n  // Data stored over single group\n  Teuchos::RCP<MAP> d_map;\n  Teuchos::RCP<GRAPH> d_graph;\n  Teuchos::RCP<MATRIX> d_A_therm, d_A_fast;\n  Teuchos::RCP<VECTOR> d_x_therm, d_x_fast;\n  Teuchos::RCP<VECTOR> d_b_therm, d_b_fast;\n\npublic:\n  // Constructor\n  Two_Group_Diffusion(SP_Assembly assembly, RCP_PL params, const Vec_Dbl& dz);\n\n  // Solve\n  virtual void solve(const Vec_Dbl& temperatures,\n                     const Vec_Dbl& densities,\n                     Vec_Dbl& power) override;\n\nprivate:\n  int cellid(int ix, int iy, int iz)\n  {\n    Expects(ix >= 0);\n    Expects(ix < d_Nx);\n    Expects(iy >= 0);\n    Expects(iy < d_Ny);\n    Expects(iz >= 0);\n    Expects(iz < d_Nz);\n    int cell = ix + d_Nx * (iy + d_Ny * iz);\n    Ensures(cell >= 0);\n    Ensures(cell < d_num_cells);\n    return cell;\n  }\n\n  void build_matrices(const std::vector<XS_Data>& xs_data);\n\n  // Compute 2-norm of vector\n  double vec_norm(const Teuchos::ArrayRCP<double>& vec)\n  {\n    double nrm = 0.0;\n    for (auto val : vec)\n      nrm += val * val;\n    return std::sqrt(nrm);\n  }\n\n  // Apply scale factor to vector data\n  void scale_vec(Teuchos::ArrayRCP<double>& vec, double factor)\n  {\n    for (auto& val : vec)\n      val *= factor;\n  }\n};\n\n//---------------------------------------------------------------------------//\n} // end namespace enrico\n\n//---------------------------------------------------------------------------//\n#endif // Two_Group_Diffusion_h\n\n//---------------------------------------------------------------------------//\n// end of Two_Group_Diffusion.h\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "e99e650068fb353a0dd88ef9fda21977f6ecef7f", "size": 3713, "ext": "h", "lang": "C", "max_stars_repo_path": "include/smrt/Two_Group_Diffusion.h", "max_stars_repo_name": "pshriwise/enrico", "max_stars_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smrt/Two_Group_Diffusion.h", "max_issues_repo_name": "pshriwise/enrico", "max_issues_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smrt/Two_Group_Diffusion.h", "max_forks_repo_name": "pshriwise/enrico", "max_forks_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_forks_repo_licenses": ["BSD-3-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.3333333333, "max_line_length": 79, "alphanum_fraction": 0.5943980609, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.36284292741932317}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <mpi.h>\n\n/* Pull in the CBLAS header. */\n#ifdef _MACOSX\n#include <Accelerate/Accelerate.h>\n#else\n#ifdef _ATLAS\n#include <cblas.h>\n#else\n#include <gsl_cblas.h>\n#endif /* _ATLAS */\n#endif /* _MACOSX */\n\n/* These headers are provided by ScaleME. */\n#include \"ScaleME.h\"\n\n#include \"precision.h\"\n\n#include \"mlfma.h\"\n#include \"direct.h\"\n#include \"itsolver.h\"\n#include \"util.h\"\n\nint matvec (cplx *out, cplx *in, cplx *cur, int id) {\n\tlong i, nelt = (long)fmaconf.numbases * (long)fmaconf.bspboxvol;\n\n\t/* Compute the contrast pressure. */\n#pragma omp parallel for default(shared) private(i)\n\tfor (i = 0; i < nelt; ++i) cur[i] = in[i] * fmaconf.contrast[i];\n\n\t/* Reset the direct-interaction buffer and compute\n\t * the matrix-vector product for the Green's matrix. */\n\tclrdircache();\n\tScaleME_applyParFMA (cur, out);\n\n\tif (!id) return 0;\n\n\t/* Add in the identity portion. */\n#pragma omp parallel for default(shared) private(i)\n\tfor (i = 0; i < nelt; ++i) out[i] = fmaconf.cellvol * in[i] - out[i];\n\n\treturn 0;\n}\n\nint gmres (cplx *rhs, cplx *sol, int guess,\n\t\tint mit, real tol, int quiet, augspace *aug) {\n\tlong j, nelt = (long)fmaconf.numbases * (long)fmaconf.bspboxvol, lwork;\n\tint i, rank, one = 1, mred = mit;\n\tcplx *h, *v, *mvp, *beta, *vp, *hp, *s, cr,\n\t\tcone = 1., czero = 0., *azp, *zp;\n\treal rhn, err, *c;\n\n\tMPI_Comm_rank (MPI_COMM_WORLD, &rank);\n\n\t/* Allocate space for all required complex vectors. */\n\tlwork = (mit + 1) * (mit + nelt + 1) + nelt + mit;\n\tv = calloc (lwork, sizeof(cplx));\t/* The Krylov subspace. */\n\tbeta = v + nelt * (mit + 1);\t\t/* The least-squares RHS. */\n\tmvp = beta + mit + 1;\t\t\t/* Buffer for matrix-vector product. */\n\th = mvp + nelt;\t\t\t\t/* The upper Hessenberg matrix. */\n\ts = h + (mit + 1) * mit;\t\t/* Givens rotation sines. */\n\n\t/* Allocate space for the Givens rotation cosines. */\n\tc = malloc (mit * sizeof(real));\n\n\t/* Compute the norm of the RHS for residual scaling. */\n\trhn = parnorm(rhs, nelt);\n\n\t/* Compute the initial matrix-vector product for the input guess. */\n\tif (guess) matvec (v, sol, mvp, 1);\n\n\t/* Subtract from the RHS to form the residual. */\n#pragma omp parallel for default(shared) private(j)\n\tfor (j = 0; j < nelt; ++j) v[j] = rhs[j] - v[j];\n\n\t/* Zero the initial guess if one wasn't provided. */\n\tif (!guess) memset (sol, 0, nelt * sizeof(cplx));\n\n\t/* Find the norm of the initial residual. */\n\terr = parnorm(v, nelt);\n\n\t/* Construct the initial Arnoldi vector by normalizing the residual. */\n#pragma omp parallel for default(shared) private(j)\n\tfor (j = 0; j < nelt; ++j) v[j] /= err;\n\n\t/* Construct the vector beta for the minimization problem. */\n\tbeta[0] = err;\n\n\t/* Report the RRE. */\n\terr /= rhn;\n\tif (!rank && !quiet) printf (\"True residual: %g\\n\", err);\n\n\t/* The reduced number of iterations, if the space is augmented. */\n\tif (aug) mred = mit - aug->ntot;\n\n\tfor (i = 0; i < mit && err > tol; ++i) {\n\t\t/* Point to the working space for this iteration. */\n\t\tvp = v + i * nelt;\n\t\thp = h + i * (mit + 1);\n\n\t\t/* Compute the next expansion of the Krylov space. */\n\t\tif (!aug || i < mred) matvec (vp + nelt, vp, mvp, 1);\n\t\telse {\n\t\t\t/* Update with the next augmented vector. */\n\t\t\tazp = aug->az + nelt * \n\t\t\t\t((aug->nmax + aug->start + mred - i) % aug->nmax);\n\t\t\t/* Use the augmented space. */\n\t\t\tmemcpy (vp + nelt, azp, nelt * sizeof(cplx));\n\t\t}\n\n\t\t/* Perform modified Gram-Schmidt to orthogonalize the basis. */\n\t\t/* This also builds the Hessenberg matrix column, including\n\t\t * the 2-norm of the next basis vector. */\n\t\tcmgs (vp + nelt, hp, v, nelt, i + 1);\n\n\t\t/* Watch for breakdown. */\n\t\tif (cabs(hp[i + 1]) < REAL_EPSILON) {\n\t\t\t++i;\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Apply previous Givens rotations to the Hessenberg column. */\n\t\tfor (j = 0; j < i; ++j)\n\t\t\tROT (&one, hp + j, &one, hp + j + 1, &one, c + j, s + j);\n\n\t\t/* Compute the Givens rotation for the current iteration. */\n\t\tLARTG (hp + i, hp + i + 1, c + i, s + i, &cr);\n\t\t/* Apply the current Givens rotation to the Hessenberg column. */\n\t\thp[i] = cr;\n\t\thp[i + 1] = 0;\n\t\t/* Perform the rotation on the vector beta. */\n\t\tROT (&one, beta + i, &one, beta + i + 1, &one, c + i, s + i);\n\n\t\t/* Estimate the RRE for this iteration. */\n\t\terr = cabs(beta[i + 1]) / rhn;\n\t\tif (!rank && !quiet) printf (\"GMRES(%d): %g\\n\", i, err);\n\n\t\t/* Flush the output buffers. */\n\t\tfflush (stdout);\n\t\tfflush (stderr);\n\t}\n\n\t/* If there were any GMRES iterations, update the solution. */\n\tif (i > 0 && aug) {\n\t\t/* Compute the optimum solution in the Krylov basis. */\n\t\tcplx *ys;\n\t\tys = malloc(i * sizeof(cplx));\n\t\tmemcpy (ys, beta, i * sizeof(cplx));\n\t\tTRSV (CblasColMajor, CblasUpper, CblasNoTrans,\n\t\t\t\tCblasNonUnit, i, h, mit + 1, ys, 1);\n\n\t\t/* Compute the next Krylov vector in the augmented space. */\n\t\taug->start = (aug->start + 1) % aug->nmax;\n\t\tif (aug->ntot < aug->nmax) ++(aug->ntot);\n\t\tazp = aug->az + nelt * aug->start;\n\n\t\tbeta[i] = 0;\n\t\tfor (j = i - 1; j >= 0; --j) {\n\t\t\t/* Invert the Givens rotations. */\n\t\t\ts[j] = -s[j];\n\t\t\tROT (&one, beta + j, &one, beta + j + 1, &one, c + j, s + j);\n\t\t}\n\t\tGEMV (CblasColMajor, CblasNoTrans, nelt, i + 1,\n\t\t\t\t&cone, v, nelt, beta, 1, &czero, azp, 1);\n\n\t\t/* Overwrite the Krylov subspace with the augmented subspace.\n\t\t * The start pointer has already been incremented! */\n\t\tfor (j = mred; j < i; ++j) {\n\t\t\tzp = aug->z + nelt * \n\t\t\t\t((aug->nmax + aug->start + mred - j - 1) % aug->nmax);\n\t\t\tmemcpy(v + j * nelt, zp, nelt * sizeof(cplx));\n\t\t}\n\n\t\t/* Compute the solution update. */\n\t\tzp = aug->z + nelt * aug->start;\n\t\tGEMV (CblasColMajor, CblasNoTrans, nelt, i,\n\t\t\t\t&cone, v, nelt, ys, 1, &czero, zp, 1);\n\t\tfor (j = 0; j < nelt; ++j) sol[j] += zp[j];\n\n\t\tfree(ys);\n\t} else if (i > 0) {\n\t\t/* Compute the minimizer of the least-squares problem. */\n\t\tTRSV (CblasColMajor, CblasUpper, CblasNoTrans,\n\t\t\t\tCblasNonUnit, i, h, mit + 1, beta, 1);\n\n\t\t/* Compute the solution update in place. */\n\t\tGEMV (CblasColMajor, CblasNoTrans, nelt, i,\n\t\t\t\t&cone, v, nelt, beta, 1, &cone, sol, 1);\n\t}\n\n\tfree (v);\n\tfree (c);\n\n\treturn i;\n}\n\nint bicgstab (cplx *rhs, cplx *sol,\n\t\tint guess, int mit, real tol, int quiet) {\n\tlong j, nelt = (long)fmaconf.numbases * (long)fmaconf.bspboxvol;\n\tint i, rank;\n\tcplx *r, *rhat, *v, *p, *mvp, *t;\n\tcplx rho, alpha, omega, beta;\n\treal err, rhn;\n\n\tMPI_Comm_rank (MPI_COMM_WORLD, &rank);\n\n\trho = alpha = omega = 1.;\n\n\t/* Allocate and zero the work arrays. */\n\tr = calloc (6L * nelt, sizeof(cplx));\n\trhat = r + nelt;\n\tv = rhat + nelt;\n\tp = v + nelt;\n\tt = p + nelt;\n\tmvp = t + nelt;\n\n\t/* Compute the norm of the right-hand side for residual scaling. */\n\trhn = parnorm(rhs, nelt);\n\n\t/* Compute the inital matrix-vector product for the input guess. */\n\tif (guess) matvec (r, sol, mvp, 1);\n\n\t/* Subtract from the RHS to form the residual. */\n#pragma omp parallel for default(shared) private(j)\n\tfor (j = 0; j < nelt; ++j) r[j] = rhs[j] - r[j];\n\n\tif (!guess) memset (sol, 0, nelt * sizeof(cplx));\n\n\t/* Copy the initial residual as the test vector. */\n\tmemcpy (rhat, r, nelt * sizeof(cplx));\n\n\t/* Find the norm of the initial residual. */\n\terr = parnorm(r, nelt) / rhn;\n\tif (!rank && !quiet) printf (\"True residual: %g\\n\", err);\n\n\t/* Run iterations until convergence or the maximum is reached. */\n\tfor (i = 0; i < mit && err > tol; ++i) {\n\t\t/* Pre-compute portion of beta from previous iteration. */\n\t\tbeta = alpha / (rho * omega);\n\t\t/* Compute rho for this iteration. */\n\t\trho = pardot (rhat, r, nelt);\n\t\t/* Include the missing factor in beta. */\n\t\tbeta *= rho;\n\n\t\t/* Update the search vector. */\n#pragma omp parallel for default(shared) private(j)\n\t\tfor (j = 0; j < nelt; ++j)\n\t\t\tp[j] = r[j] + beta * (p[j] - omega * v[j]);\n\n\t\t/* Compute the first search step, v = A * p. */\n\t\tmatvec (v, p, mvp, 1);\n\n\t\t/* Compute the next alpha. */\n\t\talpha = rho / pardot (rhat, v, nelt);\n\n#pragma omp parallel for default(shared) private(j)\n\t\tfor (j = 0; j < nelt; ++j) {\n\t\t\t/* Update the solution vector. */\n\t\t\tsol[j] += alpha * p[j];\n\t\t\t/* Update the residual vector. */\n\t\t\tr[j] -= alpha * v[j];\n\t\t}\n\n\t\t/* Compute the scaled residual norm and stop if convergence\n\t\t * has been achieved. */\n\t\terr = parnorm(r, nelt) / rhn;\n\t\tif (!rank && !quiet) printf (\"BiCG-STAB(%0.1f): %g\\n\", 0.5 + i, err);\n\n\t\t/* Flush the output buffers. */\n\t\tfflush (stdout);\n\t\tfflush (stderr);\n\n\t\tif (err < tol) break;\n\n\t\t/* Compute the next search step, t = A * r. */\n\t\tmatvec (t, r, mvp, 1);\n\n\t\t/* Compute the update direction. */\n\t\tomega = pardot (t, r, nelt) / pardot (t, t, nelt);\n\n\t\t/* Update both the residual and the solution guess. */\n#pragma omp parallel for default(shared) private(j)\n\t\tfor (j = 0; j < nelt; ++j) {\n\t\t\t/* Update the solution vector. */\n\t\t\tsol[j] += omega * r[j];\n\t\t\t/* Update the residual vector. */\n\t\t\tr[j] -= omega * t[j];\n\t\t}\n\n\t\t/* Compute the scaled residual norm. */\n\t\terr = parnorm(r, nelt) / rhn;\n\t\tif (!rank && !quiet) printf (\"BiCG-STAB(%d): %g\\n\", i + 1, err);\n\n\t\tfflush (stdout);\n\t\tfflush (stderr);\n\t}\n\n\tfree (r);\n\treturn i;\n}\n", "meta": {"hexsha": "476e08b91b87054306ecabab03f77cc218111aa7", "size": 8924, "ext": "c", "lang": "C", "max_stars_repo_path": "itsolver.c", "max_stars_repo_name": "ahesford/afma", "max_stars_repo_head_hexsha": "4cce650b07341234402096dea3c8ab04deb7375f", "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": "itsolver.c", "max_issues_repo_name": "ahesford/afma", "max_issues_repo_head_hexsha": "4cce650b07341234402096dea3c8ab04deb7375f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "itsolver.c", "max_forks_repo_name": "ahesford/afma", "max_forks_repo_head_hexsha": "4cce650b07341234402096dea3c8ab04deb7375f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-12T17:29:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-08T10:23:36.000Z", "avg_line_length": 29.2590163934, "max_line_length": 72, "alphanum_fraction": 0.6019722098, "num_tokens": 3064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3625895657385554}}
{"text": "#ifndef TETRA_DOS_ELHAMILTONIAN_H\n#define TETRA_DOS_ELHAMILTONIAN_H\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_sf_trig.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include \"environment.h\"\n\nvoid ElHamiltonian_Recip(Environment *env, double k[3], gsl_matrix_complex *H);\n\nvoid ElHamiltonian(Environment *env, double k[3], gsl_matrix_complex *H);\n\ngsl_complex EpsilonAE(Environment *env, double k[3]);\n\ngsl_complex EpsilonBE(Environment *env, double k[3]);\n\ngsl_complex EpsilonAO(Environment *env, double k[3]);\n\ngsl_complex EpsilonBO(Environment *env, double k[3]);\n\n#endif // TETRA_DOS_ELHAMILTONIAN_H\n", "meta": {"hexsha": "eeae60fd78a29af10873c7151eae0d22acc02905", "size": 681, "ext": "h", "lang": "C", "max_stars_repo_path": "tetra_dos/elHamiltonian.h", "max_stars_repo_name": "tflovorn/vo2mft", "max_stars_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tetra_dos/elHamiltonian.h", "max_issues_repo_name": "tflovorn/vo2mft", "max_issues_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tetra_dos/elHamiltonian.h", "max_forks_repo_name": "tflovorn/vo2mft", "max_forks_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T15:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T15:11:23.000Z", "avg_line_length": 27.24, "max_line_length": 79, "alphanum_fraction": 0.7826725404, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.36258956573855533}}
{"text": "#include \"cimple_c_from_py.h\"\n#include \"setoper.h\"\n#include \"cimple_safe_mode.h\"\n#include <cdd.h>\n#include <gsl/gsl_matrix.h>\n\nint main(){\n\n    dd_set_global_constants();\n    // Initialize state:\n    system_dynamics *s_dyn;\n    cost_function *f_cost;\n    discrete_dynamics *d_dyn;\n    current_state *now;\n\n    system_alloc(&now, &s_dyn, &f_cost, &d_dyn);\n    system_init(now, s_dyn, f_cost, d_dyn);\n\n\n\n    double sec = 2;\n    ACT(4, now, d_dyn, s_dyn, f_cost, sec);\n\n    system_dynamics_free(s_dyn);\n    discrete_dynamics_free(d_dyn);\n    cost_function_free(f_cost);\n    state_free(now);\n\n    dd_free_global_constants();\n    return 0;\n}\n", "meta": {"hexsha": "a36ee23d21f24624ad69b645c097855057c4836c", "size": 637, "ext": "c", "lang": "C", "max_stars_repo_path": "Interface/Cimple/main.c", "max_stars_repo_name": "shaesaert/TuLiPXML", "max_stars_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T23:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T23:44:28.000Z", "max_issues_repo_path": "Interface/Cimple/main.c", "max_issues_repo_name": "shaesaert/TuLiPXML", "max_issues_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-10-03T18:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-21T09:50:09.000Z", "max_forks_repo_path": "Interface/Cimple/main.c", "max_forks_repo_name": "shaesaert/TuLiPXML", "max_forks_repo_head_hexsha": "56cf4d58a9d7e17b6f6aebe6de8d5a1231035671", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-06T12:58:52.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-06T12:58:52.000Z", "avg_line_length": 19.90625, "max_line_length": 48, "alphanum_fraction": 0.6813186813, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.36254290850033105}}
{"text": "/* TwoAdvSelfSims.c \n\nSimulation calculating fixation probability of second beneficial allele, given existing\nben allele at initial frequency p. For use in the study \"Linkage and the limits to natural\nselection in partially selfing populations\".\n\nSimulation uses routines found with the GNU Scientific Library (GSL)\n(http://www.gnu.org/software/gsl/)\nSince GSL is distributed under the GNU General Public License \n(http://www.gnu.org/copyleft/gpl.html), you must download it \nseparately from this file.\n\nThis program can be compiled with e.g. GCC using a command like:\ngcc TwoAdvSelfSims -lm -lgsl -lgslcblas -I/usr/local/include -L/usr/local/lib TwoAdvSelfSims.c\n\nThen run by executing:\n./TwoAdvSelfSims N self rec ha sa hb sb p reps\nWhere:\n- N is the population size\n- self is the rate of self-fertilisation\n- rec is recombination rate\n- ha, hb is dominance at the original, introduced beneficial allele\n- sa, sb is selection coefficient of the original, introduced beneficial allele\n- p is the initial frequency of the first beneficial allele (when the second is introduced)\n- reps is how many times the second allele should FIX before simulation stops \n(the number of actual runs is greater due to stochastic loss of second allele)\n\nNote that haplotypes are defined as:\nx1 = ab\nx2 = Ab\nx3 = aB\nx4 = AB\n\nGenotypes defined as:\ng11 = g1 = ab/ab\ng12 = g2 = Ab/ab\ng13 = g3 = aB/ab\ng14 = g4 = AB/ab\ng22 = g5 = Ab/Ab\ng23 = g6 = Ab/aB\ng24 = g7 = Ab/AB\ng33 = g8 = aB/aB\ng34 = g9 = aB/AB\ng44 = g10 = AB/AB\n\nOutput files are the parameters;\nfollowed by number of times each haplotype fixed;\nfollowed by average total generations elapsed in each case;\nThen total number of simulations ran;\nThen fixation prob of allele, both unscaled and scaled to unlinked case, \nalong with 95% CI intervals for the latter case;\nthen number of allele fixations.\n\nNote that 'fixation' DIFFERS depending on the inputs of sa, sb.\nIf sa >= sb (interference case) then 'fixation' counts as fixation of second allele on any genetic background.\nIf sa < sb (replacement case) then 'fixation' only considers fixation of second allele with neutral haplotype\n(I.e. where the 'less fit' neutral allele at locus A fixes, instead of selected allele).\n\n*/\n\n/* Preprocessor statements */\n#include <stdio.h>\n#include <time.h>\n#include <math.h>\n#include <stddef.h>\n#include <string.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_cdf.h>\n\n/* Function prototypes */\nvoid geninit(double *geninit, double FIS, const gsl_rng *r);\nvoid selection(double *geninit);\nvoid reproduction(double *geninit);\nunsigned int hcheck(double *geninit, double *haps, unsigned int *hf, unsigned int stype);\n\n/* Global variable declaration */\nunsigned int N = 0;\t\t/* Pop size */\ndouble rec = 0;\t\t\t/* Recombination rate */\ndouble self = 0;\t\t/* Rate of self-fertilisation */\ndouble ha = 0;\t\t\t/* Dominance of site A */\ndouble sa = 0;\t\t\t/* Fitness of site A */\ndouble hb = 0;\t\t\t/* Dominance of site B */\ndouble sb = 0;\t\t\t/* Fitness of site B */\ndouble pee = 0;\t\t\t/* Freq of initial sweep */\n\n/* Main program */\nint main(int argc, char *argv[]){\n\tunsigned int i; \t\t\t\t/* A counter */\n\tunsigned int reps;\t\t\t\t/* Length of simulation (no. of introductions of neutral site) */\n\tunsigned int stype = 0;\t\t\t/* What type of sim (replacement or hitch-hiking)? */\n\tunsigned int nsfix = 0;\t\t\t/* sims where target type fixed */\n\tunsigned int nstot = 0;\t\t\t/* total sims ran */\t\n\tunsigned int gens = 0;\t\t\t/* Number gens elapsed */\n\tunsigned int isfin = 0;\t\t\t/* Is sim finished? */\n\tunsigned int hf = 0;\t\t\t/* The hap that fixed */\n\tdouble pf = 0;\t\t\t\t\t/* Overall fix prob */\n\tdouble FIS = 0;\t\t\t\t\t/* Wright's FIS */\n\tdouble StdFix = 0;\t\t\t\t/* Standard Fixation prob if unlinked */\n\tdouble citop = 0;\n\tdouble cibot = 0;\n\tdouble nsfix2 = 0;\t\t\t\n\tdouble nstot2 = 0;\t\t\t\n\tchar selfchar[10];\n\tchar recchar[15];\n\tchar hchar[10];\n\tchar pchar[10];\n\tchar fname[64];\n\tFILE *ofp_tr;\n\t\n\t/* GSL random number definitions */\n\tconst gsl_rng_type * T; \n\tgsl_rng * r;\n\t\n\t/* This reads in data from command line. */\n\tif(argc != 10){\n\t\tfprintf(stderr,\"Invalid number of input values.\\n\");\n\t\texit(1);\n\t}\n\tN = strtod(argv[1],NULL);\n\tself = strtod(argv[2],NULL);\n\trec = strtod(argv[3],NULL);\n\tha = strtod(argv[4],NULL);\n\tsa = strtod(argv[5],NULL);\n\thb = strtod(argv[6],NULL);\n\tsb = strtod(argv[7],NULL);\n\tpee = strtod(argv[8],NULL);\n\treps = strtod(argv[9],NULL);\n\t\n\tif(sa >= sb){\n\t\tstype = 0;\n\t}else if(sa < sb){\n\t\tstype = 1;\n\t}\n\tFIS = self/(2.0-self);\n\t\n\t/* Arrays definition and memory assignment */\n\tdouble *genotype = calloc(10,sizeof(double));\t\t\t\t/* Genotype frequencies */\n\tunsigned int *gensamp = calloc(10,sizeof(unsigned int));\t/* New population samples */\n\tdouble *haps = calloc(4,sizeof(double));\t\t\t\t\t/* Haplotypes */\n\tunsigned int *pfix = calloc(4,sizeof(unsigned int));\t\t/* Haplotypes that fix */\n\tunsigned int *tfix = calloc(4,sizeof(unsigned int));\t\t/* time that haps fix */\n\t  \n\t/* create a generator chosen by the \n    environment variable GSL_RNG_TYPE */\n     \n\tgsl_rng_env_setup();\n\tif (!getenv(\"GSL_RNG_SEED\")) gsl_rng_default_seed = time(0);\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc(T);\n\t\n\tnsfix = 0;\n\tnstot = 0;\n\t\n    while(nsfix < reps){\n    \tnstot++;\n\t\n\t\t/* Initialising genotypes */\n\t\tgeninit(genotype,FIS,r);\n\t\tgens = 0;\n\t\tisfin = 0;\n\t\thf = 0;\n\t\t\n\t\twhile(isfin == 0){\n    \t\t/* Selection routine */\n    \t\tselection(genotype);\n    \t\t\n\t    \t/* Reproduction routine */\n    \t\treproduction(genotype);\n       \t\t\n    \t\t/* Sampling based on new frequencies */\n\t       \tgsl_ran_multinomial(r,10,N,genotype,gensamp);\n       \t\tfor(i = 0; i < 10; i++){\n    \t   \t\t*(genotype + i) = (*(gensamp + i))/(1.0*N);\n\t       \t}\n\t       \t\n\t       \tgens++;\n\t       \tisfin = hcheck(genotype, haps, &hf, stype);\n       \t}\n       \t\n       \tif(isfin == 1){\n       \t\t(*(pfix + hf))++;\n    \t  \t(*(tfix + hf)) += gens;\n\t       \tif(stype == 0){\n       \t\t\tnsfix += (*(haps + 2) + *(haps + 3));\n       \t\t}else if(stype == 1){\n    \t   \t\tnsfix += (*(haps + 2));\n\t       \t}\n       \t}\n    \n\t}\t/* End of simulation */\n\t\n\tpf = nsfix/(1.0*nstot);\n\tStdFix = 2*sb*((hb+FIS-hb*FIS)/(1+FIS));\t\t/* Fix prob of new allele if unlinked */\n\t\n\tnstot2 = nstot + 3.84;\n\tnsfix2 = (1.0/(nstot2))*(nsfix + (3.84/2.0));\n\tcitop = nsfix2 + 1.96*sqrt((1.0/(nstot2))*nsfix2*(1.0-nsfix2));\n\tcibot = nsfix2 - 1.96*sqrt((1.0/(nstot2))*nsfix2*(1.0-nsfix2));\t\n\tcitop = citop/(1.0*StdFix);\n\tcibot = cibot/(1.0*StdFix);\t\n\t\n\t/* Printing solutions to file */\n\t/* First, converting values to strings */\n    sprintf(selfchar, \"%0.2lf\",self);\n    sprintf(recchar, \"%0.7lf\",rec);\n    sprintf(hchar, \"%0.3lf\",ha);\n    sprintf(pchar, \"%0.5lf\",pee);            \n\n\tstrcpy(fname,\"sim_self\");\n\tstrcat(fname,selfchar);\n\tstrcat(fname,\"rec\");\n\tstrcat(fname,recchar);\n\tstrcat(fname,\"h\");\n\tstrcat(fname,hchar);\n\tstrcat(fname,\"p\");\n\tstrcat(fname,pchar);\n\tstrcat(fname,\".sim\");\n\t\n\tofp_tr = fopen(fname,\"a+\");\n\tfprintf(ofp_tr,\"%d %lf %lf %lf %lf %lf %lf %lf \",N,self,rec,ha,sa,hb,sb,pee);\n\tfor(i = 0; i < 4; i++){\n\t\tfprintf(ofp_tr,\"%d \",*(pfix + i));\n\t}\n\tfor(i = 0; i < 4; i++){\n\t\tfprintf(ofp_tr,\"%lf \",((*(tfix + i)))/(1.0*(*(pfix + i))));\n\t}\n\tfprintf(ofp_tr,\"%d %lf %lf %lf %lf %d\\n\",nstot,pf,pf/(1.0*StdFix),citop,cibot,reps);\n\tfclose(ofp_tr);\t\n\t\n\t/* Freeing memory and wrapping up */\n \tgsl_rng_free(r);\n \tfree(tfix);\n \tfree(pfix);\n \tfree(haps);\n \tfree(gensamp);\n\tfree(genotype);\n\treturn 0;\n}\n\n/* Initialising genotypes */\nvoid geninit(double *geninit, double FIS, const gsl_rng *r){\n\n\tunsigned int htype = 0;\t\t/* Type of het assignment */\n\t\n\tdouble *ptype = calloc(3,sizeof(double));\n\tunsigned int *ctype = calloc(3,sizeof(double));\t\n\t\t\n\t/* Routine to determine initial background of second mutant, given first is at frequency p. */\n\t*(ptype + 0) = (1-pee)*(1-pee) + FIS*pee*(1-pee);\n\t*(ptype + 1) = 2*pee*(1-pee)*(1-FIS);\n\t*(ptype + 2) = pee*pee + FIS*pee*(1-pee);\n\t\n\t/* First initialise baseline freqs */\n\t*(geninit + 0) = *(ptype + 0);\n\t*(geninit + 1) = *(ptype + 1);\n\t*(geninit + 2) = 0;\n\t*(geninit + 3) = 0;\n\t*(geninit + 4) = *(ptype + 2);\n\t*(geninit + 5) = 0;\n\t*(geninit + 6) = 0;\n\t*(geninit + 7) = 0;\n\t*(geninit + 8) = 0;\n\t*(geninit + 9) = 0;\n\t\n\t/* Then decide where to add new mutant */\n\tgsl_ran_multinomial(r,3,1,ptype,ctype);\n\tif(*(ctype + 0) == 1){\n\t\t*(geninit + 0) -= 1/(1.0*N);\n\t\t*(geninit + 2) += 1/(1.0*N);\n\t}else if(*(ctype + 1) == 1){\n\t\t*(geninit + 1) -= 1/(1.0*N);\n\t  \thtype = gsl_ran_bernoulli(r,0.5);\n\t  \tif(htype == 0){\n\t  \t\t*(geninit + 5) += 1/(1.0*N);\n\t  \t}else if(htype == 1){\n\t  \t\t*(geninit + 3) += 1/(1.0*N);\n\t  \t}\n\t}else if(*(ctype + 2) == 1){\n\t\t*(geninit + 4) -= 1/(1.0*N);\n\t\t*(geninit + 6) += 1/(1.0*N);\n\t}\n\t\n\tfree(ctype);\n\tfree(ptype);\n\n}\t/* End of gen initiation routine */\n\n/* Selection routine */\nvoid selection(double *geninit){\n\t/* Fitness of each genotype */\n\tdouble W11, W12, W13, W14, W22, W23, W24, W33, W34, W44;\t\t\n\tdouble Wmean;\t\t\t\t/* Mean fitness */\n\t\n\tW11 = 1;\n\tW12 = 1 + ha*sa;\n\tW13 = 1 + hb*sb;\n\tW14 = 1 + ha*sa + hb*sb;\n\tW22 = 1 + sa;\n\tW23 = 1 + ha*sa + hb*sb;\n\tW24 = 1 + sa + hb*sb;\n\tW33 = 1 + sb;\n\tW34 = 1 + ha*sa + sb;\n\tW44 = 1 + sa + sb;\n\t\n\t/* Mean fitness calculation */\n\tWmean = ((*(geninit + 0))*W11) + ((*(geninit + 1))*W12) + ((*(geninit + 2))*W13) + ((*(geninit + 3))*W14) + ((*(geninit + 4))*W22) + ((*(geninit + 5))*W23) + ((*(geninit + 6))*W24) + ((*(geninit + 7))*W33) + ((*(geninit + 8))*W34) + ((*(geninit + 9))*W44);\n\t\n\t/* Changing frequencies by selection */\n\t*(geninit + 0) = ((*(geninit + 0))*W11)/Wmean;\n\t*(geninit + 1) = ((*(geninit + 1))*W12)/Wmean;\n\t*(geninit + 2) = ((*(geninit + 2))*W13)/Wmean;\n\t*(geninit + 3) = ((*(geninit + 3))*W14)/Wmean;\n\t*(geninit + 4) = ((*(geninit + 4))*W22)/Wmean;\n\t*(geninit + 5) = ((*(geninit + 5))*W23)/Wmean;\n\t*(geninit + 6) = ((*(geninit + 6))*W24)/Wmean;\n\t*(geninit + 7) = ((*(geninit + 7))*W33)/Wmean;\n\t*(geninit + 8) = ((*(geninit + 8))*W34)/Wmean;\n\t*(geninit + 9) = ((*(geninit + 9))*W44)/Wmean;\n\t\n}\t/* End of selection routine */\n\n/* Reproduction routine */\nvoid reproduction(double *geninit){\n\t/* Fed-in genotype frequencies (for ease of programming) */\n\tdouble g11s, g12s, g13s, g14s, g22s, g23s, g24s, g33s, g34s, g44s;\n\t/* Haplotypes */\n\tdouble x1, x2, x3, x4;\n\t\n\t/* Initial definition of genotypes */\n\tg11s = *(geninit + 0);\n\tg12s = *(geninit + 1);\n\tg13s = *(geninit + 2);\n\tg14s = *(geninit + 3);\n\tg22s = *(geninit + 4);\n\tg23s = *(geninit + 5);\n\tg24s = *(geninit + 6);\n\tg33s = *(geninit + 7);\n\tg34s = *(geninit + 8);\n\tg44s = *(geninit + 9);\n\t\n\t/* Baseline change in haplotype frequencies */\n\tx1 = g11s + (g12s + g13s + g14s)/2.0 - ((g14s - g23s)*rec)/2.0;\n\tx2 = g22s + (g12s + g23s + g24s)/2.0 + ((g14s - g23s)*rec)/2.0;\n\tx3 = g33s + (g13s + g23s + g34s)/2.0 + ((g14s - g23s)*rec)/2.0;\n\tx4 = g44s + (g14s + g24s + g34s)/2.0 - ((g14s - g23s)*rec)/2.0;\n\t\n\t/* Change in SEXUAL frequencies (both outcrossing and selfing) */\n\t*(geninit + 0) = (g11s + (g12s + g13s + g14s*pow((1 - rec),2) + g23s*pow(rec,2))/4.0)*self + (1 - self)*pow(x1,2);\n\t*(geninit + 4) = (g22s + (g12s + g24s + g23s*pow((1 - rec),2) + g14s*pow(rec,2))/4.0)*self + (1 - self)*pow(x2,2);\n\t*(geninit + 7) = (g33s + (g13s + g34s + g23s*pow((1 - rec),2) + g14s*pow(rec,2))/4.0)*self + (1 - self)*pow(x3,2);\n\t*(geninit + 9) = (g44s + (g24s + g34s + g14s*pow((1 - rec),2) + g23s*pow(rec,2))/4.0)*self + (1 - self)*pow(x4,2);\n\t*(geninit + 1) = ((g12s + (g14s + g23s)*(1 - rec)*rec)*self)/2.0 + 2.0*(1 - self)*x1*x2;\n\t*(geninit + 2) = ((g13s + (g14s + g23s)*(1 - rec)*rec)*self)/2.0 + 2.0*(1 - self)*x1*x3;\n\t*(geninit + 3) = ((g14s*pow((1 - rec),2) + g23s*pow(rec,2))*self)/2.0 + 2.0*(1 - self)*x1*x4;\n\t*(geninit + 5) = ((g23s*pow((1 - rec),2) + g14s*pow(rec,2))*self)/2.0 + 2.0*(1 - self)*x2*x3;\n\t*(geninit + 6) = ((g24s + (g14s + g23s)*(1 - rec)*rec)*self)/2.0 + 2.0*(1 - self)*x2*x4;\n\t*(geninit + 8) = ((g34s + (g14s + g23s)*(1 - rec)*rec)*self)/2.0 + 2.0*(1 - self)*x3*x4;\n\t\t\n}\t/* End of reproduction routine */\n\n/* Has any allele fixed or not? */\nunsigned int hcheck(double *geninit, double *haps, unsigned int *hf, unsigned int stype){\n\t/* Fed-in genotype frequencies (for ease of programming) */\n\tdouble g11s, g12s, g13s, g14s, g22s, g23s, g24s, g33s, g34s, g44s;\n\tunsigned int retval = 0;\n\t\n\t/* Initial definition of genotypes */\n\tg11s = *(geninit + 0);\n\tg12s = *(geninit + 1);\n\tg13s = *(geninit + 2);\n\tg14s = *(geninit + 3);\n\tg22s = *(geninit + 4);\n\tg23s = *(geninit + 5);\n\tg24s = *(geninit + 6);\n\tg33s = *(geninit + 7);\n\tg34s = *(geninit + 8);\n\tg44s = *(geninit + 9);\n\t\n\t/* Calculation of haplotypes */\n\t*(haps + 0) = g11s + (g12s + g13s + g14s)/2.0;\n\t*(haps + 1) = g22s + (g12s + g23s + g24s)/2.0;\n\t*(haps + 2) = g33s + (g13s + g23s + g34s)/2.0;\n\t*(haps + 3) = g44s + (g14s + g24s + g34s)/2.0;\n\t\n/* \tprintf(\"Haps are %lf %lf %lf %lf\\n\",*(haps + 0),*(haps + 1),*(haps + 2),*(haps + 3));*/\n\t\n\tif(*(haps + 0) == 1){\n\t\tretval = 1;\n\t\t*hf = 0;\n\t}\n\telse if(*(haps + 1) == 1){\n\t\tretval = 1;\n\t\t*hf = 1;\n\t}\n\telse if(*(haps + 2) == 1){\n\t\tretval = 1;\n\t\t*hf = 2;\n\t}\n\telse if(*(haps + 3) == 1){\n\t\tretval = 1;\n\t\t*hf = 3;\n\t}else if(stype == 1){\n\t\tif( (*(haps + 2) + *(haps + 3) ) == 0 ){\n\t\t\tretval = 2;\n\t\t\t*hf = 0;\n\t\t}\n\t}\n\t\n\treturn retval;\n\t\t\n}\t/* End of hap check routine */\n\n/* End of program */\n", "meta": {"hexsha": "58ed7233be4ed49ebeea5acae795ffc76b29980b", "size": 13117, "ext": "c", "lang": "C", "max_stars_repo_path": "TwoAdvSelfSims.c", "max_stars_repo_name": "MattHartfield/TwoAdvSelfSims", "max_stars_repo_head_hexsha": "afb4d3aeba05bad8ae1440213d998d1d4e5a4daf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TwoAdvSelfSims.c", "max_issues_repo_name": "MattHartfield/TwoAdvSelfSims", "max_issues_repo_head_hexsha": "afb4d3aeba05bad8ae1440213d998d1d4e5a4daf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TwoAdvSelfSims.c", "max_forks_repo_name": "MattHartfield/TwoAdvSelfSims", "max_forks_repo_head_hexsha": "afb4d3aeba05bad8ae1440213d998d1d4e5a4daf", "max_forks_repo_licenses": ["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.6072289157, "max_line_length": 257, "alphanum_fraction": 0.5954867729, "num_tokens": 4812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3625106226342994}}
{"text": "/**\n *\n * @file testing_zgemm.c\n *\n *  PLASMA testing routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Emmanuel Agullo\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @precisions normal z -> c d s\n *\n **/\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#include <plasma.h>\n#include <cblas.h>\n#include <lapacke.h>\n#include <core_blas.h>\n#include \"testing_zmain.h\"\n\n#undef REAL\n#define COMPLEX\n\nstatic int check_solution(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K,\n                          PLASMA_Complex64_t alpha, PLASMA_Complex64_t *A, int LDA,\n                          PLASMA_Complex64_t *B, int LDB,\n                          PLASMA_Complex64_t beta, PLASMA_Complex64_t *Cref, PLASMA_Complex64_t *Cplasma, int LDC);\n\nint testing_zgemm(int argc, char **argv)\n{\n    /* Check for number of arguments*/\n    if ( argc != 8) {\n        USAGE(\"GEMM\", \"alpha beta M N K LDA LDB LDC\",\n              \"   - alpha  : alpha coefficient\\n\"\n              \"   - beta   : beta coefficient\\n\"\n              \"   - M      : number of rows of matrices A and C\\n\"\n              \"   - N      : number of columns of matrices B and C\\n\"\n              \"   - K      : number of columns of matrix A / number of rows of matrix B\\n\"\n              \"   - LDA    : leading dimension of matrix A\\n\"\n              \"   - LDB    : leading dimension of matrix B\\n\"\n              \"   - LDC    : leading dimension of matrix C\\n\");\n        return -1;\n    }\n\n    PLASMA_Complex64_t alpha = (PLASMA_Complex64_t) atol(argv[0]);\n    PLASMA_Complex64_t beta = (PLASMA_Complex64_t) atol(argv[1]);\n    int M     = atoi(argv[2]);\n    int N     = atoi(argv[3]);\n    int K     = atoi(argv[4]);\n    int LDA   = atoi(argv[5]);\n    int LDB   = atoi(argv[6]);\n    int LDC   = atoi(argv[7]);\n\n    double eps;\n    int info_solution;\n    int i, j, ta, tb;\n    int LDAxK = LDA*max(M,K);\n    int LDBxN = LDB*max(K,N);\n    int LDCxN = LDC*N;\n\n    PLASMA_Complex64_t *A      = (PLASMA_Complex64_t *)malloc(LDAxK*sizeof(PLASMA_Complex64_t));\n    PLASMA_Complex64_t *B      = (PLASMA_Complex64_t *)malloc(LDBxN*sizeof(PLASMA_Complex64_t));\n    PLASMA_Complex64_t *C      = (PLASMA_Complex64_t *)malloc(LDCxN*sizeof(PLASMA_Complex64_t));\n    PLASMA_Complex64_t *Cinit  = (PLASMA_Complex64_t *)malloc(LDCxN*sizeof(PLASMA_Complex64_t));\n    PLASMA_Complex64_t *Cfinal = (PLASMA_Complex64_t *)malloc(LDCxN*sizeof(PLASMA_Complex64_t));\n\n    /* Check if unable to allocate memory */\n    if ((!A)||(!B)||(!Cinit)||(!Cfinal)){\n        printf(\"Out of Memory \\n \");\n        return -2;\n    }\n\n    eps = LAPACKE_dlamch_work('e');\n\n    printf(\"\\n\");\n    printf(\"------ TESTS FOR PLASMA ZGEMM ROUTINE -------  \\n\");\n    printf(\"            Size of the Matrix %d by %d\\n\", M, N);\n    printf(\"\\n\");\n    printf(\" The matrix A is randomly generated for each test.\\n\");\n    printf(\"============\\n\");\n    printf(\" The relative machine precision (eps) is to be %e \\n\",eps);\n    printf(\" Computational tests pass if scaled residuals are less than 10.\\n\");\n\n    /*----------------------------------------------------------\n     *  TESTING ZGEMM\n     */\n\n    /* Initialize A, B, C */\n    LAPACKE_zlarnv_work(IONE, ISEED, LDAxK, A);\n    LAPACKE_zlarnv_work(IONE, ISEED, LDBxN, B);\n    LAPACKE_zlarnv_work(IONE, ISEED, LDCxN, C);\n\n#ifdef COMPLEX\n    for (ta=0; ta<3; ta++) {\n        for (tb=0; tb<3; tb++) {\n#else\n    for (ta=0; ta<2; ta++) {\n        for (tb=0; tb<2; tb++) {\n#endif\n            for ( i = 0; i < M; i++)\n                for (  j = 0; j < N; j++)\n                    Cinit[LDC*j+i] = C[LDC*j+i];\n            for ( i = 0; i < M; i++)\n                for (  j = 0; j < N; j++)\n                    Cfinal[LDC*j+i] = C[LDC*j+i];\n\n            /* PLASMA ZGEMM */\n            PLASMA_zgemm(trans[ta], trans[tb], M, N, K, alpha, A, LDA, B, LDB, beta, Cfinal, LDC);\n\n            /* Check the solution */\n            info_solution = check_solution(trans[ta], trans[tb], M, N, K, \n                                           alpha, A, LDA, B, LDB, beta, Cinit, Cfinal, LDC);\n\n            if (info_solution == 0) {\n                printf(\"***************************************************\\n\");\n                printf(\" ---- TESTING ZGEMM (%s, %s) ............... PASSED !\\n\", transstr[ta], transstr[tb]);\n                printf(\"***************************************************\\n\");\n            }\n            else {\n                printf(\"************************************************\\n\");\n                printf(\" - TESTING ZGEMM (%s, %s) ... FAILED !\\n\", transstr[ta], transstr[tb]);\n                printf(\"************************************************\\n\");\n            }\n        }\n    }\n#ifdef _UNUSED_\n    }}\n#endif\n    free(A); free(B); free(C);\n    free(Cinit); free(Cfinal);\n\n    return 0;\n}\n\n/*--------------------------------------------------------------\n * Check the solution\n */\n\nstatic int check_solution(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K,\n                          PLASMA_Complex64_t alpha, PLASMA_Complex64_t *A, int LDA,\n                          PLASMA_Complex64_t *B, int LDB,\n                          PLASMA_Complex64_t beta, PLASMA_Complex64_t *Cref, PLASMA_Complex64_t *Cplasma, int LDC)\n{\n    int info_solution;\n    double Anorm, Bnorm, Cinitnorm, Cplasmanorm, Clapacknorm, Rnorm, result;\n    double eps;\n    PLASMA_Complex64_t beta_const;\n\n    double *work = (double *)malloc(max(K,max(M, N))* sizeof(double));\n    int Am, An, Bm, Bn;\n\n    beta_const  = -1.0;\n\n    if (transA == PlasmaNoTrans) {\n        Am = M; An = K;\n    } else {\n        Am = K; An = M;\n    }\n    if (transB == PlasmaNoTrans) {\n        Bm = K; Bn = N;\n    } else {\n        Bm = N; Bn = K;\n    }\n\n    Anorm       = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), Am, An, A,       LDA, work);\n    Bnorm       = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), Bm, Bn, B,       LDB, work);\n    Cinitnorm   = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M,  N,  Cref,    LDC, work);\n    Cplasmanorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M,  N,  Cplasma, LDC, work);\n\n    cblas_zgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, \n                CBLAS_SADDR(alpha), A, LDA, B, LDB, CBLAS_SADDR(beta), Cref, LDC);\n\n    Clapacknorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work);\n\n    cblas_zaxpy(LDC * N, CBLAS_SADDR(beta_const), Cplasma, 1, Cref, 1);\n\n    Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work);\n\n    eps = LAPACKE_dlamch_work('e');\n\n    printf(\"Rnorm %e, Anorm %e, Bnorm %e, Cinitnorm %e, Cplasmanorm %e, Clapacknorm %e\\n\", \n           Rnorm, Anorm, Bnorm, Cinitnorm, Cplasmanorm, Clapacknorm);\n\n    result = Rnorm / ((Anorm + Bnorm + Cinitnorm) * N * eps);\n    printf(\"============\\n\");\n    printf(\"Checking the norm of the difference against reference ZGEMM \\n\");\n    printf(\"-- ||Cplasma - Clapack||_oo/((||A||_oo+||B||_oo+||C||_oo).N.eps) = %e \\n\", \n           result);\n\n    if (  isnan(Rnorm) || isinf(Rnorm) || isnan(result) || isinf(result) || (result > 10.0) ) {\n         printf(\"-- The solution is suspicious ! \\n\");\n         info_solution = 1;\n    }\n    else {\n         printf(\"-- The solution is CORRECT ! \\n\");\n         info_solution= 0 ;\n    }\n\n    free(work);\n\n    return info_solution;\n}\n", "meta": {"hexsha": "165503a2b08e2ad8c58a7a263ec370bfa8139723", "size": 7538, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/testing_zgemm.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/testing_zgemm.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/testing_zgemm.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.0669856459, "max_line_length": 115, "alphanum_fraction": 0.5404616609, "num_tokens": 2341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.5, "lm_q1q2_score": 0.36243514403198956}}
{"text": "#ifndef _PARAMETERS_H_\n#define _PARAMETERS_H_\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <cstdlib>\n#include \"../Headers/voxel.h\"\n#include <math.h>\n#include <gsl/gsl_rng.h>\n\nusing namespace std;\n\nclass Parameters{\n//Atributs\n\tpublic:\n\tint it; //Contador\n\tint nt;\t// Nombre de passos total\n   \tint ntout; // Nombre de pasos per l'output\n\tint neq; //Number of equations\n\tfloat dt; // Pas de temps\n\tfloat t;\n\t\n\tstring Dir_Output;\n    string Dir_Input;\n    string NumPar_Dat;\n\t\n\t\n\t\n\t\n\tstring Data_Dat;\n\tstring Init_Cond_Dat;\n   \tint nNodes;\n   \tint nNodes_inh;\n    string Kex_Dat;\n    string Kin_Dat;\n\t\n\tfloat ** Kex; //Coupling matrix for excitatory population\n\tfloat ** Kin; //Coupling matrix for inhibitory population\n\tvoxel * V; //Voxel\n\t\n\t\n\t\n\tofstream fout_data;\n\tofstream fout_init_cond;\n\t\t\n\n        public:\n        Parameters();\n        ~Parameters();\n\t\n\t//M\u00e8todes\n\t\n\tvoid Read_Kex_Dat(void);\n\tvoid Read_Kin_Dat(void);\n\tvoid RefreshDelay(void);\n\tvoid Read_NumPar_Dat(void);\n\t\t\n\t\n\tvoid WriteData();\n\tvoid WriteInitialConditions(int);\n\tvoid openfiles();\n\tvoid closefiles();\n\t\n        //private:\n\n\t\n        \n\n};\n\n#endif\n", "meta": {"hexsha": "dddd2395479b7e1ef657054237c2541972b85fa2", "size": 1142, "ext": "h", "lang": "C", "max_stars_repo_path": "TEST_1/Headers/Parameters.h", "max_stars_repo_name": "dmalagarriga/PLoS_2015_segregation", "max_stars_repo_head_hexsha": "949afedf96945c11ee84b1a6c9842e5257fb5be8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-28T08:49:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-28T08:49:49.000Z", "max_issues_repo_path": "TEST_1/Headers/Parameters.h", "max_issues_repo_name": "dmalagarriga/PLoS_2015_segregation", "max_issues_repo_head_hexsha": "949afedf96945c11ee84b1a6c9842e5257fb5be8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TEST_1/Headers/Parameters.h", "max_forks_repo_name": "dmalagarriga/PLoS_2015_segregation", "max_forks_repo_head_hexsha": "949afedf96945c11ee84b1a6c9842e5257fb5be8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.8611111111, "max_line_length": 58, "alphanum_fraction": 0.6751313485, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.362430456252567}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <omp.h>\n#include <timerlib.h>\n#ifndef NOBLAS\n#ifdef MKL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n#endif\n#include \"gdrdgemm.h\"\n\n\n#define NMAT 2048\nvoid gdr_check_and_restart(double a[][NMAT],\n\t\t\t   double b[][NMAT], \n\t\t\t   double c[][NMAT])\n{\n    int try =0;\n    static int initialized = 0;\n    if (initialized) return;\n    while(1){\n\tint i,j;\n\tfor(i=0;i<NMAT;i++){\n\t    for(j=0;j<NMAT;j++){\n\t\ta[i][j]=0;\n\t\tb[i][j]=i*NMAT+j;\n\t\tc[i][j]=0;\n\t    }\n\t}\n\tfor(i=0;i<NMAT;i++)a[i][i]=1;\n\tcblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,\n\t\t     NMAT,NMAT, NMAT, 1.0, a, NMAT, b, NMAT, 0.0, c, NMAT);\n\tcblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,\n\t\t     NMAT,NMAT, NMAT, 1.0, a, NMAT, b, NMAT, 0.0, c, NMAT);\n\tmygdrdgemm(NMAT, NMAT, NMAT, 1.0, (double*)a, NMAT,\n\t\t   (double*)b, NMAT, 0.0, (double*) c, NMAT);\n\tint err = 0;\n\tfor(i=0;i<NMAT;i++){\n\t    for(j=0;j<NMAT;j++){\n\t\tif (b[i][j] != c[i][j]){\n\t\t    err ++;\n\t\t}\n\t    }\n\t}\n\tif (err == 0){\n\t    fprintf(stderr,\"gdr_check_and_restart passed %d\\n\", try);\n\t    initialized=1;\n\t    return;\n\t}\n\ttry++;\n\tfprintf(stderr, \"gdr_check_and_restart, err=%d try=%d\\n\", err, try);\n\tgdr_free();\n\tgdr_init();\n    }\n}\n\t\n\t   \n\n\t\n\nvoid gdrblas_dgemm\n(\n#ifndef MKL \n   const enum CBLAS_ORDER             ORDER,\n   const enum CBLAS_TRANSPOSE             TRANSA,\n   const enum CBLAS_TRANSPOSE             TRANSB,\n#else\n   const CBLAS_ORDER             ORDER,\n   const CBLAS_TRANSPOSE             TRANSA,\n   const CBLAS_TRANSPOSE             TRANSB,\n#endif   \n   const int                        M,\n   const int                        N,\n   const int                        K,\n   const double                     ALPHA,\n   const double *                   A,\n   const int                        LDA,\n   const double *                   B,\n   const int                        LDB,\n   const double                     BETA,\n   double *                         C,\n   const int                        LDC\n)\n{\n    int NOTA, NOTB,gdrdoneflag;\n    double alpha = ALPHA, beta = BETA;\n    int F77M=M, F77N=N, F77K=K, F77lda=LDA, F77ldb=LDB, F77ldc=LDC;\n    \n    if(      TRANSA == CblasNoTrans ){\n\tNOTA = 1;\n    }else{\n\tNOTA = 0;\n    }\n    if(      TRANSB == CblasNoTrans ){\n\tNOTB = 1;\n    }else{\n\tNOTB = 0;\n    }\n    \n    if( ORDER == CblasColMajor ){\n\tgdrdoneflag=0;\n\tgdr_dgemm_(&NOTA,&NOTB,&F77M,&F77N,&F77K, &alpha, &beta, \n\t\t   &F77lda, &F77ldb, &F77ldc,A,B,C, &gdrdoneflag);\n    }  else  {\n\tgdrdoneflag=0;\n\tgdr_dgemm_(&NOTA,&NOTB,&F77N,&F77M,&F77K, &alpha, &beta, \n\t\t   &F77ldb, &F77lda, &F77ldc,B,A,C, &gdrdoneflag);\n    }\n    \n    if(gdrdoneflag!=1){\n\tcblas_dgemm(ORDER, TRANSA, TRANSB,\n\t\t    M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC);\n    }\n    /*\n     * End of HPL_dgemm\n     */\n}\nvoid dumpcmat(int m, int n, int nc, double c[][nc])\n{\n    static int callcount = 0;\n    static FILE* fid;\n    if (callcount == 0){\n\tfid = fopen(\"/tmp/matdata\", \"w\");\n    }\n    callcount ++;\n    if(callcount < 8){\n\tfprintf(fid,\"\\nPrint CMAT callcount=%d\\n\",callcount);\n\tint i, j;\n\tfor(i=0;i<m;i++){\n\t    fprintf(fid,\"\\ni=%d\\n\", i);\n\t    for(j=0;j<n;j++){\n\t\tif ((j%8)==0 )fprintf(fid,\"\\n%5d:\", j);\n\t\tfprintf(fid,\" %20.12e\",c[i][j]);\n\t    }\n\t}\n    }\n}\ndouble touchcmat(int m, int n, int nc, double c[][nc])\n{\n    double sum=0;\n    int i, j;\n    for(i=0;i<m;i++){\n\tfor(j=0;j<n;j++){\n\t    sum += c[i][j]*c[i][j];\n\t}\n    }\n    return sum;\n}\n\ndouble ssum = 0.0;\n\nvoid mygdrdgemm(int m,\n\t\tint n,\n\t\tint k,\n\t\tdouble alpha,\n\t\tdouble * a,\n\t\tint na,\n\t\tdouble * b,\n\t\tint nb,\n\t\tdouble beta,\n\t\tdouble * c,\n\t\tint nc)\n{\n    int nota=1, notb=1;\n    int gdrdoneflag = 0;\n    static int first_call = 1;\n    if (first_call){\n\tgdrdgemm_set_procname(MP_myprocid());\n\tfirst_call=0;\n\tinit_current_time();\n    }\n    //    char str[128];\n    //    sprintf(str,\"before sums = %25.20e %25.20e %25.20e\",\n    //\t    touchcmat(m,k,na,a),  touchcmat(k,n,nb,b), touchcmat(m,n,nc,c));\n    //    MP_message(str);\n    //    dprintf(9,\"mygdrdgemm omp_max_threads=%d procs=%d\\n\",\n    //\t    omp_get_max_threads(),omp_get_num_procs());\n    double zero=0.0;\n    //    int tmp=0;\n    //    gdr_dgemm_(&nota, &notb, &n, &m, &k, &zero, &beta, &nb, &na, &nc,\n    //\t       b, a, c, &tmp);\n    gdr_dgemm_(&nota, &notb, &n, &m, &k, &alpha, &beta, &nb, &na, &nc,\n\t       b, a, c, &gdrdoneflag);\n    //\tcblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,\n    //\t\t     m,n, k, alpha, a, na, b, nb, beta, c, nc);\n    //\tgdrdoneflag=1;\n    //    fprintf(stderr,\"gdrflag=%d\\n\", gdrdoneflag);\n    if(gdrdoneflag!=1){\n\tcblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,\n\t\t     m,n, k, alpha, a, na, b, nb, beta, c, nc);\n    }\n    //    dumpcmat(m,n,nc,c);\n    //    sprintf(str,\"after sums = %25.20e %25.20e %25.20e\",\n    //\t    touchcmat(m,k,na,a),  touchcmat(k,n,nb,b), touchcmat(m,n,nc,c));\n    //    MP_message(str);\n}\n", "meta": {"hexsha": "ad967758bc3124aabedff6dd06d2a4cfe10f7077", "size": 4879, "ext": "c", "lang": "C", "max_stars_repo_path": "gdrdgemm.c", "max_stars_repo_name": "jmakino/lu2", "max_stars_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-07T09:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T05:00:16.000Z", "max_issues_repo_path": "gdrdgemm.c", "max_issues_repo_name": "jmakino/lu2", "max_issues_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdrdgemm.c", "max_forks_repo_name": "jmakino/lu2", "max_forks_repo_head_hexsha": "5c9447c142e91dc03e351d47920a7c5e22126dbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-13T15:31:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-13T15:31:32.000Z", "avg_line_length": 24.395, "max_line_length": 75, "alphanum_fraction": 0.5300266448, "num_tokens": 1760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.36237550459407475}}
{"text": "/*\n * Copyright 2017 Daniel Eachern Huang\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 AUGUR_MCMCLIB_H\n#define AUGUR_MCMCLIB_H\n\n#include \"augur_util.h\"\n#include \"augur_math.h\"\n#include \"augur_vecop.h\"\n#include \"augur_blkop.h\"\n#include \"augur_blkstk.h\"\n#include \"augur_dist.h\"\n#include <augur_iface.h>\n#include <math.h>\n#include <gsl/gsl_rng.h>\n\ntypedef struct mcmc {\n  AugurMod_t curr;\n  AugurMod_t prop;\n  AugurAux_t aux;\n  int accept;\n  double currLL;\n  double propLL;\n  double eps;\n  double L;\n  double leapLen;\n  double deltaMax;\n  int nutsalloc;\n} mcmc_t;\n\nmcmc_t MCMC;\ngsl_rng* h_rng;\n\nvoid dump_state(mcmc_t state) {\n  printf(\"currLL: %f\\n\", state.currLL);\n  printf(\"propLL: %f\\n\", state.propLL);\n  printf(\"eps: %f\\n\", state.eps);\n  printf(\"leapLen: %f\\n\", state.leapLen);\n  printf(\"L: %f\\n\", state.L);\n  \n}\n\n\n// double modObjFn(AugurMod_t curr, AugurAux_t aux);\nEXTERNC void mcmcStep();\n\n/*\nvoid acceptAlways() {\n  MCMC.currLL = modObjFn(MCMC.curr, MCMC.aux);\n}\n*/\n\n\n/**\n * Returns TRUE if we should accept, FALSE if we should reject.\n */\nBool_t augur_mcmc_ar( double auxll\n\t\t    , double (*objFn)(AugurAux_t, AugurMod_t)\n\t\t    ) {\n  double currll = objFn(MCMC.aux, MCMC.curr);\n  double propll = objFn(MCMC.aux, MCMC.prop);\n  double u = gsl_rng_uniform(h_rng);\n\n  if (augur_log(u) < propll - currll + auxll) {\n    return TRUE;\n  }\n  else {\n    return FALSE;\n  }\n}\n\n\n/**\n * Returns TRUE if we should accept, FALSE if we should reject.\n */\n__HOSTORDEV__ Bool_t augur_mcmc_ar_idx\n       ( double auxll\n       , AugurAux_t aux, AugurMod_t curr, AugurMod_t prop\n       , double (*objFn)(AugurAux_t, AugurMod_t)\n       ) {\n  double currll = objFn(aux, curr);\n  double propll = objFn(aux, prop);\n  // double u = gsl_rng_uniform(h_rng);\n  double u = augur_std_uniform_sample(aux.rng);\n\n  if (augur_log(u) < propll - currll + auxll) {\n    return TRUE;\n  }\n  else {\n    return FALSE;\n  }\n}\n\n\nint acceptReject(double auxLL, double (*objFn)(AugurAux_t, AugurMod_t)) {\n  MCMC.propLL = objFn(MCMC.aux, MCMC.prop);\n  double u = gsl_rng_uniform(h_rng);\n  // printf(\"currLL: %f  propLL: %f  auxLL: %f   ar: %d\\n\", MCMC.currLL, MCMC.propLL, auxLL, log(u) < MCMC.propLL - MCMC.currLL + auxLL);\n  if (log(u) < MCMC.propLL - MCMC.currLL + auxLL) {\n    MCMC.accept += 1;\n    AugurMod_t tmp = MCMC.curr;\n    MCMC.curr = MCMC.prop;\n    MCMC.prop = tmp;\n    // double tmp2 = MCMC.currLL;\n    MCMC.currLL = MCMC.propLL;\n    // MCMC.propLL = tmp2;\n    return 1;\n  }\n  else {\n    return 0;\n  }\n}\n\nvoid swapCurrProp(double (*objFn)(AugurAux_t, AugurMod_t)) {\n  MCMC.propLL = objFn(MCMC.aux, MCMC.prop);\n  AugurMod_t tmp = MCMC.curr;\n  MCMC.curr = MCMC.prop;\n  MCMC.prop = tmp;\n  double tmp2 = MCMC.currLL;\n  MCMC.currLL = MCMC.propLL;\n  MCMC.propLL = tmp2;\n}\n\nvoid initMcmc() {\n  const gsl_rng_type * T;\n  gsl_rng_env_setup();\n  T = gsl_rng_default;\n  h_rng = gsl_rng_alloc (T);\n  \n  // MCMC.curr = curr;\n  // MCMC.prop = prop;\n  // MCMC.aux = aux;\n  MCMC.accept = 0;\n  // MCMC.currLL = objFn(MCMC.aux, MCMC.curr);\n  MCMC.propLL = MCMC.currLL;\n  MCMC.eps = 1.0;\n  MCMC.L = 20;\n  MCMC.leapLen = 10.0;\n  MCMC.deltaMax = 1000.0;\n  MCMC.nutsalloc = 0;\n  return;\n}\n\nEXTERNC void setHmcParams(double eps, double leapLen) {\n  MCMC.eps = eps;\n  MCMC.leapLen = leapLen;\n}\n\nEXTERNC void setHmcParams2(double eps, int L) {\n  MCMC.eps = eps;\n  MCMC.L = L;\n}\n\n#define max(x, y) ( x < y ? y : x)\n\ndouble h_sample_uniform(gsl_rng* rng, double left, double right) {\n  double u = gsl_rng_uniform(rng);\n  return left + u * (right - left);\n}\n\n\n/**\n * Metropololis-within-gibbs Kernel. (Note it is host/dev code)\n */\n__HOSTORDEV__ void augur_mcmc_mwg\n      ( AugurAux_t aux, AugurMod_t curr, AugurMod_t prop\n      , double* llCorrect\n      , void (*proposal)(AugurAux_t, AugurMod_t, AugurMod_t)\n      , void (*swap)(AugurAux_t, AugurMod_t, AugurMod_t, int)\n      , double (*objFn)(AugurAux_t, AugurMod_t) ) {\n  proposal(aux, curr, prop);\n  if (augur_mcmc_ar_idx(*llCorrect, aux, curr, prop, objFn)) {\n    // Accept, so copy proposal theta into current theta (maintain invariant)\n    swap(aux, curr, prop, 0);\n  }\n  else {\n    // Reject, so copy current theta into proposal theta (maintain invariant)\n    swap(aux, curr, prop, 1);\n  }\n}\n  \n\n/**\n * Gradient checking. (Call from host code)\n */\nvoid h_augur_chk_grad\n      ( AugurMemLoc_t loc, AugurBlk_t* pt, AugurBlk_t* grad\n      , AugurAux_t aux, AugurMod_t curr\n      , double (*objFn)(AugurAux_t, AugurMod_t) ) {\n  double eps = 10e-8;\n  printf(\"Evaluating gradient at point:\\n\");\n  h_augur_blk_dump(loc, pt);\n  \n  for (uint_t i = 0; i < pt->num_blks; i++) {\n    switch (pt->typs[i]) {\n    case AUGUR_DBL: {\n      // TODO \n      break;\n    }\n    case AUGUR_VEC: {\n      AugurFlatVec_t* fvec = (AugurFlatVec_t*) pt->blks[i];\n      for (int j = 0; j < fvec->base_elems; j++) {\n\th_augur_flat_vec_basis_add(loc, fvec, j, eps);\n\tdouble plus = objFn(aux, curr);\n\th_augur_flat_vec_basis_add(loc, fvec, j, -2.0 * eps);\n\tdouble minus = objFn(aux, curr);\n\tdouble fin_diff = (plus - minus) / (2.0 * eps);\n\tdouble ad;\n\th_augur_flat_vec_getd_idx(loc, &ad, (AugurFlatVec_t*) (grad->blks[i]), j);\n\tprintf(\"plus: %f, minus: %f\\n\", plus, minus);\n\tprintf(\"auto-diff: %f, finite-diff: %f, error: %f\\n\", ad, fin_diff, ad - fin_diff);\n\th_augur_flat_vec_basis_add(loc, fvec, j, eps);\n      }\n      break;\n    }\n    case AUGUR_MAT: {\n      AugurMat_t* mat = (AugurMat_t*) pt->blks[i];\n      for (int j = 0; j < mat->row * mat->col; j++) {\n\th_augur_mat_basis_add(loc, mat, j, eps);\n\tdouble plus = objFn(aux, curr);\n\th_augur_mat_basis_add(loc, mat, j, -2.0 * eps);\n\tdouble minus = objFn(aux, curr);\n\tdouble fin_diff = (plus - minus) / (2.0 * eps);\n\tdouble ad;\n\th_augur_mat_getd_idx(loc, &ad, (AugurMat_t*) (grad->blks[i]), j);\t\n\tprintf(\"auto-diff: %f, finite-diff: %f, error: %f\\n\", ad, fin_diff, ad - fin_diff);\n\th_augur_mat_basis_add(loc, mat, j, eps);\n      }\n      break;\n    }\n    default: {\n      // TODO\n      break;\n    }\n    }\n  }\n}\n\n\n/**\n * Calls a gradient function. (Call from host code)\n *\n * The struct curr contains \"the point\" we are evaluating gradfn at.\n * The result of the gradient computation is in grad, which is part of\n * the struct aux.\n */\nvoid h_augur_mcmc_call_grad\n      ( AugurMemLoc_t loc\n      , AugurAux_t aux, AugurMod_t curr\n      , AugurBlk_t* grad\n      , void (*gradfn)(AugurAux_t, AugurMod_t)\n      ) {\n  h_augur_blk_zero(loc, grad);\n  gradfn(aux, curr);\n}\n\n\n/**\n * The struct curr contains pt, \"the point\" we are evaluating gradfn at.\n */\nvoid h_augur_mcmc_chkcall_grad\n      ( AugurMemLoc_t loc\n      , AugurAux_t aux, AugurMod_t curr\n      , AugurBlk_t* grad \n      , void (*gradfn)(AugurAux_t, AugurMod_t)\n      , AugurBlk_t* pt\n      , double (*objfn) (AugurAux_t, AugurMod_t)\n      , Bool_t f_chkgrad\n      ) {\n  h_augur_mcmc_call_grad(loc, aux, curr, grad, gradfn);\n  if (f_chkgrad) {\n    h_augur_chk_grad(loc, pt, grad, aux, curr, objfn);\n  }\n}\n\n/**\n * Leapfrog simulation. (Call from host code)\n * \n * Leapfrog with (POSITIVE) gradient of log-likelihood of objfn. \n * (Signs are important!!)\n *\n * theta0 / thetaStar: initial / proposal point\n * grad: result of gradient\n * p0 / pStar: initial / proposal momentum\n * \n * mod.thetaStar = thetaStar\n * aux.grad = grad\n * \n * gradfn(aux, mod) evaluates gradient at thetaStar, putting result in grad\n *\n */\nvoid h_augur_mcmc_leapfrog1\n      ( AugurMemLoc_t loc\n      , AugurAux_t aux, AugurMod_t mod\n      , AugurBlk_t* grad, AugurBlk_t* thetaStar, AugurBlk_t* pStar\n      , void (*gradfn)(AugurAux_t, AugurMod_t)\n      , double stepsize\n      ) {\n  // Simulate Hamiltonian dynamics first half step of momentum\n  // pStar = p0 + stepsize / 2.0 * d_like(x, thetaStar)\n  h_augur_mcmc_call_grad(loc, aux, mod, grad, gradfn);\n  h_augur_blk_scale_plus(loc, pStar, pStar, stepsize / 2.0, grad);  \n  \n  // Full step for position\n  // Position: thetaStar = thetaStar + stepsize * pStar\n  h_augur_blk_scale_plus(loc, thetaStar, thetaStar, stepsize, pStar);\n  \n  // Simulate last half step of momentum\n  // pStar = pStar + stepsize / 2.0 * d_like(x, thetaStar)\n  h_augur_mcmc_call_grad(loc, aux, mod, grad, gradfn);\n  h_augur_blk_scale_plus(loc, pStar, pStar, stepsize / 2.0, grad);\n}\n\n/**\n * Leapfrog simulation. (Call from host code)\n * \n * Leapfrog with (POSITIVE) gradient of log-likelihood of objfn. \n * (Signs are important!!)\n *\n * theta0 / thetaStar: initial / proposal point\n * grad: result of gradient\n * p0 / pStar: initial / proposal momentum\n * \n * curr.theta0 = theta0, prop.theta0 = thetaStar, aux.grad = grad\n * \n * gradfn(aux, curr) evaluates gradient at theta0, putting result in grad\n * gradfn(aux, prop) evaluates gradient at thetaStar, putting result in grad\n *\n */\nvoid h_augur_mcmc_leapfrog\n      ( AugurMemLoc_t loc\n      , AugurAux_t aux, AugurMod_t curr, AugurMod_t prop      \n      , AugurBlk_t* theta0, AugurBlk_t* thetaStar\n      , AugurBlk_t* grad, AugurBlk_t* p0, AugurBlk_t* pStar\n      , void (*gradfn)(AugurAux_t, AugurMod_t)\n      , double (*objfn) (AugurAux_t, AugurMod_t)\n      , double stepsize, int simsteps\n      ) {\n  // Simulate Hamiltonian dynamics first half step of momentum\n  // pStar = p0 + stepsize / 2.0 * d_like(x, theta0)\n  h_augur_mcmc_call_grad(loc, aux, curr, grad, gradfn);\n  h_augur_blk_scale_plus(loc, pStar, p0, stepsize / 2.0, grad);   \n  \n  // Simulate full steps\n  for (uint_t l = 0; l < simsteps; l++) {\n    // Full step for position\n    // Position: thetaStar = thetaStar + stepsize * pStar\n    h_augur_blk_scale_plus(loc, thetaStar, thetaStar, stepsize, pStar);\n\n    // Move momentum except at last step    \n    if (l != simsteps-1) {\n      // Momentum: pStar = pStar + stepsize * d_like(x, thetaStar)\n      h_augur_mcmc_call_grad(loc, aux, prop, grad, gradfn);   \n      h_augur_blk_scale_plus(loc, pStar, pStar, stepsize, grad);\n    }\n  }\n\n  // Simulate last half step of momentum\n  // pStar = pStar + stepsize / 2.0 * d_like(x, thetaStar)\n  h_augur_mcmc_call_grad(loc, aux, prop, grad, gradfn);\n  h_augur_blk_scale_plus(loc, pStar, pStar, stepsize / 2.0, grad);\n}\n\n/**\n * Hamiltonian Monte Carlo Kernel. (Call from host code)\n *\n * Suppose this kernel moves blk = [p_1, .., p_n]. \n * Then we have the following equalities on the inputs:\n * \n * curr.blk = theta0\n * prop.blk = thetaStar\n *\n * For compositionality, we maintain the invariant that:\n * curr.blk = prop.blk\n */\nvoid h_augur_mcmc_hmc\n     ( AugurMemLoc_t loc\n     , AugurAux_t aux, AugurMod_t curr, AugurMod_t prop      \n     , AugurBlk_t* theta0, AugurBlk_t* thetaStar\n     , AugurBlk_t* grad, AugurBlk_t* p0, AugurBlk_t* pStar\n     , double simlen, double eps\n     , void (*computeGrad)(AugurAux_t, AugurMod_t)\n     , double (*objFn)(AugurAux_t, AugurMod_t)\n     ) {\n  // Initialize momentum\n  h_augur_blk_randn(aux.rng, p0);\n\n  // Randomize simsteps\n  double scale_eps = h_augur_uniform_sample(h_rng, 0.8, 1.2);\n  double stepsize = scale_eps * eps;\n  double s = h_augur_uniform_sample(h_rng, 0.9, 1.1);\n  uint_t simsteps = augur_max(1, round(s * simlen / stepsize));\n\n  // Simulate Hamiltonian dynamics with Leapfrog method\n  h_augur_mcmc_leapfrog(loc, aux, curr, prop, theta0, thetaStar, grad, p0, pStar, computeGrad, objFn, stepsize, simsteps);\n  \n  // Compute correction \n  double initMomLL = h_augur_blk_dot(loc, p0, p0) / 2.0;\n  double propMomLL = h_augur_blk_dot(loc, pStar, pStar) / 2.0;\n  double auxll = initMomLL - propMomLL;\n\n  // After trajectory, compute whether we should accept or reject\n  if (augur_mcmc_ar(auxll, objFn)) {\n    // Accept, so copy proposal theta into current theta (for invariant)\n    h_augur_blk_cpy(loc, theta0, thetaStar);\n  }\n  else {\n    // Reject, so copy current theta into proposal theta (for invariant)\n    h_augur_blk_cpy(loc, thetaStar, theta0);\n  }\n}\n\n\n/**\n * Elliptical Slice Sampling Kernel. (Note it is host/dev code)\n *\n * Suppose this kernel moves param = currTheta. \n * Then we have the following equalities on the inputs:\n * \n * curr.param = currTheta\n * prop.param = propTheta\n *\n * For compositionality, we maintain the invariant that:\n * curr.param = prop.param\n */\n__HOSTORDEV__ void augur_mcmc_eslice\n      ( AugurAux_t aux, AugurMod_t curr, AugurMod_t prop\n      , AugurVec_t* curr_theta, AugurVec_t* prop_theta\n      , AugurVec_t* mean, AugurMat_t* cov\n      , AugurMat_t* L, AugurVec_t* nu\n      , double (*objfn)(AugurAux_t, AugurMod_t) ) {\n  augur_mvnormal_sample(aux.rng, nu, mean, cov, L, nu);\n  double u = augur_std_uniform_sample(aux.rng);\n  double log_y = objfn(aux, curr) + augur_log(u);\n  \n  double theta = augur_uniform_sample(aux.rng, 0.0, 2.0 * AUGUR_PI);\n  double theta_min = theta - 2.0 * AUGUR_PI;\n  double theta_max = theta;\n\n  while (TRUE) {\n    double diff = theta_max - theta_min;\n    if (diff < 1e-8) {\n      // Maintain invariant that curr == prop\n      augur_vec_cpy(prop_theta, curr_theta);\n      break;\n    }\n\n    // propSt = (currSt - mean) * cos(theta) + (nu - mean) * sin(theta) + mean;\n    for (uint_t i = 0; i < prop_theta->elems; i++) {\n      double mean_i = AUGUR_VEC_GETD(mean, i);\n      double a = (AUGUR_VEC_GETD(curr_theta, i) - mean_i) * augur_cos(theta);\n      double b = (AUGUR_VEC_GETD(nu, i) - mean_i) * augur_sin(theta);\n      AUGUR_VEC_SETD(prop_theta, i, a + b + mean_i);\n    }\n\n    double prop_ll = objfn(aux, prop);\n    if (prop_ll > log_y) {      \n      // Maintain invariant that curr == prop\n      augur_vec_cpy(curr_theta, prop_theta);\n      break;\n    }\n\n    // Shrink bracket\n    if (theta < 0) {\n      theta_min = theta;\n    }\n    else {\n      theta_max = theta;\n    }\n    theta = augur_uniform_sample(aux.rng, theta_min, theta_max);\n  }\n}\n\n\n/**\n * Reflective Slice Kernel. (Call from host code)\n *\n * Suppose this kernel moves blk = [p_1, .., p_n]. \n * Then we have the following equalities on the inputs:\n * \n * curr.blk = theta0\n * prop.blk = thetaStar\n *\n * For compositionality, we maintain the invariant that:\n * curr.blk = prop.blk\n */\nvoid h_augur_mcmc_refl_slice\n     ( AugurMemLoc_t loc\n     , AugurAux_t aux, AugurMod_t curr, AugurMod_t prop\n     , AugurBlk_t* theta0, AugurBlk_t* thetaProp\n     , AugurBlk_t* grad, AugurBlk_t* p0\n     , double simlen, double eps\n     , void (*computeGrad)(AugurAux_t, AugurMod_t)\n     , double (*objFn)(AugurAux_t, AugurMod_t)\n     ) {\n  // Initialize momentum\n  h_augur_blk_randn(aux.rng, p0);\n\n  // Compute slice level\n  double z = objFn(aux, curr) - gsl_ran_exponential(h_rng, 1.0);\n  int cond = 0;\n  double stepsize = eps;\n  uint_t simsteps = augur_max(1, round(simlen / stepsize));\n\n  for (int i = 0 ; i < simsteps; i++) {\n    // Take scaled-step in direction of momentum\n    h_augur_blk_scale_plus(loc, thetaProp, thetaProp, stepsize, p0);\n\n    cond = objFn(aux, prop) < z;\n    if (cond) {\n      // Reflect (outside version) if we leave slice\n      \n      // Compute grad at outside point\n      h_augur_blk_zero(loc, grad);\n      computeGrad(aux, prop);\n\n      // Compute reflection and update direction\n      double angle1 = h_augur_blk_dot(loc, p0, grad);\n      double angle2 = h_augur_blk_dot(loc, grad, grad);\n      double scale = angle1 / angle2;\n      h_augur_blk_scale_plus(loc, p0, p0, -2.0 * scale, grad);\n\n    }\n  }\n  \n  if (!cond) {\n    // Copy if we are in slice\n    h_augur_blk_cpy(loc, theta0, thetaProp);\n  }\n}\n\n\n/* NUTS */\n\ntypedef enum NutsDir {\n  NUTS_MINUS = 0,\n  NUTS_PLUS = 1,\n} NutsDir_t;\n\ntypedef struct NutsRet {\n  int n;\n  int s;\n} NutsRet_t;\n\ntypedef struct NutsRT {\n  AugurBlk_t* work;\n  AugurBlkStk_t* theta_prop_stk;\n  AugurBlkStk_t* theta_stk;\n  AugurBlkStk_t* mom_stk;\n} NutsRT_t;\n\ntypedef struct NutsInfo {\n  AugurAux_t aux;\n  AugurMod_t mod;\n  AugurBlk_t* grad;\n  double (*modObjFn)(AugurAux_t, AugurMod_t);\n  void (*computeGrad)(AugurAux_t, AugurMod_t);\n  double stepsize;\n  double logu;\n} NutsInfo_t;\n\nint h_augur_nuts_update_s(AugurMemLoc_t loc, int s, AugurBlk_t* work, AugurBlk_t* theta_plus, AugurBlk_t* mom_plus, AugurBlk_t* theta_minus, AugurBlk_t* mom_minus) {\n  if (s == 1) { \n    h_augur_blk_minus(loc, work, theta_plus, theta_minus);\n    int ut1 = augur_indicator(h_augur_blk_dot(loc, work, mom_plus) >= 0.0);\n    int ut2 = augur_indicator(h_augur_blk_dot(loc, work, mom_minus) >= 0.0);\n    if (ut1 && ut2) {\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/**\n * info.mod.theta = theta (gradient is always evaluated at latest value of theta)\n *\n * Invariants:\n * Suppose dir = PLUS, then:\n *\n * theta: latest value of theta^+\n * mom: latest value of mom^+ \n */\nNutsRet_t h_augur_nuts_build_tree\n      ( AugurMemLoc_t loc, NutsInfo_t* info , NutsRT_t* rt\n      , AugurBlk_t* shape\n      , AugurBlk_t* theta, AugurBlk_t* mom, int j, NutsDir_t dir\n      , int tab) {\n  if (j == 0) {\n    // Simulate (updates theta, mom)\n    h_augur_mcmc_leapfrog1(loc, info->aux, info->mod,\n\t\t\t   info->grad, theta, mom,\n\t\t\t   info->computeGrad,\n\t\t\t   info->stepsize);\n\n    // Update return value\n    augur_blk_stk_push(loc, rt->theta_prop_stk, shape, theta);\n    \n    // Check stopping condition\n    NutsRet_t ret;\n    double ll = info->modObjFn(info->aux, info->mod) - 0.5 * h_augur_blk_dot(loc, mom, mom);\n    ret.n = augur_indicator(info->logu <= ll);\n    ret.s = augur_indicator(info->logu < MCMC.deltaMax + ll);\n\n    return ret; \n  }\n  else {    \n    // Build left subtree\n    NutsRet_t left = h_augur_nuts_build_tree(loc, info, rt, shape, theta, mom, j - 1, dir, tab+2);\n\n    // Build right subtree (if we should keep going)\n    if (left.s == 1) {\n      // Save \"left\"-most\n      if (j == 1) {\n\taugur_blk_stk_push(loc, rt->theta_stk, shape, theta);\n\taugur_blk_stk_push(loc, rt->mom_stk, shape, mom);\n      }\n      \n      NutsRet_t right = h_augur_nuts_build_tree(loc, info, rt, shape, theta, mom, j - 1, dir, tab+2);\n\n      // Propogate proposal with probability proportional to size of subtrees\n      AugurBlk_t* prop1 = augur_blk_stk_pop(rt->theta_prop_stk);\n      AugurBlk_t* prop2 = augur_blk_stk_pop(rt->theta_prop_stk);\n      double bias = ((double) right.n) / (left.n + right.n);\n      if (h_augur_bernoulli_sample(h_rng, bias) == 0) {\n\taugur_blk_stk_push(loc, rt->theta_prop_stk, shape, prop2);\n      }\n      else {\n\taugur_blk_stk_push(loc, rt->theta_prop_stk, shape, prop1);\n      }\n      augur_blk_stk_dump(loc, rt->theta_prop_stk);\n\n      // Propogate tree size\n      left.n += right.n;\n\n      // Check u-turn\n      AugurBlk_t* theta_minus; AugurBlk_t* mom_minus;\n      AugurBlk_t* theta_plus; AugurBlk_t* mom_plus;\n      switch (dir) {\n      case NUTS_MINUS: {\n\ttheta_plus = augur_blk_stk_peek(rt->theta_stk);\n\tmom_plus = augur_blk_stk_peek(rt->mom_stk);\n\ttheta_minus = theta;\n\tmom_minus = mom;\n\tbreak;\n      }\n      case NUTS_PLUS: {\n\ttheta_minus = augur_blk_stk_peek(rt->theta_stk);\n\tmom_minus = augur_blk_stk_peek(rt->mom_stk);\n\ttheta_plus = theta;\n\tmom_plus = mom;\n\tbreak;\n      }\n      }\n      left.s = h_augur_nuts_update_s(loc, right.s, rt->work, theta_plus, mom_plus, theta_minus, mom_minus);\n\n      // Pop \"left\"-most\n      if (j > 1) {\n\taugur_blk_stk_pop(rt->theta_stk);\n\taugur_blk_stk_pop(rt->mom_stk);\n      }           \n    }\n\n    return left;\n  }\n}\n\n\n/**\n * No-U-Turn Kernel. (Call from host code)\n *\n * Suppose this kernel moves blk = [p_1, .., p_n]. \n * Then we have the following equalities on the inputs:\n * \n * curr.blk = theta0\n * prop.blk = thetaStar\n *\n * For compositionality, we maintain the invariant that:\n * curr.blk = prop.blk\n */\nvoid h_augur_mcmc_nuts\n      ( AugurMemLoc_t loc, AugurAux_t aux, AugurMod_t curr, AugurMod_t prop      \n      , AugurBlk_t* theta0, AugurBlk_t* theta_prop\n      , AugurBlk_t* grad, AugurBlk_t* work\n      , AugurBlk_t* theta_minus, AugurBlk_t* mom_minus\n      , AugurBlk_t* theta_plus, AugurBlk_t* mom_plus\n      , AugurBlk_t* shape\n      , double stepsize\n      , void (*computeGrad)(AugurAux_t, AugurMod_t)\n      , double (*modObjFn)(AugurAux_t, AugurMod_t)\n      ) {\n  // Initialize simulation values\n  h_augur_blk_cpy(loc, theta_minus, theta0);\n  h_augur_blk_randn(aux.rng, mom_minus);  \n  h_augur_blk_cpy(loc, theta_plus, theta0);\n  h_augur_blk_cpy(loc, mom_plus, mom_minus);\n  \n  // Initialize info\n  NutsInfo_t info;\n  info.aux = aux;\n  info.mod = prop;\n  info.grad = grad;\n  info.modObjFn = modObjFn;\n  info.computeGrad = computeGrad;\n  info.logu = modObjFn(aux, curr) - 0.5 * h_augur_blk_dot(loc, mom_minus, mom_minus) - gsl_ran_exponential(h_rng, 1.0);\n\n  // Initialize auxilliary nuts runtime values\n  NutsRT_t rt;\n  rt.work = work;\n  AugurBlkStk_t theta_prop_stk = augur_blk_stk_stk_alloc();\n  AugurBlkStk_t theta_stk = augur_blk_stk_stk_alloc();\n  AugurBlkStk_t mom_stk = augur_blk_stk_stk_alloc();\n  rt.theta_prop_stk = &theta_prop_stk;\n  rt.theta_stk = &theta_stk;\n  rt.mom_stk = &mom_stk;\n  \n  int n = 1;\n  int j = 0;\n  int s = 1;\n\n  while (TRUE) {    \n    NutsRet_t nuts_ret;\n    augur_blk_stk_reset(rt.theta_stk);\n    augur_blk_stk_reset(rt.mom_stk);\n    if (h_augur_bernoulli_sample(h_rng, 0.5)) {\n      info.stepsize = -stepsize;\n      h_augur_blk_cpy(loc, theta_prop, theta_minus);\n      nuts_ret = h_augur_nuts_build_tree(loc, &info, &rt, shape, theta_prop, mom_minus, j, NUTS_MINUS, 0);\n      h_augur_blk_cpy(loc, theta_minus, theta_prop);\n    }\n    else {\n      info.stepsize = stepsize;\n      h_augur_blk_cpy(loc, theta_prop, theta_plus);\n      nuts_ret = h_augur_nuts_build_tree(loc, &info, &rt, shape, theta_prop, mom_plus, j, NUTS_PLUS, 0);\n      h_augur_blk_cpy(loc, theta_plus, theta_prop);\n    }\n\n    AugurBlk_t* theta_prop_p = augur_blk_stk_pop(rt.theta_prop_stk);\n    Bool_t f_cpy = FALSE;\n    if (nuts_ret.s == 1) {\n      double bias = augur_min(1.0, ((double) nuts_ret.n) / n);\n      if (h_augur_bernoulli_sample(h_rng, bias) == 1) {\n\t// Update proposal\t  \n\th_augur_blk_cpy(loc, theta_prop, theta_prop_p);\n\tf_cpy = TRUE;\n      }\n    }\n    \n    n += nuts_ret.n;\n    s = h_augur_nuts_update_s(loc, nuts_ret.s, rt.work, theta_plus, mom_plus, theta_minus, mom_minus);\n    j += 1;\n    \n    if (s != 1) {\n      // Maintain invariant\n      if (f_cpy) {\n\th_augur_blk_cpy(loc, theta0, theta_prop);\n      }\n      else {\n\th_augur_blk_cpy(loc, theta_prop, theta0);\n      }\n      break;\n    }\n  }\n}\n\n#endif\n", "meta": {"hexsha": "ebc916a9f95dc7fb34b02de18e6364e82688ed24", "size": 22513, "ext": "h", "lang": "C", "max_stars_repo_path": "cbits/augur_mcmclib.h", "max_stars_repo_name": "rjnw/augurv2", "max_stars_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-03-06T19:51:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-18T15:07:41.000Z", "max_issues_repo_path": "cbits/augur_mcmclib.h", "max_issues_repo_name": "rjnw/augurv2", "max_issues_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-09-20T19:18:13.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-20T19:38:00.000Z", "max_forks_repo_path": "cbits/augur_mcmclib.h", "max_forks_repo_name": "rjnw/augurv2", "max_forks_repo_head_hexsha": "0430482297e81288d58a16d43a98ea9d0196d640", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-10-10T21:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-18T20:17:36.000Z", "avg_line_length": 28.8998716303, "max_line_length": 165, "alphanum_fraction": 0.6596188869, "num_tokens": 7335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3623456753854544}}
{"text": "#ifdef HAVE_LIBGSL\n/* interface_gsl.h\n * Easel's interfaces to the GNU Scientific Library\n * \n * SRE, Tue Jul 13 15:36:48 2004\n * SVN $Id: interface_gsl.h 664 2011-02-27 17:08:36Z eddys $\n * SVN $URL: https://svn.janelia.org/eddylab/eddys/easel/branches/hmmer/3.1/interface_gsl.h $\n */\n#ifndef eslINTERFACE_GSL_INCLUDED\n#define eslINTERFACE_GSL_INCLUDED\n\n#include <stdlib.h>\n#include <easel/easel.h>\n#include <easel/dmatrix.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_eigen.h>\n\nextern int esl_GSL_MatrixInversion(ESL_DMATRIX *A, ESL_DMATRIX **ret_Ai);\n\n\n#endif /*eslINTERFACE_GSL_INCLUDED*/\n#endif /*HAVE_LIBGSL*/\n", "meta": {"hexsha": "ac090d60bbedbeacc26c8b3a0d99eef961c642be", "size": 676, "ext": "h", "lang": "C", "max_stars_repo_path": "Linux/easel/interface_gsl.h", "max_stars_repo_name": "YJY-98/PROSAVA", "max_stars_repo_head_hexsha": "6c1beb53922471218386b7ed24e72fb093fe457c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Linux/easel/interface_gsl.h", "max_issues_repo_name": "YJY-98/PROSAVA", "max_issues_repo_head_hexsha": "6c1beb53922471218386b7ed24e72fb093fe457c", "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": "Linux/easel/interface_gsl.h", "max_forks_repo_name": "YJY-98/PROSAVA", "max_forks_repo_head_hexsha": "6c1beb53922471218386b7ed24e72fb093fe457c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.04, "max_line_length": 93, "alphanum_fraction": 0.7529585799, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.36223849540970315}}
{"text": "/*\n *  aeif_cond_beta_multisynapse.h\n *\n *  This file is part of NEST.\n *\n *  Copyright (C) 2004 The NEST Initiative\n *\n *  NEST 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 *  NEST 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 NEST.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#ifndef AEIF_COND_BETA_MULTISYNAPSE_H\n#define AEIF_COND_BETA_MULTISYNAPSE_H\n\n// Generated includes:\n#include \"config.h\"\n\n#ifdef HAVE_GSL\n\n// External includes:\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_odeiv.h>\n\n// Includes from nestkernel:\n#include \"archiving_node.h\"\n#include \"connection.h\"\n#include \"event.h\"\n#include \"nest_types.h\"\n#include \"ring_buffer.h\"\n#include \"universal_data_logger.h\"\n\n/* BeginDocumentation\n Name: aeif_cond_beta_multisynapse - Conductance based adaptive exponential\n                                      integrate-and-fire neuron model according\n                                      to Brette and Gerstner (2005) with\n                                      multiple synaptic rise time and decay\n                                      time constants, and synaptic conductance\n                                      modeled by a beta function.\n\n Description:\n\n aeif_cond_beta_multisynapse is a conductance-based adaptive exponential\n integrate-and-fire neuron model. It allows an arbitrary number of synaptic\n rise time and decay time constants. Synaptic conductance is modeled by a\n beta function, as described by A. Roth and M.C.W. van Rossum\n in Computational Modeling Methods for Neuroscientists, MIT Press 2013,\n Chapter 6.\n\n The time constants are supplied by two arrays, \"tau_rise\" and \"tau_decay\" for\n the synaptic rise time and decay time, respectively. The synaptic\n reversal potentials are supplied by the array \"E_rev\". The port numbers\n are automatically assigned in the range from 1 to n_receptors.\n During connection, the ports are selected with the property \"receptor_type\".\n\n The membrane potential is given by the following differential equation:\n C dV/dt = -g_L(V-E_L) + g_L*Delta_T*exp((V-V_T)/Delta_T) + I_syn_tot(V, t)\n           - w + I_e\n\n where:\n I_syn_tot(V,t) = \\sum_i g_i(t) (V - E_{rev,i}) ,\n\n the synapse i is excitatory or inhibitory depending on the value of E_{rev,i}\n and the differential equation for the spike-adaptation current w is:\n\n tau_w * dw/dt = a(V - E_L) - w\n\n When the neuron fires a spike, the adaptation current w <- w + b.\n\nParameters:\nThe following parameters can be set in the status dictionary.\n\nDynamic state variables:\n  V_m        double - Membrane potential in mV\n  w          double - Spike-adaptation current in pA.\n\nMembrane Parameters:\n  C_m        double - Capacity of the membrane in pF\n  t_ref      double - Duration of refractory period in ms.\n  V_reset    double - Reset value for V_m after a spike. In mV.\n  E_L        double - Leak reversal potential in mV.\n  g_L        double - Leak conductance in nS.\n  I_e        double - Constant external input current in pA.\n  Delta_T    double - Slope factor in mV\n  V_th       double - Spike initiation threshold in mV\n  V_peak     double - Spike detection threshold in mV.\n\nAdaptation parameters:\n  a          double - Subthreshold adaptation in nS.\n  b          double - Spike-triggered adaptation in pA.\n  tau_w      double - Adaptation time constant in ms\n\nSynaptic parameters\n  E_rev      double vector - Reversal potential in mV.\n  tau_rise  double vector - Rise time of synaptic conductance in ms (beta\n                      function).\n  tau_decay double vector - Decay time of synaptic conductance in ms (beta\n                      function).\n\nIntegration parameters\n  gsl_error_tol  double - This parameter controls the admissible error of the\n                          GSL integrator. Reduce it if NEST complains about\n                          numerical instabilities.\n\n Examples:\n\n import nest\n import numpy as np\n\n neuron = nest.Create('aeif_cond_beta_multisynapse')\n nest.SetStatus(neuron, {\"V_peak\": 0.0, \"a\": 4.0, \"b\":80.5})\n nest.SetStatus(neuron, {'E_rev':[0.0,0.0,0.0,-85.0],\n                         'tau_decay':[50.0,20.0,20.0,20.0],\n                         'tau_rise':[10.0,10.0,1.0,1.0]})\n\n spike = nest.Create('spike_generator', params = {'spike_times':\n                                                 np.array([10.0])})\n\n voltmeter = nest.Create('voltmeter', 1, {'withgid': True})\n\n delays=[1.0, 300.0, 500.0, 700.0]\n w=[1.0, 1.0, 1.0, 1.0]\n for syn in range(4):\n     nest.Connect(spike, neuron, syn_spec={'model': 'static_synapse',\n                                           'receptor_type': 1 + syn,\n                                           'weight': w[syn],\n                                           'delay': delays[syn]})\n\n nest.Connect(voltmeter, neuron)\n\n nest.Simulate(1000.0)\n dmm = nest.GetStatus(voltmeter)[0]\n Vms = dmm[\"events\"][\"V_m\"]\n ts = dmm[\"events\"][\"times\"]\n import pylab\n pylab.figure(2)\n pylab.plot(ts, Vms)\n pylab.show()\n\n Sends: SpikeEvent\n\n Receives: SpikeEvent, CurrentEvent, DataLoggingRequest\n\n author: Bruno Golosio 07/10/2016\n SeeAlso: aeif_cond_alpha_multisynapse\n */\n\nnamespace nest\n{\n/**\n * Function computing right-hand side of ODE for GSL solver.\n * @note Must be declared here so we can befriend it in class.\n * @note Must have C-linkage for passing to GSL. Internally, it is\n *       a first-class C++ function, but cannot be a member function\n *       because of the C-linkage.\n * @note No point in declaring it inline, since it is called\n *       through a function pointer.\n * @param void* Pointer to model neuron instance.\n */\nextern \"C\" int\naeif_cond_beta_multisynapse_dynamics( double, const double*, double*, void* );\n\n/**\n * Conductance based exponential integrate-and-fire neuron model according to\n * Brette and Gerstner\n * (2005) with multiple ports.\n */\nclass aeif_cond_beta_multisynapse : public Archiving_Node\n{\n\npublic:\n  aeif_cond_beta_multisynapse();\n  aeif_cond_beta_multisynapse( const aeif_cond_beta_multisynapse& );\n  virtual ~aeif_cond_beta_multisynapse();\n\n  friend int\n  aeif_cond_beta_multisynapse_dynamics( double, const double*, double*, void* );\n\n  /**\n   * Import sets of overloaded virtual functions.\n   * @see Technical Issues / Virtual Functions: Overriding, Overloading, and\n   * Hiding\n   */\n  using Node::handle;\n  using Node::handles_test_event;\n\n  port send_test_event( Node&, rport, synindex, bool );\n\n  void handle( SpikeEvent& );\n  void handle( CurrentEvent& );\n  void handle( DataLoggingRequest& );\n\n  port handles_test_event( SpikeEvent&, rport );\n  port handles_test_event( CurrentEvent&, rport );\n  port handles_test_event( DataLoggingRequest&, rport );\n\n  void get_status( DictionaryDatum& ) const;\n  void set_status( const DictionaryDatum& );\n\nprivate:\n  void init_state_( const Node& proto );\n  void init_buffers_();\n  void calibrate();\n  void update( Time const&, const long, const long );\n\n  // The next two classes need to be friends to access the State_ class/member\n  friend class RecordablesMap< aeif_cond_beta_multisynapse >;\n  friend class UniversalDataLogger< aeif_cond_beta_multisynapse >;\n\n  // ----------------------------------------------------------------\n\n  /**\n   * Independent parameters of the model.\n   */\n  struct Parameters_\n  {\n    double V_peak_;  //!< Spike detection threshold in mV\n    double V_reset_; //!< Reset Potential in mV\n    double t_ref_;   //!< Refractory period in ms\n\n    double g_L;     //!< Leak Conductance in nS\n    double C_m;     //!< Membrane Capacitance in pF\n    double E_L;     //!< Leak reversal Potential (aka resting potential) in mV\n    double Delta_T; //!< Slope faktor in ms.\n    double tau_w;   //!< adaptation time-constant in ms.\n    double a;       //!< Subthreshold adaptation in nS.\n    double b;       //!< Spike-triggered adaptation in pA\n    double V_th;    //!< Spike threshold in mV.\n\n    std::vector< double > tau_rise;  //!< Rise time of synaptic conductance\n                                     //!< in ms.\n    std::vector< double > tau_decay; //!< Decay time of synaptic conductance\n                                     //!< in ms.\n    std::vector< double > E_rev;     //!< reversal potentials in mV\n\n    double I_e; //!< Intrinsic current in pA.\n\n    double gsl_error_tol; //!< error bound for GSL integrator\n\n    // boolean flag which indicates whether the neuron has connections\n    bool has_connections_;\n\n    Parameters_(); //!< Sets default parameter values\n\n    void get( DictionaryDatum& ) const; //!< Store current values in dictionary\n    void set( const DictionaryDatum& ); //!< Set values from dictionary\n\n    //! Return the number of receptor ports\n    inline size_t\n    n_receptors() const\n    {\n      return E_rev.size();\n    }\n  };\n\n  // ----------------------------------------------------------------\n\n  /**\n   * State variables of the model.\n   * @note Copy constructor and assignment operator required because\n   *       of C-style arrays.\n   */\n  struct State_\n  {\n\n    /**\n     * Enumeration identifying elements in state vector State_::y_.\n     * This enum identifies the elements of the vector. It must be public to be\n     * accessible from the iteration function. The last two elements of this\n     * enum (DG, G) will be repeated\n     * n times at the end of the state vector State_::y with n being the number\n     * of synapses.\n     */\n    enum StateVecElems\n    {\n      V_M = 0,\n      W,  // 1\n      DG, // 2\n      G,  // 3\n      STATE_VECTOR_MIN_SIZE\n    };\n\n    static const size_t NUMBER_OF_FIXED_STATES_ELEMENTS = 2;        // V_M, W\n    static const size_t NUMBER_OF_STATES_ELEMENTS_PER_RECEPTOR = 2; // DG, G\n\n    std::vector< double > y_; //!< neuron state\n    int r_;                   //!< number of refractory steps remaining\n\n    State_( const Parameters_& ); //!< Default initialization\n    State_( const State_& );\n    State_& operator=( const State_& );\n\n    void get( DictionaryDatum& ) const;\n    void set( const DictionaryDatum& );\n\n  }; // State_\n\n  // ----------------------------------------------------------------\n\n  /**\n   * Buffers of the model.\n   */\n  struct Buffers_\n  {\n    Buffers_( aeif_cond_beta_multisynapse& );\n    Buffers_( const Buffers_&, aeif_cond_beta_multisynapse& );\n\n    //! Logger for all analog data\n    UniversalDataLogger< aeif_cond_beta_multisynapse > logger_;\n\n    /** buffers and sums up incoming spikes/currents */\n    std::vector< RingBuffer > spikes_;\n    RingBuffer currents_;\n\n    /** GSL ODE stuff */\n    gsl_odeiv_step* s_;    //!< stepping function\n    gsl_odeiv_control* c_; //!< adaptive stepsize control function\n    gsl_odeiv_evolve* e_;  //!< evolution function\n    gsl_odeiv_system sys_; //!< struct describing system\n\n    // IntergrationStep_ should be reset with the neuron on ResetNetwork,\n    // but remain unchanged during calibration. Since it is initialized with\n    // step_, and the resolution cannot change after nodes have been created,\n    // it is safe to place both here.\n    double step_;            //!< simulation step size in ms\n    double IntegrationStep_; //!< current integration time step,\n                             //!< updated by solver\n\n    /**\n     * Input current injected by CurrentEvent.\n     * This variable is used to transport the current applied into the\n     * _dynamics function computing the derivative of the state vector.\n     * It must be a part of Buffers_, since it is initialized once before\n     * the first simulation, but not modified before later Simulate calls.\n     */\n    double I_stim_;\n  };\n\n  // ----------------------------------------------------------------\n\n  /**\n   * Internal variables of the model.\n   */\n  struct Variables_\n  {\n\n    /** initial value to normalise synaptic conductance */\n    std::vector< double > g0_;\n\n    /**\n     * Threshold detection for spike events: P.V_peak if Delta_T > 0.,\n     * P.V_th if Delta_T == 0.\n     */\n    double V_peak;\n\n    unsigned int refractory_counts_;\n  };\n\n  // Access functions for UniversalDataLogger -------------------------------\n\n  //! Read out state vector elements, used by UniversalDataLogger\n  template < State_::StateVecElems elem >\n  double\n  get_y_elem_() const\n  {\n    return S_.y_[ elem ];\n  }\n\n  // Data members -----------------------------------------------------------\n\n  /**\n   * @defgroup aeif_cond_beta_multisynapse\n   * Instances of private data structures for the different types\n   * of data pertaining to the model.\n   * @note The order of definitions is important for speed.\n   * @{\n   */\n  Parameters_ P_;\n  State_ S_;\n  Variables_ V_;\n  Buffers_ B_;\n  /** @} */\n\n  //! Mapping of recordables names to access functions\n  static RecordablesMap< aeif_cond_beta_multisynapse > recordablesMap_;\n};\n\ninline port\naeif_cond_beta_multisynapse::send_test_event( Node& target,\n  rport receptor_type,\n  synindex,\n  bool )\n{\n  SpikeEvent e;\n  e.set_sender( *this );\n\n  return target.handles_test_event( e, receptor_type );\n}\n\ninline port\naeif_cond_beta_multisynapse::handles_test_event( CurrentEvent&,\n  rport receptor_type )\n{\n  if ( receptor_type != 0 )\n  {\n    throw UnknownReceptorType( receptor_type, get_name() );\n  }\n  return 0;\n}\n\ninline port\naeif_cond_beta_multisynapse::handles_test_event( DataLoggingRequest& dlr,\n  rport receptor_type )\n{\n  if ( receptor_type != 0 )\n  {\n    throw UnknownReceptorType( receptor_type, get_name() );\n  }\n  return B_.logger_.connect_logging_device( dlr, recordablesMap_ );\n}\n\ninline void\naeif_cond_beta_multisynapse::get_status( DictionaryDatum& d ) const\n{\n  P_.get( d );\n  S_.get( d );\n  Archiving_Node::get_status( d );\n\n  ( *d )[ names::recordables ] = recordablesMap_.get_list();\n}\n\ninline void\naeif_cond_beta_multisynapse::set_status( const DictionaryDatum& d )\n{\n  Parameters_ ptmp = P_; // temporary copy in case of errors\n  ptmp.set( d );         // throws if BadProperty\n  State_ stmp = S_;      // temporary copy in case of errors\n  stmp.set( d );         // throws if BadProperty\n\n  // We now know that (ptmp, stmp) are consistent. We do not\n  // write them back to (P_, S_) before we are also sure that\n  // the properties to be set in the parent class are internally\n  // consistent.\n  Archiving_Node::set_status( d );\n\n  // if we get here, temporaries contain consistent set of properties\n  P_ = ptmp;\n  S_ = stmp;\n}\n\n} // namespace\n\n#endif // HAVE_GSL\n#endif // AEIF_COND_BETA_MULTISYNAPSE_H //\n", "meta": {"hexsha": "d3d5b7876f1bfeb7e640442658962eb450a45499", "size": 14777, "ext": "h", "lang": "C", "max_stars_repo_path": "NEST-14.0-FPGA/models/aeif_cond_beta_multisynapse.h", "max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z", "max_issues_repo_path": "NEST-14.0-FPGA/models/aeif_cond_beta_multisynapse.h", "max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster", "max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z", "max_forks_repo_path": "NEST-14.0-FPGA/models/aeif_cond_beta_multisynapse.h", "max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z", "avg_line_length": 31.7103004292, "max_line_length": 80, "alphanum_fraction": 0.6533125804, "num_tokens": 3606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.36221434332600855}}
{"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file rk_6_2.c\n * \\brief Source file to optimize Runge-Kutta 6 steps 2nd order methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include <string.h>\n#include <math.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include <libintl.h>\n#include <gsl/gsl_rng.h>\n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"rk.h\"\n#include \"rk_6_2.h\"\n\n#define DEBUG_RK_6_2 0          ///< macro to debug.\n\n/**\n * Function to obtain the coefficients of a 6 steps 2nd order Runge-Kutta \n * method.\n */\nint\nrk_tb_6_2 (Optimize * optimize) ///< Optimize struct.\n{\n  long double *tb, *r;\n#if DEBUG_RK_6_2\n  fprintf (stderr, \"rk_tb_6_2: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t6 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  b21 (tb) = r[2];\n  t3 (tb) = r[3];\n  b31 (tb) = r[4];\n  b32 (tb) = r[5];\n  t4 (tb) = r[6];\n  b41 (tb) = r[7];\n  b42 (tb) = r[8];\n  b43 (tb) = r[9];\n  t5 (tb) = r[10];\n  b51 (tb) = r[11];\n  b52 (tb) = r[12];\n  b53 (tb) = r[13];\n  b54 (tb) = r[14];\n  b62 (tb) = r[15];\n  b63 (tb) = r[16];\n  b64 (tb) = r[17];\n  b65 (tb) = r[18];\n  b61 (tb) = (0.5L - b62 (tb) * t2 (tb) - b63 (tb) * t3 (tb)\n              - b64 (tb) * t4 (tb) - b65 (tb) * t5 (tb)) / t1 (tb);\n  if (isnan (b61 (tb)))\n    return 0;\n  rk_b_6 (tb);\n#if DEBUG_RK_6_2\n  rk_print_tb (optimize, \"rk_tb_6_2\", stderr);\n  fprintf (stderr, \"rk_tb_6_2: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 6 steps 2nd order, 3rd order in\n * equations depending only in time, Runge-Kutta method.\n */\nint\nrk_tb_6_2t (Optimize * optimize)        ///< Optimize struct.\n{\n  long double *tb, *r;\n#if DEBUG_RK_6_2\n  fprintf (stderr, \"rk_tb_6_2t: start\\n\");\n#endif\n  tb = optimize->coefficient;\n  r = optimize->random_data;\n  t6 (tb) = 1.L;\n  t1 (tb) = r[0];\n  t2 (tb) = r[1];\n  b21 (tb) = r[2];\n  t3 (tb) = r[3];\n  b31 (tb) = r[4];\n  b32 (tb) = r[5];\n  t4 (tb) = r[6];\n  b41 (tb) = r[7];\n  b42 (tb) = r[8];\n  b43 (tb) = r[9];\n  t5 (tb) = r[10];\n  b51 (tb) = r[11];\n  b52 (tb) = r[12];\n  b53 (tb) = r[13];\n  b54 (tb) = r[14];\n  b61 (tb) = r[15];\n  b62 (tb) = r[16];\n  b63 (tb) = r[17];\n  b64 (tb) = (1.L / 3.L - 0.5L * t5 (tb)\n              - b61 (tb) * t1 (tb) * (t1 (tb) - t5 (tb))\n              - b62 (tb) * t2 (tb) * (t2 (tb) - t5 (tb))\n              - b63 (tb) * t3 (tb) * (t3 (tb) - t5 (tb)))\n    / (t4 (tb) * (t4 (tb) - t5 (tb)));\n  if (isnan (b64 (tb)))\n    return 0;\n  b65 (tb) = (0.5L - b61 (tb) * t1 (tb) - b62 (tb) * t2 (tb)\n              - b63 (tb) * t3 (tb) - b64 (tb) * t4 (tb)) / t5 (tb);\n  if (isnan (b65 (tb)))\n    return 0;\n  rk_b_6 (tb);\n#if DEBUG_RK_6_2\n  rk_print_tb (optimize, \"rk_tb_6_2t\", stderr);\n  fprintf (stderr, \"rk_tb_6_2t: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 6 steps 1st-2nd order Runge-Kutta \n * pair.\n */\nint\nrk_tb_6_2p (Optimize * optimize)        ///< Optimize struct.\n{\n  long double *tb;\n#if DEBUG_RK_6_2\n  fprintf (stderr, \"rk_tb_6_2p: start\\n\");\n#endif\n  if (!rk_tb_6_2 (optimize))\n    return 0;\n  tb = optimize->coefficient;\n  e61 (tb) = e62 (tb) = e63 (tb) = e64 (tb) = 0.L;\n  rk_e_6 (tb);\n#if DEBUG_RK_6_2\n  fprintf (stderr, \"rk_tb_6_2p: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to obtain the coefficients of a 6 steps 1st-2nd order, 1st-3rd order\n * in equations depending only in time, Runge-Kutta pair.\n */\nint\nrk_tb_6_2tp (Optimize * optimize)       ///< Optimize struct.\n{\n  long double *tb;\n#if DEBUG_RK_6_2\n  fprintf (stderr, \"rk_tb_6_2tp: start\\n\");\n#endif\n  if (!rk_tb_6_2t (optimize))\n    return 0;\n  tb = optimize->coefficient;\n  e61 (tb) = e62 (tb) = e63 (tb) = e64 (tb) = 0.L;\n  rk_e_6 (tb);\n#if DEBUG_RK_6_2\n  fprintf (stderr, \"rk_tb_6_2tp: end\\n\");\n#endif\n  return 1;\n}\n\n/**\n * Function to calculate the objective function of a 6 steps 2nd order \n * Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_6_2 (RK * rk)   ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_6_2\n  fprintf (stderr, \"rk_objective_tb_6_2: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b60 (tb) < 0.L)\n    o += b60 (tb);\n  if (b61 (tb) < 0.L)\n    o += b61 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L,\n             fmaxl (t1 (tb),\n                    fmaxl (t2 (tb),\n                           fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_6_2\n  fprintf (stderr, \"rk_objective_tb_6_2: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_6_2: end\\n\");\n#endif\n  return o;\n}\n\n/**\n * Function to calculate the objective function of a 6 steps 2nd order, third\n * order in equations depending only on time, Runge-Kutta method.\n *\n * \\return objective function value.\n */\nlong double\nrk_objective_tb_6_2t (RK * rk)  ///< RK struct.\n{\n  long double *tb;\n  long double o;\n#if DEBUG_RK_6_2\n  fprintf (stderr, \"rk_objective_tb_6_2t: start\\n\");\n#endif\n  tb = rk->tb->coefficient;\n#if DEBUG_RK_6_2\n  rk_print_tb (optimize, \"rk_objective_tb_6_2t\", stderr);\n#endif\n  o = fminl (0.L, b20 (tb));\n  if (b30 (tb) < 0.L)\n    o += b30 (tb);\n  if (b40 (tb) < 0.L)\n    o += b40 (tb);\n  if (b50 (tb) < 0.L)\n    o += b50 (tb);\n  if (b60 (tb) < 0.L)\n    o += b60 (tb);\n  if (b64 (tb) < 0.L)\n    o += b64 (tb);\n  if (b65 (tb) < 0.L)\n    o += b65 (tb);\n  if (o < 0.L)\n    {\n      o = 40.L - o;\n      goto end;\n    }\n  o = 30.L\n    + fmaxl (1.L,\n             fmaxl (t1 (tb),\n                    fmaxl (t2 (tb),\n                           fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));\n  if (rk->strong)\n    {\n      rk_bucle_ac (rk);\n      o = fminl (o, *rk->ac0->optimal);\n    }\nend:\n#if DEBUG_RK_6_2\n  fprintf (stderr, \"rk_objective_tb_6_2t: optimal=%Lg\\n\", o);\n  fprintf (stderr, \"rk_objective_tb_6_2t: end\\n\");\n#endif\n  return o;\n}\n", "meta": {"hexsha": "277f47f514a3f51e65264c6bb28c1416558a4659", "size": 7416, "ext": "c", "lang": "C", "max_stars_repo_path": "rk_6_2.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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": "rk_6_2.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rk_6_2.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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.4845360825, "max_line_length": 80, "alphanum_fraction": 0.59600863, "num_tokens": 2745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3620491459819027}}
{"text": "//\n//  parameter.h\n//  EpiGenMCMC\n//\n//  Created by Lucy Li on 08/04/2016.\n//  Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved.\n//\n\n#ifndef EpiGenMCMC_parameter_h\n#define EpiGenMCMC_parameter_h\n\n\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_cdf.h>\n\n\nclass Parameter {\n    std::vector <double> parameter_values;\n    std::vector <std::string> parameter_names;\n    std::vector <bool> estimate;\n    std::vector <std::string> transform;\n    std::vector <std::string> prior;\n    std::vector <double> prior_par_1;\n    std::vector <double> prior_par_2;\n    std::vector <double> prior_par_3;\n    std::vector <std::string> proposal;\n    std::vector <double> proposal_sd;\n    std::vector <double> proposal_lower;\n    std::vector <double> proposal_upper;\n    std::vector <double> accepted;\n    std::vector <double> rejected;\n    std::vector <double> acceptance_rate;\n    std::vector <int> params_to_estim;\n    int total_params;\n    int curr_param_to_estimate;\n    double old_param_value;\n    double optimal_acceptance;\n    double lower_acceptance;\n    double upper_acceptance;\n    int adapt_every;\n    int max_adapt_times;\n    bool stop_adapting;\n    double get_prior(double, int) const;\n    double get_transform(double, std::string, bool) const;\npublic:\n    Parameter();\n    Parameter(const Parameter &);\n    Parameter (std::string);\n    bool is_estim(int) const;\n    int get_curr_estim() const;\n    void set_next_param();\n    int get_total_params() const;\n    int get_total_params_to_estim() const;\n    int get_estim_index(int) const;\n    double get(std::string) const;\n    double get(int) const;\n    double get_lower(int) const;\n    double get_upper(int) const;\n    void set(int, double);\n    std::vector<double> get_values_vector() const;\n    std::vector <std::string> get_names_vector() const;\n    std::string getname(int) const;\n    void reset();\n    void accept();\n    void reject();\n    double get_acceptance() const;\n    void stop_adapt();\n    void start_adapt();\n    void adapt();\n    double propose(gsl_rng *);\n    double get_prior_ratio() const;\n    double get_prior_all() const;\n    bool param_exists(std::string) const;\n    void transform_param(int, bool);\n    double get_lognormal_sd (double, double) const;\n    double get_lognormal_mean (double, double) const;\n};\n\n\n\nstruct MCMCoptions {\n    int particles;\n    int iterations;\n    int log_every;\n    int pfilter_every;\n    double pfilter_threshold;\n    int which_likelihood;\n    int num_trees;\n    std::string log_filename;\n    std::string traj_filename;\n    std::string model;\n    int total_dt;\n    double sim_dt;\n    int num_groups;\n    int seed;\n    bool verbose;\n    bool save_traj;\n    bool use_lhs;\n    int lhs_divides;\n    int lhs_iterations;\n    int num_threads;\n    double heat_factor;\n    int heat_length;\n    double cool_rate;\n    gsl_rng ** rng;\n    MCMCoptions();\n    MCMCoptions(const MCMCoptions&);\n    MCMCoptions(std::string);\n    \n};\n\n\n\n\n#endif\n", "meta": {"hexsha": "73f15bb8d2d2656217107e53435bd62629ad7a8e", "size": 3074, "ext": "h", "lang": "C", "max_stars_repo_path": "src/parameter.h", "max_stars_repo_name": "lucymli/EpiGenMCMC", "max_stars_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-04-01T09:55:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-09T16:14:41.000Z", "max_issues_repo_path": "src/parameter.h", "max_issues_repo_name": "lucymli/EpiGenMCMC", "max_issues_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-05T05:49:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-15T04:48:15.000Z", "max_forks_repo_path": "src/parameter.h", "max_forks_repo_name": "lucymli/EpiGenMCMC", "max_forks_repo_head_hexsha": "a30e18196c34d7ebcdf7ff51bad55c412d0b0ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-13T16:20:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-16T22:17:38.000Z", "avg_line_length": 24.9918699187, "max_line_length": 77, "alphanum_fraction": 0.6851008458, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.661922862511608, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3618984826059622}}
{"text": "#define MIN(a, b) ((a) < (b) ? (a) : (b))\n#define MAX(a, b) ((a) > (b) ? (a) : (b))\n\n#define DefaultWorkSize 1e9 // 1GB\n#define NumSplitDefaultMax 20\n\n#define OUTPUT stdout // stderr\n\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cmath> \n#include <iostream>\n#include <typeinfo>\n\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#include <sys/time.h>\n#include <float.h>\n\n#if defined (MKL)\n#include <mkl_cblas.h>\n#include <mkl_trans.h>\n#include <mkl_spblas.h>\n#else\n#include <cblas.h>\n#endif\n\n#include <omp.h>\n\n#if defined (FLOAT128)\n#if defined (ARM)\n#define __float128 long double\n#define FLT128_MAX LDBL_MAX\n#define FLT128_MIN LDBL_MIN\n#else\n#include <quadmath.h>\n#endif\n//#ifdef __INTEL_COMPILER\n//__float128 std::abs (const __float128 x);\n//#endif\n#include <mplapack/mpblas__Float128.h>\n#endif\n\n#if defined (CUBLAS)\n#include <cuda.h>\n#include <cuda_runtime_api.h>\n#include <cublas_v2.h>\n#endif\n\n#include \"../../include/ozblas.h\"\n#include \"ozblas_internal.h\"\n\n// -------------------------------------\n// constexpr functions\n// -------------------------------------\n\n// -------------------------------------\n// getEmin\n// -------------------------------------\ntemplate <typename TYPE>\nconstexpr int32_t getEmin () {\n\tfprintf (OUTPUT, \"OzBLAS error: TYPE is not specified in getEmin.\\n\");\n\texit (1);\n\treturn 0;\n}\ntemplate <>\nconstexpr int32_t getEmin <float> () {\n\treturn -126;\n}\ntemplate <>\nconstexpr int32_t getEmin <double> () {\n\treturn -1022;\n}\n#if defined (FLOAT128)\ntemplate <>\nconstexpr int32_t getEmin <__float128> () {\n\treturn -16382;\n}\n#endif\n\n// -------------------------------------\n// getEpse\n// -------------------------------------\ntemplate <typename TYPE>\nconstexpr int32_t getEpse () {\n\tfprintf (OUTPUT, \"OzBLAS error: TYPE is not specified in getEpse.\\n\");\n\texit (1);\n\treturn 0;\n}\ntemplate <>\nconstexpr int32_t getEpse <float> () {\n\treturn 24;\n}\ntemplate <>\nconstexpr int32_t getEpse <double> () {\n\treturn 53;\n}\n#if defined (FLOAT128)\ntemplate <>\nconstexpr int32_t getEpse <__float128> () {\n\treturn 113;\n}\n#endif\n\n// -------------------------------------\n// getTypeMax\n// -------------------------------------\ntemplate <typename TYPE>\nconstexpr TYPE getTypeMax () {\n\tfprintf (OUTPUT, \"OzBLAS error: TYPE is not specified in getTypeMax.\\n\");\n\texit (1);\n\treturn 0;\n}\ntemplate <>\nconstexpr float getTypeMax <float> () {\n\treturn FLT_MAX;\n}\ntemplate <>\nconstexpr double getTypeMax <double> () {\n\treturn DBL_MAX;\n}\n#if defined (FLOAT128)\ntemplate <>\nconstexpr __float128 getTypeMax <__float128> () {\n\treturn FLT128_MAX;\n}\n#endif\n\n// -------------------------------------\n// getTypeMin\n// -------------------------------------\ntemplate <typename TYPE>\nconstexpr TYPE getTypeMin () {\n\tfprintf (OUTPUT, \"OzBLAS error: TYPE is not specified in getTypeMin.\\n\");\n\texit (1);\n\treturn 0;\n}\ntemplate <>\nconstexpr float getTypeMin <float> () {\n\treturn FLT_MIN;\n}\ntemplate <>\nconstexpr double getTypeMin <double> () {\n\treturn DBL_MIN;\n}\n#if defined (FLOAT128)\ntemplate <>\nconstexpr __float128 getTypeMin <__float128> () {\n\treturn FLT128_MIN;\n}\n#endif\n\n/*\n#define SCALBN scalbnl\n#define LOG2 log2l\n#define LOG logl\n#define CEIL ceill\n#define FABS fabsl\n*/\n", "meta": {"hexsha": "c77ae4ec9c82c99e1cab6547d5290e0d38e6a1e6", "size": 3175, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cpu/ozblas_common.h", "max_stars_repo_name": "wsmoses/Riken-blas", "max_stars_repo_head_hexsha": "97c20aa5d8e186790aa505f6be4d1f48eee352e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpu/ozblas_common.h", "max_issues_repo_name": "wsmoses/Riken-blas", "max_issues_repo_head_hexsha": "97c20aa5d8e186790aa505f6be4d1f48eee352e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpu/ozblas_common.h", "max_forks_repo_name": "wsmoses/Riken-blas", "max_forks_repo_head_hexsha": "97c20aa5d8e186790aa505f6be4d1f48eee352e3", "max_forks_repo_licenses": ["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.7204968944, "max_line_length": 74, "alphanum_fraction": 0.617007874, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.36168323196501356}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n#include <gbpInterpolate.h>\n\n// params is not used at the moment but we must allow for\n//   it to meet the required ADaPS function definition\nvoid free_interpolate(void **interp, void *params) {\n    if((*interp) != NULL) {\n        SID_free(SID_FARG((interp_info *)(*interp))->x);\n        SID_free(SID_FARG((interp_info *)(*interp))->y);\n        gsl_interp_free(((interp_info *)(*interp))->interp);\n        gsl_interp_accel_free(((interp_info *)(*interp))->accel);\n        SID_free(SID_FARG * interp);\n    }\n}\n", "meta": {"hexsha": "9956115ec58b01bf6b583f69989396569ffde763", "size": 621, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpInterpolate/free_interpolate.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpMath/gbpInterpolate/free_interpolate.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpMath/gbpInterpolate/free_interpolate.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 32.6842105263, "max_line_length": 65, "alphanum_fraction": 0.6602254428, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.36128810180239307}}
{"text": "#ifndef TNet_Types_h\n#define TNet_Types_h\n\n#ifdef HAVE_ATLAS\nextern \"C\"{\n  #include <cblas.h>\n  #include <clapack.h>\n}\n#endif\n\n\nnamespace TNet \n{\n  // TYPEDEFS ..................................................................\n#if DOUBLEPRECISION\n  typedef double  BaseFloat;\n#else\n  typedef float   BaseFloat;\n#endif\n\n#ifndef UINT_16\n  typedef unsigned short  UINT_16   ;\n  typedef unsigned        UINT_32   ;\n  typedef short           INT_16    ;\n  typedef int             INT_32    ;\n  typedef float           FLOAT_32  ;\n  typedef double          DOUBLE_64 ;\n#endif\n\n\n\n  // ...........................................................................\n  // The following declaration assumes that SSE instructions are enabled\n  // and that we are using GNU C/C++ compiler, which defines the __attribute__ \n  // notation.\n  //\n  // ENABLE_SSE is defined in <config.h>. Its value depends on options given\n  // in the configure phase of builidng the library\n#if defined(__GNUC__ )\n  // vector of four single floats\n  typedef float  v4sf __attribute__((vector_size(16))); \n  // vector of two single doubles\n  typedef double v2sd __attribute__((vector_size(16))); \n\n  typedef BaseFloat BaseFloat16Aligned __attribute__((aligned(16))) ;\n\n  typedef union \n  {\n    v4sf    v;\n    float   f[4];\n  } f4vector; \n\n  typedef union \n  {\n    v2sd    v;\n    double  f[2];\n  } d2vector; \n#endif // ENABLE_SSE && defined(__GNUC__ )\n\n\n\n  typedef enum\n  {\n#ifdef HAVE_ATLAS\n    TRANS    = CblasTrans,\n    NO_TRANS = CblasNoTrans\n#else\n    TRANS    = 'T',\n    NO_TRANS = 'N'\n#endif\n  } MatrixTrasposeType;\n\n\n\n} // namespace TNet\n\n#endif // #ifndef TNet_Types_h\n\n", "meta": {"hexsha": "6a5bfac14b99140720fdfd97be71bada2bee2490", "size": 1642, "ext": "h", "lang": "C", "max_stars_repo_path": "src/KaldiLib/Types.h", "max_stars_repo_name": "troylee/nnet-asr", "max_stars_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/KaldiLib/Types.h", "max_issues_repo_name": "troylee/nnet-asr", "max_issues_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/KaldiLib/Types.h", "max_forks_repo_name": "troylee/nnet-asr", "max_forks_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d", "max_forks_repo_licenses": ["Apache-2.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.7848101266, "max_line_length": 80, "alphanum_fraction": 0.5998781973, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3612880938297934}}
{"text": "#include <linux/types.h>\r\n#include \"sweeny_uf.h\"\r\n#include \"extract_args.h\"\r\n#include \"timeseries.h\"\r\n#include <stdio.h>\r\n#include <stdio.h>\r\n#include <math.h>\r\n#include <gsl/gsl_rng.h> //Verwendung von Mersenne-Twister Pseudozufallszahlengenerator\r\n\r\n#define TS_FILE_D \"../time_series/uf/simulation_l%u_q%.4f_b%.4f_c%.4f_s%u.hdf5\"\r\n#define BUF_LEN 512\r\nchar fn[BUF_LEN];\r\nchar impl_title[] = \"Union-Find implementation\";\r\n\r\nchar verbose=0;\r\n__u64 *four_cs_moment ;\r\n__u64 *sec_cs_moment ;\r\n__u32 *size_giant;\r\n__u32 *num_bonds;\r\n__u32 *num_cluster;\r\n__u32 DX;\r\n__u32 N;\r\n__u32 seed=123456;\r\ndouble q=2; \r\ndouble coupling;\r\ndouble beta;\r\ndouble v;\r\ndouble K;\r\n__u32 steps;\r\n__u32 cutoff;\r\nint main(int argc, char *argv[])\r\n{\r\n\r\n    if(!extractArgs(argc, argv,impl_title))\r\n      return EXIT_FAILURE;\r\n    snprintf(fn,BUF_LEN,TS_FILE_D,DX,q,beta,coupling,seed);\r\n    if(!init_observables())\r\n        return EXIT_FAILURE;\r\n    if(!init_sweeny_uf( q,DX,beta,coupling,cutoff,steps,seed,num_bonds,num_cluster,size_giant,sec_cs_moment,four_cs_moment))\r\n        return EXIT_FAILURE;\r\n    if(!simulate_sweeny_uf())\r\n        return EXIT_FAILURE;\r\n    destroy_sweeny_uf();\r\n    save_timeseries();\r\n    destroy_observables();\r\n    return EXIT_SUCCESS;\r\n}\r\n/******************************************************************************\r\n *****************************************************************************/\r\n", "meta": {"hexsha": "d840baa8419cf3a7b9cddc68283094b468c3b576", "size": 1407, "ext": "c", "lang": "C", "max_stars_repo_path": "src/sy_uf_mc.c", "max_stars_repo_name": "ernmeel/sweeny", "max_stars_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-03T10:57:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-10T14:18:40.000Z", "max_issues_repo_path": "src/sy_uf_mc.c", "max_issues_repo_name": "ernmeel/sweeny", "max_issues_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-19T09:29:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-20T09:32:03.000Z", "max_forks_repo_path": "src/sy_uf_mc.c", "max_forks_repo_name": "ermeel86/sweeny", "max_forks_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-04-10T14:18:57.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-10T14:18:57.000Z", "avg_line_length": 28.14, "max_line_length": 125, "alphanum_fraction": 0.6254442075, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.36116192442933465}}
{"text": "/**\n * \\file IIRFilter.h\n */\n\n#ifndef ATK_EQ_IIRFILTER_H\n#define ATK_EQ_IIRFILTER_H\n\n#include <algorithm>\n#include <cassert>\n#include <vector>\n\n#include <gsl/gsl>\n\n#include <ATK/config.h>\n#include <ATK/Core/TypeTraits.h>\n#include <ATK/EQ/config.h>\n\nnamespace ATK\n{\n  /// IIR filter template class (Direct Form I)\n  template<class Coefficients >\n  class IIRFilter final : public Coefficients\n  {\n  protected:\n    /// Simplify parent calls\n    using Parent = Coefficients;\n    using typename Parent::DataType;\n    using typename Parent::AlignedScalarVector;\n    using Parent::converted_inputs;\n    using Parent::outputs;\n    using Parent::coefficients_in;\n    using Parent::coefficients_out;\n    using Parent::input_sampling_rate;\n    using Parent::output_sampling_rate;\n    using Parent::nb_input_ports;\n    using Parent::nb_output_ports;\n    \n    using Parent::in_order;\n    using Parent::out_order;\n    using Parent::input_delay;\n    using Parent::output_delay;\n    using Parent::setup;\n    \n  public:\n    /*!\n     * @brief Constructor\n     * @param nb_channels is the number of input and output channels\n     */\n    explicit IIRFilter(gsl::index nb_channels = 1)\n      :Parent(nb_channels)\n    {\n    }\n\n    /// Move constructor\n    IIRFilter(IIRFilter&& other)\n    :Parent(std::move(other))\n    {\n    }\n\n    void setup() final\n    {\n      Parent::setup();\n      input_delay = in_order;\n      output_delay = out_order;\n\n      if (out_order > 0)\n      {\n        coefficients_out_2.resize(out_order, 0);\n        for (unsigned int i = 1; i < out_order; ++i)\n        {\n          coefficients_out_2[i] = coefficients_out[out_order - 1] * coefficients_out[i] + coefficients_out[i - 1];\n        }\n        coefficients_out_2[0] = coefficients_out[out_order - 1] * coefficients_out[0];\n      }\n      if (out_order > 1)\n      {\n        coefficients_out_3.resize(out_order, 0);\n        for (unsigned int i = 0; i < 2; ++i)\n        {\n          coefficients_out_3[i] = coefficients_out[out_order - 2]  * coefficients_out[i] + coefficients_out[out_order - 1] * coefficients_out_2[i];\n        }\n        for (unsigned int i = 2; i < out_order; ++i)\n        {\n          coefficients_out_3[i] = coefficients_out[out_order - 2]  * coefficients_out[i] + coefficients_out[out_order - 1] * coefficients_out_2[i] + coefficients_out[i - 2];\n        }\n        if (out_order > 2)\n        {\n          coefficients_out_4.resize(out_order, 0);\n          for (unsigned int i = 0; i < 3; ++i)\n          {\n            coefficients_out_4[i] = coefficients_out[out_order - 3]  * coefficients_out[i] + coefficients_out[out_order - 2] * coefficients_out_2[i] + coefficients_out[out_order - 1] * coefficients_out_3[i];\n          }\n          for (unsigned int i = 3; i < out_order; ++i)\n          {\n            coefficients_out_4[i] = coefficients_out[out_order - 3]  * coefficients_out[i] + coefficients_out[out_order - 2] * coefficients_out_2[i] + coefficients_out[out_order - 1] * coefficients_out_3[i] + coefficients_out[i - 3];\n          }\n        }\n        else // out_order = 2\n        {\n          coefficients_out_4.resize(out_order, 0);\n          for (unsigned int i = 0; i < 2; ++i)\n          {\n            coefficients_out_4[i] = coefficients_out[out_order - 2] * coefficients_out_2[i] + coefficients_out[out_order - 1] * coefficients_out_3[i];\n          }\n        }\n      }\n    }\n    \n    template<typename T>\n    void handle_recursive_iir(const T* ATK_RESTRICT coefficients_out_ptr, const T* ATK_RESTRICT coefficients_out_2_ptr, const T* ATK_RESTRICT coefficients_out_3_ptr, const T* ATK_RESTRICT coefficients_out_4_ptr, DataType* ATK_RESTRICT output, gsl::index size) const\n    {\n      gsl::index i = 0;\n      if (out_order > 2)\n      {\n        for (i = 0; i < std::min(size - 3, size); i += 4)\n        {\n          DataType tempout = output[i];\n          DataType tempout2 = output[i] * coefficients_out_ptr[out_order - 1] + output[i + 1];\n          DataType tempout3 = output[i] * coefficients_out_ptr[out_order - 2] + tempout2 * coefficients_out_ptr[out_order - 1] + output[i + 2];\n          DataType tempout4 = output[i] * coefficients_out_ptr[out_order - 3] + tempout2 * coefficients_out_ptr[out_order - 2] + tempout3 * coefficients_out_ptr[out_order - 1] + output[i + 3];\n          \n          ATK_VECTORIZE_REMAINDER for (unsigned int j = 0; j < out_order; ++j)\n          {\n            tempout += coefficients_out_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];\n            tempout2 += coefficients_out_2_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];\n            tempout3 += coefficients_out_3_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];\n            tempout4 += coefficients_out_4_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];\n          }\n          output[i] = tempout;\n          output[i + 1] = tempout2;\n          output[i + 2] = tempout3;\n          output[i + 3] = tempout4;\n        }\n      }\n      else if(out_order == 2)\n      {\n        for (i = 0; i < std::min(size - 3, size); i += 4)\n        {\n          DataType tempout = output[i];\n          DataType tempout2 = output[i] * coefficients_out_ptr[out_order - 1] + output[i + 1];\n          DataType tempout3 = output[i] * coefficients_out_ptr[out_order - 2] + tempout2 * coefficients_out_ptr[out_order - 1] + output[i + 2];\n          DataType tempout4 = tempout2 * coefficients_out_ptr[out_order - 2] + tempout3 * coefficients_out_ptr[out_order - 1] + output[i + 3];\n          \n          ATK_VECTORIZE_REMAINDER for (unsigned int j = 0; j < out_order; ++j)\n          {\n            tempout += coefficients_out_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];\n            tempout2 += coefficients_out_2_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];\n            tempout3 += coefficients_out_3_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];\n            tempout4 += coefficients_out_4_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];\n          }\n          output[i] = tempout;\n          output[i + 1] = tempout2;\n          output[i + 2] = tempout3;\n          output[i + 3] = tempout4;\n        }\n      }\n      for (; i < size; ++i)\n      {\n        DataType tempout = output[i];\n        for (unsigned int j = 0; j < out_order; ++j)\n        {\n          tempout += coefficients_out_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];\n        }\n        output[i] = tempout;\n      }\n    }\n    \n    void process_impl(gsl::index size) const final\n    {\n      assert(input_sampling_rate == output_sampling_rate);\n      assert(nb_input_ports == nb_output_ports);\n      assert(coefficients_in.data());\n      assert(out_order == 0 || coefficients_out.data() != nullptr);\n\n      const auto* ATK_RESTRICT coefficients_in_ptr = coefficients_in.data();\n      const auto* ATK_RESTRICT coefficients_out_ptr = coefficients_out.data();\n      const auto* ATK_RESTRICT coefficients_out_2_ptr = coefficients_out_2.data();\n      const auto* ATK_RESTRICT coefficients_out_3_ptr = coefficients_out_3.data();\n      const auto* ATK_RESTRICT coefficients_out_4_ptr = coefficients_out_4.data();\n\n      for(gsl::index channel = 0; channel < nb_input_ports; ++channel)\n      {\n        const DataType* ATK_RESTRICT input = converted_inputs[channel] - static_cast<int64_t>(in_order);\n        DataType* ATK_RESTRICT output = outputs[channel];\n\n        for(gsl::index i = 0; i < size; ++i)\n        {\n          output[i] = 0;\n        }\n\n        for (gsl::index j = 0; j < in_order + 1; ++j)\n        {\n          for (gsl::index i = 0; i < size; ++i)\n          {\n            output[i] += coefficients_in_ptr[j] * input[i + j];\n          }\n        }\n\n        handle_recursive_iir(coefficients_out_ptr, coefficients_out_2_ptr, coefficients_out_3_ptr, coefficients_out_4_ptr, output, size);\n      }\n    }\n    \n    /// Returns the vector of internal coefficients for the MA section \n    const AlignedScalarVector& get_coefficients_in() const\n    {\n      return coefficients_in;\n    }\n    \n    /// Returns the vector of internal coefficients for the AR section, without degree 0 implicitely set to -1\n    const AlignedScalarVector& get_coefficients_out() const\n    {\n      return coefficients_out;\n    }\n\n  protected:\n    AlignedScalarVector coefficients_out_2;\n    AlignedScalarVector coefficients_out_3;\n    AlignedScalarVector coefficients_out_4;\n  };\n\n  /// IIR filter template class. Transposed Direct Form II implementation\n  template<class Coefficients >\n  class IIRTDF2Filter final : public Coefficients\n  {\n  public:\n    /// Simplify parent calls\n    using Parent = Coefficients;\n    using typename Parent::DataType;\n    using typename Parent::AlignedScalarVector;\n    using Parent::converted_inputs;\n    using Parent::outputs;\n    using Parent::coefficients_in;\n    using Parent::coefficients_out;\n    using Parent::input_sampling_rate;\n    using Parent::output_sampling_rate;\n    using Parent::nb_input_ports;\n    using Parent::nb_output_ports;\n    \n    using Parent::in_order;\n    using Parent::out_order;\n    using Parent::input_delay;\n    using Parent::output_delay;\n    using Parent::setup;\n  protected:\n    mutable typename Parent::AlignedVector state;\n  public:\n    explicit IIRTDF2Filter(gsl::index nb_channels = 1)\n      :Parent(nb_channels)\n    {\n    }\n    \n    /// Move constructor\n    IIRTDF2Filter(IIRTDF2Filter&& other)\n      :Parent(std::move(other))\n    {\n    }\n    \n    void setup() final\n    {\n      Parent::setup();\n      input_delay = in_order;\n      output_delay = out_order;\n      state.assign(nb_input_ports * (std::max(input_delay, output_delay) + 1), TypeTraits<DataType>::Zero());\n    }\n    \n    void process_impl(gsl::index size) const final\n    {\n      assert(input_sampling_rate == output_sampling_rate);\n      \n      for(gsl::index channel = 0; channel < nb_input_ports; ++channel)\n      {\n        const DataType* ATK_RESTRICT input = converted_inputs[channel];\n        DataType* ATK_RESTRICT output = outputs[channel];\n        DataType* ATK_RESTRICT current_state = &state[channel * (std::max(input_delay, output_delay) + 1)];\n        \n        for(gsl::index i = 0; i < size; ++i)\n        {\n          output[i] = coefficients_in[in_order] * input[i] + current_state[0];\n          auto min_order = std::min(input_delay, output_delay);\n          \n          for(gsl::index j = 0; j < min_order; ++j)\n          {\n            current_state[j] = current_state[j + 1] + input[i] * coefficients_in[in_order - static_cast<int64_t>(j) - 1] + output[i] * coefficients_out[out_order - static_cast<int64_t>(j) - 1];\n          }\n          for(gsl::index j = min_order; j < input_delay; ++j)\n          {\n            current_state[j] = current_state[j + 1] + input[i] * coefficients_in[in_order - static_cast<int64_t>(j) - 1];\n          }\n          for(gsl::index j = min_order; j < output_delay; ++j)\n          {\n            current_state[j] = current_state[j + 1] + output[i] * coefficients_out[out_order - static_cast<int64_t>(j) - 1];\n          }\n        }\n      }\n    }\n\n    /// Returns the vector of internal coefficients for the MA section\n    const AlignedScalarVector& get_coefficients_in() const\n    {\n      return coefficients_in;\n    }\n    \n    /// Returns the vector of internal coefficients for the AR section, without degree 0 implicitely set to -1\n    const AlignedScalarVector& get_coefficients_out() const\n    {\n      return coefficients_out;\n    }\n  };\n\n}\n\n#endif\n", "meta": {"hexsha": "1406a91ebf6ff1af77bbb6db0d0466d4a50fa7fe", "size": 11393, "ext": "h", "lang": "C", "max_stars_repo_path": "ATK/EQ/IIRFilter.h", "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/IIRFilter.h", "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/IIRFilter.h", "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": 36.3993610224, "max_line_length": 265, "alphanum_fraction": 0.6248573686, "num_tokens": 2932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.3611619180957901}}
{"text": "/* specfunc/elementary.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include \"gsl_sf_elementary.h\"\n\n#include \"error.h\"\n#include \"check.h\"\n\nint\ngsl_sf_multiply_e(const double x, const double y, gsl_sf_result * result)\n{\n  const double ax = fabs(x);\n  const double ay = fabs(y);\n\n  if(x == 0.0 || y == 0.0) {\n    /* It is necessary to eliminate this immediately.\n     */\n    result->val = 0.0;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if((ax <= 1.0 && ay >= 1.0) || (ay <= 1.0 && ax >= 1.0)) {\n    /* Straddling 1.0 is always safe.\n     */\n    result->val = x*y;\n    result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    const double f = 1.0 - 2.0 * GSL_DBL_EPSILON;\n    const double min = GSL_MIN_DBL(fabs(x), fabs(y));\n    const double max = GSL_MAX_DBL(fabs(x), fabs(y));\n    if(max < 0.9 * GSL_SQRT_DBL_MAX || min < (f * DBL_MAX)/max) {\n      result->val = GSL_COERCE_DBL(x*y);\n      result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n      CHECK_UNDERFLOW(result);\n      return GSL_SUCCESS;\n    }\n    else {\n      OVERFLOW_ERROR(result);\n    }\n  }\n}\n\n\nint\ngsl_sf_multiply_err_e(const double x, const double dx,\n                         const double y, const double dy,\n                         gsl_sf_result * result)\n{\n  int status = gsl_sf_multiply_e(x, y, result);\n  result->err += fabs(dx*y) + fabs(dy*x);\n  return status;\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_multiply(const double x, const double y)\n{\n  EVAL_RESULT(gsl_sf_multiply_e(x, y, &result));\n}\n\n", "meta": {"hexsha": "6491ce14fbb0d9513e80e4e30ceb705663d70a22", "size": 2436, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/elementary.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/elementary.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/specfunc/elementary.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 28.0, "max_line_length": 75, "alphanum_fraction": 0.6379310345, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3611570421707804}}
{"text": "#include <viaio/VImage.h>\n#include <math.h>\n#include <string.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_math.h>\n#include \"gsl_utils.h\"\n\n#define ABS(x) ((x) >= 0) ? (x) : -(x)\n#define MIN(a,b) ((a) < (b)) ? (a) : (b)\n#define MAX(a,b) ((a) > (b)) ? (a) : (b)\n#define ROUND(x) (int)(((x) >= 0) ? ((x) + 0.5) : ((x) - 0.5))\n\n\nvoid whitecov2(VImage effect_image,VImage rho_vol,\n\t       gsl_matrix_float* Y, gsl_matrix_float* X, gsl_matrix_float* con,\n\t       VFloat* Dfs, int numlags, int slice)\n{\n  int numcon = 1;\n  int n = Y->size1;\n  VFloat Df = Dfs[numcon];\n    \n  int i=0,j=0,k=0;\n\n  /* some checks and warnings */\n  if(X->size2 != n) \n    VError(\"whitecov2: Warning! sizes of design and data matrix do not match, n=%d, %ld\",n,X->size2);        \n\n  if(X->size1 != con->size2) \n    VError(\"whitecov2: Warning! contrast and design do not match.\");\n\n  gsl_vector_float* irho = gsl_vector_float_alloc(VImageNBands(rho_vol));\n  if(numlags == 1) {\n    float* p = irho->data;\n    const float drho = 0.01; \n    for(i=0;i<irho->size;i++) {\n      float tmp = ROUND((VPixel(rho_vol, i, slice, 0, VFloat) / drho)) * drho;\n      tmp = MIN(tmp, (1-drho));\n      tmp = MAX(tmp, (-1+drho));             \n      *p++ = tmp;\n    }\n  }\n  else {\n    float* p = irho->data;\n    for(i=1;i<=irho->size;i++)\n      *p++ = i;\n  }\n\n  /* : X=X';  */\n  gsl_matrix_float* transX = gsl_matrix_float_alloc(X->size2, X->size1);\n  gsl_matrix_float_transpose_memcpy(transX, X);\n    \n  /* : Xstar=X; */\n  gsl_matrix_float* XStar = gsl_matrix_float_alloc(transX->size1, transX->size2);\n  gsl_matrix_float_memcpy(XStar, transX);\n\n  /* END allocate memory buffer */\n\n  /****************************** order == 1 *****************************/\n  if (numlags == 1) {\n\n    /* allocate memory buffers */\n    gsl_vector_float* pixBig = gsl_vector_float_alloc(irho->size);\n    gsl_matrix_float* pinvXStar = gsl_matrix_float_alloc(XStar->size2, XStar->size1);\n    gsl_matrix_float* V = gsl_matrix_float_alloc(pinvXStar->size1, pinvXStar->size1);\n    gsl_matrix_float* buffer_01 = gsl_matrix_float_alloc(con->size1,V->size2);\n    gsl_matrix_float* buffer_02 = gsl_matrix_float_alloc(con->size1,con->size1);\n    gsl_matrix_float* cVcinv = gsl_matrix_float_alloc(con->size1, con->size1);\n    \n    gsl_vector_float* u = funique(irho); \n    float* rho = u->data;\n    for(i=0;i<u->size;i++) {\n\n      /* :  pix=int16(find(irho==rho)); */\n      float* p = irho->data;\n      float* ppB = pixBig->data;\n      int counter = 0;\n      for(j=0;j<irho->size;j++) {\n\tif(*p++ == *rho) {\n\t  *ppB++ = (float)j;\n\t  counter++;\n\t}\n      }\n      gsl_vector_float* pix = gsl_vector_float_alloc(counter);\n      ppB = pixBig->data;\n      float* pp = pix->data;\n      for(j=0;j<counter;j++) *pp++ = *ppB++;            \n\n      /* : Ystar=Y(:,pix); */\n      gsl_matrix_float* YStar = fmat_subcols(Y,pix);\n\n      /* : factor=1./sqrt(1-rho^2); */\n      float factor = pow(1 - *rho * *rho, -0.5);\n\n      /* : Ystar(k1,:)=(Y(k1,pix)-rho*Y(k1-1,pix))*factor; */ \n      /* point to last element */\n      float* pStar = YStar->data+(YStar->size1*YStar->size2)-1;\n      /* traverse matrix in reverse order */\n      for (j = 0; j < (YStar->size1-1)*YStar->size2; ++j) {\n\t*pStar = (*pStar - *rho * *(pStar - YStar->size2)) * factor;\n\tpStar--;\n      }            \n\n      /* : Xstar(k1,:)=(X(k1,:)-rho*X(k1-1,:))*factor; */\n      pStar = XStar->data+XStar->size2;\n      float* pX = transX->data+transX->size2;\n      for (j = 0; j < (XStar->size1-1)*XStar->size2; ++j) {\n\t*pStar++ = (*pX - *rho * *(pX - transX->size2)) * factor;\n\tpX++;\n      }\n\n      /* : pinvXstar=pinv(Xstar); */\n      fmat_PseudoInv(XStar,pinvXStar);\n\n      /* : betahat=pinvXstar*Ystar; */\n      gsl_matrix_float* betahat = fmat_x_mat(pinvXStar, YStar,NULL);\n\n      /* : resid=Ystar-Xstar*betahat; */\n      gsl_matrix_float* buffer = fmat_x_mat(XStar, betahat, NULL);\n      gsl_matrix_float_sub(YStar, buffer);\n      gsl_matrix_float* resid =  YStar;\n      gsl_matrix_float_free(buffer);\n\n      /* : SSE=sum(resid.^2,1); */\n      buffer = gsl_matrix_float_alloc(resid->size1, resid->size2);\n      gsl_matrix_float_memcpy (buffer, resid);\n      gsl_matrix_float_mul_elements (buffer, buffer);\n      gsl_vector_float* sse = fsum(buffer, 1,NULL);\n      gsl_matrix_float_free(buffer);\n\n      /* : sd=sqrt(SSE/Df); */\n      gsl_vector_float* sd = gsl_vector_float_alloc(sse->size);\n      float* pSSE = sse->data;\n      float* pSD = sd->data;\n      for (j = 0; j < sse->size; ++j) {\n\t*pSD++ = (float)sqrt(*pSSE++/Df);\n      }\n\n      /* :   V=pinvXstar*pinvXstar'; */\n      fmat_x_matT(pinvXStar, pinvXStar, V);\n\n      /* : mag_ef=contrast*betahat; */\n      gsl_matrix_float* mag_ef = fmat_x_mat(con, betahat, NULL);\n\n      /* : mag_sd=sqrt(diag(contrast*V*contrast'))*sd; */\n      fmat_x_mat(con,V,buffer_01);\n      fmat_x_matT(buffer_01, con, buffer_02);            \n\n      gsl_vector_float_view diag = gsl_matrix_float_diagonal(buffer_02);\n      gsl_matrix_float* mag_sd = gsl_matrix_float_alloc(diag.vector.size, sd->size);\n      float* pMag = mag_sd->data;\n      for (j = 0; j < diag.vector.size; ++j) {\n\tfloat s = sqrt(gsl_vector_float_get(&diag.vector,j)); \n\tpSD = sd->data;\n\tfor (k = 0; k < sd->size; ++k) {\n\t  *pMag++ = s * (*pSD++);\n\t}\n      }\n\n      /* effect_slice(pix,1)= (mag_ef./(mag_sd+(mag_sd<=0)).*(mag_sd>0))'; */\n      VFloat* peff = VPixelPtr(effect_image,slice,0,0);\n      float* pmeff = mag_ef->data;\n      float* pmsd = mag_sd->data;\n      float* ppix = pix->data;\n      for (j=0; j<pix->size; ++j) {\n\t*(peff+(int)*ppix++) = *pmeff / (*pmsd+(*pmsd<=0)) * (*pmsd>0);\n\tpmeff++; pmsd++;\n      }\n            \n      /* free some memory */\n      gsl_matrix_float_free(betahat);\n      gsl_matrix_float_free(YStar);           \n      gsl_matrix_float_free(mag_ef);\n      gsl_matrix_float_free(mag_sd);\n      gsl_vector_float_free(pix);\n      gsl_vector_float_free(sse);\n      gsl_vector_float_free(sd);\n      \n      rho++;\n    } /* END for(i=0;i<u->size;i++)  */\n\n    /* free some memory */\n    gsl_vector_float_free(pixBig);\n    gsl_matrix_float_free(pinvXStar);\n    gsl_matrix_float_free(V);\n    gsl_matrix_float_free(buffer_01);\n    gsl_matrix_float_free(buffer_02);\n    gsl_matrix_float_free(cVcinv);\n\n  } /******************* END order == 1 **********************************/ \n    \n/*************************** order > 1 *********************************/\n    else{\n\n      /* allocate memory buffer */\n      gsl_vector_float* Coradj_pix = gsl_vector_float_alloc(VImageNColumns(rho_vol)+1);\n      gsl_matrix_float* Ainv = gsl_matrix_float_alloc(Coradj_pix->size, Coradj_pix->size);\n      gsl_matrix* dbuff = gsl_matrix_alloc(Ainv->size1,Ainv->size2);\n      gsl_matrix_float* A = gsl_matrix_float_alloc(Ainv->size1,Ainv->size2);\n      int nl = Ainv->size2;\n      gsl_matrix_float* buffer_01 = gsl_matrix_float_alloc(n-nl,1);\n      gsl_matrix_float* buffer_02 = gsl_matrix_float_alloc(A->size1,1);\n      gsl_matrix_float* buffer_03 = gsl_matrix_float_alloc(A->size1,transX->size2);\n      gsl_matrix_float* B = gsl_matrix_float_alloc(buffer_01->size1, A->size2);\n      gsl_matrix_float* Vmhalf = gsl_matrix_float_alloc(n-nl,n);\n      gsl_matrix_float* buffer_04 = gsl_matrix_float_alloc(Vmhalf->size1, transX->size2);\n      gsl_matrix_float* YStar = gsl_matrix_float_alloc(n,1);\n      gsl_matrix_float* pinvXStar = gsl_matrix_float_alloc(XStar->size2, XStar->size1);\n      gsl_matrix_float* betahat = gsl_matrix_float_alloc(pinvXStar->size1, YStar->size2);\n      gsl_matrix_float* buffer_05 = gsl_matrix_float_alloc(XStar->size1, betahat->size2);\n      gsl_vector_float* sse = gsl_vector_float_alloc(1);\n      gsl_vector_float* sd = gsl_vector_float_alloc(YStar->size2);\n      gsl_matrix_float* V = gsl_matrix_float_alloc(pinvXStar->size1, pinvXStar->size1);\n      gsl_matrix_float* mag_ef = gsl_matrix_float_alloc(con->size1, betahat->size2);\n      gsl_matrix_float* buffer_06 = gsl_matrix_float_alloc(con->size1, V->size2);\n      gsl_matrix_float* buffer_07 = gsl_matrix_float_alloc(con->size1, con->size1);\n      gsl_matrix_float* mag_sd = gsl_matrix_float_alloc(con->size1, sd->size);\n      gsl_matrix_float* buffer_08 = gsl_matrix_float_alloc(mag_ef->size1, mag_ef->size2);\n      gsl_vector_float* sst = gsl_vector_float_alloc(1);\n      /* END allocate memory buffer */\n      \n \n     /* we know that irho only contains a list of indices for every voxel so we can skip\n        the unique call and iterate over irho itself */\n      float* rho = irho->data;\n      for(i=0;i<irho->size;i++) {\n\n        /* : Coradj_pix=squeeze(rho_vol(pix,slice,:)); */\n        float* pCoradj = Coradj_pix->data+1;\n        for(k=0;k<Coradj_pix->size-1;k++) {\n          *(pCoradj++) = VPixel(rho_vol, \n                                i,\n                                slice,\n                                k,\n                                VFloat);\n        }\n\n        /* : [Ainvt posdef]=chol(toeplitz([1 Coradj_pix'])); */\n\n        /* at first the toeplitz matrix */\n        Coradj_pix->data[0] = 1;\n        fmat_toeplitz(Coradj_pix, Ainv);\n        /* the cholesky decomposition */\n        /* double buffer */\n        for(j=0;j<Ainv->size1;j++) {\n          for(k=0;k<Ainv->size2;k++) {\n            gsl_matrix_set(dbuff,j,k,(double)gsl_matrix_float_get(Ainv,j,k));\n          }\n        }\n\n        if(gsl_linalg_cholesky_decomp(dbuff) == GSL_EDOM)\n          VError(\"Calculation error, cholesky decomposition failed for pix=%d\",i);\n\n        /* note: the gsl cholesky factorization returns the inverse\n         * of Ainvt in the lower triangular part of it's output matrix. \n         * Since we will use the inverse matrix of Ainvt in the next steps we\n         * will work with the lower triangular part in contrast to the matlab algorithm */\n\n        /* convert back to float and remove upper triangular matrix */\n        for(j=0;j<Ainv->size1;j++) {\n          for(k=0;k<Ainv->size2;k++) {\n            if(j<k) {\n              gsl_matrix_float_set(Ainv,j,k,0);\n            } \n            else {\n              gsl_matrix_float_set(Ainv,j,k,(float)gsl_matrix_get(dbuff,j,k));\n            }\n          }\n        }\n\n        /* :  A=inv(Ainvt'); */\n        fInv(Ainv, A);\n\n        /* : B=ones(n-nl,1)*A(nl,:); */\n\tgsl_matrix_float_set_all(buffer_01,1);\n        gsl_matrix_float_view subm = gsl_matrix_float_submatrix(A,nl-1,0,1,A->size2);\n        fmat_x_mat(buffer_01,&subm.matrix,B);\n\n        /* : Vmhalf=spdiags(double(B),double(1:nl),double(n-nl),double(n)); */\n        gsl_matrix_float_set_zero(Vmhalf);\n        for(j=0;j<B->size1;j++) {\n          for(k=0;k<B->size2;k++) {\n            gsl_matrix_float_set(Vmhalf,j,k+1+j,gsl_matrix_float_get(B,j,k));\n          }\n        }\n\n        /* : Ystar=single(zeros(n,1)); */\n        gsl_matrix_float_set_zero(YStar);\n\n        /* : Ystar(1:nl)=A*Y(1:nl,pix); */\n        subm = gsl_matrix_float_submatrix(Y,0,i,nl,1);\n        fmat_x_mat(A,&subm.matrix,buffer_02);\n        for(j=0;j<nl;j++) {\n          gsl_matrix_float_set(YStar,j,0,gsl_matrix_float_get(buffer_02,j,0));\n        }\n\n\t/* : Ystar((nl+1):n)=single(Vmhalf*double(Y(:,pix))); */\n\tsubm = gsl_matrix_float_submatrix(Y,0,i,Y->size1,1);\n\tfmat_x_mat(Vmhalf,&subm.matrix,buffer_01);\n\tfor(j=nl;j<n;j++) {\n\t  gsl_matrix_float_set(YStar,j,0,gsl_matrix_float_get(buffer_01,j-nl,0));\n\t}\n\n        /* : Xstar(1:nl,:)=A*X(1:nl,:); */\n        subm = gsl_matrix_float_submatrix(transX,0,0,nl,transX->size2);\n        fmat_x_mat(A, &subm.matrix, buffer_03);\n        for(j=0;j<buffer_03->size1;j++) {\n\n          for(k=0;k<buffer_03->size2;k++) {\n            gsl_matrix_float_set(XStar,j,k,gsl_matrix_float_get(buffer_03,j,k));\n          }\n        }\n\n        /* : Xstar((nl+1):n,:)=single(Vmhalf*double(X)); */\n        fmat_x_mat(Vmhalf,transX,buffer_04);\n        for(j=nl;j<n;j++) {\n          for(k=0;k<transX->size2;k++) {\n            gsl_matrix_float_set(XStar,j,k,gsl_matrix_float_get(buffer_04,j-nl,k));\n          }\n        }\n\n        /* : pinvXstar=pinv(Xstar); */\n        fmat_PseudoInv(XStar,pinvXStar);\n\n        /* : betahat=pinvXstar*Ystar; */\n        fmat_x_mat(pinvXStar, YStar,betahat);\n\n\n        /* : resid=Ystar-Xstar*betahat; */\n        fmat_x_mat(XStar, betahat, buffer_05);\n        gsl_matrix_float_sub(YStar, buffer_05);\n        gsl_matrix_float* resid =  YStar;\n\n        /* : SSE=sum(resid.^2,1); */\n        gsl_matrix_float_mul_elements (resid, resid);\n        fsum(resid, 1,sse);\n\n        /* : sd=sqrt(SSE/Df); */\n        float* pSSE = sse->data;\n        float* pSD = sd->data;\n        for (j = 0; j < sse->size; ++j) {\n          *pSD++ = (float)sqrt(*pSSE++/Df);\n        }\n\n        /* :   V=pinvXstar*pinvXstar'; */\n        fmat_x_matT(pinvXStar, pinvXStar, V);\n\n        /* : mag_ef=contrast*betahat; */\n        fmat_x_mat(con, betahat, mag_ef);\n\n        /* : mag_sd=sqrt(diag(contrast*V*contrast'))*sd; */\n        fmat_x_mat(con,V,buffer_06);\n        fmat_x_matT(buffer_06, con, buffer_07);\n\n        gsl_vector_float_view diag = gsl_matrix_float_diagonal(buffer_07);\n        float* pMag = mag_sd->data;\n        for (j = 0; j < diag.vector.size; ++j) {\n          float s = sqrt(gsl_vector_float_get(&diag.vector,j)); \n          pSD = sd->data;\n          for (k = 0; k < sd->size; ++k) {\n            *pMag++ = s * *pSD++;\n          }\n        }\n\n\t/* effect_slice(pix,1)= (mag_ef./(mag_sd+(mag_sd<=0)).*(mag_sd>0))'; */\n\tVFloat* peff = VPixelPtr(effect_image, slice, 0, 0);\n\tfloat* pmeff = mag_ef->data;\n\tfloat* pmsd = mag_sd->data;\n\t*(peff+i) = *pmeff / (*pmsd+(*pmsd<=0)) * (*pmsd>0);\n\n        /* next value */\n        rho++;\n      } /* END for(i=0;i<irho->size;i++) */\n      \n      /* free some memory */\n      gsl_vector_float_free(Coradj_pix);\n      gsl_matrix_float_free(Ainv);\n      gsl_matrix_free(dbuff);\n      gsl_matrix_float_free(A);\n      gsl_matrix_float_free(buffer_01);\n      gsl_matrix_float_free(buffer_02);\n      gsl_matrix_float_free(buffer_03);\n      gsl_matrix_float_free(buffer_04);\n      gsl_matrix_float_free(B);\n      gsl_matrix_float_free(Vmhalf);\n      gsl_matrix_float_free(YStar);\n      gsl_matrix_float_free(pinvXStar);\n      gsl_matrix_float_free(buffer_05);\n      gsl_vector_float_free(sd);\n      gsl_matrix_float_free(V);\n      gsl_matrix_float_free(mag_ef);\n      gsl_matrix_float_free(buffer_06);\n      gsl_matrix_float_free(buffer_07);\n      gsl_matrix_float_free(mag_sd);\n      gsl_matrix_float_free(buffer_08);\n      gsl_vector_float_free(sse);\n      gsl_vector_float_free(sst);\n\n    }/************************************** END order > 1 ***************************************/\n            \n  /* : \n   * minus = ones(size(effect_slice),'single');\n   * minus(find(effect_slice<0))=single(-1.0);\n   * effect_slice=single(sqrt(Df .* log(1 + effect_slice.^2 ./ Df) .* (1 - 0.5 ./ Df)));\n   * effect_slice=effect_slice .* minus; \n   */\n  double u=0;\n  VFloat* peff = VPixelPtr(effect_image, slice,0,0);\n  for (i = 0; i < VImageNColumns(effect_image) * VImageNRows(effect_image); ++i) {\n    VFloat oldVal = *peff;\n    Df = Dfs[0];\n    u = (double)(*peff);\n    u = sqrt(Df * log(1.0 + pow(u,2.0) / Df) * (1 - 0.5 / Df));\n    u = (oldVal < 0) ? u * (-1.0) : u;\n    if (gsl_isnan(u) || gsl_isinf(u)) u = 0;\n    (*peff) = (float)u;\n    peff++;\n  }\n  \n  /* free allocated memory */\n  gsl_matrix_float_free(XStar); \n  gsl_matrix_float_free(transX);\n  /* END free allocated memory */\n}\n", "meta": {"hexsha": "dbb6cf85e494640d926979be126e7296393252df", "size": 15295, "ext": "c", "lang": "C", "max_stars_repo_path": "src/stats/vlisa_prewhitening/whitecov2.c", "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_issues_repo_path": "src/stats/vlisa_prewhitening/whitecov2.c", "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_forks_repo_path": "src/stats/vlisa_prewhitening/whitecov2.c", "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "avg_line_length": 36.0731132075, "max_line_length": 109, "alphanum_fraction": 0.5854200719, "num_tokens": 4685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.36114937704008593}}
{"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     mpepc_pose_follower.h\n* \\author   Jong Jin Park\n*\n* Declaration of MPEPCPoseFollower.\n*/\n\n#ifndef MPEPC_POSE_FOLLOWER_H\n#define MPEPC_POSE_FOLLOWER_H\n\n#include <mpepc/trajectory/params.h>\n#include <mpepc/trajectory/robot_trajectory_info.h>\n#include <core/pose.h>\n#include <mpepc/control/control_law_coordinates.h>\n#include <nlopt.h>\n#include <vector>\n#include <memory>\n\nnamespace vulcan\n{\n\nnamespace mpepc\n{\n\nclass  RobotSimulator;\nclass  TrajectoryEvaluator;\nclass  TaskManifold;\nstruct trajectory_planner_debug_info_t;\n\n/**\n* MPEPCPoseFollower optimizes velocity gain given a pose to converge to.\n*\n* The optimizer handles the simulate/evaluate loop internally and finds the optimal\n* target along with the intermediate trajectories generated by the optimization\n* algorithm. NLopt package is used for the numerical optimzation, and a number of\n* different algorithms can be implemented.\n*/\nclass MPEPCPoseFollower\n{\n\npublic:\n\n    /**\n    * Constructor for MPEPCPoseFollower.\n    *\n    * \\param    params          Parameters for the optimization\n    */\n    MPEPCPoseFollower(const mpepc_optimizer_params_t& params);\n\n    /**\n    * Destructor for MPEPCPoseFollower.\n    */\n    ~MPEPCPoseFollower(void);\n\n    /**\n    * Setup sets up the optmizer with the robot simulator and trajectory evaluator to be used.\n    *\n    * \\param    simulator       RobotSimulator to use for the trajectory generation.\n    * \\param    evaluator       TrajectoryEvaluator for calculating the cost of a trajectory.\n    */\n    void setup(RobotSimulator& simulator, TrajectoryEvaluator& evaluator); // NOTE: This feels very unsafe. A better way?\n\n    /**\n    * setInitialGuesses adds a goal pose (if navigation task) and the previous optimum\n    * to the initial guesses for local optimizer.\n    *\n    * \\param    task                 TaskManifold that contains the goal.\n    * \\param    previousMotionTarget Previous output of the metric planner, i.e. the previous optimum.\n    */\n    void setInitialGuesses(const TaskManifold&    task,\n                           const motion_target_t& previousMotionTarget);\n\n    /**\n    * run runs the optimizer and finds the best motion target by evaluating the expected\n    * costs of an estimated trajectory generated from a candidate motion target.\n    *\n    * It returns the optimal target found, while the intermediate information including\n    * all trajectories considered are stored in the provided debug info instance.\n    *\n    * \\param    debugInfo        Place to store relevant information\n    * \\return   Optimal target found\n    */\n    motion_target_t runOptimizer(trajectory_planner_debug_info_t& debugInfo);\n\n    /**\n    * evaluateCost calculates the cost of a fixed-length trajectory represented by the given optimizer_target_t.\n    * The length of the trajectory is specified in the given instance of the planner_data_t.\n    *\n    * \\param    coords          Optimization variable, currently encoding a target pose in the robot frame and a velocity gain for the kinematic control law.\n    * \\return   Cost of the trajectory.\n    */\n    double evaluateCost(const double x[]);\n\n    /**\n    * evaluateGradient calculates the gradient around a particular point, by a simple forward differencing.\n    *\n    * \\param    coords          Optimization variable, currently encoding a target pose in the robot frame and a velocity gain for the kinematic control law.\n    * \\param    cost            Evaluated cost at the given coordinate.\n    * \\param    gradient        Calculated gradient for each dimension (r, theta, delta, velocity) [output]\n    */\n    void evaluateGradient(const double x[], double cost, double gradient[]);\n\n    bool haveFoundSolution(void) const { return haveFoundSolution_; };\n\n//     /**\n//     * evaluateSingleMotionTarget is a method which resets the data and info struct and evaluate a single optimizer target.\n//     * The optimization_info_t will hold a single trajectory considered. TODO: Do i need this?\n//     *\n//     * \\param candidateMotionTarget\n//     * \\param data\n//     * \\param info\n//     */\n//     double evaluateSingleMotionTarget(const motion_target_t& candidateMotionTarget, const planner_data_t& data, optimization_info_t& info);\n\nprivate:\n\n    // setting up the optimizer\n    void setupNLOpt(void);\n\n    // optimizers\n    nlopt_opt globalOptimizer;\n    nlopt_opt localOptimizer;\n\n    // simulator and evaluator\n    RobotSimulator*      simulator_;\n    TrajectoryEvaluator* evaluator_;\n\n    robot_trajectory_info_t trajectory;\n\n    // debug info\n    trajectory_planner_debug_info_t* optimizerInfo_;\n\n    // inital robot state\n    pose_t robotPose_;\n\n    // target pose to converge to\n    pose_t   targetPose_;\n    motion_target_t candidateMotionTarget_;\n\n    // indicator for finding a right solution\n    bool haveFoundSolution_;\n\n    // parameters\n    mpepc_optimizer_params_t params_;\n};\n\n\n} // mpepc\n} // vulcan\n\n#endif // MPEPC_POSE_FOLLOWER_H\n", "meta": {"hexsha": "2d5843c6cec787635313867e401180d941e6cc81", "size": 5301, "ext": "h", "lang": "C", "max_stars_repo_path": "src/mpepc/trajectory/mpepc_pose_follower.h", "max_stars_repo_name": "h2ssh/Vulcan", "max_stars_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T09:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:31.000Z", "max_issues_repo_path": "src/mpepc/trajectory/mpepc_pose_follower.h", "max_issues_repo_name": "h2ssh/Vulcan", "max_issues_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-05T08:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:00:50.000Z", "max_forks_repo_path": "src/mpepc/trajectory/mpepc_pose_follower.h", "max_forks_repo_name": "h2ssh/Vulcan", "max_forks_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T00:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:56:38.000Z", "avg_line_length": 32.9254658385, "max_line_length": 157, "alphanum_fraction": 0.7160913035, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.3611493770400859}}
{"text": "\n#ifndef BIO_MATRIX_DEPENDENCIES_H_\n#define BIO_MATRIX_DEPENDENCIES_H_\n\n#include \"bio/defs.h\"\n#include \"bio/matrix.h\"\n#include \"bio/contingency_homogeneity.h\"\n\n#include <boost/array.hpp>\n\n#include <gsl/gsl_math.h>\n\n#include <vector>\n#include <numeric>\n#include <set>\n\nBIO_NS_START\n\n/** Indexes a pair of bases for comparison. */\nstruct BasePair\n{\n\t/** The index of the base we wish to analyse. */\n\tunsigned observed_index;\n\n\t/** The index of the base we condition on. */\n\tunsigned conditioned_index;\n\n\tBasePair(unsigned observed_index, unsigned conditioned_index);\n\n\tbool operator<(const BasePair & rhs) const;\n};\n\nstd::ostream &\noperator<<(std::ostream & os, const BasePair & base_pair);\n\n/** A contingency table to compare a pair of bases. */\ntypedef ContingencyTable<4, 4> base_pair_contingency_table_t;\n\n/** The contingency tables for all base pairs in a pssm. */\ntypedef std::map<BasePair, base_pair_contingency_table_t> pssm_contingency_tables_t;\n\n/** The results of analysing the dependencies between a pair of bases. */\nstruct BasePairDependencyResults\n{\n\tdouble homogeneity_bayes_factor;\n};\n\n/** The results of the dependencies between all base pairs in a pssm. */\ntypedef std::map< BasePair, BasePairDependencyResults > pssm_dependency_results_t;\n\n/** An iterator pointing to a result. */\ntypedef pssm_dependency_results_t::const_iterator pssm_dependency_result_it;\n\n/** A less than operator that lets us sort by scores. */\nstruct HomogeneityLessThen\n{\n\tbool operator()(pssm_dependency_result_it lhs, pssm_dependency_result_it rhs) const;\n};\n\n/** An ordered set of results. */\ntypedef std::set< pssm_dependency_result_it, HomogeneityLessThen > pssm_dependency_result_set;\n\n/** Contains all the sequences that were used to compose a Pssm. Indexed first by position then by sequence number. */\ntypedef std::vector< std::vector<char> > pssm_source_matrix_t;\ntypedef boost::shared_ptr< pssm_source_matrix_t > pssm_source_matrix_ptr_t;\ntypedef std::map< TableLink, pssm_source_matrix_ptr_t > pssm_source_map_t;\n\n\nstd::ostream &\noperator<<(std::ostream & os, pssm_source_map_t::value_type value);\n\nvoid\nbuild_all_pssm_sources(pssm_source_map_t & pssm_source_map);\n\n/** Take a Transfac matrix and generate a matrix from the sequences that defined it. */\nvoid\nbuild_pssm_source(\n\tconst Matrix * matrix,\n\tpssm_source_matrix_t & pssm_source);\n\n/** Adds a sequence to a pssm source. */\nvoid\nadd_sequence_to_pssm_source(\n\tconst seq_t & sequence,\n\tpssm_source_matrix_t & pssm_source);\n\n/** Count the conditional frequencies in a matrix and generate contingency tables. */\nvoid\ncount_frequencies(\n\tconst pssm_source_matrix_t & pssm_source,\n\tpssm_contingency_tables_t & contingency_tables);\n\n/** Calculate the dependencies in all the contingency tables. */\nvoid\ncalculate_dependencies(\n\tpssm_contingency_tables_t & contingency_tables,\n\tpssm_dependency_results_t & results);\n\n/** Build an ordered set of results. */\nvoid\nbuild_result_set(\n\tpssm_dependency_results_t & results,\n\tpssm_dependency_result_set & result_set);\n\n\n\nstruct MatrixDependencies\n{\n\tpssm_source_matrix_t pssm_source;\n\tpssm_contingency_tables_t contingency_tables;\n\tpssm_dependency_results_t results;\n\tpssm_dependency_result_set result_set;\n\n\tMatrixDependencies(const pssm_source_matrix_t & pssm_source);\n\tMatrixDependencies(const Matrix * matrix);\n\tMatrixDependencies();\n};\n\ntypedef std::map<const Matrix *, MatrixDependencies> matrix_dependencies_map_t;\n\nBIO_NS_END\n\n\n\n\n#endif //BIO_MATRIX_DEPENDENCIES_H_\n", "meta": {"hexsha": "1700e32c8d672a9f96fcc4ce36883b3b9716f334", "size": 3470, "ext": "h", "lang": "C", "max_stars_repo_path": "C++/include/bio/matrix_dependencies.h", "max_stars_repo_name": "JohnReid/biopsy", "max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C++/include/bio/matrix_dependencies.h", "max_issues_repo_name": "JohnReid/biopsy", "max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C++/include/bio/matrix_dependencies.h", "max_forks_repo_name": "JohnReid/biopsy", "max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3228346457, "max_line_length": 118, "alphanum_fraction": 0.7904899135, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3608716091339978}}
{"text": "#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_cblas.h>\n\n#include \"tests.h\"\n\nvoid\ntest_symm (void) {\nconst double flteps = 1e-4, dbleps = 1e-6;\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha = -0.3f;\n   float beta = -1.0f;\n   float A[] = { -0.581f };\n   int lda = 1;\n   float B[] = { 0.157f, 0.451f };\n   int ldb = 2;\n   float C[] = { -0.869f, -0.871f };\n   int ldc = 2;\n   float C_expected[] = { 0.896365f, 0.949609f };\n   cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], flteps, \"ssymm(case 1518)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha = -0.3f;\n   float beta = -1.0f;\n   float A[] = { 0.874f };\n   int lda = 1;\n   float B[] = { 0.085f, 0.069f };\n   int ldb = 1;\n   float C[] = { -0.495f, -0.828f };\n   int ldc = 1;\n   float C_expected[] = { 0.472713f, 0.809908f };\n   cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], flteps, \"ssymm(case 1519)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha = -1.0f;\n   float beta = 0.0f;\n   float A[] = { -0.671f, -0.343f, 0.6f, 0.177f };\n   int lda = 2;\n   float B[] = { 0.043f, 0.01f };\n   int ldb = 2;\n   float C[] = { 0.988f, 0.478f };\n   int ldc = 2;\n   float C_expected[] = { 0.032283f, 0.012979f };\n   cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], flteps, \"ssymm(case 1520)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha = -1.0f;\n   float beta = 0.0f;\n   float A[] = { 0.069f, 0.096f, 0.139f, -0.044f };\n   int lda = 2;\n   float B[] = { -0.448f, 0.07f };\n   int ldb = 1;\n   float C[] = { 0.361f, 0.995f };\n   int ldc = 1;\n   float C_expected[] = { 0.021182f, 0.065352f };\n   cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], flteps, \"ssymm(case 1521)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha = 0.0f;\n   float beta = -0.3f;\n   float A[] = { 0.745f };\n   int lda = 1;\n   float B[] = { -0.269f, 0.448f };\n   int ldb = 2;\n   float C[] = { -0.986f, 0.2f };\n   int ldc = 2;\n   float C_expected[] = { 0.2958f, -0.06f };\n   cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], flteps, \"ssymm(case 1522)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha = 0.0f;\n   float beta = -0.3f;\n   float A[] = { 0.96f };\n   int lda = 1;\n   float B[] = { 0.392f, -0.07f };\n   int ldb = 1;\n   float C[] = { -0.235f, 0.554f };\n   int ldc = 1;\n   float C_expected[] = { 0.0705f, -0.1662f };\n   cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], flteps, \"ssymm(case 1523)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha = -0.3f;\n   float beta = 0.1f;\n   float A[] = { -0.839f, 0.498f, -0.215f, -0.314f };\n   int lda = 2;\n   float B[] = { -0.66f, 0.593f };\n   int ldb = 2;\n   float C[] = { -0.806f, 0.525f };\n   int ldc = 2;\n   float C_expected[] = { -0.208474f, 0.0657906f };\n   cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], flteps, \"ssymm(case 1524)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha = -0.3f;\n   float beta = 0.1f;\n   float A[] = { 0.994f, -0.117f, -0.639f, 0.925f };\n   int lda = 2;\n   float B[] = { -0.478f, 0.147f };\n   int ldb = 1;\n   float C[] = { -0.814f, 0.316f };\n   int ldc = 1;\n   float C_expected[] = { 0.0662993f, -0.0259703f };\n   cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], flteps, \"ssymm(case 1525)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha = -0.3;\n   double beta = 1;\n   double A[] = { -0.981 };\n   int lda = 1;\n   double B[] = { -0.823, 0.83 };\n   int ldb = 2;\n   double C[] = { 0.991, 0.382 };\n   int ldc = 2;\n   double C_expected[] = { 0.7487911, 0.626269 };\n   cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], dbleps, \"dsymm(case 1526)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha = -0.3;\n   double beta = 1;\n   double A[] = { -0.248 };\n   int lda = 1;\n   double B[] = { 0.74, 0.068 };\n   int ldb = 1;\n   double C[] = { -0.905, 0.742 };\n   int ldc = 1;\n   double C_expected[] = { -0.849944, 0.7470592 };\n   cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], dbleps, \"dsymm(case 1527)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha = -1;\n   double beta = 1;\n   double A[] = { 0.591, -0.01, -0.192, -0.376 };\n   int lda = 2;\n   double B[] = { 0.561, 0.946 };\n   int ldb = 2;\n   double C[] = { 0.763, 0.189 };\n   int ldc = 2;\n   double C_expected[] = { 0.440909, 0.550306 };\n   cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], dbleps, \"dsymm(case 1528)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha = -1;\n   double beta = 1;\n   double A[] = { -0.786, 0.87, 0.222, -0.043 };\n   int lda = 2;\n   double B[] = { -0.503, -0.526 };\n   int ldb = 1;\n   double C[] = { -0.027, -0.391 };\n   int ldc = 1;\n   double C_expected[] = { -0.305586, -0.301952 };\n   cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], dbleps, \"dsymm(case 1529)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha = 0.1;\n   double beta = 0.1;\n   double A[] = { -0.468 };\n   int lda = 1;\n   double B[] = { -0.881, 0.692 };\n   int ldb = 2;\n   double C[] = { -0.812, -0.395 };\n   int ldc = 2;\n   double C_expected[] = { -0.0399692, -0.0718856 };\n   cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], dbleps, \"dsymm(case 1530)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha = 0.1;\n   double beta = 0.1;\n   double A[] = { 0.849 };\n   int lda = 1;\n   double B[] = { -0.887, 0.518 };\n   int ldb = 1;\n   double C[] = { 0.414, -0.251 };\n   int ldc = 1;\n   double C_expected[] = { -0.0339063, 0.0188782 };\n   cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], dbleps, \"dsymm(case 1531)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha = -1;\n   double beta = 1;\n   double A[] = { 0.457, 0.624, 0.807, 0.349 };\n   int lda = 2;\n   double B[] = { -0.609, 0.03 };\n   int ldb = 2;\n   double C[] = { 0.719, -0.624 };\n   int ldc = 2;\n   double C_expected[] = { 0.973103, -0.143007 };\n   cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], dbleps, \"dsymm(case 1532)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha = -1;\n   double beta = 1;\n   double A[] = { -0.133, -0.117, -0.163, 0.795 };\n   int lda = 2;\n   double B[] = { -0.882, 0.549 };\n   int ldb = 1;\n   double C[] = { 0.715, -0.327 };\n   int ldc = 1;\n   double C_expected[] = { 0.661927, -0.866649 };\n   cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[i], C_expected[i], dbleps, \"dsymm(case 1533)\");\n     }\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {-1.0f, 0.0f};\n   float beta[2] = {1.0f, 0.0f};\n   float A[] = { 0.476f, 0.816f };\n   int lda = 1;\n   float B[] = { 0.282f, 0.852f, -0.891f, -0.588f };\n   int ldb = 2;\n   float C[] = { 0.9f, 0.486f, -0.78f, -0.637f };\n   int ldc = 2;\n   float C_expected[] = { 1.461f, -0.149664f, -0.835692f, 0.369944f };\n   cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"csymm(case 1534) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"csymm(case 1534) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {-1.0f, 0.0f};\n   float beta[2] = {1.0f, 0.0f};\n   float A[] = { 0.048f, 0.172f };\n   int lda = 1;\n   float B[] = { 0.786f, 0.783f, 0.809f, -0.569f };\n   int ldb = 1;\n   float C[] = { -0.227f, -0.215f, 0.881f, 0.233f };\n   int ldc = 1;\n   float C_expected[] = { -0.130052f, -0.387776f, 0.7443f, 0.121164f };\n   cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"csymm(case 1535) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"csymm(case 1535) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {0.0f, 1.0f};\n   float beta[2] = {0.0f, 1.0f};\n   float A[] = { -0.495f, -0.012f, 0.843f, -0.986f, -0.243f, 0.833f, 0.921f, 0.004f };\n   int lda = 2;\n   float B[] = { 0.876f, 0.612f, 0.805f, -0.57f };\n   int ldb = 2;\n   float C[] = { 0.938f, -0.24f, -0.874f, -0.062f };\n   int ldc = 2;\n   float C_expected[] = { 1.82769f, 0.628319f, 0.93157f, 1.21158f };\n   cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"csymm(case 1536) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"csymm(case 1536) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {0.0f, 1.0f};\n   float beta[2] = {0.0f, 1.0f};\n   float A[] = { -0.812f, 0.83f, 0.705f, 0.15f, -0.463f, 0.901f, -0.547f, -0.483f };\n   int lda = 2;\n   float B[] = { -0.808f, -0.664f, 0.352f, -0.102f };\n   int ldb = 1;\n   float C[] = { -0.64f, 0.399f, 0.896f, -0.163f };\n   int ldc = 1;\n   float C_expected[] = { -0.631906f, 0.496142f, 0.697798f, 1.62656f };\n   cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"csymm(case 1537) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"csymm(case 1537) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {-1.0f, 0.0f};\n   float beta[2] = {0.0f, 1.0f};\n   float A[] = { 0.342f, -0.906f };\n   int lda = 1;\n   float B[] = { 0.676f, 0.863f, -0.517f, -0.138f };\n   int ldb = 2;\n   float C[] = { 0.274f, 0.388f, -0.271f, 0.205f };\n   int ldc = 2;\n   float C_expected[] = { -1.40107f, 0.59131f, 0.096842f, -0.692206f };\n   cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"csymm(case 1538) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"csymm(case 1538) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {-1.0f, 0.0f};\n   float beta[2] = {0.0f, 1.0f};\n   float A[] = { 0.418f, 0.354f };\n   int lda = 1;\n   float B[] = { -0.74f, 0.018f, 0.395f, 0.248f };\n   int ldb = 1;\n   float C[] = { -0.162f, 0.175f, -0.853f, 0.652f };\n   int ldc = 1;\n   float C_expected[] = { 0.140692f, 0.092436f, -0.729318f, -1.09649f };\n   cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"csymm(case 1539) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"csymm(case 1539) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {-0.3f, 0.1f};\n   float beta[2] = {0.0f, 0.1f};\n   float A[] = { 0.12f, 0.496f, 0.313f, -0.136f, 0.987f, 0.532f, 0.58f, -0.687f };\n   int lda = 2;\n   float B[] = { -0.587f, 0.278f, 0.857f, 0.136f };\n   int ldb = 2;\n   float C[] = { 0.162f, 0.249f, -0.665f, 0.456f };\n   int ldc = 2;\n   float C_expected[] = { -0.22769f, -0.0269913f, 0.0502096f, 0.0841558f };\n   cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"csymm(case 1540) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"csymm(case 1540) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   float alpha[2] = {-0.3f, 0.1f};\n   float beta[2] = {0.0f, 0.1f};\n   float A[] = { 0.579f, -0.859f, 0.192f, -0.737f, 0.396f, -0.498f, 0.751f, -0.379f };\n   int lda = 2;\n   float B[] = { 0.84f, -0.755f, -0.019f, -0.063f };\n   int ldb = 1;\n   float C[] = { 0.04f, 0.639f, -0.876f, -0.778f };\n   int ldc = 1;\n   float C_expected[] = { 0.115459f, 0.329813f, 0.288206f, 0.110315f };\n   cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], flteps, \"csymm(case 1541) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, \"csymm(case 1541) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {0, 0};\n   double beta[2] = {0, 0};\n   double A[] = { 0.511, -0.486 };\n   int lda = 1;\n   double B[] = { 0.985, -0.923, -0.234, -0.756 };\n   int ldb = 2;\n   double C[] = { -0.16, 0.049, 0.618, -0.349 };\n   int ldc = 2;\n   double C_expected[] = { 0.0, 0.0, 0.0, 0.0 };\n   cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zsymm(case 1542) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zsymm(case 1542) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {0, 0};\n   double beta[2] = {0, 0};\n   double A[] = { 0.46, -0.816 };\n   int lda = 1;\n   double B[] = { 0.404, 0.113, -0.904, -0.627 };\n   int ldb = 1;\n   double C[] = { 0.114, 0.318, 0.636, -0.839 };\n   int ldc = 1;\n   double C_expected[] = { 0.0, 0.0, 0.0, 0.0 };\n   cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zsymm(case 1543) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zsymm(case 1543) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {-1, 0};\n   double beta[2] = {-0.3, 0.1};\n   double A[] = { -0.835, 0.344, 0.975, 0.634, 0.312, -0.659, -0.624, -0.175 };\n   int lda = 2;\n   double B[] = { -0.707, -0.846, 0.825, -0.661 };\n   int ldb = 2;\n   double C[] = { 0.352, -0.499, 0.267, 0.548 };\n   int ldc = 2;\n   double C_expected[] = { -2.160518, -0.156877, 0.648536, 0.867299 };\n   cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zsymm(case 1544) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zsymm(case 1544) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 121;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {-1, 0};\n   double beta[2] = {-0.3, 0.1};\n   double A[] = { -0.409, 0.013, -0.308, -0.317, -0.535, -0.697, -0.385, 0.119 };\n   int lda = 2;\n   double B[] = { 0.299, -0.233, 0.093, 0.664 };\n   int ldb = 1;\n   double C[] = { 0.699, 0.47, -0.347, -0.182 };\n   int ldc = 1;\n   double C_expected[] = { -0.550491, 0.249777, 0.559487, 0.348221 };\n   cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zsymm(case 1545) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zsymm(case 1545) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {1, 0};\n   double beta[2] = {0, 1};\n   double A[] = { -0.151, 0.635 };\n   int lda = 1;\n   double B[] = { 0.711, -0.869, 0.153, 0.647 };\n   int ldb = 2;\n   double C[] = { -0.299, 0.43, -0.307, 0.133 };\n   int ldc = 2;\n   double C_expected[] = { 0.014454, 0.283704, -0.566948, -0.307542 };\n   cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zsymm(case 1546) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zsymm(case 1546) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 141;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {1, 0};\n   double beta[2] = {0, 1};\n   double A[] = { 0.793, -0.543 };\n   int lda = 1;\n   double B[] = { 0.054, -0.045, 0.989, 0.453 };\n   int ldb = 1;\n   double C[] = { 0.443, -0.641, -0.809, -0.83 };\n   int ldc = 1;\n   double C_expected[] = { 0.659387, 0.377993, 1.860256, -0.986798 };\n   cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zsymm(case 1547) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zsymm(case 1547) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 101;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {1, 0};\n   double beta[2] = {-1, 0};\n   double A[] = { -0.432, -0.293, -0.819, 0.44, -0.818, -0.258, -0.836, 0.683 };\n   int lda = 2;\n   double B[] = { -0.259, -0.878, 0.161, 0.744 };\n   int ldb = 2;\n   double C[] = { 0.436, -0.655, -0.61, -0.875 };\n   int ldc = 2;\n   double C_expected[] = { -0.521112, 0.460053, -0.04741, 1.148005 };\n   cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zsymm(case 1548) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zsymm(case 1548) imag\");\n     };\n   };\n  };\n\n\n  {\n   int order = 102;\n   int side = 142;\n   int uplo = 122;\n   int M = 1;\n   int N = 2;\n   double alpha[2] = {1, 0};\n   double beta[2] = {-1, 0};\n   double A[] = { -0.656, 0.378, -0.688, 0.676, 0.967, -0.804, 0.455, -0.425 };\n   int lda = 2;\n   double B[] = { 0.791, -0.947, -0.945, -0.444 };\n   int ldb = 1;\n   double C[] = { 0.014, -0.814, -0.091, -0.417 };\n   int ldc = 1;\n   double C_expected[] = { 0.775374, 1.400882, -0.431711, 1.802857 };\n   cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc);\n   {\n     int i;\n     for (i = 0; i < 2; i++) {\n       gsl_test_rel(C[2*i], C_expected[2*i], dbleps, \"zsymm(case 1549) real\");\n       gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, \"zsymm(case 1549) imag\");\n     };\n   };\n  };\n\n\n}\n", "meta": {"hexsha": "88a672a7ae5635002b096f571a29c3b4f9ff9b5f", "size": 20972, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_symm.c", "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 692.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_symm.c", "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1096.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_symm.c", "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "avg_line_length": 25.3285024155, "max_line_length": 86, "alphanum_fraction": 0.4950410071, "num_tokens": 9238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5, "lm_q1q2_score": 0.36087160314879896}}
{"text": "/**\n *\n * @file testing_spemv.c\n *\n *  PLASMA testing routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Dulceneia Becker\n * @date 2011-10-06\n * @generated s Tue Jan  7 11:45:19 2014\n *\n **/\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#include <plasma.h>\n#include <cblas.h>\n#include <lapacke.h>\n#include <core_blas.h>\n#include \"testing_smain.h\"\n\n#define REAL\n#undef COMPLEX\n\n/*--------------------------------------------------------------\n * Check the pemv\n */\nstatic int check_solution(PLASMA_enum trans, PLASMA_enum storev, \n                          int M, int N, int L,\n                          float alpha, float *A, int LDA,\n                                                    float *X, int INCX,\n                          float beta,  float *Y0, int INCY0,\n                                                    float *Y,  int INCY,\n                          float *W, float *Rnorm)\n{\n    int k;\n    float eps = LAPACKE_slamch_work('e');\n    float *work;\n    float mzone = -1.0;\n\n    /* Copy x to w */\n    if ( trans == PlasmaNoTrans ) {\n        k = N;\n    } else {\n        k = M;\n    }\n    \n    work = (float *)malloc(k * sizeof(float));\n    cblas_scopy(k, Y0, INCY0, W, 1);\n    \n    /* w = a A x + b w */\n    cblas_sgemv(CblasColMajor, (CBLAS_TRANSPOSE)trans, \n                M, N,\n                (alpha), A,  LDA, \n                                    X,  INCX,\n                (beta),  W,  1);\n\n    /* y - w */\n    cblas_saxpy(k, (mzone), Y, INCY, W, 1);\n    \n    /* Max Norm */\n    *Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, 'm', 1, k, W, 1, work);\n    \n    if ( (*Rnorm / (M*N)) > eps) {\n        return 1;\n    } else {\n        return 0;\n    }\n}\n\n/*--------------------------------------------------------------\n * Testing SPEMV\n */\nint testing_spemv(int argc, char **argv)\n{\n    /* Check for number of arguments*/\n    if ( argc != 1) {\n        USAGE(\"PEMV\", \"N\",\n              \"   - N      : number of columns\\n\");\n        return -1;\n    }\n\n    /* Args */\n    int arg_n = atoi(argv[0]);\n\n    /* Local variables */\n    float *A, *X, *Y, *A0, *Y0, *work;\n    float alpha, beta, alpha0, beta0;\n    int n    = arg_n;\n    int lda  = arg_n;\n\n    int info_solution = 0;\n    int i, j, k, t;\n    int nbtests = 0;\n    int nfails = 0;\n    int storev;\n    int l = 0;\n    int m = n;\n    int incx = 1;\n    int incy = 1;\n    char *cstorev;\n    float rnorm;\n    float eps = LAPACKE_slamch_work('e');\n\n    /* Allocate Data */\n    A    = (float *)malloc(lda*n*sizeof(float));\n    A0   = (float *)malloc(lda*n*sizeof(float));\n    X    = (float *)malloc(lda*n*sizeof(float));\n    Y    = (float *)malloc(lda*n*sizeof(float));\n    Y0   = (float *)malloc(    n*sizeof(float));\n    work = (float *)malloc(  2*n*sizeof(float));\n\n    LAPACKE_slarnv_work(1, ISEED, 1, &alpha0);\n    LAPACKE_slarnv_work(1, ISEED, 1, &beta0 );\n\n    /* Check if unable to allocate memory */\n    if ( (!A) || (!X) || (!Y0) || (!work) ) {\n        printf(\"Out of Memory \\n \");\n        exit(0);\n    }\n    \n     /* Initialize Data */\n    PLASMA_splrnt(n, n, A,  lda, 479 );\n    PLASMA_splrnt(n, n, X,  lda, 320 );\n    PLASMA_splrnt(n, 1, Y0, n,   573 );\n\n    printf(\"\\n\");\n    printf(\"------ TESTS FOR PLASMA SPEMV ROUTINE -------  \\n\");\n    printf(\"\\n\");\n    printf(\" The matrix A is randomly generated for each test.\\n\");\n    printf(\" The relative machine precision (eps) is %e \\n\",eps);\n    printf(\" Computational tests pass if scaled residual is less than eps.\\n\");\n    printf(\"\\n\");\n\n    nfails = 0;\n    for (i=0; i<6; i++) {\n        \n        /* m and n cannot be greater than lda (arg_n) */\n        switch (i) {\n        case 0: l = 0;       m = arg_n;   n = m;        break;\n        case 1: l = 0;       m = arg_n;   n = arg_n/2;  break; /**/\n        case 2: l = arg_n;   m = l;       n = l;        break;\n        case 3: l = arg_n/2; m = l;       n = arg_n;    break;\n        case 4: l = arg_n/2; m = arg_n-l; n = l;        break;\n        case 5: l = arg_n/3; m = arg_n-l; n = arg_n/2;  break; /**/\n        }\n\n        /* Colwise ConjTrans & Rowwise NoTrans */\n#ifdef COMPLEX\n        for (t=0; t<3; t++) {\n#else\n        for (t=0; t<2; t++) {\n#endif\n\n            /* Swap m and n for transpose cases */\n            if ( t == 1 ) {\n                k = m; m = n; n = k;\n            }\n\n            LAPACKE_slacpy_work( LAPACK_COL_MAJOR, 'A', m, n, \n                                 A, lda, A0, lda);\n\n            if ( trans[t] == PlasmaNoTrans ) {\n                storev = PlasmaRowwise;\n                cstorev = storevstr[0];\n\n                /* zeroed the upper right triangle */\n                int64_t i, j;\n                for (j=(n-l); j<n; j++) {\n                    for (i=0; i<(j-(n-l)); i++) {\n                        A0[i+j*lda] = 0.0;\n                    }\n                }\n            }\n            else {\n                storev = PlasmaColumnwise;\n                cstorev = storevstr[1];\n\n                /* zeroed the lower left triangle */\n                int64_t i, j;\n                for (j=0; j<(l-1); j++) {\n                    for (i=(m-l+1+j); i<m; i++) {\n                        A0[i+j*lda] = 0.0;\n                    }\n                }\n            }\n\n            for (j=0; j<3; j++) {\n\n                /* Choose alpha and beta */\n                alpha = ( j==1 ) ? 0.0 : alpha0;\n                beta  = ( j==2 ) ? 0.0 : beta0;\n\n                /* incx and incy: 1 or lda */\n                for (k=0; k<4; k++) {\n                    switch (k) {\n                    case 0:  incx = 1;    incy = 1;    break;\n                    case 1:  incx = 1;    incy = lda;  break;\n                    case 2:  incx = lda;  incy = 1;    break;\n                    case 3:  incx = lda;  incy = lda;  break;\n                    }\n                    \n                    /* initialize Y with incy */\n                    cblas_scopy(n, Y0, 1, Y, incy);\n                    \n                    /* SPEMV */\n                    CORE_spemv( trans[t], storev, m, n, l, \n                                alpha, A, lda, \n                                       X, incx,\n                                beta,  Y, incy, \n                                work);\n                    \n                    /* Check the solution */\n                    info_solution = check_solution(trans[t], storev, \n                                                   m, n, l, \n                                                   alpha, A0,  lda,\n                                                          X,   incx, \n                                                   beta,  Y0,  1, \n                                                          Y,   incy, \n                                                   work, &rnorm);\n                    \n                    if ( info_solution != 0 ) {\n                        nfails++;\n                        printf(\"Failed: t=%s, s=%s, M=%3d, N=%3d, L=%3d, alpha=%e, incx=%3d, beta=%e, incy=%3d, rnorm=%e\\n\", \n                               transstr[t], cstorev, m, n, l, (alpha), incx, (beta), incy, rnorm );\n                    }\n                    nbtests++;\n                }\n            }\n        }\n    }\n\n    if ( nfails )\n        printf(\"%d / %d tests failed\\n\", nfails, nbtests);\n\n    printf(\"***************************************************\\n\");\n    if (nfails == 0) {\n        printf(\" ---- TESTING SPEMV ...... PASSED !\\n\");\n    }\n    else {\n        printf(\" ---- TESTING SPEMV ... FAILED !\\n\");\n    }\n    printf(\"***************************************************\\n\");\n\n    free( A0 );\n    free( A );\n    free( X );\n    free( Y0 );\n    free( Y );\n\n    return 0;\n}\n\n", "meta": {"hexsha": "ca4807bc72262ea536e464eec7dc6b3872eb57dc", "size": 7716, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/testing_spemv.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/testing_spemv.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/testing_spemv.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.9069767442, "max_line_length": 125, "alphanum_fraction": 0.3865992742, "num_tokens": 2141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3605898614608009}}
{"text": "/* Copyright (c) 2011-2012, J\u00e9r\u00e9my Fix. All rights reserved. */\n\n/* Redistribution and use in source and binary forms, with or without */\n/* modification, are permitted provided that the following conditions are met: */\n\n/* * Redistributions of source code must retain the above copyright notice, */\n/* this list of conditions and the following disclaimer. */\n/* * Redistributions in binary form must reproduce the above copyright notice, */\n/* this list of conditions and the following disclaimer in the documentation */\n/* and/or other materials provided with the distribution. */\n/* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */\n\n/* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND */\n/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */\n/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */\n/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */\n/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */\n/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */\n/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */\n/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */\n/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */\n/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */\n\n#ifndef UKF_PARAMETER_NDIM_H\n#define UKF_PARAMETER_NDIM_H\n\n#include <gsl/gsl_linalg.h> // For the Cholesky decomposition\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_blas.h>\n\n#include \"ukf_types.h\"\n\nnamespace ukf\n{\n    namespace parameter\n    {\n\n        /**\n          * @short Allocation of the vectors/matrices and initialization\n          *\n          */\n        void ukf_init(ukf_param &p, ukf_state &s)\n        {\n            // Init the lambda\n            p.lambda = p.alpha * p.alpha * (p.n + p.kpa) - p.n;\n            p.gamma = sqrt(p.n + p.lambda);\n            p.nbSamples = 2 * p.n + 1;\n\n            // Init the matrices used to iterate\n            s.Kk = gsl_matrix_alloc(p.n,p.no); // Kalman gain\n            gsl_matrix_set_zero(s.Kk);\n\n            s.Kk_T = gsl_matrix_alloc(p.no,p.n);\n            gsl_matrix_set_zero(s.Kk_T);\n\n            s.Pwdk = gsl_matrix_alloc(p.n,p.no);\n            gsl_matrix_set_zero(s.Pwdk);\n\n            // Whatever the type of evolution noise, its covariance is set to evolution_noise\n            s.Prrk = gsl_matrix_alloc(p.n,p.n);\n            p.evolution_noise->init(p,s);\n\n            // Whatever the type of observation noise, its covariance is set to observation_noise\n            s.Peek = gsl_matrix_alloc(p.no,p.no);\n            gsl_matrix_set_identity(s.Peek);\n            gsl_matrix_scale(s.Peek, p.observation_noise);\n\n            s.Pddk = gsl_matrix_alloc(p.no, p.no); // Covariance of the output\n            gsl_matrix_set_zero(s.Pddk);\n\n            s.w = gsl_vector_alloc(p.n); // Parameter vector\n            gsl_vector_set_zero(s.w);\n\n            s.wk = gsl_vector_alloc(p.n); // Vector holding one sigma point\n            gsl_vector_set_zero(s.wk);\n\n            s.Pk = gsl_matrix_alloc(p.n,p.n); // Covariance matrix\n            gsl_matrix_set_identity(s.Pk);\n            gsl_matrix_scale(s.Pk,p.prior_pi);\n\n            s.Sk = gsl_matrix_alloc(p.n,p.n); // Matrix holding the cholesky decomposition of Pk\n            // Initialize Sk to the cholesky decomposition of Pk\n            gsl_matrix_memcpy(s.Sk, s.Pk);\n            gsl_linalg_cholesky_decomp(s.Sk);\n            // Set all the elements of Lpi strictly above the diagonal to zero\n            for(int k = 0 ; k < p.n ; k++)\n                for(int j = 0 ; j < k ; j++)\n                    gsl_matrix_set(s.Sk,j,k,0.0);\n\n            s.cSk = gsl_vector_alloc(p.n); // Vector holding one column of Lpi\n            gsl_vector_set_zero(s.cSk);\n\n            s.wm  = gsl_vector_alloc(p.nbSamples); // Weights used to compute the mean of the sigma points images\n            s.wc = gsl_vector_alloc(p.nbSamples); // Weights used to update the covariance matrices\n\n            // Set the weights\n            gsl_vector_set(s.wm, 0, p.lambda / (p.n + p.lambda));\n            gsl_vector_set(s.wc, 0, p.lambda / (p.n + p.lambda) + (1.0 - p.alpha*p.alpha + p.beta));\n            for(int j = 1 ; j < p.nbSamples; j ++)\n            {\n                gsl_vector_set(s.wm, j, 1.0 / (2.0 * (p.n + p.lambda)));\n                gsl_vector_set(s.wc, j, 1.0 / (2.0 * (p.n + p.lambda)));\n            }\n\n            s.dk = gsl_matrix_alloc(p.no, p.nbSamples); // Holds the image of the sigma points\n            gsl_matrix_set_zero(s.dk);\n\n            s.ino_dk = gsl_vector_alloc(p.no); // Holds the inovation\n            gsl_vector_set_zero(s.ino_dk);\n\n            s.d_mean = gsl_vector_alloc(p.no); // Holds the mean of the sigma points images\n            gsl_vector_set_zero(s.d_mean);\n\n            s.sigmaPoints = gsl_matrix_alloc(p.n,p.nbSamples); // Holds the sigma points in the columns\n            gsl_matrix_set_zero(s.sigmaPoints);\n\n            // Temporary vectors/matrices\n            s.vec_temp_n = gsl_vector_alloc(p.n);\n            s.vec_temp_output = gsl_vector_alloc(p.no);\n\n            s.mat_temp_n_1 = gsl_matrix_alloc(p.n,1);\n            s.mat_temp_n_output = gsl_matrix_alloc(p.n, p.no);\n            s.mat_temp_output_n = gsl_matrix_alloc(p.no, p.n);\n            s.mat_temp_1_output = gsl_matrix_alloc(1,p.no);\n            s.mat_temp_output_1 = gsl_matrix_alloc(p.no, 1);\n            s.mat_temp_output_output = gsl_matrix_alloc(p.no, p.no);\n            s.mat_temp_n_n = gsl_matrix_alloc(p.n, p.n);\n        }\n\n        /**\n          * @short Free of memory allocation\n          *\n          */\n        void ukf_free(ukf_param &p, ukf_state &s)\n        {\n            gsl_matrix_free(s.Kk);\n            gsl_matrix_free(s.Kk_T);\n            gsl_matrix_free(s.Pwdk);\n            gsl_matrix_free(s.Pddk);\n            gsl_matrix_free(s.Peek);\n            gsl_matrix_free(s.Prrk);\n\n            gsl_vector_free(s.w);\n            gsl_vector_free(s.wk);\n\n            gsl_matrix_free(s.Pk);\n            gsl_matrix_free(s.Sk);\n            gsl_vector_free(s.cSk);\n\n            gsl_vector_free(s.wm);\n            gsl_vector_free(s.wc);\n\n            gsl_matrix_free(s.dk);\n            gsl_vector_free(s.ino_dk);\n            gsl_vector_free(s.d_mean);\n\n            gsl_matrix_free(s.sigmaPoints);\n\n            gsl_vector_free(s.vec_temp_n);\n            gsl_vector_free(s.vec_temp_output);\n\n            gsl_matrix_free(s.mat_temp_n_1);\n            gsl_matrix_free(s.mat_temp_n_output);\n            gsl_matrix_free(s.mat_temp_output_n);\n            gsl_matrix_free(s.mat_temp_1_output);\n            gsl_matrix_free(s.mat_temp_output_1);\n\n            gsl_matrix_free(s.mat_temp_output_output);\n            gsl_matrix_free(s.mat_temp_n_n);\n        }\n\n        /**\n          * @short Iteration for the statistical linearization\n          *\n          */\n\ttemplate<typename GFUNC>\n\tvoid ukf_iterate(ukf_param &p, ukf_state &s, \n\t\t\t GFUNC g, \n\t\t\t gsl_vector * xk, gsl_vector* dk)\n        {\n\n            // Here, we implement the UKF for parameter estimation in the vectorial case\n            // The notations follow p93 of the PhD thesis of Van Der Merwe, \"Sigma-Point Kalman Filters for Probabilistic Inference in Dynamic State-Space Models\"\n\n            // ************************************************** //\n            // ************ Time update equations    ************ //\n            // ************************************************** //\n            // Add the evolution noise to the parameter covariance Eq 3.137\n            gsl_matrix_add(s.Pk, s.Prrk);\n\n            // ************************************************** //\n            // ************ Compute the sigma points ************ //\n            // ************************************************** //\n            // Equations 3.138\n            // w_k^j = w_(k-1)  <-- this is here denoted s.w\n            // w_k^j = w_(k-1) + gamma Sk_j for 1 <= j <= n\n            // w_k^j = w_(k-1) - gamma Sk_j for n+1 <= j <= 2n\n\n            // Perform a cholesky decomposition of Pk\n            gsl_matrix_memcpy(s.Sk, s.Pk);\n            gsl_linalg_cholesky_decomp(s.Sk);\n            // Set all the elements of Lpi strictly above the diagonal to zero\n            for(int k = 0 ; k < p.n ; ++k)\n                for(int j = 0 ; j < k ; ++j)\n                    gsl_matrix_set(s.Sk,j,k,0.0);\n\n            gsl_matrix_set_col(s.sigmaPoints,0, s.w);\n            for(int j = 1 ; j < p.n+1 ; ++j)\n                for(int i = 0 ; i < p.n ; ++i)\n                    gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) + p.gamma * gsl_matrix_get(s.Sk,i,j-1));\n\n            for(int j = p.n+1 ; j < p.nbSamples ; ++j)\n                for(int i = 0 ; i < p.n ; ++i)\n                    gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) - p.gamma * gsl_matrix_get(s.Sk,i,j-(p.n+1)));\n\n\n\n            /**************************************************/\n            /***** Compute the images of the sigma points *****/\n            /**************************************************/\n\n            // Compute the images of the sigma points\n            // and the mean of the dk\n            gsl_vector_set_zero(s.d_mean);\n            for(int j = 0 ; j < p.nbSamples ; j++)\n            {\n                // Equation 3.129\n                gsl_matrix_get_col(s.wk, s.sigmaPoints,j);\n                g(s.wk,xk, s.vec_temp_output);\n                gsl_matrix_set_col(s.dk, j, s.vec_temp_output);\n\n                // Equation 3.140\n                // Update the mean : y_mean = sum_[j=0..2n] w_j y_j\n                gsl_vector_scale(s.vec_temp_output, gsl_vector_get(s.wm,j));\n                gsl_vector_add(s.d_mean, s.vec_temp_output);\n            }\n\n            /**************************************************/\n            /************** Update the statistics *************/\n            /**************************************************/\n\n            gsl_matrix_set_zero(s.Pwdk);\n            gsl_matrix_memcpy(s.Pddk, s.Peek); // Add R^e_k to Pddk, Eq 3.142\n            for(int j = 0 ; j < p.nbSamples ; ++j)\n            {\n                // Update of Pwdk\n                // (wk - w)\n                gsl_matrix_get_col(s.wk, s.sigmaPoints,j);\n                gsl_vector_sub(s.wk, s.w);\n                gsl_matrix_set_col(s.mat_temp_n_1, 0, s.wk);\n\n                // (dk - d_mean)\n                gsl_matrix_get_col(s.vec_temp_output, s.dk, j);\n                gsl_vector_sub(s.vec_temp_output, s.d_mean);\n                gsl_matrix_set_col(s.mat_temp_output_1, 0, s.vec_temp_output);\n\n                // compute wc_j . (wk - w_mean) * (dk - d_mean)^T\n                gsl_blas_dgemm(CblasNoTrans, CblasTrans, gsl_vector_get(s.wc,j) , s.mat_temp_n_1, s.mat_temp_output_1, 0.0, s.mat_temp_n_output);\n\n                // Equation 3.142\n                // And add it to Pwdk\n                gsl_matrix_add(s.Pwdk, s.mat_temp_n_output);\n\n                // Equation 3.143\n                // Update of Pddk\n                gsl_matrix_get_col(s.vec_temp_output, s.dk, j);\n                gsl_vector_sub(s.vec_temp_output, s.d_mean);\n                gsl_matrix_set_col(s.mat_temp_output_1, 0, s.vec_temp_output);\n                gsl_blas_dgemm(CblasNoTrans, CblasTrans, gsl_vector_get(s.wc,j) , s.mat_temp_output_1, s.mat_temp_output_1, 0.0, s.mat_temp_output_output);\n\n                gsl_matrix_add(s.Pddk, s.mat_temp_output_output);\n            }\n\n            // ************************************************** //\n            // ******* Kalman gain and parameters update ******** //\n            // ************************************************** //\n\n            //*** Ki = Pwdk Pddk^-1\n            // Compute the inverse of Pddk\n            gsl_matrix_memcpy(s.mat_temp_output_output, s.Pddk);\n            gsl_linalg_cholesky_decomp(s.mat_temp_output_output);\n            gsl_linalg_cholesky_invert(s.mat_temp_output_output);\n\n            // Compute the product : Pwdk . Pddk^-1\n            // Equation 3.144\n            gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Pwdk, s.mat_temp_output_output, 0.0, s.Kk);\n\n            // Update of the parameters\n            // wk = w_(k-1) + Kk * (dk - d_mean)\n            // Equation 3.145\n\n            // Set the inovations\n            /*for(int i = 0 ; i < p.no; ++i)\n                s.ino_dk->data[i] = dk->data[i] - s.d_mean->data[i];\n            gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Kk, &gsl_matrix_view_array(s.ino_dk->data,p.no,1).matrix, 0.0, s.mat_temp_n_1);\n            gsl_matrix_get_col(s.vec_temp_n, s.mat_temp_n_1, 0);\n            gsl_vector_add(s.w, s.vec_temp_n);*/\n\n            for(int i = 0 ; i < p.no; ++i)\n                s.ino_dk->data[i] = dk->data[i] - s.d_mean->data[i];\n            gsl_blas_dgemv(CblasNoTrans, 1.0, s.Kk, s.ino_dk, 1.0, s.w);\n\n            // Update of the parameter covariance\n            // Pk = P_(k-1) - Kk Pddk Kk^T\n            // Equation 3.146\n            gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Kk, s.Pddk, 0.0, s.mat_temp_n_output);\n            gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, s.mat_temp_n_output , s.Kk, 0.0, s.mat_temp_n_n);\n            gsl_matrix_sub(s.Pk, s.mat_temp_n_n);\n\n            // Update of the evolution noise\n            p.evolution_noise->updateEvolutionNoise(p, s);\n        }\n\n        /**\n          * @short Evaluation of the output from the sigma points\n          *\n          */\n      void ukf_evaluate(ukf_param &p, ukf_state &s, \n\t\t\tvoid(*g)(gsl_vector*, gsl_vector*, gsl_vector*), \n\t\t\tgsl_vector * xk, gsl_vector * dk)\n        {\n            // ************************************************** //\n            // ************ Compute the sigma points ************ //\n            // ************************************************** //\n            // Equations 3.138\n            // w_k^j = w_(k-1)  <-- this is here denoted s.w\n            // w_k^j = w_(k-1) + gamma Sk_j for 1 <= j <= n\n            // w_k^j = w_(k-1) - gamma Sk_j for n+1 <= j <= 2n\n\n            // Perform a cholesky decomposition of Pk\n            gsl_matrix_memcpy(s.mat_temp_n_n, s.Pk);\n            gsl_linalg_cholesky_decomp(s.mat_temp_n_n);\n            // Set all the elements of Lpi strictly above the diagonal to zero\n            for(int k = 0 ; k < p.n ; ++k)\n                for(int j = 0 ; j < k ; ++j)\n                    gsl_matrix_set(s.mat_temp_n_n,j,k,0.0);\n\n            gsl_matrix_set_col(s.sigmaPoints,0, s.w);\n            for(int j = 1 ; j < p.n+1 ; ++j)\n                for(int i = 0 ; i < p.n ; ++i)\n                    gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) + p.gamma * gsl_matrix_get(s.mat_temp_n_n,i,j-1));\n\n            for(int j = p.n+1 ; j < p.nbSamples ; ++j)\n                for(int i = 0 ; i < p.n ; ++i)\n                    gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) - p.gamma * gsl_matrix_get(s.mat_temp_n_n,i,j-(p.n+1)));\n\n\n            /**************************************************/\n            /***** Compute the images of the sigma points *****/\n            /**************************************************/\n\n            // Compute the images of the sigma points\n            // and the mean of the dk\n            gsl_vector_set_zero(dk);\n            for(int j = 0 ; j < p.nbSamples ; j++)\n            {\n                // Equation 3.129\n                gsl_matrix_get_col(s.wk, s.sigmaPoints,j);\n                g(s.wk,xk, s.vec_temp_output);\n                gsl_matrix_set_col(s.dk, j, s.vec_temp_output);\n\n                // Equation 3.140\n                // Update the mean : y_mean = sum_[j=0..2n] w_j y_j\n                gsl_vector_scale(s.vec_temp_output, gsl_vector_get(s.wm,j));\n                gsl_vector_add(dk, s.vec_temp_output);\n            }\n        }\n\n        /**\n          * @short Returns a set of sigma points\n          */\n        void getSigmaPoints(ukf_param &p, ukf_state &s, gsl_matrix * sigmaPoints)\n        {\n            //gsl_matrix * sigmaPoints = gsl_matrix_alloc(p.n, p.nbSamples);\n\n            // ************************************************** //\n            // ************ Compute the sigma points ************ //\n            // ************************************************** //\n            // Equations 3.138\n            // w_k^j = w_(k-1)  <-- this is here denoted s.w\n            // w_k^j = w_(k-1) + gamma Sk_j for 1 <= j <= n\n            // w_k^j = w_(k-1) - gamma Sk_j for n+1 <= j <= 2n\n\n            // Perform a cholesky decomposition of Pk\n            gsl_matrix_memcpy(s.mat_temp_n_n, s.Pk);\n            gsl_linalg_cholesky_decomp(s.mat_temp_n_n);\n            // Set all the elements of Lpi strictly above the diagonal to zero\n            for(int k = 0 ; k < p.n ; ++k)\n                for(int j = 0 ; j < k ; ++j)\n                    gsl_matrix_set(s.mat_temp_n_n,j,k,0.0);\n\n            gsl_matrix_set_col(sigmaPoints,0, s.w);\n            for(int j = 1 ; j < p.n+1 ; ++j)\n                for(int i = 0 ; i < p.n ; ++i)\n                    gsl_matrix_set(sigmaPoints, i, j, gsl_vector_get(s.w, i) + p.gamma * gsl_matrix_get(s.mat_temp_n_n,i,j-1));\n\n            for(int j = p.n+1 ; j < p.nbSamples ; ++j)\n                for(int i = 0 ; i < p.n ; ++i)\n                    gsl_matrix_set(sigmaPoints, i, j, gsl_vector_get(s.w, i) - p.gamma * gsl_matrix_get(s.mat_temp_n_n,i,j-(p.n+1)));\n\n        }\n\n    } // parameter\n} // ukf\n\n#endif // SL_PARAMETER_NDIM_H\n", "meta": {"hexsha": "464ef3d67ccc1dba6318fdbb4cf073b02cec2402", "size": 17599, "ext": "h", "lang": "C", "max_stars_repo_path": "src/ukf_parameter_ndim.h", "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_issues_repo_path": "src/ukf_parameter_ndim.h", "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_forks_repo_path": "src/ukf_parameter_ndim.h", "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 52.0, "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "avg_line_length": 43.2407862408, "max_line_length": 162, "alphanum_fraction": 0.5240070459, "num_tokens": 4406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.36058986146080085}}
{"text": "// align.h\n//\n// prototypes for align.cc\n//\n// dw, 12/12/3\n\n#include <gsl/gsl_matrix.h>\n\n#include \"pdb.h\"\n#include <map>\n\n// find rigid body transformation z=Rx+t minimizing \n// least squares error ||y-z||**2\n// find rigid body transformation z=Rx+t minimizing \n// least squares error ||y-z||**2\nvoid align(gsl_matrix_const_view , gsl_matrix_const_view, gsl_matrix *, gsl_vector *, double *);\n\ndouble align(vector<atom>&, vector<atom>&, map<int, int>&, int, vector<atom>&,\n    vector<atom>&, map<int, int>&, int);\n\n", "meta": {"hexsha": "67f809f264cc93e146ab0cedabf6bc7d107e5701", "size": 515, "ext": "h", "lang": "C", "max_stars_repo_path": "core/LZerD/stats/align.h", "max_stars_repo_name": "tecdatalab/legacy", "max_stars_repo_head_hexsha": "9b5286d3375fff691a80ceb44172549e9a6bdee5", "max_stars_repo_licenses": ["Apache-2.0"], "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/LZerD/stats/align.h", "max_issues_repo_name": "tecdatalab/legacy", "max_issues_repo_head_hexsha": "9b5286d3375fff691a80ceb44172549e9a6bdee5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-06-17T16:13:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T05:23:59.000Z", "max_forks_repo_path": "db/Updater/generators/LZerD/stats/align.h", "max_forks_repo_name": "tecdatalab/biostructure", "max_forks_repo_head_hexsha": "a30e907e83fa5bbfb934d951b7c663b622104fcc", "max_forks_repo_licenses": ["Apache-2.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.5238095238, "max_line_length": 96, "alphanum_fraction": 0.6776699029, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3605495121184134}}
{"text": "/* StdVarTrajs_Sampling.c \n\nSimulation for calculating allele trajectories, adaptation from standing variation\nTo be fed into MSMS\n\nSimulation uses routines found with the GNU Scientific Library (GSL)\n(http://www.gnu.org/software/gsl/)\nSince GSL is distributed under the GNU General Public License \n(http://www.gnu.org/copyleft/gpl.html), you must download it \nseparately from this file.\n\nThis program can be compiled with e.g. GCC using a command like:\ngcc StdVarTrajs_Sampling -lm -lgsl -lgslcblas -I/usr/local/include -L/usr/local/lib StdVarTrajs_Sampling.c\n\nThen run by executing:\n./StdVarTrajs_Sampling N s h x0 reps cutoff\nWhere:\n- N is the (haploid) size\n- s is the selection coefficient of the beneficial allele\n- h is dominance of the beneficial allele\n- x0 is frequency of the allele when it started to be selected for\n- reps is how many times the second allele should FIX before simulation stops \n(the number of actual runs is greater due to stochastic loss)\n- cutoff denotes how high the derived allele can be in the neutral phase ('0' for fixation, '1' for x0 + 1/2N)\n*/\n\n/* Preprocessor statements */\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n#include <stddef.h>\n#include <string.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n\n#define INITTS 310000\n\n/* Function prototypes */\nvoid geninit(double *geninit, double pee);\nvoid selection(double *geninit, double h, double s);\nvoid reproduction(double *geninit);\nvoid bentraj(double *XFreq, unsigned int *btime, double *genotype, double x0, unsigned int rep, unsigned int N, double s, double h, const gsl_rng *r);\nvoid neutraj(double *NFreq, unsigned int *ntime, double *genotype, double x0, unsigned int rep, unsigned int N, unsigned int cutoff, const gsl_rng *r);\nvoid trajprint(double **AFreq, unsigned int *ttime, unsigned int rep);\nvoid Wait();\n\n/* Initialising genotypes */\nvoid geninit(double *geninit, double pee){\n\t\n\t*(geninit + 0) = (1-pee)*(1-pee);\n\t*(geninit + 1) = 2*pee*(1-pee);\n\t*(geninit + 2) = pee*pee;\n\n}\t/* End of gen initiation routine */\n\n/* Selection routine (single locus) */\nvoid selection(double *geninit, double h, double s){\n\t/* Fitness of each genotype */\n\tdouble WAA, WAa, Waa;\n\tdouble Wmean;\t\t\t\t/* Mean fitness */\n\t\n\tWaa = 1;\n\tWAa = 1 + h*s;\n\tWAA = 1 + s;\n\t\n\t/* Mean fitness calculation */\n\tWmean = ((*(geninit + 0))*Waa) + ((*(geninit + 1))*WAa) + ((*(geninit + 2))*WAA);\n\t\n\t/* Changing frequencies by selection */\n\t*(geninit + 0) = ((*(geninit + 0))*Waa)/Wmean;\n\t*(geninit + 1) = ((*(geninit + 1))*WAa)/Wmean;\n\t*(geninit + 2) = ((*(geninit + 2))*WAA)/Wmean;\n\t\n}\t/* End of selection routine */\n\n/* Reproduction routine */\nvoid reproduction(double *geninit){\n\n\t/* Fed-in genotype frequencies (for ease of programming) */\n\tdouble gaas, gAas, gAAs;\n\t/* Haplotypes */\n\tdouble xA, xa;\n\t\n\t/* Initial definition of genotypes */\n\tgaas = *(geninit + 0);\n\tgAas = *(geninit + 1);\n\tgAAs = *(geninit + 2);\n\t\n\t/* Baseline change in haplotype frequencies with obligate outcrossing */\n\txA = gAAs + (gAas)/2.0;\n\txa = gaas + (gAas)/2.0;\n\t\n\t/* Change in frequencies (HWE) */\n\t*(geninit + 0) = pow(xa,2);\n\t*(geninit + 1) = 2.0*xA*xa;\n\t*(geninit + 2) = pow(xA,2);\n\t\t\n}\t/* End of reproduction routine */\n\n\n/* Routine to simulate beneficial allele trajectory */\nvoid bentraj(double *XFreq, unsigned int *btime, double *genotype, double x0, unsigned int rep, unsigned int N, double s, double h, const gsl_rng *r){\n\n\tunsigned int gt = 1;\t\t/* Generation time */\n\tunsigned int done = 0;\t\t/* Counter if routine done or not */\n\tunsigned int exitl = 0;\t\t/* Decide if exit loop or not */\n\tunsigned int i;\t\t\t\t/* Genotype counter */\n\tdouble x = 0;\t\t\t\t/* Beneficial allele frequency */\n\t\n\tunsigned int *gensamp = calloc(3,sizeof(unsigned int));\t\t/* New population samples */\n\t\n\twhile(done == 0){\n\t\texitl = 0;\n\t\tgt = 1;\n\t\tx = x0;\n\t\t*(XFreq + 0) = x0;\n\t\t/* Initiating genotypes */\n\t\tgeninit(genotype,x0);\n\t\twhile(exitl == 0){\n\t\t\n\t\t\t/* Selection routine */\n    \t\tselection(genotype,h,s);\n    \t\t\n\t\t\t/* Reproduction routine */\n    \t\treproduction(genotype);\n    \t\t       \t\t\n    \t\t/* Sampling based on new frequencies */\n\t       \tgsl_ran_multinomial(r,3,N,genotype,gensamp);\n       \t\tfor(i = 0; i < 3; i++){\n    \t   \t\t*(genotype + i) = (*(gensamp + i))/(1.0*N);\n\t       \t}\n    \t\t\n\t       \tx = 0.5*(*(genotype + 1)) + (*(genotype + 2));\t\t\t\n\t\t\t*(XFreq + gt) = x;\n\t\t\tgt += 1;\n\t\t\tif(gt > INITTS){\n\t\t\t\tfprintf(stderr,\"Number of generations in selection trajectory exceed vector length (INITTS).\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\t\n\t\t\tif( (x == 1) || (x == 0) ){\n\t\t\t\texitl = 1;\n\t\t\t}\n\t\t}\n\t\n\t\tif(x == 1){\n\t\t\tdone = 1;\n\t\t\t*(btime + rep) = (gt - 1);\n\t\t}\n\t}\n\t\n\tfree(gensamp);\n\t\n}\n\n/* Routine to simulate neutral allele trajectory */\nvoid neutraj(double *NFreq, unsigned int *ntime, double *genotype, double x0, unsigned int rep, unsigned int N, unsigned int cutoff, const gsl_rng *r){\n\n\tunsigned int gt = 1;\t\t/* Generation time */\n\tunsigned int done = 0;\t\t/* Counter if routine done or not */\n\tunsigned int exitl = 0;\t\t/* Decide if exit loop or not */\n\tunsigned int i;\t\t\t\t/* Genotype counter */\n\tdouble x = 0;\t\t\t\t/* Neutral allele frequency */\n\tdouble xmax = 1;\t\t\t/* Value of x to use as maximum cutoff */\n\t\n\tunsigned int *gensamp = calloc(3,sizeof(unsigned int));\t\t/* New population samples */\n\t\n\tif(cutoff == 0){\n\t\txmax = 1;\n\t}else if(cutoff == 1){\n\t\txmax = x0 + (1.0/(2.0*N));\n\t\tif(xmax > 1){\n\t\t\txmax = 1;\n\t\t}\n\t}\n/*\tprintf(\"xmax is %lf\\n\",xmax);\t*/\n\t\n\twhile(done == 0){\n\t\texitl = 0;\n\t\tgt = 0;\t\t/* Note start from zero here since x0 case defined in selection trajectory */\n\t\tx = x0;\n\t\t\n\t\t/* Initiating genotypes */\n\t\tgeninit(genotype,x0);\n\t\t\n\t\twhile(exitl==0){\n\t\t\n\t\t\t/* Reproduction routine */\n    \t\treproduction(genotype);\n\t\t\t\n\t\t\t/* Random sampling of allele frequencies (drift) */\n\t       \tgsl_ran_multinomial(r,3,N,genotype,gensamp);\n       \t\tfor(i = 0; i < 3; i++){\n    \t   \t\t*(genotype + i) = (*(gensamp + i))/(1.0*N);\n\t       \t}\n\t       \tx = 0.5*(*(genotype + 1)) + (*(genotype + 2));\t\t\t\n\t\t\t*(NFreq + gt) = x;\n\n\t\t\tgt++;\n\t\t\tif(gt > INITTS){\n\t\t\t\tprintf(\"Number of generations in neutral trajectory exceed vector length (INITTS).\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\t\n\t\t\tif( (x == 0) || (x >= xmax) ){\n\t\t\t\texitl = 1;\n\t\t\t}\n\t\t}\n\t\n\t\tif(x == 0){\n\t\t\tdone = 1;\n\t\t\t*(ntime + rep) = (gt - 1);\n\t\t}\n\t}\n\t\n\tfree(gensamp);\n\t\n}\n\n/* Print out trajectories to file */\nvoid trajprint(double **AFreq, unsigned int *ttime, unsigned int rep){\n\tunsigned int j;\n\tchar filename[32];\n\tFILE *ofp_tr;\t\t\t\t/* Pointer for file output */\n\n\tsprintf(filename,\"Traj/ATraj%d.dat\",(rep + 1));\n\tofp_tr = fopen(filename,\"w\");\n\t\n\tfor(j = 0; j < *(ttime + rep); j++){\n\t\tfprintf(ofp_tr,\"%lf %lf %lf\\n\",*((*(AFreq + 0)) + j),*((*(AFreq + 1)) + j),*((*(AFreq + 2)) + j));\n\t}\n\t\n\tfclose(ofp_tr);\n\t\n}\n\nvoid Wait(){\n\tprintf(\"Press Enter to Continue\");\n\twhile( getchar() != '\\n' );\n\tprintf(\"\\n\");\t\n}\n\n/* Main program */\nint main(int argc, char *argv[]){\n\n\t/* Declare variables here */\n\tunsigned int i, a;\t\t\t/* Rep counter, memory counter */\n\tunsigned int N = 0;\t\t\t/* Population Size */\n\tunsigned int Nreps = 0;\t\t/* Number of repetitions */\n\tunsigned int acc = 0;\t\t/* Accumulator (when merging two trajectories) */\n\tunsigned int es = 10;\t\t/* How many extra steps to put in the trajectory files */\n\tunsigned int cutoff = 0;\t/* What kind of back-in-time cutoff to use */\n\tint j;\t\t\t\t\t\t/* Timestep counter */\n\tdouble s = 0;\t\t\t\t/* Strength of selection */\n\tdouble h = 0;\t\t\t\t/* Dominance level */\n\tdouble x0 = 0;\t\t\t\t/* Initial allele frequency */\n\tdouble lim = 0;\t\t\t\t/* Limit of acceptable allele frequencies */\n\tdouble dx = 0;\t\t\t\t/* Rescaled timestep so can be used by MSMS */\n\tFILE *ofp_sd;\t\t\t\t/* Pointer for seed output */\n\n\t/* GSL random number definitions */\n\tconst gsl_rng_type * T;\n\tgsl_rng * r;\n\t\n\t/* Reading in data from command line */\n\t/* <Program> N s h x0 NReps cutoff */\n\tif(argc != 7){\n\t\tfprintf(stderr,\"Six inputs are needed (N s h x0 Reps cutoff).\\n\");\n\t\texit(1);\n\t}\n\t\n\tN = atoi(argv[1]);\n\tif(N <= 0){\n\t\tfprintf(stderr,\"Total Population size N is zero or negative, not allowed.\\n\");\n\t\texit(1);\n\t}\n\t\n\t/* Defining min frequency limit ** based on unscaled N ** */\n\tlim = (1.0/(1.0*N));\n\t\n\t/* Defining timestep, dx = 1/4N since that's what MSMS uses */\n\tdx = (1.0/(4.0*N));\n\t\n\ts = strtod(argv[2],NULL);\n\tif(s < 0){\n\t\tfprintf(stderr,\"Allele strength s is negative, not allowed.\\n\");\n\t\texit(1);\n\t}\n\t\n\th = strtod(argv[3],NULL);\n\tif(h < 0 || h > 1){\n\t\tfprintf(stderr,\"Dominance value must lie between 0 and 1.\\n\");\n\t\texit(1);\n\t}\n\t\n\tx0 = strtod(argv[4],NULL);\n\tif(x0 < lim || x0 > (1-lim)){\n\t\tfprintf(stderr,\"Initial mutant frequency must lie between %0.5lf and %0.5lf.\\n\",lim,1-lim);\n\t\texit(1);\n\t}\n\t\n\t/* Number of samples/reps to take */\n\tNreps = atoi(argv[5]);\n\tif(Nreps <= 0){\n\t\tfprintf(stderr,\"Must set positive number of repetitions.\\n\");\n\t\texit(1);\n\t}\n\t\n\t/* Determining cutoff */\n\tcutoff = atoi(argv[6]);\n\tif(!(cutoff == 0 || cutoff == 1)){\n\t\tfprintf(stderr,\"'Cutoff' switch must equal 0 or 1.\\n\");\n\t\texit(1);\n\t}\n\t\n\tunsigned int *btime = calloc(Nreps,sizeof(unsigned int));\t\t\t/* Number of generations needed for ben allele fixation */\n\tunsigned int *ntime = calloc(Nreps,sizeof(unsigned int));\t\t\t/* Number of generations needed for neut allele loss */\n\tunsigned int *ttime = calloc(Nreps,sizeof(unsigned int));\t\t\t/* Number of generations needed for whole processes */\n\tdouble *genotype = calloc(3,sizeof(double));\t\t\t\t\t\t/* Genotype frequencies */\n\t\n\t/* create a generator chosen by the \n    environment variable GSL_RNG_TYPE */\n     \n\tgsl_rng_env_setup();\n\tif (!getenv(\"GSL_RNG_SEED\")) gsl_rng_default_seed = time(0);\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc(T);\n\tofp_sd = fopen(\"Seed.dat\",\"w\");\n\tfprintf(ofp_sd,\"%lu\\n\",gsl_rng_default_seed);\n\tfclose(ofp_sd);\n\t\n\tmkdir(\"Traj/\", 0777);\n\t\n\t/* Executing simulation */\n\tfor(i = 0; i < Nreps; i++){\n\t\t\n\t\tif(Nreps > 100){\n\t\t\tif(i%100 == 0){\n\t\t\t\tprintf(\"Starting run %d\\n\",i);\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tdouble *XFreq = calloc(INITTS,sizeof(double));\t\t\t/* Beneficial allele frequency */\n\t\tdouble *NFreq = calloc(INITTS,sizeof(double));\t\t\t/* Neutral allele frequency */\n\n\t\t/* Simulating beneficial trajectories */\n\t\tbentraj(XFreq, btime, genotype, x0, i, N, s, h, r);\n\t\t\n\t\t/* Simulation neutral trajectory */\n\t\tneutraj(NFreq, ntime, genotype, x0, i, N, cutoff, r);\n\t\t\n\t\t*(ttime + i) = (*(btime+i)) + (*(ntime+i) + 2 + es);\n/*\t\tprintf(\"%d %d %d\\n\",*(btime+i),*(ntime+i),*(ttime+i));\t*/\n\t\t\n\t\t/* Defining memory for AFreq */\n\t\tdouble **AFreq = calloc(3,sizeof(double *));\t\t\t\t\t/* Allele frequency over time */\n\t\tfor(a = 0; a < 3; a++){\t\t\t\t\t\t\t\t\t\t\t/* Assigning space for each run */\n\t\t\tAFreq[a] = calloc(*(ttime + i),sizeof(double));\n\t\t}\n\t\t\n\t\t/* Merging trajectories \n\t\tTiming is set up so tfix = 0\n\t\tAnd discrete generations is scaled by timestep, dx\n\t\t*/\n\t\t\n\t\t/* First add ten timesteps for x = 0\n\t\tSo trajectory fully covered in MSMS */\n\t\tacc = 0;\n\t\tfor(j = 0; j < es; j++){\n\t\t\t*((*(AFreq + 0)) + j) = ((*(ttime + i) - es - 1)*dx) + (es - j);\n\t\t\t*((*(AFreq + 1)) + j) = 1.0;\n\t\t\t*((*(AFreq + 2)) + j) = 0.0;\n\t\t}\n\t\tfor(j = *(ntime + i); j >= 0; j--){\n\t\t\t*((*(AFreq + 0)) + acc + es) = (*(ttime + i) - acc - es - 1)*dx;\n\t\t\t*((*(AFreq + 1)) + acc + es) = 1.0-(*(NFreq + j));\n\t\t\t*((*(AFreq + 2)) + acc + es) = *(NFreq + j);\n\t\t\tacc++;\n\t\t}\n\t\tfor(j = 0; j <= *(btime + i); j++){\n\t\t\t*((*(AFreq + 0)) + acc + es) = (*(ttime + i) - acc - es - 1)*dx;\n\t\t\t*((*(AFreq + 1)) + acc + es) = 1.0-(*(XFreq + j));\n\t\t\t*((*(AFreq + 2)) + acc + es) = *(XFreq + j);\n\t\t\tacc++;\n\t\t}\n\t\t/*\n\t\t*(ttime + i) = (acc-1);\t\n\t\tprintf(\"%d\\n\",*(ttime+i));\n\t\t*/\n\t\t\n\t\tfree(NFreq);\n\t\tfree(XFreq);\n\t\t\n\t\t/* Printout of trajectories */\n\t\ttrajprint(AFreq, ttime, i);\n\t\t\n\t\tfor(a = 0; a < 3; a++){\n\t \t\tfree(AFreq[a]);\n\t\t}\n\t\tfree(AFreq);\n\t\t\n\t}\n\t\n\tgsl_rng_free(r);\n\tfree(genotype);\n\tfree(ttime);\n\tfree(ntime);\n\tfree(btime);\n\t\t\n\treturn 0;\n\t\n}\t/* End of main program */\n\n/* End of File */", "meta": {"hexsha": "cfd4fc49f9b516a5bd4bb0c64fdca5ef4be9d858", "size": 11896, "ext": "c", "lang": "C", "max_stars_repo_path": "StdVarTrajs_Sampling.c", "max_stars_repo_name": "MattHartfield/SweepDomSelf", "max_stars_repo_head_hexsha": "473915781ba2a180ef54234e8adbd8cdf2ea81d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "StdVarTrajs_Sampling.c", "max_issues_repo_name": "MattHartfield/SweepDomSelf", "max_issues_repo_head_hexsha": "473915781ba2a180ef54234e8adbd8cdf2ea81d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StdVarTrajs_Sampling.c", "max_forks_repo_name": "MattHartfield/SweepDomSelf", "max_forks_repo_head_hexsha": "473915781ba2a180ef54234e8adbd8cdf2ea81d8", "max_forks_repo_licenses": ["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.3914081146, "max_line_length": 151, "alphanum_fraction": 0.6072629455, "num_tokens": 3791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.36053760626224673}}
{"text": "#include <stdlib.h>\n#include <cblas.h>\n\n#include \"tasks.h\"\n\n\nvoid syrk_task_par_reconfigure(int nth)\n{\n    // empty\n}\n\n\nvoid syrk_task_par_finalize(void)\n{\n    // empty\n}\n\n\nvoid syrk_task_par(void *ptr, int nth, int me)\n{\n    struct syrk_task_arg *arg = (struct syrk_task_arg*) ptr;\n\n    int n       = arg->n;\n    int k       = arg->k;\n    double *A21 = arg->A21;\n    double *A22 = arg->A22;\n    int ldA     = arg->ldA;\n\n    // Balance the load by flops.\n    int part[nth + 1];\n    const int total_work = n * (n + 1) / 2;\n    const int ideal_part_work = total_work / nth;\n    part[0] = 0;\n    part[nth] = n;\n    for (int k = 1; k < nth; ++k) {\n        part[k] = part[k - 1];\n        int work = 0;\n        while (work < ideal_part_work && part[k] < n) {\n            work += n - part[k];\n            part[k] += 1;\n        }\n    }\n\n    const int my_first_col = part[me];\n    const int my_num_cols  = part[me + 1] - part[me];\n    const int i1 = my_first_col;\n    const int i2 = i1 + my_num_cols;\n    const int m2 = n - i2;\n\n    // TODO Insert picture (see krnl_syrk in task_chol_par).\n\n    if (my_num_cols > 0) {\n        cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans,\n                    my_num_cols, k,\n                    -1.0, A21 + i1,                           ldA,\n                     1.0, A22 + i1 + my_first_col * ldA,      ldA);\n    }\n\n    if (m2 > 0) {\n        cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,\n                    m2, my_num_cols, k,\n                    -1.0, A21 + i2,                      ldA,\n                          A21 + my_first_col,            ldA,\n                     1.0, A22 + i2 + my_first_col * ldA, ldA);\n    }\n}\n\n", "meta": {"hexsha": "fe0e5b500142a56769daf35c0fe03739074a6abc", "size": 1663, "ext": "c", "lang": "C", "max_stars_repo_path": "src/examples/dpotrf/task-syrk-par.c", "max_stars_repo_name": "NLAFET/pcp-runtime", "max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/dpotrf/task-syrk-par.c", "max_issues_repo_name": "NLAFET/pcp-runtime", "max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/dpotrf/task-syrk-par.c", "max_forks_repo_name": "NLAFET/pcp-runtime", "max_forks_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_forks_repo_licenses": ["BSD-3-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.4558823529, "max_line_length": 67, "alphanum_fraction": 0.4924834636, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.36020496371853805}}
{"text": "/**\n* Drizzle utilities\n*/\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_statistics.h>\n#include <math.h>\n\n#include \"aXe_grism.h\"\n#include \"aXe_utils.h\"\n#include \"spc_trace_functions.h\"\n#include \"crossdisp_utils.h\"\n#include \"aper_conf.h\"\n#include \"trace_conf.h\"\n#include \"disp_conf.h\"\n#include \"spc_wl_calib.h\"\n#include \"drizzle_utils.h\"\n\n\nd_point\nget_refwave_position(dispstruct * disp, trace_func * trace, d_point refpix,\n                     aperture_conf *conf)\n{\n  double a=0.0;\n  double b, c, c_star;\n  double *cf;\n  double rot;\n  double dx, dy, dtr;\n  d_point res;\n\n  // check for a dispersion solution\n  // higher that quadratic order\n  if (disp->pol->size > 3)\n    // this can not be solved; give an error\n    aXe_message(aXe_M_FATAL, __FILE__, __LINE__,\n                \"Order of dispersion solution: %i!\\n\"\n                \"At most qudratic solutions are allowed!\\n\",\n                disp->pol->size-1);\n  else if (disp->pol->size > 2)\n    // store the quadratic term, if it exists\n    a = gsl_vector_get(disp->pol, 2);  // ddlambda-term\n  else\n    // set the qudratic term to zero\n    a=0.0;\n\n  // store the constant and linear terms\n  b = gsl_vector_get(disp->pol, 1);  // dlambda-term\n  c = gsl_vector_get(disp->pol, 0);  // lambda0-term\n\n  // store the dydx value\n  cf = trace->data;\n\n  // dydx -->  rotation angle\n  rot = get_rotation_angle(cf[2]);\n\n  // determine the wavelength difference\n  c_star = c - conf->drz_lamb0;\n\n  // transform the wavelength difference\n  // into a path length difference\n  if (a)\n    dtr = (-1.0*b+sqrt(b*b - 4.0*a*c_star))/(2.0*a);\n  else\n    dtr = c_star/b;\n\n  // path length difference --> dx, dy\n  dx = dtr*cos(rot);\n  dy = dtr*sin(rot);\n\n  // compute the absolute values\n  // for the reference position\n  // in the stamp images\n  res.x = refpix.x + dx;\n  res.y = refpix.y + dy;\n\n  // return the result\n  return res;\n}\n\ndouble\nget_drizzle_width(object *ob, int beamnum,trace_func * trace)\n{\n  double drizzle_width, drizzle_orient;\n  double orig_width, orig_orient;\n  double rotation, angle, oangle, factor;\n  double *cf;\n  beam *b = ob->beams+beamnum;\n\n  cf = trace->data;\n  rotation = get_rotation_angle(cf[2]);\n\n  orig_orient = b->orient;\n  orig_width  = b->width;\n\n  drizzle_orient = orig_orient-rotation;\n\n  angle  = drizzle_orient / M_PI * 180.;\n  oangle = orig_orient / M_PI * 180.;\n\n  drizzle_width = fabs(orig_width * sin (drizzle_orient));\n  factor = drizzle_width/orig_width;\n\n  if (angle > 180.0)\n    angle = angle-180.0;\n  if (angle < 30.0 || angle > 150.0)\n     fprintf (stdout,\n              \"Angle: %4.0f --> %4.0f, Width: %5.1f --> %5.1f, %5.3f\\n\",\n              oangle, angle, orig_width, drizzle_width, factor);\n\n  return drizzle_width;\n}\n\ngsl_matrix  *\nget_drizzle_coeffs(dispstruct * disp, trace_func * trace,\n                   int boxwidth, int boxheight, int trlength,\n                   double relx, double rely, aperture_conf *conf,\n                   double orient, dispstruct * outdisp, double cdcorr,\n                   double sprefreso, double spmeanreso)\n{\n  double a, b, c;\n  double ao, bo, co, bref, cref;\n  double a11, a12, a21, a22;\n  double xr, yr;\n  //double lambda0;\n  //double dlambda;\n  double tmp, rotation;\n  double *cf;\n  double shear_term;\n\n  gsl_matrix * ret = gsl_matrix_alloc(2,11);\n  gsl_matrix * rotcoeffs;\n\n  gsl_matrix_set_all (ret, 0.0);\n\n\n  /* get the dispersion at the objects point */\n  if (disp->pol->size > 2)\n    a = gsl_vector_get(disp->pol, 2);\n    //    fprintf (stdout, \"quadratic solution:  %f\\n\", a);\n  else\n    a = 0.0;\n\n  b = gsl_vector_get(disp->pol, 1);  // dlambda-term\n  c = gsl_vector_get(disp->pol, 0);  // lambda0-term\n\n  /* get the dispersion at the mean reference point */\n  if (outdisp->pol->size > 2){\n    ao = gsl_vector_get(outdisp->pol, 2);\n    //    fprintf (stdout, \"quadratic solution:  %f, old: %f\\n\", a, ao);\n  }\n  else{\n    ao = 0.0;\n  }\n  bo = gsl_vector_get(outdisp->pol, 1);  // dlambda-term\n  co = gsl_vector_get(outdisp->pol, 0);  // lambda0-term\n  if (conf->drz_resol == 0.0) {\n    conf->drz_resol = bo + ao*((double)trlength)/2.0;\n  }\n  if (conf->drz_lamb0 == 0.0) {\n    conf->drz_lamb0 = co;\n  }\n\n  //  fprintf (stdout, \"lambda terms:  4785.0 <-> %f, 24.0 <-> %f\\n\", cref, bref);\n\n  cref = conf->drz_lamb0;\n  bref = conf->drz_resol;\n  bref = sprefreso;\n\n  // Bugfix on Sept. 15th 2010:\n  // Check whether the ratio of the average dispersion on the grism images\n  // and the dispersion on the drizzled images is outsidethe range 0.95 < ratio < 1.05.\n  // If yes, adjust \"trlength\" which, from now on, is the length of the\n  // drizzled image. This fix is necessary to allow a different sampling\n  // in axedrizzle. The range was introduced such that the bug-fixed\n  // version delivers identical results when using the default sampling.\n  if ((spmeanreso / sprefreso > 1.05) || (spmeanreso / sprefreso < 0.95))\n    trlength = (int)(spmeanreso / sprefreso * (double)trlength) + 0.5;\n\n  /* put the below lines to go BACK to\n   * the old computation of the length of\n   * the aXedrizzled images:\n  fprintf(stdout, \"New spectral length: %i\", trlength);\n  trlength = (int)ceil(bo/bref*sqrt(pow((double)boxwidth,2.0)\n                                    +pow((double)boxheight,2.0)));\n  trlength = (int)ceil(spmeanreso/sprefreso*sqrt(pow((double)boxwidth,2.0)\n                                                 +pow((double)boxheight,2.0)));\n  fprintf(stdout, \"<--> old spectral length: %i\\n\", trlength);\n  */\n\n  //fprintf (stdout,\"Drizzled to resolution: %e, mean resolution for object: %e\\n\", sprefreso, spmeanreso);\n\n\n  gsl_matrix_set(ret, 0,10,trlength);\n  //  gsl_matrix_set(ret, 1,10,bref);\n\n  cf = trace->data;\n  rotation = get_rotation_angle(cf[2]);\n  rotcoeffs = get_coeffs_back(trace);\n  a11 = gsl_matrix_get(rotcoeffs,0,0);\n  a12 = gsl_matrix_get(rotcoeffs,0,1);\n  a21 = gsl_matrix_get(rotcoeffs,1,0);\n  a22 = gsl_matrix_get(rotcoeffs,1,1);\n\n  // the following lines have to be changed\n  // in order to go from a integer\n  // center definition to floating point center\n  // definition.\n  xr = (relx+1.0)-((double)(boxwidth/2)+1);  // +1.0 to compensate for \"sp_sex.c\" around line 537\n  yr = (rely+1.0)-((double)(boxheight/2)+1); // +1.0 to compensate for \"sp_sex.c\" around line 537\n\n  if (b < 0.0)\n    shear_term = -tan(orient-rotation);\n  else\n    shear_term = tan(orient-rotation);\n\n  // Transformations for X, without the lambda-terms, only rotation:\n  //  tmp = xoffs-(((double)trlength/2.0)+1)-a11*xr-a12*yr;\n  //  gsl_matrix_set(ret, 0,0,tmp);  // constant term\n\n  //  tmp = a11;\n  //  gsl_matrix_set(ret, 0,1,tmp);  // x-term\n\n  //  tmp = a12;\n  //  gsl_matrix_set(ret, 0,2,tmp);  // y-term\n  //----------------------------------------------------------------------------------\n\n\n\n\n  //------------------------------------------------------------------\n  // Mathematica based run\n  tmp = 1.0/bref*(c - cref - a11*b*xr + a*a11*a11*xr*xr - a12*b*yr + 2*a*a11*a12*xr*yr + a*a12*a12*yr*yr) +\n    (a21*xr + a22*yr)/shear_term - ((double)(trlength/2)+1.0) + conf->drz_xstart;\n  gsl_matrix_set(ret, 0,0,tmp);  // constant term\n\n  tmp = 1.0/bref*(a11*b - 2*a*a11*a11*xr - 2*a*a11*a12*yr) - a21/shear_term;\n  gsl_matrix_set(ret, 0,1,tmp);  // x-term\n\n  tmp = 1.0/bref*(a12*b - 2*a*a12*a12*yr - 2*a*a11*a12*xr) - a22/shear_term;\n  gsl_matrix_set(ret, 0,2,tmp);  // y-term\n\n  tmp = a*a11*a11/bref;\n  gsl_matrix_set(ret, 0,3,tmp);  // x^2-term\n\n  tmp = 2*a*a11*a12/bref;\n  gsl_matrix_set(ret, 0,4,tmp); ; // xy-term\n\n  tmp = a*a12*a12/bref;\n  gsl_matrix_set(ret, 0,5,tmp);  // y^2-term\n\n  //------------------------------------------------------------------\n\n\n  // Transformations for Y:\n  tmp = -1.0*(a21*xr+a22*yr) * cdcorr; // -1.5  is some kind of a fudge factor, no idea where it comes from\n  gsl_matrix_set(ret, 1,0,tmp);  // constant term\n\n  tmp = a21 * cdcorr;\n  gsl_matrix_set(ret, 1,1,tmp);  // x-term\n\n  tmp = a22 * cdcorr;\n  gsl_matrix_set(ret, 1,2,tmp);  // y-term\n\n  gsl_matrix_free(rotcoeffs);\n\n  return ret;\n}\n\ngsl_matrix *\nget_coeffs_back(trace_func * trace)\n{\n  double *cf;\n  double rotation;\n  gsl_matrix * ret = gsl_matrix_alloc(2,2);\n\n  //  ret = gsl_matrix_alloc (2,2);\n  gsl_matrix_set_all (ret, 0.0);\n\n  cf = trace->data;\n\n  rotation = get_rotation_angle(cf[2]);\n\n  gsl_matrix_set(ret, 0, 0,      cos(rotation));\n  gsl_matrix_set(ret, 0, 1,      sin(rotation));\n  gsl_matrix_set(ret, 1, 0, -1.0*sin(rotation));\n  gsl_matrix_set(ret, 1, 1,      cos(rotation));\n\n  return ret;\n}\n\ndouble\nget_rotation_angle(double dxdy){\n  double rotation=0.0;\n\n  rotation = atan2(dxdy, 1.0);\n\n  return rotation;\n}\n\n// Start functions for an alternative approach to store the object information\nobjectobs **\nmalloc_objectobs(){\n  objectobs **allobjects;\n\n  allobjects = (objectobs **) malloc (NMAXOBJ*sizeof(objectobs *));\n\n  return allobjects;\n}\n\nvoid\nfree_objectobs(objectobs **allobjects){\n  //  int i, nobjs=0;\n  //  while (allobjects[nobjs])\n  //    nobjs++;\n  //  for (i=0; i<nobjs; i++){\n  //      free(allobjects[i]);\n  //      //    allobjects[i] = NULL;\n  //  }\n  free(allobjects);\n}\n\nint\nadd_observation(char * filename, char *  conf_file, objectobs ** allobjects, int nobjects,\n                object ** oblist, int list_size, px_point pixmax, int sci_numext)\n{\n\n  int i, j, dec;\n  int beamID = 0;\n  int get_scale=0;\n  int tlength;\n  gsl_matrix * drzcoeffs;\n  double cdscale;\n  double drzscale;\n  dispstruct * disp;\n  calib_function *wl_calib;\n  double l1, l2, spreso;\n\n  drzcoeffs = get_crossdisp_matrix(filename, sci_numext);\n\n  if (drzcoeffs->size1 > 1 && drzcoeffs->size2)\n    get_scale = 1;\n\n  if (get_scale){\n    drzscale =  (double)get_float_from_keyword(filename, 1, \"DRZSCALE\");\n  }\n  for (i=0; i < list_size; i++){\n    if (oblist[i]->beams[beamID].ignore == 0){\n      dec = 0;\n\n      if (get_scale)\n        cdscale = drzscale * get_crossdisp_scale(oblist[i]->beams[beamID].spec_trace,\n                                                 oblist[i]->beams[beamID].refpoint, drzcoeffs, pixmax);\n      else\n        cdscale=1.0;\n\n      disp = get_dispstruct_at_pos(conf_file, 1, beamID,oblist[i]->beams[beamID].refpoint);\n      wl_calib = create_calib_from_gsl_vector(1, disp->pol);\n      l1 =  wl_calib->func (0.0,  wl_calib->order,  wl_calib->coeffs);\n      l2 =  wl_calib->func (1.0,  wl_calib->order,  wl_calib->coeffs);\n      spreso = fabs(l2-l1);\n\n      // compute the tracelength\n      tlength = get_beam_trace_length(oblist[i]->beams[beamID]);\n\n      for (j=0; j < nobjects; j++){\n        if (allobjects[j]->OBJID == oblist[i]->ID){\n          add_obs_to_allobj(allobjects[j], oblist[i], pixmax, cdscale, spreso, tlength);\n          dec = 1;\n        }\n      }\n      if (dec == 0) {\n        nobjects = add_obj_to_allobj(allobjects, nobjects, oblist[i], pixmax, cdscale, spreso, tlength);\n      }\n      free_dispstruct(disp);\n      free_calib(wl_calib);\n    }\n  }\n  gsl_matrix_free(drzcoeffs);\n  return nobjects;\n}\n\nvoid\nadd_obs_to_allobj(objectobs *actobject, object * actobs, px_point pixmax, double cdscale, double spreso, int tlength)\n{\n\n  int xmin, xmax, ymin, ymax;\n  //double m, b;\n  gsl_vector_int * xvec;\n  gsl_vector_int * yvec;\n  px_point bbox;\n  px_point mins;\n\n  double *gaga;\n\n  xvec = gsl_vector_int_alloc (4);\n  yvec = gsl_vector_int_alloc (4);\n\n  /* Store the refpoint */\n  actobject->refpoint[actobject->nobs].x = actobs->beams[0].refpoint.x;\n  actobject->refpoint[actobject->nobs].y = actobs->beams[0].refpoint.y;\n\n  //*************************************************\n  // patch to correct the reference point in case\n  // that the the trace descritpion\n  // does have a non negligeable first order term!\n  gaga = actobs->beams[0].spec_trace->data;\n  actobject->refpoint[actobject->nobs].y = actobject->refpoint[actobject->nobs].y + gaga[1];\n  //*************************************************\n\n  gsl_vector_int_set(xvec, 0, actobs->beams[0].corners[0].x);\n  gsl_vector_int_set(xvec, 1, actobs->beams[0].corners[1].x);\n  gsl_vector_int_set(xvec, 2, actobs->beams[0].corners[2].x);\n  gsl_vector_int_set(xvec, 3, actobs->beams[0].corners[3].x);\n  xmin = gsl_stats_int_min(xvec->data, 1, 4);\n  xmax = gsl_stats_int_max(xvec->data, 1, 4);\n  gsl_vector_int_set(yvec, 0, actobs->beams[0].corners[0].y);\n  gsl_vector_int_set(yvec, 1, actobs->beams[0].corners[1].y);\n  gsl_vector_int_set(yvec, 2, actobs->beams[0].corners[2].y);\n  gsl_vector_int_set(yvec, 3, actobs->beams[0].corners[3].y);\n  ymin = gsl_stats_int_min(yvec->data, 1, 4);\n  ymax = gsl_stats_int_max(yvec->data, 1, 4);\n\n  bbox = recalc_bbox(xmin, xmax, ymin, ymax, pixmax);\n  mins = recalc_mins(xmin, xmax, ymin, ymax, pixmax);\n\n  actobject->width[actobject->nobs]    = bbox.x;\n  actobject->height[actobject->nobs]   = bbox.y;\n  actobject->tlength[actobject->nobs]  = tlength;\n  actobject->objwidth[actobject->nobs] = actobs->beams[0].width;\n  actobject->orient[actobject->nobs]   = actobs->beams[0].orient;\n  actobject->cdscale[actobject->nobs]   = cdscale;\n  actobject->spreso[actobject->nobs]   = spreso;\n\n  actobject->relrefpt[actobject->nobs].x = actobs->beams[0].refpoint.x - (double)mins.x;\n  actobject->relrefpt[actobject->nobs].y = actobs->beams[0].refpoint.y - (double)mins.y;\n\n  actobject->nobs = actobject->nobs + 1;\n\n  gsl_vector_int_free(xvec);\n  gsl_vector_int_free(yvec);\n}\n\nint\nadd_obj_to_allobj(objectobs **allobjects, int nobjects, object * actobs,\n                   px_point pixmax, double cdscale, double spreso, int tlength)\n{\n  int xmin, xmax, ymin, ymax;\n  //double m, b;\n\n  gsl_vector_int * xvec;\n  gsl_vector_int * yvec;\n\n  px_point bbox;\n  px_point mins;\n\n  double *gaga;\n\n  //  object *ob = malloc (sizeof (object));\n  objectobs *objobs = malloc (sizeof (objectobs));\n\n  xvec = gsl_vector_int_alloc (4);\n  yvec = gsl_vector_int_alloc (4);\n\n  allobjects[nobjects] = objobs;\n  /* Store the refpoint */\n  allobjects[nobjects]->refpoint[0].x = actobs->beams[0].refpoint.x;\n  allobjects[nobjects]->refpoint[0].y = actobs->beams[0].refpoint.y;\n\n  //*************************************************\n  // patch to correct the reference point in case\n  // that the the trace descritpion\n  // does have a non negligeable first order term!\n  gaga = actobs->beams[0].spec_trace->data;\n  allobjects[nobjects]->refpoint[0].y = allobjects[nobjects]->refpoint[0].y + gaga[1];\n  //*************************************************\n\n  allobjects[nobjects]->OBJID = actobs->ID;\n  allobjects[nobjects]->nobs = 1;\n  allobjects[nobjects]->pointer = 0;\n\n\n  gsl_vector_int_set(xvec, 0, actobs->beams[0].corners[0].x);\n  gsl_vector_int_set(xvec, 1, actobs->beams[0].corners[1].x);\n  gsl_vector_int_set(xvec, 2, actobs->beams[0].corners[2].x);\n  gsl_vector_int_set(xvec, 3, actobs->beams[0].corners[3].x);\n  xmin = gsl_stats_int_min(xvec->data, 1, 4);\n  xmax = gsl_stats_int_max(xvec->data, 1, 4);\n\n  gsl_vector_int_set(yvec, 0, actobs->beams[0].corners[0].y);\n  gsl_vector_int_set(yvec, 1, actobs->beams[0].corners[1].y);\n  gsl_vector_int_set(yvec, 2, actobs->beams[0].corners[2].y);\n  gsl_vector_int_set(yvec, 3, actobs->beams[0].corners[3].y);\n  ymin = gsl_stats_int_min(yvec->data, 1, 4);\n  ymax = gsl_stats_int_max(yvec->data, 1, 4);\n\n  bbox = recalc_bbox(xmin, xmax, ymin, ymax, pixmax);\n  mins = recalc_mins(xmin, xmax, ymin, ymax, pixmax);\n\n  allobjects[nobjects]->width[0]   = bbox.x;\n  allobjects[nobjects]->height[0]  = bbox.y;\n  allobjects[nobjects]->tlength[0] = tlength;\n  allobjects[nobjects]->objwidth[0] = actobs->beams[0].width;\n  allobjects[nobjects]->orient[0]   = actobs->beams[0].orient;\n  allobjects[nobjects]->cdscale[0]  = cdscale;\n  allobjects[nobjects]->spreso[0]   = spreso;\n\n  allobjects[nobjects]->relrefpt[0].x = actobs->beams[0].refpoint.x - (double)mins.x;\n  allobjects[nobjects]->relrefpt[0].y = actobs->beams[0].refpoint.y - (double)mins.y;\n\n  ++nobjects;\n\n  gsl_vector_int_free(xvec);\n  gsl_vector_int_free(yvec);\n\n  return nobjects;\n}\n\nvoid print_objectobs(objectobs **allobjects, int nobjects){\n  int i, j;\n\n  for (i = 0; i < nobjects; i++){\n   fprintf(stdout, \"OBJID: %i, no of observ.: %i\\n\", allobjects[i]->OBJID, allobjects[i]->nobs);\n    for (j = 0; j < allobjects[i]->nobs; j++){\n      fprintf(stdout, \"No %i: width %f, height: %f, \\n\", j, allobjects[i]->relrefpt[j].x, allobjects[i]->relrefpt[j].y);\n    }\n  }\n}\nvoid print_objectobs2(objectobs allobjects[], int nobjects){\n  int i, j;\n\n  for (i = 0; i < nobjects; i++){\n   fprintf(stdout, \"OBJID: %i, no of observ.: %i\\n\", allobjects[i].OBJID, allobjects[i].nobs);\n    for (j = 0; j < allobjects[i].nobs; j++){\n      fprintf(stdout, \"No %i: width %f, height: %f, \\n\", j, allobjects[i].relrefpt[j].x, allobjects[i].relrefpt[j].y);\n    }\n  }\n}\nint make_refpoints( char * conf_file, char * filename, px_point pixmax, objectobs **allobjects, int nobjects)\n{\n  int i, j;\n  int nobs;\n  int max_width, max_height, omax;\n  double xmean, ymean;\n  //double xdata[NMAXOBS];\n  //double ydata[NMAXOBS];\n  //  objectobs  oneobject;\n  objectobs *oneobject; // = malloc (sizeof (objectobs));\n\n  gsl_vector * xvec;\n  gsl_vector * yvec;\n  aperture_conf *conf;\n  gsl_matrix * drzcoeffs;\n  //double cdscale;\n  double drzscale;\n  trace_func  *trace;\n  int beamID=0;\n  dispstruct * disp;\n  calib_function *wl_calib;\n  double l1, l2;\n\n  conf = get_aperture_descriptor(conf_file);\n  get_extension_numbers(filename, conf,conf->optkey1,conf->optval1);\n  drzcoeffs = get_crossdisp_matrix(filename,conf->science_numext);\n  drzscale =  (double)get_float_from_keyword(filename, 1, \"DRZSCALE\");\n\n  for (i=0; i < nobjects; i++){\n    oneobject = allobjects[i];\n    nobs = oneobject->nobs;\n\n    xvec = gsl_vector_alloc (nobs);\n    yvec = gsl_vector_alloc (nobs);\n    for (j=0; j < nobs; j++){\n      gsl_vector_set(xvec, j, oneobject->refpoint[j].x);\n      gsl_vector_set(yvec, j, oneobject->refpoint[j].y);\n    }\n    xmean = gsl_stats_mean(xvec->data, 1, nobs);\n    ymean = gsl_stats_mean(yvec->data, 1, nobs);\n\n    max_width  = gsl_stats_int_max(oneobject->width,  1, nobs);\n    max_height = gsl_stats_int_max(oneobject->height, 1, nobs);\n    omax       = gsl_stats_max(oneobject->objwidth, 1, nobs);\n\n    allobjects[i]->mean_refpoint.x = xmean;\n    allobjects[i]->mean_refpoint.y = ymean;\n    allobjects[i]->max_width  = max_width;\n    allobjects[i]->max_height = max_height;\n    allobjects[i]->owidthmax  = omax;\n\n    allobjects[i]->max_tlength = gsl_stats_int_max(oneobject->tlength, 1, nobs);\n\n    /*\n     * Look whether the cross dispersion scale is given in the configuration.\n     * If not determine the cross dispersion scale at the mean reference point an store it\n     * store also the mean correction in for to correct the width.\n     *\n     */\n    if (conf->drz_scale < 1.0e-16){\n      trace = get_tracefunc_at(conf_file, allobjects[i]->mean_refpoint);\n      allobjects[i]->cdrefscale = drzscale * get_crossdisp_scale(trace, allobjects[i]->mean_refpoint, drzcoeffs, pixmax);\n    }\n    else{\n      allobjects[i]->cdrefscale = conf->drz_scale;\n    }\n    for (j=0; j < nobs; j++){\n      gsl_vector_set(xvec, j, oneobject->cdscale[j]);\n    }\n    xmean = gsl_stats_mean(xvec->data, 1, nobs);\n    allobjects[i]->cdmeanscale  = xmean;\n\n    /*\n     * look whether the wavelength dispersion is given in the conig file\n     * if not determine the wavelength dispersion at the mean reference point amd store\n     * it. Store also the mean wavelength dispersion to correct the length\n     */\n    if (conf->drz_resol < 1.0e-16){\n      disp = get_dispstruct_at_pos(conf_file, 1, beamID, allobjects[i]->mean_refpoint);\n      wl_calib = create_calib_from_gsl_vector(1, disp->pol);\n      l1 =  wl_calib->func (0.0,  wl_calib->order,  wl_calib->coeffs);\n      l2 =  wl_calib->func (1.0,  wl_calib->order,  wl_calib->coeffs);\n      allobjects[i]->sprefreso = fabs(l2-l1);\n    }\n    else{\n       allobjects[i]->sprefreso = conf->drz_resol;\n    }\n    for (j=0; j < nobs; j++){\n      gsl_vector_set(xvec, j, oneobject->spreso[j]);\n    }\n    xmean = gsl_stats_mean(xvec->data, 1, nobs);\n    allobjects[i]->spmeanreso  = xmean;\n\n    gsl_vector_free(xvec);\n    gsl_vector_free(yvec);\n  }\n\n  gsl_matrix_free(drzcoeffs);\n  free(conf);\n\n  return 0;\n}\n\nd_point\nget_mean_refpoint(objectobs **allobjects, int nobjects, int ID,int * boxwidth,\n                  int * boxheight, double * relx, double * rely,\n                  double * objwidth, double *orient, double * cdref,\n                  double *cdscale, double *cdmeanscale, double *sprefreso, double *spreso,\n                  double *spmeanreso, int *tlength)\n{\n  int i, dec=0;\n  d_point mpoint;\n\n  for (i=0; i < nobjects; i++){\n    if (allobjects[i]->OBJID == ID){\n      mpoint.x = allobjects[i]->mean_refpoint.x;\n      mpoint.y = allobjects[i]->mean_refpoint.y;\n      *boxwidth  = allobjects[i]->max_width;\n      *boxheight = allobjects[i]->max_height;\n      *tlength   = allobjects[i]->max_tlength;\n      *objwidth  = allobjects[i]->owidthmax;\n      *cdref     = allobjects[i]->cdrefscale;\n      *cdmeanscale     = allobjects[i]->cdmeanscale;\n      *spmeanreso= allobjects[i]->spmeanreso;\n      *sprefreso = allobjects[i]->sprefreso;\n      *orient    = allobjects[i]->orient[allobjects[i]->pointer];\n      *cdscale   = allobjects[i]->cdscale[allobjects[i]->pointer];\n      *spreso    = allobjects[i]->spreso[allobjects[i]->pointer];\n      *relx      = allobjects[i]->relrefpt[allobjects[i]->pointer].x;\n      *rely      = allobjects[i]->relrefpt[allobjects[i]->pointer].y;\n      ++allobjects[i]->pointer;\n      dec=1;\n    }\n  }\n  return mpoint;\n}\npx_point\nrecalc_bbox(int xmin, int xmax, int ymin, int ymax, px_point pixmax)\n{\n  px_point ret;\n\n  if (xmax > pixmax.x)\n    xmax = pixmax.x;\n  if (ymax > pixmax.y)\n    ymax = pixmax.y;\n  if (xmin < 1)\n    xmin = 1;\n  if (ymin < 1)\n    ymin = 1;\n\n\n  ret.x = xmax - xmin + 2;\n  ret.y = ymax - ymin + 2;\n\n  return ret;\n}\n/*\nI am not sure what this routine is doing,\nbut one should make it better.\n*/\npx_point\nrecalc_mins(int xmin, int xmax, int ymin, int ymax, px_point pixmax)\n{\n  double m, b;\n  px_point ret;\n\n  m = ((double)ymin - (double)ymax)/((double)xmax - (double)xmin);\n  b = (double)ymin - m * (double)xmax;\n  if (xmin < 1){\n    ymax = (int)ceil(1.0*m + b);\n    xmin=1;\n  }\n  if (xmax > pixmax.x){\n    ymin = (int)ceil((float)pixmax.x*m + b);\n    xmax = pixmax.x;\n  }\n  if (ymin < 1){\n    xmax = (int)ceil((1-b)/m);\n    ymin=1;\n  }\n  if (ymax > pixmax.y){\n    xmin = (int)ceil(((float)pixmax.y-b)/m);\n    ymax=pixmax.y;\n  }\n  ret.x = xmin;\n  ret.y = ymin;\n\n  return ret;\n}\n\nint\nget_beam_trace_length(const beam actbeam)\n{\n  int trlength=0;\n  double diagonal_1 = 0.0;\n  double diagonal_2 = 0.0;\n  double xdiff, ydiff;\n\n  // compute the x- and y- differences for one corner pair\n  xdiff = (float)actbeam.corners[0].x - (float)actbeam.corners[2].x;\n  ydiff = (float)actbeam.corners[0].y - (float)actbeam.corners[2].y;\n\n  // compute the diagonal distance\n  diagonal_1 = xdiff*xdiff + ydiff*ydiff;\n\n  // compute the x- and y- differences for the other corner pair\n  xdiff = (float)actbeam.corners[1].x - (float)actbeam.corners[3].x;\n  ydiff = (float)actbeam.corners[1].y - (float)actbeam.corners[3].y;\n\n  // compute the diagonal distance\n  diagonal_2 = xdiff*xdiff + ydiff*ydiff;\n\n  // compute the tracelength\n  // from the larger diagonal\n  if (diagonal_1 > diagonal_2)\n    trlength = (int)ceil(sqrt(diagonal_1)+3.0);\n  else\n    trlength = (int)ceil(sqrt(diagonal_2)+3.0);\n\n  // return the result\n  return trlength;\n}\n", "meta": {"hexsha": "bad8d0a226c22cdaba6de26b3cb279ff3c340f4d", "size": 23344, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/drizzle_utils.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/drizzle_utils.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/drizzle_utils.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-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.6754270696, "max_line_length": 121, "alphanum_fraction": 0.6344242632, "num_tokens": 7649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.3601050324579899}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_integration.h>\n\n#include \"ccl.h\"\n\n#ifdef HAVE_ANGPOW\n#include \"Angpow/angpow_ccl.h\"\n#endif\n\n#define CCL_FRAC_RELEVANT 5E-4\n//#define CCL_FRAC_RELEVANT 1E-3\n//Gets the x-interval where the values of y are relevant\n//(meaning, that the values of y for those x are at least above a fraction frac of its maximum)\nstatic void get_support_interval(int n,double *x,double *y,double frac,\n\t\t\t\t double *xmin_out,double *xmax_out)\n{\n  int ix;\n  double ythr=-1000;\n\n  //Initialize as the original edges in case we don't find an interval\n  *xmin_out=x[0];\n  *xmax_out=x[n-1];\n\n  //Find threshold\n  for(ix=0;ix<n;ix++) {\n    if(y[ix]>ythr) ythr=y[ix];\n  }\n  ythr*=frac;\n\n  //Find minimum\n  for(ix=0;ix<n;ix++) {\n    if(y[ix]>=ythr) {\n      *xmin_out=x[ix];\n      break;\n    }\n  }\n\n  //Find maximum\n  for(ix=n-1;ix>=0;ix--) {\n    if(y[ix]>=ythr) {\n      *xmax_out=x[ix];\n      break;\n    }\n  }\n}\n\n//Wrapper around spline_eval with GSL function syntax\nstatic double speval_bis(double x,void *params)\n{\n  return ccl_spline_eval(x,(SplPar *)params);\n}\n\n\nvoid ccl_cl_workspace_free(CCL_ClWorkspace *w)\n{\n  free(w->l_arr);\n  free(w);\n}\n\nCCL_ClWorkspace *ccl_cl_workspace_new(int lmax,int l_limber,\n\t\t\t\t      double l_logstep,int l_linstep,int *status)\n{\n  int i_l,l0,increment;\n  CCL_ClWorkspace *w=(CCL_ClWorkspace *)malloc(sizeof(CCL_ClWorkspace));\n  if(w==NULL)\n    *status=CCL_ERROR_MEMORY;\n\n  if(*status==0) {\n    //Set params\n    w->lmax=lmax;\n    w->l_limber=l_limber;\n    w->l_logstep=l_logstep;\n    w->l_linstep=l_linstep;\n\n    //Compute number of multipoles\n    i_l=0; l0=0;\n    increment=CCL_MAX(((int)(l0*(w->l_logstep-1.))),1);\n    while((l0 < w->lmax) && (increment < w->l_linstep)) {\n      i_l++;\n      l0+=increment;\n      increment=CCL_MAX(((int)(l0*(w->l_logstep-1))),1);\n    }\n    increment=w->l_linstep;\n    while(l0 < w->lmax) {\n      i_l++;\n      l0+=increment;\n    }\n\n    //Allocate array of multipoles\n    w->n_ls=i_l+1;\n    w->l_arr=(int *)malloc(w->n_ls*sizeof(int));\n    if(w->l_arr==NULL)\n      *status=CCL_ERROR_MEMORY;\n  }\n\n  if(*status==0) {\n    //Redo the computation above and store values of ell\n    i_l=0; l0=0;\n    increment=CCL_MAX(((int)(l0*(w->l_logstep-1.))),1);\n    while((l0 < w->lmax) && (increment < w->l_linstep)) {\n      w->l_arr[i_l]=l0;\n      i_l++;\n      l0+=increment;\n      increment=CCL_MAX(((int)(l0*(w->l_logstep-1))),1);\n    }\n    increment=w->l_linstep;\n    while(l0 < w->lmax) {\n      w->l_arr[i_l]=l0;\n      i_l++;\n      l0+=increment;\n    }\n    //Don't go further than lmaw\n    w->l_arr[w->n_ls-1]=w->lmax;\n  }\n  \n  return w;\n}\n\nCCL_ClWorkspace *ccl_cl_workspace_new_limber(int lmax,double l_logstep,int l_linstep,int *status)\n{\n  return ccl_cl_workspace_new(lmax,-1,l_logstep,l_linstep,status);\n}\n\n//Params for lensing kernel integrand\ntypedef struct {\n  double chi;\n  SplPar *spl_pz;\n  ccl_cosmology *cosmo;\n  int *status;\n} IntLensPar;\n\n//Integrand for lensing kernel\nstatic double integrand_wl(double chip,void *params)\n{\n  IntLensPar *p=(IntLensPar *)params;\n  double chi=p->chi;\n  double a=ccl_scale_factor_of_chi(p->cosmo,chip, p->status);\n  double z=1./a-1;\n  double pz=ccl_spline_eval(z,p->spl_pz);\n  double h=p->cosmo->params.h*ccl_h_over_h0(p->cosmo,a, p->status)/CLIGHT_HMPC;\n\n  if(chi==0)\n    return h*pz;\n  else\n    return h*pz*ccl_sinn(p->cosmo,chip-chi,p->status)/ccl_sinn(p->cosmo,chip,p->status);\n}\n\n//Integral to compute lensing window function\n//chi     -> comoving distance\n//cosmo   -> ccl_cosmology object\n//spl_pz  -> normalized N(z) spline\n//chi_max -> maximum comoving distance to which the integral is computed\n//win     -> result is stored here\nstatic int window_lensing(double chi,ccl_cosmology *cosmo,SplPar *spl_pz,double chi_max,double *win)\n{\n  int gslstatus =0, status =0;\n  double result,eresult;\n  IntLensPar ip;\n  gsl_function F;\n  gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION);\n\n  ip.chi=chi;\n  ip.cosmo=cosmo;\n  ip.spl_pz=spl_pz;\n  ip.status = &status;\n  F.function=&integrand_wl;\n  F.params=&ip;\n  // This conputes the lensing kernel:\n  //   w_L(chi) = Integral[ dN/dchi(chi') * f(chi'-chi)/f(chi') , chi < chi' < chi_horizon ]\n  // Where f(chi) is the comoving angular distance (which is just chi for zero curvature).\n  gslstatus=gsl_integration_qag(&F, chi, chi_max, 0,\n                                ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION,\n                                ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS,\n                                w, &result, &eresult);\n  *win=result;\n  gsl_integration_workspace_free(w);\n  if(gslstatus!=GSL_SUCCESS || *ip.status) {\n    ccl_raise_gsl_warning(gslstatus, \"ccl_cls.c: window_lensing():\");\n    return 1;\n  }\n  //TODO: chi_max should be changed to chi_horizon\n  //we should precompute this quantity and store it in cosmo by default\n\n  return 0;\n}\n\n//Params for lensing kernel integrand\ntypedef struct {\n  double chi;\n  SplPar *spl_pz;\n  SplPar *spl_sz;\n  ccl_cosmology *cosmo;\n  int *status;\n} IntMagPar;\n\n//Integrand for magnification kernel\nstatic double integrand_mag(double chip,void *params)\n{\n  IntMagPar *p=(IntMagPar *)params;\n  double chi=p->chi;\n  double a=ccl_scale_factor_of_chi(p->cosmo,chip, p->status);\n  double z=1./a-1;\n  double pz=ccl_spline_eval(z,p->spl_pz);\n  double sz=ccl_spline_eval(z,p->spl_sz);\n  double h=p->cosmo->params.h*ccl_h_over_h0(p->cosmo,a, p->status)/CLIGHT_HMPC;\n\n  if(chi==0)\n    return h*pz*(1-2.5*sz);\n  else\n    return h*pz*(1-2.5*sz)*ccl_sinn(p->cosmo,chip-chi,p->status)/ccl_sinn(p->cosmo,chip,p->status);\n}\n\n//Integral to compute magnification window function\n//chi     -> comoving distance\n//cosmo   -> ccl_cosmology object\n//spl_pz  -> normalized N(z) spline\n//spl_pz  -> magnification bias s(z)\n//chi_max -> maximum comoving distance to which the integral is computed\n//win     -> result is stored here\nstatic int window_magnification(double chi,ccl_cosmology *cosmo,SplPar *spl_pz,SplPar *spl_sz,\n\t\t\t\tdouble chi_max,double *win)\n{\n  int gslstatus =0, status =0;\n  double result,eresult;\n  IntMagPar ip;\n  gsl_function F;\n  gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION);\n\n  ip.chi=chi;\n  ip.cosmo=cosmo;\n  ip.spl_pz=spl_pz;\n  ip.spl_sz=spl_sz;\n  ip.status = &status;\n  F.function=&integrand_mag;\n  F.params=&ip;\n  // This conputes the magnification lensing kernel:\n  //   w_M(chi) = Integral[ dN/dchi(chi') * (1-5/2 * s(chi)) * f(chi'-chi)/f(chi') , chi < chi' < chi_horizon ]\n  // Where f(chi) is the comoving angular distance (which is just chi for zero curvature)\n  // and s(chi) is the magnification bias parameter.\n  gslstatus=gsl_integration_qag(&F, chi, chi_max, 0,\n                                ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION,\n                                ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS,\n                                w, &result, &eresult);\n  *win=result;\n  gsl_integration_workspace_free(w);\n  if(gslstatus!=GSL_SUCCESS || *ip.status) {\n    ccl_raise_gsl_warning(gslstatus, \"ccl_cls.c: window_magnification():\");\n    return 1;\n  }\n  //TODO: chi_max should be changed to chi_horizon\n  //we should precompute this quantity and store it in cosmo by default\n\n  return 0;\n}\n\nstatic void clt_init_nz(CCL_ClTracer *clt,ccl_cosmology *cosmo,\n\t\t\tint nz_n,double *z_n,double *n,int *status)\n{\n  int gslstatus;\n  gsl_function F;\n  double nz_norm,nz_enorm;\n  double *nz_normalized;\n  \n  //Find redshift range where the N(z) has support\n  get_support_interval(nz_n,z_n,n,CCL_FRAC_RELEVANT,&(clt->zmin),&(clt->zmax));\n  clt->chimax=ccl_comoving_radial_distance(cosmo,1./(1+clt->zmax),status);\n  clt->chimin=ccl_comoving_radial_distance(cosmo,1./(1+clt->zmin),status);\n  clt->spl_nz=ccl_spline_init(nz_n,z_n,n,0,0);\n  if(clt->spl_nz==NULL) {\n    *status=CCL_ERROR_SPLINE;\n    ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_nz(): error initializing spline for N(z)\\n\");\n  }\n\n  if(*status==0) {\n    //Normalize n(z)\n    nz_normalized=(double *)malloc(nz_n*sizeof(double));\n    if(nz_normalized==NULL) {\n      *status=CCL_ERROR_MEMORY;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_nz(): memory allocation\\n\");\n      return;\n    }\n  }\n  \n  if(*status==0) {\n    gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION);\n    F.function=&speval_bis;\n    F.params=clt->spl_nz;\n    //Here we're just integrating the N(z) to normalize it to unit probability.\n    gslstatus=gsl_integration_qag(&F, z_n[0], z_n[nz_n-1], 0,\n\t\t\t\t  ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION,\n\t\t\t\t  ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS,\n\t\t\t\t  w, &nz_norm, &nz_enorm);\n    gsl_integration_workspace_free(w);\n    if(gslstatus!=GSL_SUCCESS) {\n      ccl_raise_gsl_warning(gslstatus, \"ccl_cls.c: clt_init_nz():\");\n      *status=CCL_ERROR_INTEG;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_nz(): integration error when normalizing N(z)\\n\");\n    }\n  }\n  \n  if(*status==0) {\n    for(int ii=0;ii<nz_n;ii++)\n      nz_normalized[ii]=n[ii]/nz_norm;\n    ccl_spline_free(clt->spl_nz);\n    clt->spl_nz=ccl_spline_init(nz_n,z_n,nz_normalized,0,0);\n    if(clt->spl_nz==NULL) {\n      *status=CCL_ERROR_SPLINE;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_nz(): error initializing normalized spline for N(z)\\n\");\n    }\n  }\n  \n  free(nz_normalized);\n}\n\nstatic void clt_init_bz(CCL_ClTracer *clt,ccl_cosmology *cosmo,\n\t\t\tint nz_b,double *z_b,double *b,int *status)\n{\n  //Initialize bias spline\n  clt->spl_bz=ccl_spline_init(nz_b,z_b,b,b[0],b[nz_b-1]);\n  if(clt->spl_bz==NULL) {\n    *status=CCL_ERROR_SPLINE;\n    ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_bz(): error initializing spline for b(z)\\n\");\n  }\n}\n\nstatic void clt_init_wM(CCL_ClTracer *clt,ccl_cosmology *cosmo,\n\t\t\tint nz_s,double *z_s,double *s,int *status)\n{\n  //Compute magnification kernel\n  int nchi;\n  double *x,*y;\n  double dchi_here=5.;\n  double zmax=clt->spl_nz->xf;\n  double chimax=ccl_comoving_radial_distance(cosmo,1./(1+zmax),status);\n  //TODO: The interval in chi (5. Mpc) should be made a macro\n\n  //In this case we need to integrate all the way to z=0. Reset zmin and chimin\n  clt->zmin=0;\n  clt->chimin=0;\n  clt->spl_sz=ccl_spline_init(nz_s,z_s,s,s[0],s[nz_s-1]);\n  if(clt->spl_sz==NULL) {\n    *status=CCL_ERROR_SPLINE;\n    ccl_cosmology_set_status_message(cosmo,\n\t\t\t\t     \"ccl_cls.c: clt_init_wM(): error initializing spline for s(z)\\n\");\n  }\n\n  if(*status==0) {\n    nchi=(int)(chimax/dchi_here)+1;\n    x=ccl_linear_spacing(0.,chimax,nchi);\n    dchi_here=chimax/nchi;\n    if(x==NULL || (fabs(x[0]-0)>1E-5) || (fabs(x[nchi-1]-chimax)>1e-5)) {\n      *status=CCL_ERROR_LINSPACE;\n      ccl_cosmology_set_status_message(cosmo,\n\t\t\t\t       \"ccl_cls.c: clt_init_wM(): Error creating linear spacing in chi\\n\");\n    }\n  }\n\n  if(*status==0) {\n    y=(double *)malloc(nchi*sizeof(double));\n    if(y==NULL) {\n      *status=CCL_ERROR_MEMORY;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_wM(): memory allocation\\n\");\n    }\n  }\n\n  if(*status==0) {\n    int clstatus=0;\n    for(int j=0;j<nchi;j++)\n      clstatus|=window_magnification(x[j],cosmo,clt->spl_nz,clt->spl_sz,chimax,&(y[j]));\n    if(clstatus) {\n      *status=CCL_ERROR_INTEG;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_wM(): error computing lensing window\\n\");\n    }\n  }\n\n  if(*status==0) {\n    clt->spl_wM=ccl_spline_init(nchi,x,y,y[0],0);\n    if(clt->spl_wM==NULL) {\n      *status=CCL_ERROR_SPLINE;\n      ccl_cosmology_set_status_message(cosmo,\n\t\t\t\t       \"ccl_cls.c: clt_init_wM(): error initializing spline for lensing window\\n\");\n    }\n  }\n  free(x); free(y);\n}\n\n//CCL_ClTracer initializer for number counts\nstatic void clt_nc_init(CCL_ClTracer *clt,ccl_cosmology *cosmo,\n\t\t\tint has_rsd,int has_magnification,\n\t\t\tint nz_n,double *z_n,double *n,\n\t\t\tint nz_b,double *z_b,double *b,\n\t\t\tint nz_s,double *z_s,double *s,int *status)\n{\n  clt->has_rsd=has_rsd;\n  clt->has_magnification=has_magnification;\n\n  if ( ((cosmo->params.N_nu_mass)>0) && clt->has_rsd){\n    *status=CCL_ERROR_NOT_IMPLEMENTED;\n    ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: ccl_cl_tracer_new(): Number counts tracers with RSD not yet implemented in cosmologies with massive neutrinos.\");\n    return;\n  }\n\n  clt_init_nz(clt,cosmo,nz_n,z_n,n,status);\n  clt_init_bz(clt,cosmo,nz_b,z_b,b,status);\n  if(clt->has_magnification)\n    clt_init_wM(clt,cosmo,nz_s,z_s,s,status);\n}\n\nstatic void clt_init_wL(CCL_ClTracer *clt,ccl_cosmology *cosmo,\n\t\t\tint *status)\n{\n  //Compute weak lensing kernel\n  int nchi;\n  double *x,*y;\n  double dchi_here=5.;\n  double zmax=clt->spl_nz->xf;\n  double chimax=ccl_comoving_radial_distance(cosmo,1./(1+zmax),status);\n  //TODO: The interval in chi (5. Mpc) should be made a macro\n  \n  //In this case we need to integrate all the way to z=0. Reset zmin and chimin\n  clt->zmin=0;\n  clt->chimin=0;\n  nchi=(int)(chimax/dchi_here)+1;\n  x=ccl_linear_spacing(0.,chimax,nchi);\n  dchi_here=chimax/nchi;\n  if(x==NULL || (fabs(x[0]-0)>1E-5) || (fabs(x[nchi-1]-chimax)>1e-5)) {\n    *status=CCL_ERROR_LINSPACE;\n    ccl_cosmology_set_status_message(cosmo,\n\t\t\t\t     \"ccl_cls.c: clt_init_wL(): Error creating linear spacing in chi\\n\");\n  }\n  \n  if(*status==0) {\n    y=(double *)malloc(nchi*sizeof(double));\n    if(y==NULL) {\n      *status=CCL_ERROR_MEMORY;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_wL(): memory allocation\\n\");\n    }\n  }\n\n  if(*status==0) {\n    int clstatus=0;\n    for(int j=0;j<nchi;j++)\n      clstatus|=window_lensing(x[j],cosmo,clt->spl_nz,chimax,&(y[j]));\n    if(clstatus) {\n      *status=CCL_ERROR_INTEG;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_wL(): error computing lensing window\\n\");\n    }\n  }\n  \n  if(*status==0) {\n    clt->spl_wL=ccl_spline_init(nchi,x,y,y[0],0);\n    if(clt->spl_wL==NULL) {\n      *status=CCL_ERROR_SPLINE;\n      ccl_cosmology_set_status_message(cosmo,\n\t\t\t\t     \"ccl_cls.c: clt_init_wL(): error initializing spline for lensing window\\n\");\n    }\n  }\n  free(x); free(y);\n}\n\nstatic void clt_init_rf(CCL_ClTracer *clt,ccl_cosmology *cosmo,\n\t\t\tint nz_rf,double *z_rf,double *rf,int *status)\n{\n  //Initialize bias spline\n  clt->spl_rf=ccl_spline_init(nz_rf,z_rf,rf,rf[0],rf[nz_rf-1]);\n  if(clt->spl_rf==NULL) {\n    *status=CCL_ERROR_SPLINE;\n    ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_rf(): error initializing spline for b(z)\\n\");\n  }\n}\n\nstatic void clt_init_ba(CCL_ClTracer *clt,ccl_cosmology *cosmo,\n\t\t\tint nz_ba,double *z_ba,double *ba,int *status)\n{\n  //Initialize bias spline\n  clt->spl_ba=ccl_spline_init(nz_ba,z_ba,ba,ba[0],ba[nz_ba-1]);\n  if(clt->spl_ba==NULL) {\n    *status=CCL_ERROR_SPLINE;\n    ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: clt_init_ba(): error initializing spline for b(z)\\n\");\n  }\n}\n\nstatic void clt_wl_init(CCL_ClTracer *clt,ccl_cosmology *cosmo,\n\t\t\tint has_intrinsic_alignment,\n\t\t\tint nz_n,double *z_n,double *n,\n\t\t\tint nz_ba,double *z_ba,double *ba,\n\t\t\tint nz_rf,double *z_rf,double *rf,int *status)\n{\n  clt->has_intrinsic_alignment=has_intrinsic_alignment;\n\n  clt_init_nz(clt,cosmo,nz_n,z_n,n,status);\n  clt_init_wL(clt,cosmo,status);\n  if(clt->has_intrinsic_alignment) {\n    clt_init_rf(clt,cosmo,nz_rf,z_rf,rf,status);\n    clt_init_ba(clt,cosmo,nz_ba,z_ba,ba,status);\n  }\n}\n\n//CCL_ClTracer creator\n//cosmo   -> ccl_cosmology object\n//tracer_type -> type of tracer. Supported: ccl_number_counts_tracer, ccl_weak_lensing_tracer\n//nz_n -> number of points for N(z)\n//z_n  -> array of z-values for N(z)\n//n    -> corresponding N(z)-values. Normalization is irrelevant\n//        N(z) will be set to zero outside the range covered by z_n\n//nz_b -> number of points for b(z)\n//z_b  -> array of z-values for b(z)\n//b    -> corresponding b(z)-values.\n//        b(z) will be assumed constant outside the range covered by z_n\nstatic CCL_ClTracer *cl_tracer(ccl_cosmology *cosmo,int tracer_type,\n\t\t\t       int has_rsd,int has_magnification,int has_intrinsic_alignment,\n\t\t\t       int nz_n,double *z_n,double *n,\n\t\t\t       int nz_b,double *z_b,double *b,\n\t\t\t       int nz_s,double *z_s,double *s,\n\t\t\t       int nz_ba,double *z_ba,double *ba,\n\t\t\t       int nz_rf,double *z_rf,double *rf,\n\t\t\t       double z_source, int * status)\n{\n  int clstatus=0;\n  CCL_ClTracer *clt=(CCL_ClTracer *)malloc(sizeof(CCL_ClTracer));\n  if(clt==NULL) {\n    *status=CCL_ERROR_MEMORY;\n    ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: ccl_cl_tracer(): memory allocation\\n\");\n  }\n\n  if(*status==0) {\n    clt->tracer_type=tracer_type;\n    \n    double hub=cosmo->params.h*ccl_h_over_h0(cosmo,1.,status)/CLIGHT_HMPC;\n    clt->prefac_lensing=1.5*hub*hub*cosmo->params.Omega_m;\n\n    if(tracer_type==ccl_number_counts_tracer)\n      clt_nc_init(clt,cosmo,has_rsd,has_magnification,\n\t\t  nz_n,z_n,n,nz_b,z_b,b,nz_s,z_s,s,status);\n    else if(tracer_type==ccl_weak_lensing_tracer)\n      clt_wl_init(clt,cosmo,has_intrinsic_alignment,\n\t\t  nz_n,z_n,n,nz_ba,z_ba,ba,nz_rf,z_rf,rf,status);\n    else if(tracer_type==ccl_cmb_lensing_tracer) {\n      clt->chi_source=ccl_comoving_radial_distance(cosmo,1./(1+z_source),status);\n      clt->chimax=clt->chi_source;\n      clt->chimin=0;\n    }\n    else {\n      free(clt);\n      *status=CCL_ERROR_INCONSISTENT;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: ccl_cl_tracer(): unknown tracer type\\n\");\n      return NULL;\n    }\n  }\n\n  if(*status) {\n    free(clt);\n    clt=NULL;\n  }\n    \n  return clt;\n}\n\n//CCL_ClTracer constructor with error checking\n//cosmo   -> ccl_cosmology object\n//tracer_type -> type of tracer. Supported: ccl_number_counts_tracer, ccl_weak_lensing_tracer\n//nz_n -> number of points for N(z)\n//z_n  -> array of z-values for N(z)\n//n    -> corresponding N(z)-values. Normalization is irrelevant\n//        N(z) will be set to zero outside the range covered by z_n\n//nz_b -> number of points for b(z)\n//z_b  -> array of z-values for b(z)\n//b    -> corresponding b(z)-values.\n//        b(z) will be assumed constant outside the range covered by z_n\nCCL_ClTracer *ccl_cl_tracer(ccl_cosmology *cosmo,int tracer_type,\n\t\t\t\tint has_rsd,int has_magnification,int has_intrinsic_alignment,\n\t\t\t\tint nz_n,double *z_n,double *n,\n\t\t\t\tint nz_b,double *z_b,double *b,\n\t\t\t\tint nz_s,double *z_s,double *s,\n\t\t\t\tint nz_ba,double *z_ba,double *ba,\n\t\t\t\tint nz_rf,double *z_rf,double *rf,\n\t\t\t\tdouble z_source, int * status)\n{\n  CCL_ClTracer *clt=cl_tracer(cosmo,tracer_type,has_rsd,has_magnification,has_intrinsic_alignment,\n\t\t\t      nz_n,z_n,n,nz_b,z_b,b,nz_s,z_s,s,\n\t\t\t      nz_ba,z_ba,ba,nz_rf,z_rf,rf,z_source,status);\n  ccl_check_status(cosmo,status);\n  return clt;\n}\n\n//CCL_ClTracer destructor\nvoid ccl_cl_tracer_free(CCL_ClTracer *clt)\n{\n  if((clt->tracer_type==ccl_number_counts_tracer) || (clt->tracer_type==ccl_weak_lensing_tracer))\n    ccl_spline_free(clt->spl_nz);\n\n  if(clt->tracer_type==ccl_number_counts_tracer) {\n    ccl_spline_free(clt->spl_bz);\n    if(clt->has_magnification) {\n      ccl_spline_free(clt->spl_sz);\n      ccl_spline_free(clt->spl_wM);\n    }\n  }\n  else if(clt->tracer_type==ccl_weak_lensing_tracer) {\n    ccl_spline_free(clt->spl_wL);\n    if(clt->has_intrinsic_alignment) {\n      ccl_spline_free(clt->spl_ba);\n      ccl_spline_free(clt->spl_rf);\n    }\n  }\n  free(clt);\n}\n\nCCL_ClTracer *ccl_cl_tracer_cmblens(ccl_cosmology *cosmo,double z_source,int *status)\n{\n  return ccl_cl_tracer(cosmo,ccl_cmb_lensing_tracer,\n\t\t\t   0,0,0,\n\t\t\t   0,NULL,NULL,0,NULL,NULL,0,NULL,NULL,\n\t\t\t   0,NULL,NULL,0,NULL,NULL,z_source,status);\n}\n\nCCL_ClTracer *ccl_cl_tracer_number_counts(ccl_cosmology *cosmo,\n\t\t\t\t\t      int has_rsd,int has_magnification,\n\t\t\t\t\t      int nz_n,double *z_n,double *n,\n\t\t\t\t\t      int nz_b,double *z_b,double *b,\n\t\t\t\t\t      int nz_s,double *z_s,double *s, int * status)\n{\n  return ccl_cl_tracer(cosmo,ccl_number_counts_tracer,has_rsd,has_magnification,0,\n\t\t\t   nz_n,z_n,n,nz_b,z_b,b,nz_s,z_s,s,\n\t\t\t   -1,NULL,NULL,-1,NULL,NULL,0, status);\n}\n\nCCL_ClTracer *ccl_cl_tracer_number_counts_simple(ccl_cosmology *cosmo,\n\t\t\t\t\t\t     int nz_n,double *z_n,double *n,\n\t\t\t\t\t\t     int nz_b,double *z_b,double *b, int * status)\n{\n  return ccl_cl_tracer(cosmo,ccl_number_counts_tracer,0,0,0,\n\t\t\t   nz_n,z_n,n,nz_b,z_b,b,-1,NULL,NULL,\n\t\t\t   -1,NULL,NULL,-1,NULL,NULL,0, status);\n}\n\nCCL_ClTracer *ccl_cl_tracer_lensing(ccl_cosmology *cosmo,\n\t\t\t\t\tint has_alignment,\n\t\t\t\t\tint nz_n,double *z_n,double *n,\n\t\t\t\t\tint nz_ba,double *z_ba,double *ba,\n\t\t\t\t\tint nz_rf,double *z_rf,double *rf, int * status)\n{\n  return ccl_cl_tracer(cosmo,ccl_weak_lensing_tracer,0,0,has_alignment,\n\t\t\t   nz_n,z_n,n,-1,NULL,NULL,-1,NULL,NULL,\n\t\t\t   nz_ba,z_ba,ba,nz_rf,z_rf,rf,0, status);\n}\n\nCCL_ClTracer *ccl_cl_tracer_lensing_simple(ccl_cosmology *cosmo,\n\t\t\t\t\t       int nz_n,double *z_n,double *n, int * status)\n{\n  return ccl_cl_tracer(cosmo,ccl_weak_lensing_tracer,0,0,0,\n\t\t\t   nz_n,z_n,n,-1,NULL,NULL,-1,NULL,NULL,\n\t\t\t   -1,NULL,NULL,-1,NULL,NULL,0, status);\n}\n\nstatic double f_dens(double a,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status)\n{\n  double z=1./a-1;\n  double pz=ccl_spline_eval(z,clt->spl_nz);\n  double bz=ccl_spline_eval(z,clt->spl_bz);\n  double h=cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/CLIGHT_HMPC;\n\n  return pz*bz*h;\n}\n\nstatic double f_rsd(double a,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status)\n{\n  double z=1./a-1;\n  double pz=ccl_spline_eval(z,clt->spl_nz);\n  double fg=ccl_growth_rate(cosmo,a,status);\n  double h=cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/CLIGHT_HMPC;\n\n  return pz*fg*h;\n}\n\nstatic double f_mag(double a,double chi,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status)\n{\n  double wM=ccl_spline_eval(chi,clt->spl_wM);\n\n  if(wM<=0)\n    return 0;\n  else\n    return wM/(a*chi);\n}\n\n//Transfer function for number counts\n//l -> angular multipole\n//k -> wavenumber modulus\n//cosmo -> ccl_cosmology object\n//w -> CCL_ClWorskpace object\n//clt -> CCL_ClTracer object (must be of the ccl_number_counts_tracer type)\nstatic double transfer_nc(int l,double k,\n\t\t\t  ccl_cosmology *cosmo,CCL_ClWorkspace *w,CCL_ClTracer *clt, int * status)\n{\n  double ret=0;\n  double x0=(l+0.5);\n  double chi0=x0/k;\n  if(chi0<=clt->chimax) {\n    double a0=ccl_scale_factor_of_chi(cosmo,chi0,status);\n    double f_all=f_dens(a0,cosmo,clt,status);\n    if(clt->has_rsd) {\n      double x1=(l+1.5);\n      double chi1=x1/k;\n      if(chi1<=clt->chimax) {\n\tdouble a1=ccl_scale_factor_of_chi(cosmo,chi1,status);\n\tdouble pk0=ccl_nonlin_matter_power(cosmo,k,a0,status);\n\tdouble pk1=ccl_nonlin_matter_power(cosmo,k,a1,status);\n\tdouble fg0=f_rsd(a0,cosmo,clt,status);\n\tdouble fg1=f_rsd(a1,cosmo,clt,status);\n\tf_all+=fg0*(1.-l*(l-1.)/(x0*x0))-fg1*2.*sqrt((l+0.5)*pk1/((l+1.5)*pk0))/x1;\n      }\n    }\n    if(clt->has_magnification)\n      f_all+=-2*clt->prefac_lensing*l*(l+1)*f_mag(a0,chi0,cosmo,clt,status)/(k*k);\n    ret=f_all;\n  }\n\n  return ret;\n}\n\nstatic double f_lensing(double a,double chi,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status)\n{\n  double wL=ccl_spline_eval(chi,clt->spl_wL);\n\n  if(wL<=0)\n    return 0;\n  else\n    return clt->prefac_lensing*wL/(a*chi);\n}\n\nstatic double f_IA_NLA(double a,double chi,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status)\n{\n  if(chi<=1E-10)\n    return 0;\n  else {\n    double a=ccl_scale_factor_of_chi(cosmo,chi, status);\n    double z=1./a-1;\n    double pz=ccl_spline_eval(z,clt->spl_nz);\n    double ba=ccl_spline_eval(z,clt->spl_ba);\n    double rf=ccl_spline_eval(z,clt->spl_rf);\n    double h=cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/CLIGHT_HMPC;\n\n    return pz*ba*rf*h/(chi*chi);\n  }\n}\n\n//Transfer function for shear\n//l -> angular multipole\n//k -> wavenumber modulus\n//cosmo -> ccl_cosmology object\n//w -> CCL_ClWorskpace object\n//clt -> CCL_ClTracer object (must be of the ccl_weak_lensing_tracer type)\nstatic double transfer_wl(int l,double k,\n\t\t\t  ccl_cosmology *cosmo,CCL_ClWorkspace *w,CCL_ClTracer *clt, int * status)\n{\n  double ret=0;\n  double chi=(l+0.5)/k;\n  if(chi<=clt->chimax) {\n    double a=ccl_scale_factor_of_chi(cosmo,chi,status);\n    double f_all=f_lensing(a,chi,cosmo,clt,status);\n    if(clt->has_intrinsic_alignment)\n      f_all+=f_IA_NLA(a,chi,cosmo,clt,status);\n    \n    ret=f_all;\n  }\n\n  return sqrt((l+2.)*(l+1.)*l*(l-1.))*ret/(k*k);\n  //return (l+1.)*l*ret/(k*k);\n}\n\nstatic double transfer_cmblens(int l,double k,ccl_cosmology *cosmo,CCL_ClTracer *clt,int *status)\n{\n  double chi=(l+0.5)/k;\n  if(chi>=clt->chi_source)\n    return 0;\n\n  if(chi<=clt->chimax) {\n    double a=ccl_scale_factor_of_chi(cosmo,chi,status);\n    double w=1-chi/clt->chi_source;\n    return clt->prefac_lensing*l*(l+1.)*w/(a*chi*k*k);\n  }\n  return 0;\n}\n\n//Wrapper for transfer function\n//l -> angular multipole\n//k -> wavenumber modulus\n//cosmo -> ccl_cosmology object\n//clt -> CCL_ClTracer object\nstatic double transfer_wrap(int il,double lk,ccl_cosmology *cosmo,\n\t\t\t    CCL_ClWorkspace *w,CCL_ClTracer *clt, int * status)\n{\n  double transfer_out=0;\n  double k=pow(10.,lk);\n\n  if(clt->tracer_type==ccl_number_counts_tracer)\n    transfer_out=transfer_nc(w->l_arr[il],k,cosmo,w,clt,status);\n  else if(clt->tracer_type==ccl_weak_lensing_tracer)\n    transfer_out=transfer_wl(w->l_arr[il],k,cosmo,w,clt,status);\n  else if(clt->tracer_type==ccl_cmb_lensing_tracer)\n    transfer_out=transfer_cmblens(w->l_arr[il],k,cosmo,clt,status);\n  else\n    transfer_out=-1;\n  return transfer_out;\n}\n\n//Params for power spectrum integrand\ntypedef struct {\n  int il;\n  ccl_cosmology *cosmo;\n  CCL_ClWorkspace *w;\n  CCL_ClTracer *clt1;\n  CCL_ClTracer *clt2;\n  int *status;\n} IntClPar;\n\n//Integrand for integral power spectrum\nstatic double cl_integrand(double lk,void *params)\n{\n  double d1,d2;\n  IntClPar *p=(IntClPar *)params;\n  d1=transfer_wrap(p->il,lk,p->cosmo,p->w,p->clt1,p->status);\n  if(d1==0)\n    return 0;\n  d2=transfer_wrap(p->il,lk,p->cosmo,p->w,p->clt2,p->status);\n  if(d2==0)\n    return 0;\n\n  double k=pow(10.,lk);\n  double chi=(p->w->l_arr[p->il]+0.5)/k;\n  double a=ccl_scale_factor_of_chi(p->cosmo,chi,p->status);\n  double pk=ccl_nonlin_matter_power(p->cosmo,k,a,p->status);\n  \n  return k*pk*d1*d2;\n}\n\n//Figure out k intervals where the Limber kernel has support\n//clt1 -> tracer #1\n//clt2 -> tracer #2\n//l    -> angular multipole\n//lkmin, lkmax -> log10 of the range of scales where the transfer functions have support\nstatic void get_k_interval(ccl_cosmology *cosmo,CCL_ClWorkspace *w,\n\t\t\t   CCL_ClTracer *clt1,CCL_ClTracer *clt2,int l,\n\t\t\t   double *lkmin,double *lkmax)\n{\n  double chimin,chimax;\n  int cut_low_1=0,cut_low_2=0;\n  \n  //Define a minimum distance only if no lensing is needed\n  if((clt1->tracer_type==ccl_number_counts_tracer) && (clt1->has_magnification==0)) cut_low_1=1;\n  if((clt2->tracer_type==ccl_number_counts_tracer) && (clt2->has_magnification==0)) cut_low_2=1;\n  \n  if(cut_low_1) {\n    if(cut_low_2) {\n      chimin=fmax(clt1->chimin,clt2->chimin);\n      chimax=fmin(clt1->chimax,clt2->chimax);\n    }\n    else {\n      chimin=clt1->chimin;\n      chimax=clt1->chimax;\n    }\n  }\n  else if(cut_low_2) {\n    chimin=clt2->chimin;\n    chimax=clt2->chimax;\n  }\n  else {\n    chimin=0.5*(l+0.5)/ccl_splines->K_MAX;\n    chimax=2*(l+0.5)/ccl_splines->K_MIN;\n  }\n  \n  if(chimin<=0)\n    chimin=0.5*(l+0.5)/ccl_splines->K_MAX;\n  \n  *lkmax=log10(fmin( ccl_splines->K_MAX  ,2  *(l+0.5)/chimin));\n  *lkmin=log10(fmax( ccl_splines->K_MIN  ,0.5*(l+0.5)/chimax));\n}\n\n//Compute angular power spectrum between two bins\n//cosmo -> ccl_cosmology object\n//il -> index in angular multipole array\n//clt1 -> tracer #1\n//clt2 -> tracer #2\nstatic double ccl_angular_cl_native(ccl_cosmology *cosmo,CCL_ClWorkspace *cw,int il,\n\t\t\t\t    CCL_ClTracer *clt1,CCL_ClTracer *clt2,int * status)\n{\n  int clastatus=0, gslstatus;\n  IntClPar ipar;\n  double result=0,eresult;\n  double lkmin,lkmax;\n  gsl_function F;\n  gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION);\n\n  ipar.il=il;\n  ipar.cosmo=cosmo;\n  ipar.w=cw;\n  ipar.clt1=clt1;\n  ipar.clt2=clt2;\n  ipar.status = &clastatus;\n  F.function=&cl_integrand;\n  F.params=&ipar;\n  get_k_interval(cosmo,cw,clt1,clt2,cw->l_arr[il],&lkmin,&lkmax);\n  // This computes the angular power spectra in the Limber approximation between two quantities a and b:\n  //  C_ell^ab = 2/(2*ell+1) * Integral[ Delta^a_ell(k) Delta^b_ell(k) * P(k) , k_min < k < k_max ]\n  // Note that we use log10(k) as an integration variable, and the ell-dependent prefactor is included\n  // at the end of this function.\n  gslstatus=gsl_integration_qag(&F, lkmin, lkmax, 0,\n                                ccl_gsl->INTEGRATION_LIMBER_EPSREL, ccl_gsl->N_ITERATION,\n                                ccl_gsl->INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS,\n                                w, &result, &eresult);\n  gsl_integration_workspace_free(w);\n\n  // Test if a round-off error occured in the evaluation of the integral\n  // If so, try another integration function, more robust but potentially slower\n  if(gslstatus == GSL_EROUND) {\n    ccl_raise_gsl_warning(gslstatus, \"ccl_cls.c: ccl_angular_cl_native(): Default GSL integration failure, attempting backup method.\");\n    gsl_integration_cquad_workspace *w_cquad= gsl_integration_cquad_workspace_alloc (ccl_gsl->N_ITERATION);\n    size_t nevals=0;\n    gslstatus=gsl_integration_cquad(&F, lkmin, lkmax, 0,\n\t\t\t\t    ccl_gsl->INTEGRATION_LIMBER_EPSREL,\n\t\t\t\t    w_cquad, &result, &eresult, &nevals);\n    gsl_integration_cquad_workspace_free(w_cquad);\n  }\n  if(gslstatus!=GSL_SUCCESS || *ipar.status) {\n    ccl_raise_gsl_warning(gslstatus, \"ccl_cls.c: ccl_angular_cl_native():\");\n    // If an error status was already set, don't overwrite it.\n    if(*status == 0){\n        *status=CCL_ERROR_INTEG;\n        ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: ccl_angular_cl_native(): error integrating over k\\n\");\n    }\n    return -1;\n  }\n  ccl_check_status(cosmo,status);\n\n  return result*M_LN10/(cw->l_arr[il]+0.5);\n}\n\nvoid ccl_angular_cls(ccl_cosmology *cosmo,CCL_ClWorkspace *w,\n\t\t     CCL_ClTracer *clt1,CCL_ClTracer *clt2,\n\t\t     int nl_out,int *l_out,double *cl_out,int *status)\n{\n  int ii,do_angpow;\n  double *l_nodes,*cl_nodes;\n  SplPar *spcl_nodes;\n  \n  //First check if ell range is within workspace\n  for(ii=0;ii<nl_out;ii++) {\n    if(l_out[ii]>w->lmax) {\n      *status=CCL_ERROR_SPLINE_EV;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: ccl_angular_cls(); \"\n\t     \"requested l beyond range allowed by workspace\\n\");\n      return;\n    }\n  }\n\n  if(*status==0) {\n    //Allocate array for power spectrum at interpolation nodes\n    l_nodes=(double *)malloc(w->n_ls*sizeof(double));\n    if(l_nodes==NULL) {\n      *status=CCL_ERROR_MEMORY;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: ccl_angular_cls(); memory allocation\\n\");\n    }\n  }\n\n  if(*status==0) {\n    cl_nodes=(double *)malloc(w->n_ls*sizeof(double));\n    if(cl_nodes==NULL) {\n      *status=CCL_ERROR_MEMORY;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: ccl_cl_angular_cls(); memory allocation\\n\");\n    }\n  }\n\n  if(*status==0) {\n    for(ii=0;ii<w->n_ls;ii++)\n      l_nodes[ii]=(double)(w->l_arr[ii]);\n\n    do_angpow=0;\n    //Now check if angpow is needed at all\n    if(w->l_limber>0) {\n      for(ii=0;ii<w->n_ls;ii++) {\n\tif(w->l_arr[ii]<=w->l_limber)\n\t  do_angpow=1;\n      }\n    }\n#ifndef HAVE_ANGPOW\n    do_angpow=0;\n#endif //HAVE_ANGPOW\n  \n    //Resort to Limber if we have lensing (this will hopefully only be temporary)\n    if(clt1->tracer_type==ccl_weak_lensing_tracer || clt2->tracer_type==ccl_weak_lensing_tracer ||\n       clt1->has_magnification || clt2->has_magnification) {\n      do_angpow=0;\n    }\n\n    //Use angpow if non-limber is needed\n    if(do_angpow)\n      ccl_angular_cls_angpow(cosmo,w,clt1,clt2,cl_nodes,status);\n    ccl_check_status(cosmo,status);\n  }\n\n  if(*status==0) {\n    //Compute limber nodes\n    for(ii=0;ii<w->n_ls;ii++) {\n      if((!do_angpow) || (w->l_arr[ii]>w->l_limber))\n\tcl_nodes[ii]=ccl_angular_cl_native(cosmo,w,ii,clt1,clt2,status);\n    }\n\n    //Interpolate into ells requested by user\n    spcl_nodes=ccl_spline_init(w->n_ls,l_nodes,cl_nodes,0,0);\n    if(spcl_nodes==NULL) {\n      *status=CCL_ERROR_MEMORY;\n      ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: ccl_cl_angular_cls(); memory allocation\\n\");\n    }\n  }\n  \n  if(*status==0) {\n    for(ii=0;ii<nl_out;ii++)\n      cl_out[ii]=ccl_spline_eval((double)(l_out[ii]),spcl_nodes);\n  }\n  \n  //Cleanup\n  ccl_spline_free(spcl_nodes);\n  free(cl_nodes);\n  free(l_nodes);\n}\n\nstatic int check_clt_fa_inconsistency(CCL_ClTracer *clt,int func_code)\n{\n  if(((func_code==ccl_trf_nz) && (clt->tracer_type==ccl_cmb_lensing_tracer)) || //lensing has no n(z)\n     (((func_code==ccl_trf_bz) || (func_code==ccl_trf_sz) || (func_code==ccl_trf_wM)) &&\n      (clt->tracer_type!=ccl_number_counts_tracer)) || //bias and magnification only for clustering\n     (((func_code==ccl_trf_rf) || (func_code==ccl_trf_ba) || (func_code==ccl_trf_wL)) &&\n      (clt->tracer_type!=ccl_weak_lensing_tracer))) //IAs only for weak lensing\n    return 1;\n  if((((func_code==ccl_trf_sz) || (func_code==ccl_trf_wM)) &&\n      (clt->has_magnification==0)) || //correct combination, but no magnification\n     (((func_code==ccl_trf_rf) || (func_code==ccl_trf_ba)) &&\n      (clt->has_intrinsic_alignment==0))) //Correct combination, but no IAs\n    return 1;\n  return 0;\n}\n\ndouble ccl_get_tracer_fa(ccl_cosmology *cosmo,CCL_ClTracer *clt,double a,int func_code,int *status)\n{\n  SplPar *spl;\n\n  if(check_clt_fa_inconsistency(clt,func_code)) {\n    *status=CCL_ERROR_INCONSISTENT;\n    ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: inconsistent combination of tracer and internal function to be evaluated\");\n    return -1;\n  }\n\n  switch(func_code) {\n  case ccl_trf_nz :\n    spl=clt->spl_nz;\n    break;\n  case ccl_trf_bz :\n    spl=clt->spl_bz;\n    break;\n  case ccl_trf_sz :\n    spl=clt->spl_sz;\n    break;\n  case ccl_trf_rf :\n    spl=clt->spl_rf;\n    break;\n  case ccl_trf_ba :\n    spl=clt->spl_ba;\n    break;\n  case ccl_trf_wL :\n    spl=clt->spl_wL;\n    break;\n  case ccl_trf_wM :\n    spl=clt->spl_wM;\n    break;\n  }\n\n  double x;\n  if((func_code==ccl_trf_wL) || (func_code==ccl_trf_wM))\n    x=ccl_comoving_radial_distance(cosmo,a,status); //x-variable is comoving distance for lensing kernels\n  else\n    x=1./a-1; //x-variable is redshift by default\n  \n  return ccl_spline_eval(x,spl);\n}\n\nint ccl_get_tracer_fas(ccl_cosmology *cosmo,CCL_ClTracer *clt,int na,double *a,double *fa,\n\t\t       int func_code,int *status)\n{\n  SplPar *spl;\n\n  if(check_clt_fa_inconsistency(clt,func_code)) {\n    *status=CCL_ERROR_INCONSISTENT;\n    ccl_cosmology_set_status_message(cosmo, \"ccl_cls.c: inconsistent combination of tracer and internal function to be evaluated\");\n    return -1;\n  }\n  \n  switch(func_code) {\n  case ccl_trf_nz :\n    spl=clt->spl_nz;\n    break;\n  case ccl_trf_bz :\n    spl=clt->spl_bz;\n    break;\n  case ccl_trf_sz :\n    spl=clt->spl_sz;\n    break;\n  case ccl_trf_rf :\n    spl=clt->spl_rf;\n    break;\n  case ccl_trf_ba :\n    spl=clt->spl_ba;\n    break;\n  case ccl_trf_wL :\n    spl=clt->spl_wL;\n    break;\n  case ccl_trf_wM :\n    spl=clt->spl_wM;\n    break;\n  }\n  \n  int compchi = (func_code==ccl_trf_wL) || (func_code==ccl_trf_wM);\n\n  int ia;\n  for(ia=0;ia<na;ia++) {\n    double x;\n    if(compchi) //x-variable is comoving distance for lensing kernels\n      x=ccl_comoving_radial_distance(cosmo,a[ia],status);\n    else //x-variable is redshift by default\n      x=1./a[ia]-1;\n    fa[ia]=ccl_spline_eval(x,spl);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "150d658deb579139badcf9efc59c9de2e94a2b84", "size": 35403, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_cls.c", "max_stars_repo_name": "vrastil/CCL", "max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccl_cls.c", "max_issues_repo_name": "vrastil/CCL", "max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccl_cls.c", "max_forks_repo_name": "vrastil/CCL", "max_forks_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3", "max_forks_repo_licenses": ["BSD-3-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.0552631579, "max_line_length": 169, "alphanum_fraction": 0.684490015, "num_tokens": 11787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.359981967491423}}
{"text": "#ifndef INFMCMC_H\n#define INFMCMC_H\n\n#include <complex.h>\n#include <fftw3.h>\n#include <gsl/gsl_rng.h>\n\n//void sampleRMWH(CHAIN *C);\n//void sampleIndependenceSampler(CHAIN *C);\n//void updateMean(CHAIN *C);\n//void updateVar(CHAIN *C);\n\nstruct _CHAIN {\n  int nj, nk; // number of Fourier coefficients in x/y direction respectively\n  int numKeptSamples;\n  int sizeObsVector;\n  int currentIter;\n  int accepted;\n  double _shortTimeAccProbAvg;\n  double _bLow, _bHigh;\n  \n  double *currentPhysicalState, *avgPhysicalState, *varPhysicalState, *_M2;\n  double *proposedPhysicalState;\n  double logLHDCurrentState;\n  double accProb, avgAccProb;\n  double rwmhStepSize, alphaPrior, priorVar, priorStd;\n  \n  // -- potentially not used --\n  double *currentStateObservations, *proposedStateObservations;\n  double *data;\n  double currentLSQFunctional;\n  double currentStateL2Norm2;\n  double obsStdDev;  \n  // --------------------------\n  \n  fftw_complex *currentSpectralState, *avgSpectralState;\n  fftw_complex *priorDraw, *proposedSpectralState;\n  \n  fftw_plan _c2r;\n  fftw_plan _r2c;\n  \n  gsl_rng *r;\n};\n\ntypedef struct _CHAIN CHAIN;\ntypedef struct _CHAIN INFCHAIN;\n\nvoid infmcmc_initChain(INFCHAIN *C, const int nj, const int nk);\nvoid infmcmc_freeChain(INFCHAIN *C);\nvoid infmcmc_resetChain(INFCHAIN *C);\nvoid infmcmc_proposeRWMH(INFCHAIN *C);\nvoid infmcmc_updateRWMH(INFCHAIN *C, double logLHDOfProposal);\nvoid infmcmc_seedWithPriorDraw(INFCHAIN *C);\nvoid infmcmc_writeChainInfo(const INFCHAIN *C, FILE *fp);\nvoid infmcmc_writeVFChain(const INFCHAIN *U, const INFCHAIN *V, FILE *fp);\nvoid infmcmc_writeChain(const INFCHAIN *C, FILE *fp);\nvoid infmcmc_printChain(INFCHAIN *C);\nvoid infmcmc_setRWMHStepSize(INFCHAIN *C, double beta);\nvoid infmcmc_adaptRWMHStepSize(INFCHAIN *C, double inc);\nvoid infmcmc_setPriorAlpha(INFCHAIN *C, double alpha);\nvoid infmcmc_setPriorVar(INFCHAIN *C, double var);\ndouble infmcmc_L2Current(INFCHAIN *C);\ndouble infmcmc_L2Proposed(INFCHAIN *C);\ndouble infmcmc_L2Prior(INFCHAIN *C);\n\nvoid infmcmc_seedWithDivFreePriorDraw(INFCHAIN *C1, INFCHAIN *C2);\nvoid infmcmc_proposeDivFreeRWMH(INFCHAIN *C1, INFCHAIN *C2);\nvoid infmcmc_updateVectorFieldRWMH(INFCHAIN *C1, INFCHAIN *C2, double logLHDOfProposal);\n\nvoid randomPriorDrawOLD(gsl_rng *r, double PRIOR_ALPHA, fftw_complex *randDrawCoeffs);\n\n#endif\n", "meta": {"hexsha": "8860be61a0f137b488b9844c8fa788ed74da93d3", "size": 2311, "ext": "h", "lang": "C", "max_stars_repo_path": "mcmclib/infmcmc.h", "max_stars_repo_name": "dmcdougall/mcmclib", "max_stars_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-21T22:02:58.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-21T22:02:58.000Z", "max_issues_repo_path": "mcmclib/infmcmc.h", "max_issues_repo_name": "dmcdougall/mcmclib", "max_issues_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcmclib/infmcmc.h", "max_forks_repo_name": "dmcdougall/mcmclib", "max_forks_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266", "max_forks_repo_licenses": ["BSD-3-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.6575342466, "max_line_length": 88, "alphanum_fraction": 0.7741237559, "num_tokens": 703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3599819601622248}}
{"text": "/*\n * File: spce_sect.h\n * External definitions for spce_sect.c\n *\n *\n */\n\n#ifndef spce_sect_H\n#define spce_sect_H\n\n#include <math.h>\n#include <gsl/gsl_roots.h>\n#include \"aXe_grism.h\"\n#include \"spc_trace_functions.h\"\n\n\n/**\n  @package spce_sect\n*/\n\n/** \n    A structure to support old gsl 0.9 gsl_interval\n*/\ntypedef struct\n{\n     double lower;\n     double upper;\n}\ngsl_interval;\n\n/** \n  A structure describing the function that has a zero at the section point,\n  including the measuring point and the slope of the line through it, \n  the function describing the spectrum trace, functions related to\n  gsl and a flag to initiate special handling of vertically oriented\n  objects.\n\n  @see fill_in_sectionfun\n  @see free_sectionfun\n*/\ntypedef struct\n{\n  int vertical;\t     /* Special handling if orientation is close to vertical */\n  double m;\t     /* slope of line through x0, y0 that is to */\n  double x0, y0;     /* intersect the trace */\n  trace_func *func;  /* Parametrization of the trace */\n\n     /* the GSL stuff has to be kept in here to avoid excessive re-allocing\n        of the solver for each pixel */\n  gsl_interval *interv;\n  gsl_function *gslfun;\n  gsl_root_fsolver *solver;\n}\nsectionfun;\n\n/* public */\n\nint fill_in_sectionfun (sectionfun * const sf, const double inclination,\n\t\t\tconst beam * const b);\nint find_section_point (sectionfun *sf, const double x, const double y,\n\t\t\tdouble *const res);\nvoid free_sectionfun (sectionfun * const sf);\n#endif\n", "meta": {"hexsha": "73d7b0bd412f50f1f8e7248ad5d6dccaac3e5887", "size": 1464, "ext": "h", "lang": "C", "max_stars_repo_path": "cextern/src/spce_sect.h", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spce_sect.h", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spce_sect.h", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.875, "max_line_length": 79, "alphanum_fraction": 0.7103825137, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.3598183531506516}}
{"text": "/////////////////\n//example25.5.c\n/////////////////\n#include <stdio.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_odeiv.h>\n#include <math.h>\n\ntypedef struct{\n  double *a; //y=a[0]x[0]+a[1]x[1]+...a[ka]y[ka]+b[0]u[0]+b[1]u[1]+...+b[kb]u[kb]\n  //  double *a; //y[t+1]=a[0]y[t]+a[1]y[t-1]+...a[ka]y[t-ka]+b[0]u[t]+b[1]u[t-1]+...+b[kb]u[t-kb]\n  double *b;\n  double *x;\n  double *u;\n  int k,kx,ku;\n  double xmax;\n  double umax;\n  double y;\n  int _dim;\n  double *_y;\n  double *_y_err;\n  double *_dydt_in;\n  double *_dydt_out;\n  double _t;\n} CRANE;\n\n#define dim_crane 4\nint cranefunc (double t, const double y[], double f[], void *params)\n{\n  CRANE *c = (CRANE *)params;\n  f[0] = y[1];\n  f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r;\n  f[2] = y[3];  \n  f[3] = (c->F+c->T*sin(y[0]))/c->M;\n  return GSL_SUCCESS;\n}\n////////////////\n#define square(x) ((x)*(x))\nCRANE crane;\nint initialize()\n{\n  crane.kx=3;\n  crane.ku=1;\n  crane.k=crane.kx+ku;\n  double *a=(double*)malloc(sizeof(double)*ka);\n  double *b=&a[kx];\n  double *x=(double*)malloc(sizeof(double)*k+1);\n  double *u=&x[kx];\n  crane.umax=20.0;//check//  crane.Fmax=30;//check\n\n#ifdef CRANESUB\n  //  crane.Fmax=_crane_Fmax;//check//  crane.Fmax=30;//check\n  //  crane.xmax=20.0;//check//  crane.Fmax=30;//check\n  if(_AP_umax>0) AP_u_max=crane.umax=_AP_umax;\n  else AP_u_max=crane.umax;\n\n  AP_u_min=-AP_u_max;\n  rr=AP_r=_AP_r;//10\n  rr_kyoyou=_rr_kyoyou;\n  C_MODE=11;\n#else\n  crane.h=0.01;\n#endif\n  crane._t=0;\n  int i;for(i=0;i<crane._dim;i++) crane._dydt_in[i]=0;\n\n  return(0);\n}\n#ifndef CRANESUB\nchar *fn=\"crane2io.dat\";\nFILE *fp;\n#endif//#ifndef CRANESUB\n\ndouble plant(double uu)\n{\n  //store previous x and u\n  int i,kx_1=crane.kx-1;\n  for(i=0;i<kx_1;i++) crane.x[i+1]=crane.x[i];\n  int ku_1=crane.ku-1;\n  for(i=0;i<ku_1;i++) crane.u[i+1]=crane.u[i];\n  //store former output\n  crane.x[0]=crane.y;\n\n  //current input\n  if(uu>crane.umax) crane.u[0]=crane.umax;  \n  else if(uu<-crane.umax) crane.u[0]=-crane.umax; \n  // current output\n  crane.y=0;\n  for(i=0;i<crane.k;i++) crane.y+=crane.a[i]*crane.x[i];\n  crane._t++;\n\n#ifndef CRANESUB\n  fprintf(fp,\"%.7e %.7e %.7e %.7e\", crane._t,crane.u[0],crane.x[0],crane.y);//crane.a,crane.da\n  fprintf(fp,\"\\n\");\n#endif\n  return(crane.x);\n  //  return(crane.X);\n}\n\n#ifndef CRANESUB\nint main()\n{\n  ////////////////////////////////////////////////////\n  /// method 1                                     ///\n  /// input ddX                                    ///\n  /// output a,x,y,F                               ///\n  ////////////////////////////////////////////////////\n  //  double h = 0.001;//,hh=0.1; h = 0.0001;//,hh=0.1;\n  double t0=5;     //stationary \n  double t1=5.0+t0;//accelerate(speed up)\n  double t2=2.0+t1;//free run\n  double t3=5.0+t2;//decelerate(slow down)\n  double t4=20+t3;   //free run\n  initialize();\n  int M=(t4/crane.h)+1;\n  double *ddX=(double*)malloc(sizeof(double)*M);\n  //  double *F  =(double*)malloc(sizeof(double)*M);\n  double Vmax=1;//dX/dt=1[m/s]\n\n  int n;\n  double t;\n  ////////////////////////////////////////////////////\n  ///   set ddX                                    ///\n  ////////////////////////////////////////////////////\n  int n0 =t0/crane.h+0.5, n4=t4/crane.h+0.5;\n  for(t=0;t<t4;t+=crane.h){\n    n=t/crane.h;\n    if(t<=t0) ddX[n]=0; //zero\n    else if(t<=t1) ddX[n]=Vmax/(t1-t0); //accelerate\n    else if(t<=t2) ddX[n]=0;            //free move\n    else if(t<=t3) ddX[n]=-Vmax/(t3-t2);//decelerate\n    else ddX[n]=0;                      //free move\n  }\n  ////////////////////////////////////////////////////\n  ///   Solve by the Runge Kutta Method of GSL     ///\n  ////////////////////////////////////////////////////\n  fp=fopen(fn,\"w\");\n  fprintf(fp,\"#%.7e %d %d %.7e %.7e %.7e %.7e #h,n0,n4,M,n,r\\n\",crane.h,n0,n4,crane.M,crane.m,crane.r,crane.C);\n  //  double dx0=0,dy0=0,da0=0;\n  //  for(n=0;n<n4;){\n  for(t=0;t<t4;t+=crane.h){\n    n=t/crane.h;\n    plant(ddX[n]);\n  }\n  fclose(fp);\n  fprintf(stdout,\"Results are stored in '%s'.\\n\",fn);\n\n  gsl_odeiv_step_free (crane._s);\n  return 0;\n}\n\n#ifndef CRANESUB\nint main()\n{\n  ////////////////////////////////////////////////////\n  /// method 1                                     ///\n  /// input ddX                                    ///\n  /// output a,x,y,F                               ///\n  ////////////////////////////////////////////////////\n  //  double h = 0.001;//,hh=0.1; h = 0.0001;//,hh=0.1;\n  double t0=5;     //stationary \n  double t1=5.0+t0;//accelerate(speed up)\n  double t2=2.0+t1;//free run\n  double t3=5.0+t2;//decelerate(slow down)\n  double t4=20+t3;   //free run\n  initialize();\n  int M=(t4/crane.h)+1;\n  double *ddX=(double*)malloc(sizeof(double)*M);\n  //  double *F  =(double*)malloc(sizeof(double)*M);\n  double Vmax=1;//dX/dt=1[m/s]\n\n  int n;\n  double t;\n  ////////////////////////////////////////////////////\n  ///   set ddX                                    ///\n  ////////////////////////////////////////////////////\n  int n0 =t0/crane.h+0.5, n4=t4/crane.h+0.5;\n  for(t=0;t<t4;t+=crane.h){\n    n=t/crane.h;\n    if(t<=t0) ddX[n]=0; //zero\n    else if(t<=t1) ddX[n]=Vmax/(t1-t0); //accelerate\n    else if(t<=t2) ddX[n]=0;            //free move\n    else if(t<=t3) ddX[n]=-Vmax/(t3-t2);//decelerate\n    else ddX[n]=0;                      //free move\n  }\n  ////////////////////////////////////////////////////\n  ///   Solve by the Runge Kutta Method of GSL     ///\n  ////////////////////////////////////////////////////\n  fp=fopen(fn,\"w\");\n  fprintf(fp,\"#%.7e %d %d %.7e %.7e %.7e %.7e #h,n0,n4,M,n,r\\n\",crane.h,n0,n4,crane.M,crane.m,crane.r,crane.C);\n  //  double dx0=0,dy0=0,da0=0;\n  //  for(n=0;n<n4;){\n  for(t=0;t<t4;t+=crane.h){\n    n=t/crane.h;\n    plant(ddX[n]);\n  }\n  fclose(fp);\n  fprintf(stdout,\"Results are stored in '%s'.\\n\",fn);\n\n  gsl_odeiv_step_free (crane._s);\n  return 0;\n}\n#endif //#ifndef SUB\n", "meta": {"hexsha": "7c249549c414946aa8c96a53ab8088c7ebb042f7", "size": 5868, "ext": "c", "lang": "C", "max_stars_repo_path": "1021/mspc/linear2sub.c", "max_stars_repo_name": "Kurogi-Lab/CAN2", "max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "1021/mspc/linear2sub.c", "max_issues_repo_name": "Kurogi-Lab/CAN2", "max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "1021/mspc/linear2sub.c", "max_forks_repo_name": "Kurogi-Lab/CAN2", "max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z", "avg_line_length": 28.6243902439, "max_line_length": 111, "alphanum_fraction": 0.478868439, "num_tokens": 2112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.35977712102411374}}
{"text": "/* multifit/gcv.c\n * \n * Copyright (C) 2016 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/*\n * References:\n *\n * [1] P. C. Hansen, \"Discrete Inverse Problems: Insight and Algorithms,\"\n * SIAM Press, 2010.\n */\n\n#include <config.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_min.h>\n\ntypedef struct\n{\n  const gsl_vector * S;\n  const gsl_vector * UTy;\n  double delta0;\n  size_t np;\n  gsl_vector * workp;\n} gcv_params;\n\nstatic double gcv_func(double lambda, void * params);\n\n/*\ngsl_multifit_linear_gcv_init()\n  Initialize Generalized Cross Validation parameters\n\nInputs: y         - right hand side vector\n        reg_param - (output) regularization parameters\n        UTy       - (output) U^T y\n        delta0    - (output) delta0\n        work      - workspace\n*/\n\nint\ngsl_multifit_linear_gcv_init(const gsl_vector * y,\n                             gsl_vector * reg_param,\n                             gsl_vector * UTy,\n                             double * delta0,\n                             gsl_multifit_linear_workspace * work)\n{\n  const size_t n = y->size;\n\n  if (n != work->n)\n    {\n      GSL_ERROR(\"y vector does not match workspace\", GSL_EBADLEN);\n    }\n  else if (UTy->size != work->p)\n    {\n      GSL_ERROR (\"UTy vector does not match workspace\", GSL_EBADLEN);\n    }\n  else\n    {\n      const size_t p = work->p;\n\n      gsl_matrix_view U = gsl_matrix_submatrix(work->A, 0, 0, n, p);\n      gsl_vector_view S = gsl_vector_subvector(work->S, 0, p);\n\n      const double smax = gsl_vector_get(&S.vector, 0);\n      const double smin = gsl_vector_get(&S.vector, p - 1);\n\n      double dr; /* residual error from projection */\n\n      double normy = gsl_blas_dnrm2(y);\n      double normUTy;\n\n      /* compute projection UTy = U^T y */\n      gsl_blas_dgemv (CblasTrans, 1.0, &U.matrix, y, 0.0, UTy);\n      normUTy = gsl_blas_dnrm2(UTy);\n\n      /* dr = ||y||^2 - ||U^T y||^2 */\n      dr = (normy + normUTy) * (normy - normUTy);\n\n      /* calculate regularization parameters */\n      gsl_multifit_linear_lreg(smin, smax, reg_param);\n\n      if (n > p && dr > 0.0)\n        *delta0 = dr;\n      else\n        *delta0 = 0.0;\n\n      return GSL_SUCCESS;\n    }\n}\n\n/*\ngsl_multifit_linear_gcv_curve()\n  Calculate Generalized Cross Validation curve for a set\nof regularization parameters\n\nInputs: reg_param - regularization parameters\n        UTy       - U^T y vector, size p\n        delta0    - delta0\n        G         - (output) GCV curve values\n        work      - workspace\n*/\n\nint\ngsl_multifit_linear_gcv_curve(const gsl_vector * reg_param,\n                              const gsl_vector * UTy,\n                              const double delta0,\n                              gsl_vector * G,\n                              gsl_multifit_linear_workspace * work)\n{\n  const size_t n = work->n;\n  const size_t p = work->p;\n  const size_t N = reg_param->size; /* number of points on GCV curve */\n\n  if (UTy->size != p)\n    {\n      GSL_ERROR(\"UTy vector does not match workspace\", GSL_EBADLEN);\n    }\n  else if (G->size != N)\n    {\n      GSL_ERROR (\"size of reg_param and G vectors do not match\",\n                 GSL_EBADLEN);\n    }\n  else\n    {\n      size_t i;\n\n      gsl_vector_view S = gsl_vector_subvector(work->S, 0, p);\n      gsl_vector_view workp = gsl_matrix_subcolumn(work->QSI, 0, 0, p);\n\n      gcv_params params;\n\n      params.S = &S.vector;\n      params.UTy = UTy;\n      params.delta0 = delta0;\n      params.np = n - p;\n      params.workp = &workp.vector;\n\n      for (i = 0; i < N; ++i)\n        {\n          double lambdai = gsl_vector_get(reg_param, i);\n          double Gi = gcv_func(lambdai, &params);\n\n          gsl_vector_set(G, i, Gi);\n        }\n\n      return GSL_SUCCESS;\n    }\n}\n\n/*\ngsl_multifit_linear_gcv_min()\n  Find regularization parameter which minimizes GCV curve\n\nInputs: reg_param - regularization parameters\n        UTy       - U^T y vector, size p\n        G         - GCV curve values\n        delta0    - delta0\n        lambda    - (output) optimal regularization parameter\n        work      - workspace\n*/\n\nint\ngsl_multifit_linear_gcv_min(const gsl_vector * reg_param,\n                            const gsl_vector * UTy,\n                            const gsl_vector * G,\n                            const double delta0,\n                            double * lambda,\n                            gsl_multifit_linear_workspace * work)\n{\n  const size_t n = work->n;\n  const size_t p = work->p;\n  const size_t npts = reg_param->size; /* number of points on GCV curve */\n\n  if (UTy->size != p)\n    {\n      GSL_ERROR(\"UTy vector does not match workspace\", GSL_EBADLEN);\n    }\n  else if (G->size != npts)\n    {\n      GSL_ERROR (\"size of reg_param and G vectors do not match\",\n                 GSL_EBADLEN);\n    }\n  else\n    {\n      int status;\n      const size_t max_iter = 500;\n      const double tol = 1.0e-4;\n      gsl_vector_view S = gsl_vector_subvector(work->S, 0, p);\n      gsl_vector_view workp = gsl_matrix_subcolumn(work->QSI, 0, 0, p);\n      gcv_params params;\n      int idxG = (int) gsl_vector_min_index(G);\n      double a = gsl_vector_get(reg_param, GSL_MIN(idxG + 1, (int) npts - 1));\n      double b = gsl_vector_get(reg_param, GSL_MAX(idxG - 1, 0));\n      double m = gsl_vector_get(reg_param, idxG);\n      size_t iter = 0;\n      gsl_function F;\n\n      /* XXX FIXME */\n      gsl_min_fminimizer *min_workspace_p;\n\n      if (idxG == 0 || idxG == ((int)npts - 1))\n        {\n          /* the minimum is an endpoint of the curve, no need to search */\n          *lambda = m;\n          return GSL_SUCCESS;\n        }\n\n      /* XXX FIXME */\n      min_workspace_p = gsl_min_fminimizer_alloc(gsl_min_fminimizer_brent);\n\n      params.S = &S.vector;\n      params.UTy = UTy;\n      params.delta0 = delta0;\n      params.np = n - p;\n      params.workp = &workp.vector;\n\n      F.function = gcv_func;\n      F.params = &params;\n\n      gsl_min_fminimizer_set(min_workspace_p, &F, m, a, b);\n\n      do\n        {\n          iter++;\n          status = gsl_min_fminimizer_iterate(min_workspace_p);\n\n          a = gsl_min_fminimizer_x_lower(min_workspace_p);\n          b = gsl_min_fminimizer_x_upper(min_workspace_p);\n\n          status = gsl_min_test_interval(a, b, 0.0, tol);\n        }\n      while (status == GSL_CONTINUE && iter < max_iter);\n\n      if (status == GSL_SUCCESS)\n        *lambda = gsl_min_fminimizer_minimum(min_workspace_p);\n      else\n        status = GSL_EMAXITER;\n\n      gsl_min_fminimizer_free(min_workspace_p);\n\n      return status;\n    }\n}\n\n/*\ngsl_multifit_linear_gcv_calc()\n  Calculate GCV function G(lambda) for given lambda\n\nInputs: reg_param - regularization parameters\n        UTy       - U^T y vector, size p\n        delta0    - delta0\n        G         - (output) GCV curve values\n        work      - workspace\n*/\n\ndouble\ngsl_multifit_linear_gcv_calc(const double lambda,\n                             const gsl_vector * UTy,\n                             const double delta0,\n                             gsl_multifit_linear_workspace * work)\n{\n  const size_t n = work->n;\n  const size_t p = work->p;\n\n  if (UTy->size != p)\n    {\n      GSL_ERROR_VAL(\"UTy vector does not match workspace\", GSL_EBADLEN, 0.0);\n    }\n  else\n    {\n      gsl_vector_view S = gsl_vector_subvector(work->S, 0, p);\n      gsl_vector_view workp = gsl_matrix_subcolumn(work->QSI, 0, 0, p);\n      gcv_params params;\n      double G;\n\n      params.S = &S.vector;\n      params.UTy = UTy;\n      params.delta0 = delta0;\n      params.np = n - p;\n      params.workp = &workp.vector;\n\n      G = gcv_func(lambda, &params);\n\n      return G;\n    }\n}\n\n/*\ngsl_multifit_linear_gcv()\n  Calculate Generalized Cross Validation curve for a set\nof regularization parameters\n\nInputs: y         - right hand side vector\n        reg_param - (output) regularization parameters\n        G         - (output) GCV curve values\n        lambda    - (output) optimal regularization parameter which\n                    minimizes GCV curve\n        G_lambda  - (output) G(lambda) value at optimal parameter\n        work      - workspace\n*/\n\nint\ngsl_multifit_linear_gcv(const gsl_vector * y,\n                        gsl_vector * reg_param,\n                        gsl_vector * G,\n                        double * lambda,\n                        double * G_lambda,\n                        gsl_multifit_linear_workspace * work)\n{\n  const size_t n = y->size;\n  const size_t N = G->size; /* number of points on GCV curve */\n\n  if (n != work->n)\n    {\n      GSL_ERROR(\"y vector does not match workspace\", GSL_EBADLEN);\n    }\n  else if (reg_param->size != N)\n    {\n      GSL_ERROR (\"size of reg_param and G vectors do not match\",\n                 GSL_EBADLEN);\n    }\n  else\n    {\n      int status;\n      const size_t p = work->p;\n      gsl_vector_view UTy = gsl_vector_subvector(work->xt, 0, p);\n      double delta0;\n\n      status = gsl_multifit_linear_gcv_init(y, reg_param, &UTy.vector, &delta0, work);\n      if (status)\n        return status;\n\n      status = gsl_multifit_linear_gcv_curve(reg_param, &UTy.vector, delta0, G, work);\n      if (status)\n        return status;\n\n      status = gsl_multifit_linear_gcv_min(reg_param, &UTy.vector, G, delta0, lambda, work);\n      if (status)\n        return status;\n\n      *G_lambda = gsl_multifit_linear_gcv_calc(*lambda, &UTy.vector, delta0, work);\n\n      return GSL_SUCCESS;\n    }\n}\n\nstatic double\ngcv_func(double lambda, void * params)\n{\n  gcv_params * par = (gcv_params *) params;\n  const gsl_vector *S = par->S;\n  const gsl_vector *UTy = par->UTy;\n  double delta0 = par->delta0;\n  size_t np = par->np;\n  gsl_vector *workp = par->workp;\n  const size_t p = S->size;\n  size_t i;\n  double lambda_sq = lambda * lambda;\n  double G, d, norm;\n  double sumf = 0.0;\n\n  /* compute workp = 1 - filter_factors */\n  for (i = 0; i < p; ++i)\n    {\n      double si = gsl_vector_get(S, i);\n      double fi = lambda_sq / (si * si + lambda_sq);\n      gsl_vector_set(workp, i, fi);\n      sumf += fi;\n    }\n\n  d = (double)np + sumf;\n\n  gsl_vector_mul(workp, UTy);\n  norm = gsl_blas_dnrm2(workp);\n\n  G = (norm*norm + delta0) / (d * d);\n\n  return G;\n}\n", "meta": {"hexsha": "2b28535e870b1affffb5935e28826606e2d708b7", "size": 10866, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit/gcv.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/gcv.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/gcv.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 27.3015075377, "max_line_length": 92, "alphanum_fraction": 0.5952512424, "num_tokens": 2911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.35968827500741174}}
{"text": "#ifndef TRANS_MYFUNC\n#define TRANS_MYFUNC\n\n\n#include <stdarg.h>\n#include <gsl/gsl_vector.h>\n#include \"../include/type.h\"\n\n\nvoid mle_result_set(mle_result* mle, double sum, gsl_vector* psi1, gsl_vector* psi2,\n                    double beta0, double beta1, double var1, double var2);\n\nvoid log_vector(gsl_vector *vec);\n\ndouble myfunc_multivar(const double x[], va_list argv);\n\nvoid myfunc_multivar_der(const double x[], double res[], va_list argv);\n\ndouble myfunc_1_2(const double x[], va_list argv);\n\nvoid myfunc_der_1_2(const double x[], double res[], va_list argv);\n\ndouble myfunc_marginal_1_2(const double x[], va_list argv);\n\nvoid myfunc_marginal_1_2_der(const double x[], double res[], va_list argv);\n\ndouble myfunc_individual(const double x[], va_list argv);\n\nvoid myfunc_individual_der(const double x[], double res[], va_list argv);\n\ndouble myfunc_marginal(const double x[], va_list argv);\n\nvoid myfunc_marginal_der(const double x[], double res[], va_list argv);\n\nint MLE_marginal_iteration(gsl_vector* i1, gsl_vector* i2,\n                           gsl_vector* s1, gsl_vector* s2,\n                           const int inclu_len, const int skip_len,\n                           mle_result* mle);\n\nint MLE_marginal_iteration_constrain(gsl_vector* i1, gsl_vector* i2,\n                                     gsl_vector* s1, gsl_vector* s2,\n                                     const int inclu_len, const int skip_len,\n                                     mle_result* mle);\n\nvoid* thread_wrapper_for_LT(void* arg);\n\nvoid* batch_wrapper_for_LT(void* arg);\n\ndouble likelihood_test(gsl_vector *i1, gsl_vector *i2, gsl_vector *s1, gsl_vector *s2,\n                        int inclu_len, int skip_len, int flag, char* id);\n\nint vec2psi(gsl_vector* psi, gsl_vector *inc, gsl_vector *skp,\n            int inclu_len, int skip_len);\n\n\n#endif\n", "meta": {"hexsha": "9f18cbda5c21992b1537216ee4a822de61bd96e3", "size": 1832, "ext": "h", "lang": "C", "max_stars_repo_path": "rMATS_C/include/myfunc.h", "max_stars_repo_name": "chunjie-sam-liu/rmats-turbo", "max_stars_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 88.0, "max_stars_repo_stars_event_min_datetime": "2020-06-01T20:20:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T17:34:39.000Z", "max_issues_repo_path": "rMATS_C/include/myfunc.h", "max_issues_repo_name": "chunjie-sam-liu/rmats-turbo", "max_issues_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 163.0, "max_issues_repo_issues_event_min_datetime": "2020-06-03T06:54:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:39:30.000Z", "max_forks_repo_path": "rMATS_C/include/myfunc.h", "max_forks_repo_name": "chunjie-sam-liu/rmats-turbo", "max_forks_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2020-06-01T20:25:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:14:46.000Z", "avg_line_length": 32.1403508772, "max_line_length": 86, "alphanum_fraction": 0.66430131, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.35960367707534796}}
{"text": "#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n#include <math.h>\n#include <gbpLib.h>\n#include <gbpRNG.h>\n#include <gbpMCMC.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_fit.h>\n#include <gsl/gsl_interp.h>\n\nvoid free_MCMC_covariance(MCMC_info *MCMC) {\n    int           i_DS;\n    MCMC_DS_info *current_DS;\n    MCMC_DS_info *next_DS;\n\n    if(MCMC->n_M != NULL) {\n        SID_log(\"Freeing MCMC covariance matrix...\", SID_LOG_OPEN);\n\n        SID_free(SID_FARG MCMC->V);\n        if(MCMC->m != NULL) {\n            gsl_matrix_free(MCMC->m);\n            MCMC->m = NULL;\n        }\n        if(MCMC->b != NULL) {\n            gsl_vector_free(MCMC->b);\n            MCMC->b = NULL;\n        }\n\n        SID_log(\"Done.\", SID_LOG_CLOSE);\n    }\n}\n", "meta": {"hexsha": "82cd405f583b650f2e03497b5c41b193aaa27a08", "size": 742, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_covariance.c", "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_issues_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_covariance.c", "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_forks_repo_path": "src/gbpMath/gbpMCMC/free_MCMC_covariance.c", "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "avg_line_length": 22.4848484848, "max_line_length": 67, "alphanum_fraction": 0.5727762803, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.359603671178204}}
{"text": "/* vector/test.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n\n#if defined( _MSC_VER ) && defined( GSL_DLL )\n#undef inline\n#define inline __forceinline \n#endif\n\n#if (!GSL_RANGE_CHECK) && defined(HAVE_INLINE)\n#undef GSL_RANGE_CHECK\n#define GSL_RANGE_CHECK 1\n#endif\n\n#include <stdlib.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_test.h>\n#include <gsl/gsl_ieee_utils.h>\n\nint status = 0;\n\n#ifndef DESC\n#define DESC \"\"\n#endif\n\n#define BASE_GSL_COMPLEX_LONG\n#include \"templates_on.h\"\n#include \"test_complex_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX_LONG\n\n#define BASE_GSL_COMPLEX\n#include \"templates_on.h\"\n#include \"test_complex_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX\n\n#define BASE_GSL_COMPLEX_FLOAT\n#include \"templates_on.h\"\n#include \"test_complex_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_GSL_COMPLEX_FLOAT\n\n#define BASE_LONG_DOUBLE\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG_DOUBLE\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_FLOAT\n\n#define BASE_ULONG\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_ULONG\n\n#define BASE_LONG\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_LONG\n\n#define BASE_UINT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UINT\n\n#define BASE_INT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_INT\n\n#define BASE_USHORT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_USHORT\n\n#define BASE_SHORT\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_SHORT\n\n#define BASE_UCHAR\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_UCHAR\n\n#define BASE_CHAR\n#include \"templates_on.h\"\n#include \"test_source.c\"\n#include \"templates_off.h\"\n#undef  BASE_CHAR\n\nvoid my_error_handler (const char *reason, const char *file,\n                       int line, int err);\n\nint\nmain (void)\n{\n  size_t stride, ostride, N;\n\n  gsl_ieee_env_setup ();\n\n  for (N = 10; N < 1024; N = 2*N + 1) \n    {\n      for (stride = 1; stride < 5 ; stride++)\n        {\n          test_func (stride, N);\n          test_float_func (stride, N);\n          test_long_double_func (stride, N);\n          test_ulong_func (stride, N);\n          test_long_func (stride, N);\n          test_uint_func (stride, N);\n          test_int_func (stride, N);\n          test_ushort_func (stride, N);\n          test_short_func (stride, N);\n          test_uchar_func (stride, N);\n          test_char_func (stride, N);\n\n          test_complex_func (stride, N);\n          test_complex_float_func (stride, N);\n          test_complex_long_double_func (stride, N);\n\n          for (ostride = 1; ostride < 5 ; ostride++)\n            {\n              test_ops (stride, ostride, N);\n              test_float_ops (stride, ostride, N);\n              test_long_double_ops (stride, ostride, N);\n              test_ulong_ops (stride, ostride, N);\n              test_long_ops (stride, ostride, N);\n              test_uint_ops (stride, ostride, N);\n              test_int_ops (stride, ostride, N);\n              test_ushort_ops (stride, ostride, N);\n              test_short_ops (stride, ostride, N);\n              test_uchar_ops (stride, ostride, N);\n              test_char_ops (stride, ostride, N);\n              test_complex_ops (stride, ostride, N);\n              test_complex_float_ops (stride, ostride, N);\n              test_complex_long_double_ops (stride, ostride, N);\n            }              \n\n          test_text (stride, N);\n          test_float_text (stride, N);\n#if HAVE_PRINTF_LONGDOUBLE\n          test_long_double_text (stride, N);\n#endif\n          test_ulong_text (stride, N);\n          test_long_text (stride, N);\n          test_uint_text (stride, N);\n          test_int_text (stride, N);\n          test_ushort_text (stride, N);\n          test_short_text (stride, N);\n          test_uchar_text (stride, N);\n          test_char_text (stride, N);\n\n          test_complex_text (stride, N);\n          test_complex_float_text (stride, N);\n#if HAVE_PRINTF_LONGDOUBLE\n          test_complex_long_double_text (stride, N);\n#endif\n\n          test_file (stride, N);\n          test_float_file (stride, N);\n          test_long_double_file (stride, N);\n          test_ulong_file (stride, N);\n          test_long_file (stride, N);\n          test_uint_file (stride, N);\n          test_int_file (stride, N);\n          test_ushort_file (stride, N);\n          test_short_file (stride, N);\n          test_uchar_file (stride, N);\n          test_char_file (stride, N);\n          test_complex_file (stride, N);\n          test_complex_float_file (stride, N);\n          test_complex_long_double_file (stride, N);\n        }\n    }\n\n#if GSL_RANGE_CHECK\n  gsl_set_error_handler (&my_error_handler);\n\n  for (N = 1; N < 1024; N *=2) \n    {\n      for (stride = 1; stride < 5 ; stride++)\n        {\n          test_trap (stride, N);\n          test_float_trap (stride, N);\n          test_long_double_trap (stride, N);\n          test_ulong_trap (stride, N);\n          test_long_trap (stride, N);\n          test_uint_trap (stride, N);\n          test_int_trap (stride, N);\n          test_ushort_trap (stride, N);\n          test_short_trap (stride, N);\n          test_uchar_trap (stride, N);\n          test_char_trap (stride, N);\n          test_complex_trap (stride, N);\n          test_complex_float_trap (stride, N);\n          test_complex_long_double_trap (stride, N);\n        }\n    }\n#endif\n\n  exit (gsl_test_summary ());\n}\n\nvoid\nmy_error_handler (const char *reason, const char *file, int line, int err)\n{\n  if (0)\n    printf (\"(caught [%s:%d: %s (%d)])\\n\", file, line, reason, err);\n  status = 1;\n}\n", "meta": {"hexsha": "649ba9fe3507602fcb9370bd07d7923a5052f42a", "size": 6880, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/libs/gsl/tests/vector/test.c", "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 692.0, "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_issues_repo_path": "tests/libs/gsl/tests/vector/test.c", "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1096.0, "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_forks_repo_path": "tests/libs/gsl/tests/vector/test.c", "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "avg_line_length": 27.4103585657, "max_line_length": 81, "alphanum_fraction": 0.6524709302, "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3594673787857312}}
{"text": "/* specfunc/result.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_exp.h>\n#include <gsl/gsl_sf_result.h>\n\n\nint\ngsl_sf_result_smash_e(const gsl_sf_result_e10 * re, gsl_sf_result * r)\n{\n  if(re->e10 == 0) {\n    /* nothing to smash */\n    r->val = re->val;\n    r->err = re->err;\n    return GSL_SUCCESS;\n  }\n  else {\n    const double av = fabs(re->val);\n    const double ae = fabs(re->err);\n\n    if(   GSL_SQRT_DBL_MIN < av && av < GSL_SQRT_DBL_MAX\n       && GSL_SQRT_DBL_MIN < ae && ae < GSL_SQRT_DBL_MAX\n       && 0.49*GSL_LOG_DBL_MIN  < re->e10 && re->e10 < 0.49*GSL_LOG_DBL_MAX\n       ) {\n      const double scale = exp(re->e10 * M_LN10);\n      r->val = re->val * scale;\n      r->err = re->err * scale;\n      return GSL_SUCCESS;\n    }\n    else {\n      return gsl_sf_exp_mult_err_e(re->e10*M_LN10, 0.0, re->val, re->err, r);\n    }\n  }\n/*\n  int stat_v;\n  int stat_e;\n\n  if(re->val == 0.0) {\n    r->val = 0.0;\n    stat_v = GSL_SUCCESS;\n  }\n  else {\n    gsl_sf_result r_val;\n    const double s = GSL_SIGN(re->val);\n    const double x_v = re->e10*M_LN10 + log(fabs(re->val));\n    stat_v = gsl_sf_exp_e(x_v, &r_val);\n    r->val = s * r_val.val;\n  }\n\n  if(re->err == 0.0) {\n    r->err = 0.0;\n    stat_e = GSL_SUCCESS;\n  }\n  else if(re->val != 0.0) {\n    r->err = fabs(r->val * re->err/re->val);\n    stat_e = GSL_SUCCESS;\n  }\n  else {\n    gsl_sf_result r_err;\n    const double x_e = re->e10*M_LN10 + log(fabs(re->err));\n    stat_e = gsl_sf_exp_e(x_e, &r_err);\n    r->err = r_err.val;\n  }\n\n  return GSL_ERROR_SELECT_2(stat_v, stat_e);\n*/\n}\n\n", "meta": {"hexsha": "43ff3bb14a4948e3ca54133f0fa5ef62d0f442b9", "size": 2401, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/result.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/result.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/result.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 26.6777777778, "max_line_length": 81, "alphanum_fraction": 0.6330695544, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.35919392085984597}}
{"text": "/**\n *\n * @file core_cgetrf.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated c Tue Jan  7 11:44:48 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex32_t\n *\n *  CORE_cgetrf - Computes an LU factorization of a general M-by-N matrix A\n *  using the tile LU algorithm with partial tile pivoting with row interchanges.\n *\n *******************************************************************************\n *\n * @param[in] m\n *          The number of rows of the matrix A. m >= 0.\n *\n * @param[in] n\n *          The number of columns of the matrix A. n >= 0.\n *\n * @param[in,out] A\n *          On entry, the M-by-N matrix to be factored.\n *          On exit, the tile factors L and U from the factorization.\n *\n * @param[in] lda\n *          The leading dimension of the array A. LDA >= max(1,M).\n *\n * @param[out] IPIV\n *          The pivot indices that define the permutations.\n *\n * @param[out] info\n *          - 0 on successful exit\n *          - <0 if -i, the i-th argument had an illegal value\n *          - >0 if i, U(i,i) is exactly zero. The factorization has been\n *            completed, but the factor U is exactly singular, and division by\n *            zero will occur if it is used to solve a system of equations.\n *\n *******************************************************************************\n *\n * @return\n *         \\retval PLASMA_SUCCESS successful exit\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_cgetrf = PCORE_cgetrf\n#define CORE_cgetrf PCORE_cgetrf\n#endif\nint CORE_cgetrf(int m, int n,\n                 PLASMA_Complex32_t *A, int lda,\n                 int *IPIV, int *info)\n{\n    *info = LAPACKE_cgetrf_work(LAPACK_COL_MAJOR, m, n, A, lda, IPIV );\n    return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "4105a20f6c64ddce88fff7c1c111c5527f651ab7", "size": 2098, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_cgetrf.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_cgetrf.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_cgetrf.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.3134328358, "max_line_length": 81, "alphanum_fraction": 0.5324118208, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.35903990981389106}}
{"text": "/* eigen/genv.c\n * \n * Copyright (C) 2007 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <stdlib.h>\n#include <math.h>\n\n#include <config.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_vector_complex.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_errno.h>\n\n/*\n * This module computes the eigenvalues and eigenvectors of a\n * real generalized eigensystem A x = \\lambda B x. Left and right\n * Schur vectors are optionally computed as well.\n *\n * This file contains routines based on original code from LAPACK\n * which is distributed under the modified BSD license.\n */\n\nstatic int genv_get_right_eigenvectors(const gsl_matrix *S,\n                                       const gsl_matrix *T,\n                                       gsl_matrix *Z,\n                                       gsl_matrix_complex *evec,\n                                       gsl_eigen_genv_workspace *w);\nstatic void genv_normalize_eigenvectors(gsl_vector_complex *alpha,\n                                        gsl_matrix_complex *evec);\n\n/*\ngsl_eigen_genv_alloc()\n  Allocate a workspace for solving the generalized eigenvalue problem.\nThe size of this workspace is O(7n).\n\nInputs: n - size of matrices\n\nReturn: pointer to workspace\n*/\n\ngsl_eigen_genv_workspace *\ngsl_eigen_genv_alloc(const size_t n)\n{\n  gsl_eigen_genv_workspace *w;\n\n  if (n == 0)\n    {\n      GSL_ERROR_NULL (\"matrix dimension must be positive integer\",\n                      GSL_EINVAL);\n    }\n\n  w = (gsl_eigen_genv_workspace *) calloc (1, sizeof (gsl_eigen_genv_workspace));\n\n  if (w == 0)\n    {\n      GSL_ERROR_NULL (\"failed to allocate space for workspace\", GSL_ENOMEM);\n    }\n\n  w->size = n;\n  w->Q = NULL;\n  w->Z = NULL;\n\n  w->gen_workspace_p = gsl_eigen_gen_alloc(n);\n\n  if (w->gen_workspace_p == 0)\n    {\n      gsl_eigen_genv_free(w);\n      GSL_ERROR_NULL (\"failed to allocate space for gen workspace\", GSL_ENOMEM);\n    }\n\n  /* compute the full Schur forms */\n  gsl_eigen_gen_params(1, 1, 1, w->gen_workspace_p);\n\n  w->work1 = gsl_vector_alloc(n);\n  w->work2 = gsl_vector_alloc(n);\n  w->work3 = gsl_vector_alloc(n);\n  w->work4 = gsl_vector_alloc(n);\n  w->work5 = gsl_vector_alloc(n);\n  w->work6 = gsl_vector_alloc(n);\n\n  if (w->work1 == 0 || w->work2 == 0 || w->work3 == 0 ||\n      w->work4 == 0 || w->work5 == 0 || w->work6 == 0)\n    {\n      gsl_eigen_genv_free(w);\n      GSL_ERROR_NULL (\"failed to allocate space for additional workspace\", GSL_ENOMEM);\n    }\n\n  return (w);\n} /* gsl_eigen_genv_alloc() */\n\n/*\ngsl_eigen_genv_free()\n  Free workspace w\n*/\n\nvoid\ngsl_eigen_genv_free(gsl_eigen_genv_workspace *w)\n{\n  RETURN_IF_NULL (w);\n\n  if (w->gen_workspace_p)\n    gsl_eigen_gen_free(w->gen_workspace_p);\n\n  if (w->work1)\n    gsl_vector_free(w->work1);\n\n  if (w->work2)\n    gsl_vector_free(w->work2);\n\n  if (w->work3)\n    gsl_vector_free(w->work3);\n\n  if (w->work4)\n    gsl_vector_free(w->work4);\n\n  if (w->work5)\n    gsl_vector_free(w->work5);\n\n  if (w->work6)\n    gsl_vector_free(w->work6);\n\n  free(w);\n} /* gsl_eigen_genv_free() */\n\n/*\ngsl_eigen_genv()\n\nSolve the generalized eigenvalue problem\n\nA x = \\lambda B x\n\nfor the eigenvalues \\lambda and right eigenvectors x.\n\nInputs: A     - general real matrix\n        B     - general real matrix\n        alpha - (output) where to store eigenvalue numerators\n        beta  - (output) where to store eigenvalue denominators\n        evec  - (output) where to store eigenvectors\n        w     - workspace\n\nReturn: success or error\n*/\n\nint\ngsl_eigen_genv (gsl_matrix * A, gsl_matrix * B, gsl_vector_complex * alpha,\n                gsl_vector * beta, gsl_matrix_complex *evec,\n                gsl_eigen_genv_workspace * w)\n{\n  const size_t N = A->size1;\n\n  /* check matrix and vector sizes */\n\n  if (N != A->size2)\n    {\n      GSL_ERROR (\"matrix must be square to compute eigenvalues\", GSL_ENOTSQR);\n    }\n  else if ((N != B->size1) || (N != B->size2))\n    {\n      GSL_ERROR (\"B matrix dimensions must match A\", GSL_EBADLEN);\n    }\n  else if (alpha->size != N || beta->size != N)\n    {\n      GSL_ERROR (\"eigenvalue vector must match matrix size\", GSL_EBADLEN);\n    }\n  else if (w->size != N)\n    {\n      GSL_ERROR (\"matrix size does not match workspace\", GSL_EBADLEN);\n    }\n  else if (evec->size1 != N)\n    {\n      GSL_ERROR (\"eigenvector matrix has wrong size\", GSL_EBADLEN);\n    }\n  else\n    {\n      int s;\n      gsl_matrix Z;\n\n      /*\n       * We need a place to store the right Schur vectors, so we will\n       * treat evec as a real matrix and store them in the left\n       * half - the factor of 2 in the tda corresponds to the\n       * complex multiplicity\n       */\n      Z.size1 = N;\n      Z.size2 = N;\n      Z.tda = 2 * N;\n      Z.data = evec->data;\n      Z.block = 0;\n      Z.owner = 0;\n\n      s = gsl_eigen_gen_QZ(A, B, alpha, beta, w->Q, &Z, w->gen_workspace_p);\n\n      if (w->Z)\n        {\n          /* save right Schur vectors */\n          gsl_matrix_memcpy(w->Z, &Z);\n        }\n\n      /* only compute eigenvectors if we found all eigenvalues */\n      if (s == GSL_SUCCESS)\n        {\n          /* compute eigenvectors */\n          s = genv_get_right_eigenvectors(A, B, &Z, evec, w);\n\n          if (s == GSL_SUCCESS)\n            genv_normalize_eigenvectors(alpha, evec);\n        }\n\n      return s;\n    }\n} /* gsl_eigen_genv() */\n\n/*\ngsl_eigen_genv_QZ()\n\nSolve the generalized eigenvalue problem\n\nA x = \\lambda B x\n\nfor the eigenvalues \\lambda and right eigenvectors x. Optionally\ncompute left and/or right Schur vectors Q and Z which satisfy:\n\nA = Q S Z^t\nB = Q T Z^t\n\nwhere (S, T) is the generalized Schur form of (A, B)\n\nInputs: A     - general real matrix\n        B     - general real matrix\n        alpha - (output) where to store eigenvalue numerators\n        beta  - (output) where to store eigenvalue denominators\n        evec  - (output) where to store eigenvectors\n        Q     - (output) if non-null, where to store left Schur vectors\n        Z     - (output) if non-null, where to store right Schur vectors\n        w     - workspace\n\nReturn: success or error\n*/\n\nint\ngsl_eigen_genv_QZ (gsl_matrix * A, gsl_matrix * B,\n                   gsl_vector_complex * alpha, gsl_vector * beta,\n                   gsl_matrix_complex * evec,\n                   gsl_matrix * Q, gsl_matrix * Z,\n                   gsl_eigen_genv_workspace * w)\n{\n  if (Q && (A->size1 != Q->size1 || A->size1 != Q->size2))\n    {\n      GSL_ERROR(\"Q matrix has wrong dimensions\", GSL_EBADLEN);\n    }\n  else if (Z && (A->size1 != Z->size1 || A->size1 != Z->size2))\n    {\n      GSL_ERROR(\"Z matrix has wrong dimensions\", GSL_EBADLEN);\n    }\n  else\n    {\n      int s;\n\n      w->Q = Q;\n      w->Z = Z;\n\n      s = gsl_eigen_genv(A, B, alpha, beta, evec, w);\n\n      w->Q = NULL;\n      w->Z = NULL;\n\n      return s;\n    }\n} /* gsl_eigen_genv_QZ() */\n\n/********************************************\n *           INTERNAL ROUTINES              *\n ********************************************/\n\n/*\ngenv_get_right_eigenvectors()\n  Compute right eigenvectors of the Schur form (S, T) and then\nbacktransform them using the right Schur vectors to get right\neigenvectors of the original system.\n\nInputs: S     - upper quasi-triangular Schur form of A\n        T     - upper triangular Schur form of B\n        Z     - right Schur vectors\n        evec  - (output) where to store eigenvectors\n        w     - workspace\n\nReturn: success or error\n\nNotes: 1) based on LAPACK routine DTGEVC\n       2) eigenvectors are stored in the order that their\n          eigenvalues appear in the Schur form\n*/\n\nstatic int\ngenv_get_right_eigenvectors(const gsl_matrix *S, const gsl_matrix *T,\n                            gsl_matrix *Z,\n                            gsl_matrix_complex *evec,\n                            gsl_eigen_genv_workspace *w)\n{\n  const size_t N = w->size;\n  const double small = GSL_DBL_MIN * N / GSL_DBL_EPSILON;\n  const double big = 1.0 / small;\n  const double bignum = 1.0 / (GSL_DBL_MIN * N);\n  size_t i, j, k, end;\n  int is;\n  double anorm, bnorm;\n  double temp, temp2, temp2r, temp2i;\n  double ascale, bscale;\n  double salfar, sbeta;\n  double acoef, bcoefr, bcoefi, acoefa, bcoefa;\n  double creala, cimaga, crealb, cimagb, cre2a, cim2a, cre2b, cim2b;\n  double dmin, xmax;\n  double scale;\n  size_t nw, na;\n  int lsa, lsb;\n  int complex_pair;\n  gsl_complex z_zero, z_one;\n  double bdiag[2] = { 0.0, 0.0 };\n  double sum[4];\n  int il2by2;\n  size_t jr, jc, ja;\n  double xscale;\n  gsl_vector_complex_view ecol;\n  gsl_vector_view re, im, re2, im2;\n\n  GSL_SET_COMPLEX(&z_zero, 0.0, 0.0);\n  GSL_SET_COMPLEX(&z_one, 1.0, 0.0);\n\n  /*\n   * Compute the 1-norm of each column of (S, T) excluding elements\n   * belonging to the diagonal blocks to check for possible overflow\n   * in the triangular solver\n   */\n\n  anorm = fabs(gsl_matrix_get(S, 0, 0));\n  if (N > 1)\n    anorm += fabs(gsl_matrix_get(S, 1, 0));\n  bnorm = fabs(gsl_matrix_get(T, 0, 0));\n\n  gsl_vector_set(w->work1, 0, 0.0);\n  gsl_vector_set(w->work2, 0, 0.0);\n\n  for (j = 1; j < N; ++j)\n    {\n      temp = temp2 = 0.0;\n      if (gsl_matrix_get(S, j, j - 1) == 0.0)\n        end = j;\n      else\n        end = j - 1;\n\n      for (i = 0; i < end; ++i)\n        {\n          temp += fabs(gsl_matrix_get(S, i, j));\n          temp2 += fabs(gsl_matrix_get(T, i, j));\n        }\n\n      gsl_vector_set(w->work1, j, temp);\n      gsl_vector_set(w->work2, j, temp2);\n\n      for (i = end; i < GSL_MIN(j + 2, N); ++i)\n        {\n          temp += fabs(gsl_matrix_get(S, i, j));\n          temp2 += fabs(gsl_matrix_get(T, i, j));\n        }\n\n      anorm = GSL_MAX(anorm, temp);\n      bnorm = GSL_MAX(bnorm, temp2);\n    }\n\n  ascale = 1.0 / GSL_MAX(anorm, GSL_DBL_MIN);\n  bscale = 1.0 / GSL_MAX(bnorm, GSL_DBL_MIN);\n\n  complex_pair = 0;\n  for (k = 0; k < N; ++k)\n    {\n      size_t je = N - 1 - k;\n\n      if (complex_pair)\n        {\n          complex_pair = 0;\n          continue;\n        }\n\n      nw = 1;\n      if (je > 0)\n        {\n          if (gsl_matrix_get(S, je, je - 1) != 0.0)\n            {\n              complex_pair = 1;\n              nw = 2;\n            }\n        }\n\n      if (!complex_pair)\n        {\n          if (fabs(gsl_matrix_get(S, je, je)) <= GSL_DBL_MIN &&\n              fabs(gsl_matrix_get(T, je, je)) <= GSL_DBL_MIN)\n            {\n              /* singular matrix pencil - unit eigenvector */\n              for (i = 0; i < N; ++i)\n                gsl_matrix_complex_set(evec, i, je, z_zero);\n\n              gsl_matrix_complex_set(evec, je, je, z_one);\n\n              continue;\n            }\n\n          /* clear vector */\n          for (i = 0; i < N; ++i)\n            gsl_vector_set(w->work3, i, 0.0);\n        }\n      else\n        {\n          /* clear vectors */\n          for (i = 0; i < N; ++i)\n            {\n              gsl_vector_set(w->work3, i, 0.0);\n              gsl_vector_set(w->work4, i, 0.0);\n            }\n        }\n\n      if (!complex_pair)\n        {\n          /* real eigenvalue */\n\n          temp = 1.0 / GSL_MAX(GSL_DBL_MIN,\n                               GSL_MAX(fabs(gsl_matrix_get(S, je, je)) * ascale,\n                                       fabs(gsl_matrix_get(T, je, je)) * bscale));\n          salfar = (temp * gsl_matrix_get(S, je, je)) * ascale;\n          sbeta = (temp * gsl_matrix_get(T, je, je)) * bscale;\n          acoef = sbeta * ascale;\n          bcoefr = salfar * bscale;\n          bcoefi = 0.0;\n\n          /* scale to avoid underflow */\n          scale = 1.0;\n          lsa = fabs(sbeta) >= GSL_DBL_MIN && fabs(acoef) < small;\n          lsb = fabs(salfar) >= GSL_DBL_MIN && fabs(bcoefr) < small;\n          if (lsa)\n            scale = (small / fabs(sbeta)) * GSL_MIN(anorm, big);\n          if (lsb)\n            scale = GSL_MAX(scale, (small / fabs(salfar)) * GSL_MIN(bnorm, big));\n\n          if (lsa || lsb)\n            {\n              scale = GSL_MIN(scale,\n                        1.0 / (GSL_DBL_MIN *\n                               GSL_MAX(1.0,\n                                 GSL_MAX(fabs(acoef), fabs(bcoefr)))));\n              if (lsa)\n                acoef = ascale * (scale * sbeta);\n              else\n                acoef *= scale;\n\n              if (lsb)\n                bcoefr = bscale * (scale * salfar);\n              else\n                bcoefr *= scale;\n            }\n\n          acoefa = fabs(acoef);\n          bcoefa = fabs(bcoefr);\n\n          /* first component is 1 */\n          gsl_vector_set(w->work3, je, 1.0);\n          xmax = 1.0;\n\n          /* compute contribution from column je of A and B to sum */\n\n          for (i = 0; i < je; ++i)\n            {\n              gsl_vector_set(w->work3, i,\n                bcoefr*gsl_matrix_get(T, i, je) -\n                acoef * gsl_matrix_get(S, i, je));\n            }\n        }\n      else\n        {\n          gsl_matrix_const_view vs =\n            gsl_matrix_const_submatrix(S, je - 1, je - 1, 2, 2);\n          gsl_matrix_const_view vt =\n            gsl_matrix_const_submatrix(T, je - 1, je - 1, 2, 2);\n\n          /* complex eigenvalue */\n\n          gsl_schur_gen_eigvals(&vs.matrix,\n                                &vt.matrix,\n                                &bcoefr,\n                                &temp2,\n                                &bcoefi,\n                                &acoef,\n                                &temp);\n          if (bcoefi == 0.0)\n            {\n              GSL_ERROR(\"gsl_schur_gen_eigvals failed on complex block\", GSL_FAILURE);\n            }\n\n          /* scale to avoid over/underflow */\n          acoefa = fabs(acoef);\n          bcoefa = fabs(bcoefr) + fabs(bcoefi);\n          scale = 1.0;\n\n          if (acoefa*GSL_DBL_EPSILON < GSL_DBL_MIN && acoefa >= GSL_DBL_MIN)\n            scale = (GSL_DBL_MIN / GSL_DBL_EPSILON) / acoefa;\n          if (bcoefa*GSL_DBL_EPSILON < GSL_DBL_MIN && bcoefa >= GSL_DBL_MIN)\n            scale = GSL_MAX(scale, (GSL_DBL_MIN/GSL_DBL_EPSILON) / bcoefa);\n          if (GSL_DBL_MIN*acoefa > ascale)\n            scale = ascale / (GSL_DBL_MIN * acoefa);\n          if (GSL_DBL_MIN*bcoefa > bscale)\n            scale = GSL_MIN(scale, bscale / (GSL_DBL_MIN*bcoefa));\n          if (scale != 1.0)\n            {\n              acoef *= scale;\n              acoefa = fabs(acoef);\n              bcoefr *= scale;\n              bcoefi *= scale;\n              bcoefa = fabs(bcoefr) + fabs(bcoefi);\n            }\n\n          /* compute first two components of eigenvector */\n\n          temp = acoef * gsl_matrix_get(S, je, je - 1);\n          temp2r = acoef * gsl_matrix_get(S, je, je) -\n                   bcoefr * gsl_matrix_get(T, je, je);\n          temp2i = -bcoefi * gsl_matrix_get(T, je, je);\n\n          if (fabs(temp) >= fabs(temp2r) + fabs(temp2i))\n            {\n              gsl_vector_set(w->work3, je, 1.0);\n              gsl_vector_set(w->work4, je, 0.0);\n              gsl_vector_set(w->work3, je - 1, -temp2r / temp);\n              gsl_vector_set(w->work4, je - 1, -temp2i / temp);\n            }\n          else\n            {\n              gsl_vector_set(w->work3, je - 1, 1.0);\n              gsl_vector_set(w->work4, je - 1, 0.0);\n              temp = acoef * gsl_matrix_get(S, je - 1, je);\n              gsl_vector_set(w->work3, je,\n                (bcoefr*gsl_matrix_get(T, je - 1, je - 1) -\n                 acoef*gsl_matrix_get(S, je - 1, je - 1)) / temp);\n              gsl_vector_set(w->work4, je,\n                bcoefi*gsl_matrix_get(T, je - 1, je - 1) / temp);\n            }\n\n          xmax = GSL_MAX(fabs(gsl_vector_get(w->work3, je)) +\n                         fabs(gsl_vector_get(w->work4, je)),\n                         fabs(gsl_vector_get(w->work3, je - 1)) +\n                         fabs(gsl_vector_get(w->work4, je - 1)));\n\n          /* compute contribution from column je and je - 1 */\n\n          creala = acoef * gsl_vector_get(w->work3, je - 1);\n          cimaga = acoef * gsl_vector_get(w->work4, je - 1);\n          crealb = bcoefr * gsl_vector_get(w->work3, je - 1) -\n                   bcoefi * gsl_vector_get(w->work4, je - 1);\n          cimagb = bcoefi * gsl_vector_get(w->work3, je - 1) +\n                   bcoefr * gsl_vector_get(w->work4, je - 1);\n          cre2a = acoef * gsl_vector_get(w->work3, je);\n          cim2a = acoef * gsl_vector_get(w->work4, je);\n          cre2b = bcoefr * gsl_vector_get(w->work3, je) -\n                  bcoefi * gsl_vector_get(w->work4, je);\n          cim2b = bcoefi * gsl_vector_get(w->work3, je) +\n                  bcoefr * gsl_vector_get(w->work4, je);\n\n          for (i = 0; i < je - 1; ++i)\n            {\n              gsl_vector_set(w->work3, i,\n                -creala * gsl_matrix_get(S, i, je - 1) +\n                crealb * gsl_matrix_get(T, i, je - 1) -\n                cre2a * gsl_matrix_get(S, i, je) +\n                cre2b * gsl_matrix_get(T, i, je));\n              gsl_vector_set(w->work4, i,\n                -cimaga * gsl_matrix_get(S, i, je - 1) +\n                cimagb * gsl_matrix_get(T, i, je - 1) -\n                cim2a * gsl_matrix_get(S, i, je) +\n                cim2b * gsl_matrix_get(T, i, je));\n            }\n        }\n\n      dmin = GSL_MAX(GSL_DBL_MIN,\n               GSL_MAX(GSL_DBL_EPSILON*acoefa*anorm,\n                       GSL_DBL_EPSILON*bcoefa*bnorm));\n\n      /* triangular solve of (a A - b B) x = 0 */\n\n      il2by2 = 0;\n      for (is = (int) je - (int) nw; is >= 0; --is)\n        {\n          j = (size_t) is;\n\n          if (!il2by2 && j > 0)\n            {\n              if (gsl_matrix_get(S, j, j - 1) != 0.0)\n                {\n                  il2by2 = 1;\n                  continue;\n                }\n            }\n\n          bdiag[0] = gsl_matrix_get(T, j, j);\n          if (il2by2)\n            {\n              na = 2;\n              bdiag[1] = gsl_matrix_get(T, j + 1, j + 1);\n            }\n          else\n            na = 1;\n\n\n          if (nw == 1)\n            {\n              gsl_matrix_const_view sv =\n                gsl_matrix_const_submatrix(S, j, j, na, na);\n              gsl_vector_view xv, bv;\n\n              bv = gsl_vector_subvector(w->work3, j, na);\n\n              /*\n               * the loop below expects the solution in the first column\n               * of sum, so set stride to 2\n               */\n              xv = gsl_vector_view_array_with_stride(sum, 2, na);\n\n              gsl_schur_solve_equation(acoef,\n                                       &sv.matrix,\n                                       bcoefr,\n                                       bdiag[0],\n                                       bdiag[1],\n                                       &bv.vector,\n                                       &xv.vector,\n                                       &scale,\n                                       &temp,\n                                       dmin);\n            }\n          else\n            {\n              double bdat[4];\n              gsl_matrix_const_view sv =\n                gsl_matrix_const_submatrix(S, j, j, na, na);\n              gsl_vector_complex_view xv =\n                gsl_vector_complex_view_array(sum, na);\n              gsl_vector_complex_view bv =\n                gsl_vector_complex_view_array(bdat, na);\n              gsl_complex z;\n\n              bdat[0] = gsl_vector_get(w->work3, j);\n              bdat[1] = gsl_vector_get(w->work4, j);\n              if (na == 2)\n                {\n                  bdat[2] = gsl_vector_get(w->work3, j + 1);\n                  bdat[3] = gsl_vector_get(w->work4, j + 1);\n                }\n\n              GSL_SET_COMPLEX(&z, bcoefr, bcoefi);\n\n              gsl_schur_solve_equation_z(acoef,\n                                         &sv.matrix,\n                                         &z,\n                                         bdiag[0],\n                                         bdiag[1],\n                                         &bv.vector,\n                                         &xv.vector,\n                                         &scale,\n                                         &temp,\n                                         dmin);\n            }\n\n          if (scale < 1.0)\n            {\n              for (jr = 0; jr <= je; ++jr)\n                {\n                  gsl_vector_set(w->work3, jr,\n                    scale * gsl_vector_get(w->work3, jr));\n                  if (nw == 2)\n                    {\n                      gsl_vector_set(w->work4, jr,\n                        scale * gsl_vector_get(w->work4, jr));\n                    }\n                }\n            }\n\n          xmax = GSL_MAX(scale * xmax, temp);\n\n          for (jr = 0; jr < na; ++jr)\n            {\n              gsl_vector_set(w->work3, j + jr, sum[jr*na]);\n              if (nw == 2)\n                gsl_vector_set(w->work4, j + jr, sum[jr*na + 1]);\n            }\n\n          if (j > 0)\n            {\n              xscale = 1.0 / GSL_MAX(1.0, xmax);\n              temp = acoefa * gsl_vector_get(w->work1, j) +\n                     bcoefa * gsl_vector_get(w->work2, j);\n              if (il2by2)\n                {\n                  temp = GSL_MAX(temp,\n                           acoefa * gsl_vector_get(w->work1, j + 1) +\n                           bcoefa * gsl_vector_get(w->work2, j + 1));\n                }\n\n              temp = GSL_MAX(temp, GSL_MAX(acoefa, bcoefa));\n              if (temp > bignum * xscale)\n                {\n                  for (jr = 0; jr <= je; ++jr)\n                    {\n                      gsl_vector_set(w->work3, jr,\n                        xscale * gsl_vector_get(w->work3, jr));\n                      if (nw == 2)\n                        {\n                          gsl_vector_set(w->work4, jr,\n                            xscale * gsl_vector_get(w->work4, jr));\n                        }\n                    }\n                  xmax *= xscale;\n                }\n\n              for (ja = 0; ja < na; ++ja)\n                {\n                  if (complex_pair)\n                    {\n                      creala = acoef * gsl_vector_get(w->work3, j + ja);\n                      cimaga = acoef * gsl_vector_get(w->work4, j + ja);\n                      crealb = bcoefr * gsl_vector_get(w->work3, j + ja) -\n                               bcoefi * gsl_vector_get(w->work4, j + ja);\n                      cimagb = bcoefi * gsl_vector_get(w->work3, j + ja) +\n                               bcoefr * gsl_vector_get(w->work4, j + ja);\n                      for (jr = 0; jr <= j - 1; ++jr)\n                        {\n                          gsl_vector_set(w->work3, jr,\n                            gsl_vector_get(w->work3, jr) -\n                            creala * gsl_matrix_get(S, jr, j + ja) +\n                            crealb * gsl_matrix_get(T, jr, j + ja));\n                          gsl_vector_set(w->work4, jr,\n                            gsl_vector_get(w->work4, jr) -\n                            cimaga * gsl_matrix_get(S, jr, j + ja) +\n                            cimagb * gsl_matrix_get(T, jr, j + ja));\n                        }\n                    }\n                  else\n                    {\n                      creala = acoef * gsl_vector_get(w->work3, j + ja);\n                      crealb = bcoefr * gsl_vector_get(w->work3, j + ja);\n                      for (jr = 0; jr <= j - 1; ++jr)\n                        {\n                          gsl_vector_set(w->work3, jr,\n                            gsl_vector_get(w->work3, jr) -\n                            creala * gsl_matrix_get(S, jr, j + ja) +\n                            crealb * gsl_matrix_get(T, jr, j + ja));\n                        }\n                    } /* if (!complex_pair) */\n                } /* for (ja = 0; ja < na; ++ja) */\n            } /* if (j > 0) */\n\n          il2by2 = 0;\n        } /* for (i = 0; i < je - nw; ++i) */\n\n      for (jr = 0; jr < N; ++jr)\n        {\n          gsl_vector_set(w->work5, jr,\n            gsl_vector_get(w->work3, 0) * gsl_matrix_get(Z, jr, 0));\n          if (nw == 2)\n            {\n              gsl_vector_set(w->work6, jr,\n                gsl_vector_get(w->work4, 0) * gsl_matrix_get(Z, jr, 0));\n            }\n        }\n\n      for (jc = 1; jc <= je; ++jc)\n        {\n          for (jr = 0; jr < N; ++jr)\n            {\n              gsl_vector_set(w->work5, jr,\n                gsl_vector_get(w->work5, jr) +\n                gsl_vector_get(w->work3, jc) * gsl_matrix_get(Z, jr, jc));\n              if (nw == 2)\n                {\n                  gsl_vector_set(w->work6, jr,\n                    gsl_vector_get(w->work6, jr) +\n                    gsl_vector_get(w->work4, jc) * gsl_matrix_get(Z, jr, jc));\n                }\n            }\n        }\n\n      /* store the eigenvector */\n\n      if (complex_pair)\n        {\n          ecol = gsl_matrix_complex_column(evec, je - 1);\n          re = gsl_vector_complex_real(&ecol.vector);\n          im = gsl_vector_complex_imag(&ecol.vector);\n\n          ecol = gsl_matrix_complex_column(evec, je);\n          re2 = gsl_vector_complex_real(&ecol.vector);\n          im2 = gsl_vector_complex_imag(&ecol.vector);\n        }\n      else\n        {\n          ecol = gsl_matrix_complex_column(evec, je);\n          re = gsl_vector_complex_real(&ecol.vector);\n          im = gsl_vector_complex_imag(&ecol.vector);\n        }\n\n      for (jr = 0; jr < N; ++jr)\n        {\n          gsl_vector_set(&re.vector, jr, gsl_vector_get(w->work5, jr));\n          if (complex_pair)\n            {\n              gsl_vector_set(&im.vector, jr, gsl_vector_get(w->work6, jr));\n              gsl_vector_set(&re2.vector, jr, gsl_vector_get(w->work5, jr));\n              gsl_vector_set(&im2.vector, jr, -gsl_vector_get(w->work6, jr));\n            }\n          else\n            {\n              gsl_vector_set(&im.vector, jr, 0.0);\n            }\n        }\n\n      /* scale eigenvector */\n      xmax = 0.0;\n      if (complex_pair)\n        {\n          for (j = 0; j < N; ++j)\n            {\n              xmax = GSL_MAX(xmax,\n                             fabs(gsl_vector_get(&re.vector, j)) +\n                             fabs(gsl_vector_get(&im.vector, j)));\n            }\n        }\n      else\n        {\n          for (j = 0; j < N; ++j)\n            {\n              xmax = GSL_MAX(xmax, fabs(gsl_vector_get(&re.vector, j)));\n            }\n        }\n\n      if (xmax > GSL_DBL_MIN)\n        {\n          xscale = 1.0 / xmax;\n          for (j = 0; j < N; ++j)\n            {\n              gsl_vector_set(&re.vector, j,\n                             gsl_vector_get(&re.vector, j) * xscale);\n              if (complex_pair)\n                {\n                  gsl_vector_set(&im.vector, j,\n                                 gsl_vector_get(&im.vector, j) * xscale);\n                  gsl_vector_set(&re2.vector, j,\n                                 gsl_vector_get(&re2.vector, j) * xscale);\n                  gsl_vector_set(&im2.vector, j,\n                                 gsl_vector_get(&im2.vector, j) * xscale);\n                }\n            }\n        }\n    } /* for (k = 0; k < N; ++k) */\n\n  return GSL_SUCCESS;\n} /* genv_get_right_eigenvectors() */\n\n/*\ngenv_normalize_eigenvectors()\n  Normalize eigenvectors so that their Euclidean norm is 1\n\nInputs: alpha - eigenvalue numerators\n        evec  - eigenvectors\n*/\n\nstatic void\ngenv_normalize_eigenvectors(gsl_vector_complex *alpha,\n                            gsl_matrix_complex *evec)\n{\n  const size_t N = evec->size1;\n  size_t i;     /* looping */\n  gsl_complex ai;\n  gsl_vector_complex_view vi;\n  gsl_vector_view re, im;\n  double scale; /* scaling factor */\n\n  for (i = 0; i < N; ++i)\n    {\n      ai = gsl_vector_complex_get(alpha, i);\n      vi = gsl_matrix_complex_column(evec, i);\n\n      re = gsl_vector_complex_real(&vi.vector);\n\n      if (GSL_IMAG(ai) == 0.0)\n        {\n          scale = 1.0 / gsl_blas_dnrm2(&re.vector);\n          gsl_blas_dscal(scale, &re.vector);\n        }\n      else if (GSL_IMAG(ai) > 0.0)\n        {\n          im = gsl_vector_complex_imag(&vi.vector);\n\n          scale = 1.0 / gsl_hypot(gsl_blas_dnrm2(&re.vector),\n                                  gsl_blas_dnrm2(&im.vector));\n          gsl_blas_zdscal(scale, &vi.vector);\n\n          vi = gsl_matrix_complex_column(evec, i + 1);\n          gsl_blas_zdscal(scale, &vi.vector);\n        }\n    }\n} /* genv_normalize_eigenvectors() */\n", "meta": {"hexsha": "a309e41e531ffed361c60d19d13ca9dfda40ee42", "size": 28767, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/eigen/genv.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/eigen/genv.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/eigen/genv.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 31.06587473, "max_line_length": 87, "alphanum_fraction": 0.4838877881, "num_tokens": 7714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.35889818633148124}}
{"text": "/**\n *\n * @file core_zhetrf2_nopiv.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.4.5\n * @author Dulceneia Becker\n * @date 2011-1-18\n **/\n/*\n * @precisions normal z -> c d s\n */\n#include <lapacke.h>\n#include \"dplasma_cores.h\"\n#include \"dplasma_zcores.h\"\n\n#if defined(PARSEC_HAVE_STRING_H)\n#include <string.h>\n#endif  /* defined(PARSEC_HAVE_STRING_H) */\n#if defined(PARSEC_HAVE_STDARG_H)\n#include <stdarg.h>\n#endif  /* defined(PARSEC_HAVE_STDARG_H) */\n#include <stdio.h>\n#ifdef PARSEC_HAVE_LIMITS_H\n#include <limits.h>\n#endif\n\n#include <cblas.h>\n#include <core_blas.h>\n\n#define max(a, b) ((a) > (b) ? (a) : (b))\n#define min(a, b) ((a) < (b) ? (a) : (b))\n\nextern void CORE_zhetrf_nopiv(int uplo, int N, int ib,\n                         PLASMA_Complex64_t *A, int LDA,\n                         PLASMA_Complex64_t *WORK, int LDWORK,\n                         int *INFO);\n\nvoid CORE_zhetrf2_nopiv(PLASMA_enum uplo, int N, int ib,\n        PLASMA_Complex64_t *A, int LDA,\n        PLASMA_Complex64_t *WORK, int LWORK, int *INFO);\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex64_t\n *\n * CORE_zhetrf2_nopiv: ZHETRF_NOPIV followed by L*D\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *          \\retval <0 if -i, the i-th argument had an illegal value\n *\n ******************************************************************************/\n#if defined(PLASMA_PARSEC_HAVE_WEAK)\n#pragma weak CORE_zhetrf2_nopiv = PCORE_zhetrf2_nopiv\n#define CORE_zhetrf2_nopiv PCORE_zhetrf2_nopiv\n#endif\nvoid CORE_zhetrf2_nopiv(PLASMA_enum uplo, int N, int ib,\n        PLASMA_Complex64_t *A, int LDA,\n        PLASMA_Complex64_t *WORK, int LWORK, int *INFO)\n{\n\n    int j;\n    PLASMA_Complex64_t alpha;\n\n    /* Factorize A as L*D*L' using the lower/upper triangle of A */\n    CORE_zhetrf_nopiv(uplo, N, ib, A, LDA, WORK, LWORK, INFO);\n\n    if (uplo==PlasmaLower) {\n\n        // Multiply L by D\n        for (j=0; j<(N-1); j++) {\n            alpha = A[LDA*j+j];\n            cblas_zscal(N-j-1, CBLAS_SADDR(alpha), &A[LDA*j+j+1], 1);\n        }\n\n    } else if (uplo==PlasmaUpper) {\n\n        // Multiply U by D\n        for (j=1; j<N; j++) {\n            alpha = A[LDA*j+j];\n            cblas_zscal(j, CBLAS_SADDR(alpha), &A[LDA*j], 1);\n        }\n\n    }\n}\n\n", "meta": {"hexsha": "7df8b6f5643382a8fe8d5e3bfa3c03edf578e2f6", "size": 2516, "ext": "c", "lang": "C", "max_stars_repo_path": "dplasma/cores/core_zhetrf2_nopiv.c", "max_stars_repo_name": "NLAFET/ABFT", "max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z", "max_issues_repo_path": "dplasma/cores/core_zhetrf2_nopiv.c", "max_issues_repo_name": "NLAFET/ABFT", "max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dplasma/cores/core_zhetrf2_nopiv.c", "max_forks_repo_name": "NLAFET/ABFT", "max_forks_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0537634409, "max_line_length": 80, "alphanum_fraction": 0.5620031797, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.35864512603294924}}
{"text": "#pragma once\n\n#include <cstring>\n#include <string>\n#include <tuple>\n#include <utility>\n\n#include <gsl/assert>\n\nnamespace xmol::utils {\n\nconstexpr static int powers_of_10[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};\n\ntemplate <int LEN> inline std::pair<bool, int> parse_uint_fixed_length(const std::string& line, int pos) noexcept {\n  bool success = GSL_LIKELY(line.size() >= pos + LEN);\n  if (GSL_UNLIKELY(!success)) {\n    return {false, 0};\n  }\n  int number = 0;\n#pragma unroll\n  for (int i = 0; i < LEN; i++) {\n    unsigned digit = static_cast<unsigned>(line[pos + i]) - '0';\n    success &= digit <= 9;\n    number += digit * powers_of_10[LEN - i - 1];\n  }\n  return std::make_pair(success, number);\n};\n\ninline std::pair<bool, int> parse_uint(const std::string& line, int pos, int LEN) noexcept {\n  switch (LEN) {\n  case (1):\n    return parse_uint_fixed_length<1>(line, pos);\n  case (2):\n    return parse_uint_fixed_length<2>(line, pos);\n  case (3):\n    return parse_uint_fixed_length<3>(line, pos);\n  case (4):\n    return parse_uint_fixed_length<4>(line, pos);\n  case (5):\n    return parse_uint_fixed_length<5>(line, pos);\n  case (6):\n    return parse_uint_fixed_length<6>(line, pos);\n  case (7):\n    return parse_uint_fixed_length<7>(line, pos);\n  case (8):\n    return parse_uint_fixed_length<8>(line, pos);\n  case (9):\n    return parse_uint_fixed_length<9>(line, pos);\n  default:\n    return {false, 0};\n  }\n};\n\nenum class SpaceStrip { NONE, LEFT, RIGHT, LEFT_AND_RIGHT };\n\ntemplate <SpaceStrip stripping = SpaceStrip::NONE>\nstd::pair<bool, int> parse_int(const std::string& line, int pos, int LEN) noexcept {\n  // short-circuit for invalid\n  if (GSL_UNLIKELY(line.size() < pos + LEN)) {\n    return {false, 0};\n  }\n\n  if (stripping == SpaceStrip::RIGHT || stripping == SpaceStrip::LEFT_AND_RIGHT) {\n    while (line[pos + LEN - 1] == ' ' && LEN > 0) {\n      --LEN;\n    }\n  }\n\n  if (stripping == SpaceStrip::LEFT || stripping == SpaceStrip::LEFT_AND_RIGHT) {\n    while (line[pos] == ' ' && LEN > 0) {\n      ++pos;\n      --LEN;\n    }\n  }\n\n  if (line[pos] == '-') {\n    bool success;\n    int value;\n    std::tie(success, value) = parse_uint(line, pos + 1, LEN - 1);\n    return {success, -value};\n  } else {\n    return parse_uint(line, pos, LEN);\n  }\n};\n\ntemplate <int WIDTH, int PRECISION, SpaceStrip STRIP> struct parse_fixed_precision_fn {\n  static_assert(PRECISION >= 0);\n  static_assert(WIDTH > 0);\n  static_assert(PRECISION == 0 || WIDTH >= PRECISION + 2);\n\n  inline std::pair<bool, double> operator()(const std::string& line, int pos) const noexcept {\n\n    if (GSL_UNLIKELY(line.size() < pos + WIDTH || (PRECISION > 0 && line[pos + WIDTH - PRECISION - 1] != '.'))) {\n      return {false, 0};\n    }\n\n    int whole = WIDTH - PRECISION;\n    if (PRECISION > 0) {\n      --whole;\n    }\n    int precision = PRECISION;\n\n    if (STRIP == SpaceStrip::LEFT_AND_RIGHT || STRIP == SpaceStrip::LEFT) {\n      while (line[pos] == ' ' && whole > 0) {\n        --whole;\n        pos++;\n      }\n    }\n\n    if (STRIP == SpaceStrip::LEFT_AND_RIGHT || STRIP == SpaceStrip::RIGHT) {\n      while (line[pos + whole + precision] == ' ' && precision > 0) {\n        --precision;\n      }\n    }\n\n    int sign = 1;\n\n    if (line[pos] == '-') {\n      sign = -1;\n      ++pos;\n      --whole;\n    }\n    bool success;\n    int whole_part;\n    std::tie(success, whole_part) = parse_uint(line, pos, whole);\n\n    if (GSL_UNLIKELY(!success)) {\n      return {false, 0};\n    }\n    if (PRECISION == 0) {\n      return {true, sign * whole_part};\n    }\n    bool success2;\n    int fraction_part;\n    std::tie(success2, fraction_part) = parse_uint(line, pos + whole + 1, precision);\n    if (GSL_UNLIKELY(!success2)) {\n      return {false, 0};\n    }\n\n    return {true, sign * (whole_part + double(fraction_part) / powers_of_10[precision])};\n  };\n};\n\ninline namespace functional_objects {\nstruct parse_fixed_precision_fn___ {\n  template <int WIDTH, int PRECISION, SpaceStrip STRIP = SpaceStrip::LEFT_AND_RIGHT>\n  inline std::pair<bool, double> parse(const std::string& line, int pos) const {\n    return parse_fixed_precision_fn<WIDTH,PRECISION,STRIP>{}(line,pos);\n  }\n};\nconstexpr parse_fixed_precision_fn___ parse_fixed_precision{};\n}\n\nstd::pair<bool, double> parse_fixed_precision_rt(const std::string& line, int pos, int width) noexcept;\n}", "meta": {"hexsha": "3adb7d7711e6a9545e749e85805decf6141ed373", "size": 4329, "ext": "h", "lang": "C", "max_stars_repo_path": "include/xmol/utils/parsing.h", "max_stars_repo_name": "sizmailov/pyxmolpp2", "max_stars_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-24T11:07:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T23:00:30.000Z", "max_issues_repo_path": "include/xmol/utils/parsing.h", "max_issues_repo_name": "sizmailov/pyxmolpp2", "max_issues_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 84.0, "max_issues_repo_issues_event_min_datetime": "2018-04-22T12:29:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T15:03:37.000Z", "max_forks_repo_path": "include/xmol/utils/parsing.h", "max_forks_repo_name": "sizmailov/pyxmolpp2", "max_forks_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-04T09:16:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T11:05:54.000Z", "avg_line_length": 27.9290322581, "max_line_length": 115, "alphanum_fraction": 0.6267036267, "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3586407860623392}}
{"text": "#ifndef _COMMON_\n#define _COMMON_\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_roots.h>\n#include \"params.h\"\n//#include \"dam_utils.h\"\n#include \"cosmo_mad.h\"\n\n#define DTOR 0.01745329251\n\ntypedef struct {\n  gsl_interp_accel *intacc;\n  gsl_spline *spline;\n  double x0,xf;\n  double y0,yf;\n} SplPar;\n\ntypedef struct {\n  double om,ol,ob;\n  double w0,wa,h0;\n  double ns,s8;\n  char **fname_window;\n  char fname_bias[256];\n  char fname_sbias[256];\n  char fname_pk[256];\n  char prefix_out[256];\n  int lmax;\n  Csm_params *cpar;\n  double chi_horizon;\n  double chi_LSS;\n  double prefac_lensing;\n  double dchi;\n  int do_nc;\n  int do_shear;\n  int do_cmblens;\n  int do_isw;\n  int has_bg;\n  int has_dens;\n  int has_rsd;\n  int has_lensing;\n  SplPar *aofchi;\n  SplPar *zofchi;\n  SplPar *hofchi;\n  SplPar *gfofchi;\n  SplPar *fgofchi;\n  SplPar **wind_0;\n  SplPar **wind_M;\n  SplPar **wind_L;\n  SplPar *bias;\n  SplPar *sbias;\n  double *cl_dd;\n  double *cl_d1l2;\n  double *cl_d2l1;\n  double *cl_dc;\n  double *cl_di;\n  double *cl_ll;\n  double *cl_lc;\n  double *cl_li;\n  double *cl_cc;\n  double *cl_ci;\n  double *cl_ii;\n  int do_w_theta;\n  int do_w_theta_logbin;\n  double th_min;\n  double th_max;\n  int n_th;\n  int n_th_logint;\n  double *wt_dd;\n  double *wt_d1l2;\n  double *wt_d2l1;\n  double *wt_dc;\n  double *wt_di;\n  double *wt_ll_pp;\n  double *wt_ll_mm;\n  double *wt_lc;\n  double *wt_li;\n  double *wt_cc;\n  double *wt_ci;\n  double *wt_ii;\n} RunParams;\n\n//Defined in common.c\nvoid dam_report_error(int level,char *fmt,...);\nvoid *dam_malloc(size_t size);\nvoid *dam_calloc(size_t nmemb,size_t size);\nFILE *dam_fopen(const char *path,const char *mode);\nint dam_linecount(FILE *f);\nSplPar *spline_init(int n,double *x,double *y,double y0,double yf);\ndouble spline_eval(double x,SplPar *spl);\nvoid spline_free(SplPar *spl);\nRunParams *param_new(void);\nvoid param_free(RunParams *par);\n\n//Defined in cosmo.c\nRunParams *init_params(char *fname_ini);\n\n//Defined in transfers.c\ndouble transfer_wrap(int l,double k,RunParams *par,char *trtype,int ibin);\n\n//Defined in spectra.c\nvoid compute_spectra(RunParams *par);\nvoid compute_w_theta(RunParams *par);\n\n//Defined in io.c\nint read_parameter_file(char *fname,RunParams *par);\nvoid write_output(RunParams *par);\n\n#endif //_COMMON_\n", "meta": {"hexsha": "405a29ad7fff5f172fbea368d9499f6f41d333eb", "size": 2326, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/data/codes/cl_corr_bm/src/common.h", "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_issues_repo_path": "benchmarks/data/codes/cl_corr_bm/src/common.h", "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 703.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_forks_repo_path": "benchmarks/data/codes/cl_corr_bm/src/common.h", "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "avg_line_length": 20.4035087719, "max_line_length": 74, "alphanum_fraction": 0.7158211522, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3585038770114118}}
{"text": "#include \"../globals.h\"\n#include <gsl/gsl_sort.h>\n#include <gsl/gsl_sort_vector.h>\n#include <gsl/gsl_vector.h>\n\n\nvoid setup_Sedov_Blast()\n{\n    Problem.Boxsize[0] = 3;\n    Problem.Boxsize[1] = 3;\n    Problem.Boxsize[2] = 3;\n\n    sprintf ( Problem.Name, \"IC_SedovBlast\" );\n\n    const double rho = 1.24E7;\n\n    Problem.Rho_Max = rho;\n\n    Density_Func_Ptr = &Sedov_Blast_Density;\n    U_Func_Ptr = &Sedov_Blast_U;\n    PostProcessing_Func_Ptr = &Sedov_Blast_PostProcessing;\n}\n\nfloat Sedov_Blast_Density ( const int ipart , const double bias )\n{\n    return 1.24E7;\n}\n\n// This function calculates the distance from each particle to the center of the Box. It returns the distance to the NNpart times furthest neighbour of zero.\n\nfloat Sedov_Blast_abs ()\n{\n\n    int NNpart = 296;\n\n    gsl_vector *abs_of_zero = gsl_vector_alloc ( Param.Npart );\n\n    for ( int i = 0; i < Param.Npart; i++ ) {\n\n        double r = sqrt ( ( P[i].Pos[0] - 0.5 * Problem.Boxsize[0] ) * ( P[i].Pos[0] - 0.5 * Problem.Boxsize[0] ) + ( P[i].Pos[1] * 0.5 * Problem.Boxsize[1] ) * ( P[i].Pos[1] - 0.5 * Problem.Boxsize[1] )\n                          + ( P[i].Pos[2] - 0.5 * Problem.Boxsize[2] ) * ( P[i].Pos[2] - 0.5 * Problem.Boxsize[2] ) );\n        gsl_vector_set ( abs_of_zero, i, r );\n    }\n\n    gsl_sort_vector ( abs_of_zero );\n\n    double dist = gsl_vector_get ( abs_of_zero, NNpart - 1 );\n\n    gsl_vector_free ( abs_of_zero );\n\n    return dist;\n\n}\n\n#ifdef KINETIC_SEDOV\nfloat Sedov_Blast_kinetic ()\n{\n\n    int NNpart = 32;\n    Radius =\n        double partpos[3][32];\n\n    float maxDistance = Sedov_Blast_abs ();\n\n    if ( Radius <= maxDistance ) {\n\n        for ( int i =; i < 3; i++ ) {\n\n            for ( int j = 0; j < NNpart, j++ ) {\n\n                double pos = P[i].Pos[j];\n                partpos[i][j] = pos;\n\n            }\n\n        }\n\n    }\n\n}\n#endif // KINETIC_SEDOV\n\n\nfloat Sedov_Blast_U ( const int ipart )\n{\n    return 0.0;\n}\n\n\n//! @todo improvement: use gsl_sort_vector_index\nvoid Sedov_Blast_PostProcessing ()\n{\n    /*const double u_sn = 4.18971E5;\n    int sn_count = pow ( Param.Npart / 3200., 3.0 );\n    sn_count = min ( sn_count, 1 );\n    //! @todo assign u_sn to sn_count innermost particles*/\n\n    float maxDistance = Sedov_Blast_abs ();\n\n    for ( int ipart = 0; ipart < Param.Npart; ++ipart ) {\n\n\n        const double x = P[ipart].Pos[0] - Problem.Boxsize[0] * 0.5;\n        const double y = P[ipart].Pos[1] - Problem.Boxsize[1] * 0.5;\n        const double z = P[ipart].Pos[2] - Problem.Boxsize[2] * 0.5;\n        double Radius = sqrt ( x * x + y * y + z * z );\n        // int NNpart = 32;\n        const double  Supernova_Energy = 0.00502765; // This is the value of one supernova energy per unit mass in Gadget units 1e51 erg\n        // const double hsml = SphP[i].Hsml;\n\n        if ( Radius <=  maxDistance ) {\n            SphP[ipart].U = Supernova_Energy;\n        }\n    }\n\n}\n", "meta": {"hexsha": "e30f533034b1c729a1122ab1707d5fc3787754e9", "size": 2870, "ext": "c", "lang": "C", "max_stars_repo_path": "src/problems/sedov.c", "max_stars_repo_name": "elehcim/WVTICs", "max_stars_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-07-29T04:44:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:18:47.000Z", "max_issues_repo_path": "src/problems/sedov.c", "max_issues_repo_name": "elehcim/WVTICs", "max_issues_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-23T12:22:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-23T12:22:14.000Z", "max_forks_repo_path": "src/problems/sedov.c", "max_forks_repo_name": "elehcim/WVTICs", "max_forks_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-29T09:38:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:31:56.000Z", "avg_line_length": 24.5299145299, "max_line_length": 203, "alphanum_fraction": 0.5905923345, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.358300873238078}}
{"text": "// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at\n// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights\n// reserved. See files LICENSE and NOTICE for details.\n//\n// This file is part of CEED, a collection of benchmarks, miniapps, software\n// libraries and APIs for efficient high-order finite element and spectral\n// element discretizations for exascale applications. For more information and\n// source code availability see http://github.com/ceed.\n//\n// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,\n// a collaborative effort of two U.S. Department of Energy organizations (Office\n// of Science and the National Nuclear Security Administration) responsible for\n// the planning and preparation of a capable exascale ecosystem, including\n// software, applications, hardware, advanced system engineering and early\n// testbed platforms, in support of the nation's exascale computing imperative.\n\n//                        libCEED + PETSc Example: CEED BPs\n//\n// This example demonstrates a simple usage of libCEED with PETSc to solve the\n// CEED BP benchmark problems, see http://ceed.exascaleproject.org/bps,\n// on a closed surface, such as the one of a discrete sphere.\n//\n// The code uses higher level communication protocols in DMPlex.\n//\n// Build with:\n//\n//     make bpssphere [PETSC_DIR=</path/to/petsc>] [CEED_DIR=</path/to/libceed>]\n//\n// Sample runs:\n//\n//     bpssphere -problem bp1 -degree 3\n//     bpssphere -problem bp2 -degree 3\n//     bpssphere -problem bp3 -degree 3\n//     bpssphere -problem bp4 -degree 3\n//     bpssphere -problem bp5 -degree 3 -ceed /cpu/self\n//     bpssphere -problem bp6 -degree 3 -ceed /gpu/cuda\n//\n//TESTARGS -ceed {ceed_resource} -test -problem bp3 -degree 3 -dm_refine 2\n\n/// @file\n/// CEED BPs example using PETSc with DMPlex\n/// See bps.c for a \"raw\" implementation using a structured grid.\n/// and bpsdmplex.c for an implementation using an unstructured grid.\nstatic const char help[] = \"Solve CEED BPs on a sphere using DMPlex in PETSc\\n\";\n\n#include <stdbool.h>\n#include <string.h>\n#include <ceed.h>\n#include <petsc.h>\n#include <petscdmplex.h>\n#include <petscksp.h>\n\n#include \"bpssphere.h\"\n#include \"include/sphereproblemdata.h\"\n#include \"include/petscutils.h\"\n#include \"include/petscversion.h\"\n#include \"include/matops.h\"\n#include \"include/libceedsetup.h\"\n\n\n#if PETSC_VERSION_LT(3,12,0)\n#ifdef PETSC_HAVE_CUDA\n#include <petsccuda.h>\n// Note: With PETSc prior to version 3.12.0, providing the source path to\n//       include 'cublas_v2.h' will be needed to use 'petsccuda.h'.\n#endif\n#endif\n\nint main(int argc, char **argv) {\n  PetscInt ierr;\n  MPI_Comm comm;\n  char ceed_resource[PETSC_MAX_PATH_LEN] = \"/cpu/self\",\n      filename[PETSC_MAX_PATH_LEN];\n  double my_rt_start, my_rt, rt_min, rt_max;\n  PetscInt degree = 3, q_extra, l_size, g_size, topo_dim = 2, num_comp_x = 3,\n           num_comp_u = 1, xl_size;\n  PetscScalar *r;\n  PetscBool test_mode, benchmark_mode, read_mesh, write_solution, simplex;\n  PetscLogStage solve_stage;\n  Vec X, X_loc, rhs, rhs_loc;\n  Mat mat_O;\n  KSP ksp;\n  DM  dm;\n  UserO user_O;\n  Ceed ceed;\n  CeedData ceed_data;\n  CeedQFunction qf_error;\n  CeedOperator op_error;\n  CeedVector rhs_ceed, target;\n  BPType bp_choice;\n  VecType vec_type;\n  PetscMemType mem_type;\n\n  ierr = PetscInitialize(&argc, &argv, NULL, help);\n  if (ierr) return ierr;\n  comm = PETSC_COMM_WORLD;\n\n  // Read command line options\n  ierr = PetscOptionsBegin(comm, NULL, \"CEED BPs in PETSc\", NULL); CHKERRQ(ierr);\n  bp_choice = CEED_BP1;\n  ierr = PetscOptionsEnum(\"-problem\",\n                          \"CEED benchmark problem to solve\", NULL,\n                          bp_types, (PetscEnum)bp_choice, (PetscEnum *)&bp_choice,\n                          NULL); CHKERRQ(ierr);\n  num_comp_u = bp_options[bp_choice].num_comp_u;\n  test_mode = PETSC_FALSE;\n  ierr = PetscOptionsBool(\"-test\",\n                          \"Testing mode (do not print unless error is large)\",\n                          NULL, test_mode, &test_mode, NULL); CHKERRQ(ierr);\n  benchmark_mode = PETSC_FALSE;\n  ierr = PetscOptionsBool(\"-benchmark\",\n                          \"Benchmarking mode (prints benchmark statistics)\",\n                          NULL, benchmark_mode, &benchmark_mode, NULL);\n  CHKERRQ(ierr);\n  write_solution = PETSC_FALSE;\n  ierr = PetscOptionsBool(\"-write_solution\",\n                          \"Write solution for visualization\",\n                          NULL, write_solution, &write_solution, NULL);\n  CHKERRQ(ierr);\n  degree = test_mode ? 3 : 2;\n  ierr = PetscOptionsInt(\"-degree\", \"Polynomial degree of tensor product basis\",\n                         NULL, degree, &degree, NULL); CHKERRQ(ierr);\n  q_extra = bp_options[bp_choice].q_extra;\n  ierr = PetscOptionsInt(\"-q_extra\", \"Number of extra quadrature points\",\n                         NULL, q_extra, &q_extra, NULL); CHKERRQ(ierr);\n  ierr = PetscOptionsString(\"-ceed\", \"CEED resource specifier\",\n                            NULL, ceed_resource, ceed_resource,\n                            sizeof(ceed_resource), NULL); CHKERRQ(ierr);\n  read_mesh = PETSC_FALSE;\n  ierr = PetscOptionsString(\"-mesh\", \"Read mesh from file\", NULL,\n                            filename, filename, sizeof(filename), &read_mesh);\n  CHKERRQ(ierr);\n  simplex = PETSC_FALSE;\n  ierr = PetscOptionsBool(\"-simplex\", \"Use simplices, or tensor product cells\",\n                          NULL, simplex, &simplex, NULL); CHKERRQ(ierr);\n  ierr = PetscOptionsEnd(); CHKERRQ(ierr);\n\n  // Setup DM\n  if (read_mesh) {\n    ierr = DMPlexCreateFromFile(PETSC_COMM_WORLD, filename, NULL, PETSC_TRUE,\n                                &dm);\n    CHKERRQ(ierr);\n  } else {\n    // Create the mesh as a 0-refined sphere. This will create a cubic surface, not a box\n    ierr = DMPlexCreateSphereMesh(PETSC_COMM_WORLD, topo_dim, simplex, 1., &dm);\n    CHKERRQ(ierr);\n    // Set the object name\n    ierr = PetscObjectSetName((PetscObject)dm, \"Sphere\"); CHKERRQ(ierr);\n    // Distribute mesh over processes\n    {\n      DM dm_dist = NULL;\n      PetscPartitioner part;\n\n      ierr = DMPlexGetPartitioner(dm, &part); CHKERRQ(ierr);\n      ierr = PetscPartitionerSetFromOptions(part); CHKERRQ(ierr);\n      ierr = DMPlexDistribute(dm, 0, NULL, &dm_dist); CHKERRQ(ierr);\n      if (dm_dist) {\n        ierr = DMDestroy(&dm); CHKERRQ(ierr);\n        dm  = dm_dist;\n      }\n    }\n    // Refine DMPlex with uniform refinement using runtime option -dm_refine\n    ierr = DMPlexSetRefinementUniform(dm, PETSC_TRUE); CHKERRQ(ierr);\n    ierr = DMSetFromOptions(dm); CHKERRQ(ierr);\n    ierr = ProjectToUnitSphere(dm); CHKERRQ(ierr);\n    // View DMPlex via runtime option\n    ierr = DMViewFromOptions(dm, NULL, \"-dm_view\"); CHKERRQ(ierr);\n  }\n\n  // Create DM\n  ierr = SetupDMByDegree(dm, degree, num_comp_u, topo_dim, false,\n                         (BCFunction)NULL);\n  CHKERRQ(ierr);\n\n  // Create vectors\n  ierr = DMCreateGlobalVector(dm, &X); CHKERRQ(ierr);\n  ierr = VecGetLocalSize(X, &l_size); CHKERRQ(ierr);\n  ierr = VecGetSize(X, &g_size); CHKERRQ(ierr);\n  ierr = DMCreateLocalVector(dm, &X_loc); CHKERRQ(ierr);\n  ierr = VecGetSize(X_loc, &xl_size); CHKERRQ(ierr);\n  ierr = VecDuplicate(X, &rhs); CHKERRQ(ierr);\n\n  // Operator\n  ierr = PetscMalloc1(1, &user_O); CHKERRQ(ierr);\n  ierr = MatCreateShell(comm, l_size, l_size, g_size, g_size,\n                        user_O, &mat_O); CHKERRQ(ierr);\n  ierr = MatShellSetOperation(mat_O, MATOP_MULT,\n                              (void(*)(void))MatMult_Ceed); CHKERRQ(ierr);\n\n  // Set up libCEED\n  CeedInit(ceed_resource, &ceed);\n  CeedMemType mem_type_backend;\n  CeedGetPreferredMemType(ceed, &mem_type_backend);\n\n  ierr = DMGetVecType(dm, &vec_type); CHKERRQ(ierr);\n  if (!vec_type) { // Not yet set by user -dm_vec_type\n    switch (mem_type_backend) {\n    case CEED_MEM_HOST: vec_type = VECSTANDARD; break;\n    case CEED_MEM_DEVICE: {\n      const char *resolved;\n      CeedGetResource(ceed, &resolved);\n      if (strstr(resolved, \"/gpu/cuda\")) vec_type = VECCUDA;\n      else if (strstr(resolved, \"/gpu/hip/occa\"))\n        vec_type = VECSTANDARD; // https://github.com/CEED/libCEED/issues/678\n      else if (strstr(resolved, \"/gpu/hip\")) vec_type = VECHIP;\n      else vec_type = VECSTANDARD;\n    }\n    }\n    ierr = DMSetVecType(dm, vec_type); CHKERRQ(ierr);\n  }\n\n  // Print summary\n  if (!test_mode) {\n    PetscInt P = degree + 1, Q = P + q_extra;\n    const char *used_resource;\n    CeedGetResource(ceed, &used_resource);\n    ierr = PetscPrintf(comm,\n                       \"\\n-- CEED Benchmark Problem %d on the Sphere -- libCEED + PETSc --\\n\"\n                       \"  libCEED:\\n\"\n                       \"    libCEED Backend                    : %s\\n\"\n                       \"    libCEED Backend MemType            : %s\\n\"\n                       \"  Mesh:\\n\"\n                       \"    Number of 1D Basis Nodes (p)       : %d\\n\"\n                       \"    Number of 1D Quadrature Points (q) : %d\\n\"\n                       \"    Global nodes                       : %D\\n\",\n                       bp_choice+1, ceed_resource, CeedMemTypes[mem_type_backend], P, Q,\n                       g_size/num_comp_u); CHKERRQ(ierr);\n  }\n\n  // Create RHS vector\n  ierr = VecDuplicate(X_loc, &rhs_loc); CHKERRQ(ierr);\n  ierr = VecZeroEntries(rhs_loc); CHKERRQ(ierr);\n  ierr = VecGetArrayAndMemType(rhs_loc, &r, &mem_type); CHKERRQ(ierr);\n  CeedVectorCreate(ceed, xl_size, &rhs_ceed);\n  CeedVectorSetArray(rhs_ceed, MemTypeP2C(mem_type), CEED_USE_POINTER, r);\n\n  // Setup libCEED's objects\n  ierr = PetscMalloc1(1, &ceed_data); CHKERRQ(ierr);\n  ierr = SetupLibceedByDegree(dm, ceed, degree, topo_dim, q_extra, num_comp_x,\n                              num_comp_u, g_size, xl_size, bp_options[bp_choice],\n                              ceed_data, true, rhs_ceed, &target); CHKERRQ(ierr);\n\n  // Gather RHS\n  CeedVectorTakeArray(rhs_ceed, MemTypeP2C(mem_type), NULL);\n  ierr = VecRestoreArrayAndMemType(rhs_loc, &r); CHKERRQ(ierr);\n  ierr = VecZeroEntries(rhs); CHKERRQ(ierr);\n  ierr = DMLocalToGlobal(dm, rhs_loc, ADD_VALUES, rhs); CHKERRQ(ierr);\n  CeedVectorDestroy(&rhs_ceed);\n\n  // Create the error Q-function\n  CeedQFunctionCreateInterior(ceed, 1, bp_options[bp_choice].error,\n                              bp_options[bp_choice].error_loc, &qf_error);\n  CeedQFunctionAddInput(qf_error, \"u\", num_comp_u, CEED_EVAL_INTERP);\n  CeedQFunctionAddInput(qf_error, \"true_soln\", num_comp_u, CEED_EVAL_NONE);\n  CeedQFunctionAddOutput(qf_error, \"error\", num_comp_u, CEED_EVAL_NONE);\n\n  // Create the error operator\n  CeedOperatorCreate(ceed, qf_error, NULL, NULL, &op_error);\n  CeedOperatorSetField(op_error, \"u\", ceed_data->elem_restr_u,\n                       ceed_data->basis_u, CEED_VECTOR_ACTIVE);\n  CeedOperatorSetField(op_error, \"true_soln\", ceed_data->elem_restr_u_i,\n                       CEED_BASIS_COLLOCATED, target);\n  CeedOperatorSetField(op_error, \"error\", ceed_data->elem_restr_u_i,\n                       CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);\n\n  // Set up Mat\n  user_O->comm = comm;\n  user_O->dm = dm;\n  user_O->X_loc = X_loc;\n  ierr = VecDuplicate(X_loc, &user_O->Y_loc); CHKERRQ(ierr);\n  user_O->x_ceed = ceed_data->x_ceed;\n  user_O->y_ceed = ceed_data->y_ceed;\n  user_O->op = ceed_data->op_apply;\n  user_O->ceed = ceed;\n\n  // Setup solver\n  ierr = KSPCreate(comm, &ksp); CHKERRQ(ierr);\n  {\n    PC pc;\n    ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr);\n    if (bp_choice == CEED_BP1 || bp_choice == CEED_BP2) {\n      ierr = PCSetType(pc, PCJACOBI); CHKERRQ(ierr);\n      ierr = PCJacobiSetType(pc, PC_JACOBI_ROWSUM); CHKERRQ(ierr);\n    } else {\n      ierr = PCSetType(pc, PCNONE); CHKERRQ(ierr);\n      MatNullSpace nullspace;\n\n      ierr = MatNullSpaceCreate(PETSC_COMM_WORLD, PETSC_TRUE, 0, 0, &nullspace);\n      CHKERRQ(ierr);\n      ierr = MatSetNullSpace(mat_O, nullspace); CHKERRQ(ierr);\n      ierr = MatNullSpaceDestroy(&nullspace); CHKERRQ(ierr);\n    }\n    ierr = KSPSetType(ksp, KSPCG); CHKERRQ(ierr);\n    ierr = KSPSetNormType(ksp, KSP_NORM_NATURAL); CHKERRQ(ierr);\n    ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,\n                            PETSC_DEFAULT); CHKERRQ(ierr);\n  }\n  ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);\n  ierr = KSPSetOperators(ksp, mat_O, mat_O); CHKERRQ(ierr);\n\n  // First run, if benchmarking\n  if (benchmark_mode) {\n    ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 1);\n    CHKERRQ(ierr);\n    my_rt_start = MPI_Wtime();\n    ierr = KSPSolve(ksp, rhs, X); CHKERRQ(ierr);\n    my_rt = MPI_Wtime() - my_rt_start;\n    ierr = MPI_Allreduce(MPI_IN_PLACE, &my_rt, 1, MPI_DOUBLE, MPI_MIN, comm);\n    CHKERRQ(ierr);\n    // Set maxits based on first iteration timing\n    if (my_rt > 0.02) {\n      ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 5);\n      CHKERRQ(ierr);\n    } else {\n      ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 20);\n      CHKERRQ(ierr);\n    }\n  }\n\n  // Timed solve\n  ierr = VecZeroEntries(X); CHKERRQ(ierr);\n  ierr = PetscBarrier((PetscObject)ksp); CHKERRQ(ierr);\n\n  // -- Performance logging\n  ierr = PetscLogStageRegister(\"Solve Stage\", &solve_stage); CHKERRQ(ierr);\n  ierr = PetscLogStagePush(solve_stage); CHKERRQ(ierr);\n\n  // -- Solve\n  my_rt_start = MPI_Wtime();\n  ierr = KSPSolve(ksp, rhs, X); CHKERRQ(ierr);\n  my_rt = MPI_Wtime() - my_rt_start;\n\n  // -- Performance logging\n  ierr = PetscLogStagePop();\n\n  // Output results\n  {\n    KSPType ksp_type;\n    KSPConvergedReason reason;\n    PetscReal rnorm;\n    PetscInt its;\n    ierr = KSPGetType(ksp, &ksp_type); CHKERRQ(ierr);\n    ierr = KSPGetConvergedReason(ksp, &reason); CHKERRQ(ierr);\n    ierr = KSPGetIterationNumber(ksp, &its); CHKERRQ(ierr);\n    ierr = KSPGetResidualNorm(ksp, &rnorm); CHKERRQ(ierr);\n    if (!test_mode || reason < 0 || rnorm > 1e-8) {\n      ierr = PetscPrintf(comm,\n                         \"  KSP:\\n\"\n                         \"    KSP Type                           : %s\\n\"\n                         \"    KSP Convergence                    : %s\\n\"\n                         \"    Total KSP Iterations               : %D\\n\"\n                         \"    Final rnorm                        : %e\\n\",\n                         ksp_type, KSPConvergedReasons[reason], its,\n                         (double)rnorm); CHKERRQ(ierr);\n    }\n    if (!test_mode) {\n      ierr = PetscPrintf(comm,\"  Performance:\\n\"); CHKERRQ(ierr);\n    }\n    {\n      PetscReal max_error;\n      ierr = ComputeErrorMax(user_O, op_error, X, target, &max_error);\n      CHKERRQ(ierr);\n      PetscReal tol = 5e-4;\n      if (!test_mode || max_error > tol) {\n        ierr = MPI_Allreduce(&my_rt, &rt_min, 1, MPI_DOUBLE, MPI_MIN, comm);\n        CHKERRQ(ierr);\n        ierr = MPI_Allreduce(&my_rt, &rt_max, 1, MPI_DOUBLE, MPI_MAX, comm);\n        CHKERRQ(ierr);\n        ierr = PetscPrintf(comm,\n                           \"    Pointwise Error (max)              : %e\\n\"\n                           \"    CG Solve Time                      : %g (%g) sec\\n\",\n                           (double)max_error, rt_max, rt_min); CHKERRQ(ierr);\n      }\n    }\n    if (benchmark_mode && (!test_mode)) {\n      ierr = PetscPrintf(comm,\n                         \"    DoFs/Sec in CG                     : %g (%g) million\\n\",\n                         1e-6*g_size*its/rt_max, 1e-6*g_size*its/rt_min); CHKERRQ(ierr);\n    }\n  }\n\n  // Output solution\n  if (write_solution) {\n    PetscViewer vtk_viewer_soln;\n\n    ierr = PetscViewerCreate(comm, &vtk_viewer_soln); CHKERRQ(ierr);\n    ierr = PetscViewerSetType(vtk_viewer_soln, PETSCVIEWERVTK); CHKERRQ(ierr);\n    ierr = PetscViewerFileSetName(vtk_viewer_soln, \"solution.vtu\"); CHKERRQ(ierr);\n    ierr = VecView(X, vtk_viewer_soln); CHKERRQ(ierr);\n    ierr = PetscViewerDestroy(&vtk_viewer_soln); CHKERRQ(ierr);\n  }\n\n  // Cleanup\n  ierr = VecDestroy(&X); CHKERRQ(ierr);\n  ierr = VecDestroy(&X_loc); CHKERRQ(ierr);\n  ierr = VecDestroy(&user_O->Y_loc); CHKERRQ(ierr);\n  ierr = MatDestroy(&mat_O); CHKERRQ(ierr);\n  ierr = PetscFree(user_O); CHKERRQ(ierr);\n  ierr = CeedDataDestroy(0, ceed_data); CHKERRQ(ierr);\n  ierr = DMDestroy(&dm); CHKERRQ(ierr);\n\n  ierr = VecDestroy(&rhs); CHKERRQ(ierr);\n  ierr = VecDestroy(&rhs_loc); CHKERRQ(ierr);\n  ierr = KSPDestroy(&ksp); CHKERRQ(ierr);\n  CeedVectorDestroy(&target);\n  CeedQFunctionDestroy(&qf_error);\n  CeedOperatorDestroy(&op_error);\n  CeedDestroy(&ceed);\n  return PetscFinalize();\n}\n", "meta": {"hexsha": "60e49520c16ec51ed199fac99726c9b1256d76e1", "size": 16354, "ext": "c", "lang": "C", "max_stars_repo_path": "examples/petsc/bpssphere.c", "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/petsc/bpssphere.c", "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_issues_repo_licenses": ["BSD-2-Clause"], "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/petsc/bpssphere.c", "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "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.7907542579, "max_line_length": 93, "alphanum_fraction": 0.6367249603, "num_tokens": 4477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786991753929, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.35814215040262515}}
{"text": "/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it>\n\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n * \n */\n/*\n * \n *\n *       Filename:  initial.h\n *\n *    Description:  Initial values\n *\n *        Version:  1.0\n *        Created:  16/05/2014 00:44:34\n *       Revision:  none\n *        License:  BSD\n *\n *         Author:  Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it\n *   Organization:  Universit\u00e0 degli Studi di Trieste\n *\n * \n */\n\n#include <gsl/gsl_const_mksa.h>\n\n#define\tBOLTZ\tGSL_CONST_MKSA_BOLTZMANN\t/* Boltzmann constant  */\n#define HBAR\tGSL_CONST_MKSA_PLANCKS_CONSTANT_HBAR /* hbar */\n\nconst double omega_c = 1000 ;\t\t\t/* critical ohmic frequency */\nconst double alpha = 5e-3 ;\t\t\t/* coupling strength */\nconst double Delta = 8.0e+9 ;\t\t\t/* pumping amplitude (GHz) */\n\ndouble T = .1 ;\t\t\t\t/* \n\t\t\t\t\t\t *  The real temperature is given by\n\t\t\t\t\t\t *  temp = T*HBAR*Delta/BOLTZ\n\t\t\t\t\t\t *\n\t\t\t\t\t\t *  HBAR*Delta/BOLTZ = 0.061\n\t\t\t\t\t\t *\n\t\t\t\t\t\t */\n\t\t\t\t\nconst double D = 1 ;                            /* normalized delta */\ndouble OMEGA = 2 ;\t\t\t\t/* normalized pumping frequency */\n\nconst double gamma0 = 0.05 ;\t\t\t/* energy hopping between sites */\n\t\nconst double t_end = 200 ;\t\t\t/* time end */\nconst double STEP = .01 ;\t\t\t/* time step */\n\nconst double R[] = { 1, 0, 0.5, -0.4 } ;   /* initial state: |z,-> */\n \n\n/* const double R[] = { 1, 0, 0.5, -0.4 } ; */ /* initial state with neg. e.p. */\n/* const double r[] = { 1, 0, 1, 0 } ;  \t initial state with pos. t.d. */\n\n", "meta": {"hexsha": "d248cb3ee03b45b7c141d794e3d3c5613dd5fefc", "size": 2778, "ext": "h", "lang": "C", "max_stars_repo_path": "initial.h", "max_stars_repo_name": "j-silver/quantum_dots", "max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "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": "initial.h", "max_issues_repo_name": "j-silver/quantum_dots", "max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "initial.h", "max_forks_repo_name": "j-silver/quantum_dots", "max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0779220779, "max_line_length": 81, "alphanum_fraction": 0.6688264939, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3581237352495997}}
{"text": "// @(#)root/matrix:$Id$\n// Authors: Fons Rademakers, Eddy Offermann   Feb 2004\n\n/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS/LICENSE.                         *\n * For the list of contributors see $ROOTSYS/README/CREDITS.             *\n *************************************************************************/\n\n#ifndef ROOT_TMatrixTSparse\n#define ROOT_TMatrixTSparse\n\n#include \"TMatrixTBase.h\"\n#include \"TMatrixTUtils.h\"\n\n\n#ifdef CBLAS\n#include <vecLib/vBLAS.h>\n//#include <cblas.h>\n#endif\n\n//////////////////////////////////////////////////////////////////////////\n//                                                                      //\n// TMatrixTSparse                                                       //\n//                                                                      //\n// Template class of a general sparse matrix in the Harwell-Boeing      //\n// format                                                               //\n//                                                                      //\n//////////////////////////////////////////////////////////////////////////\n\ntemplate<class Element> class TMatrixT;\n\ntemplate<class Element> class TMatrixTSparse : public TMatrixTBase<Element> {\n\nprotected:\n\n   Int_t   *fRowIndex;  //[fNrowIndex] row index\n   Int_t   *fColIndex;  //[fNelems]    column index\n   Element *fElements;  //[fNelems]\n\n   void Allocate(Int_t nrows,Int_t ncols,Int_t row_lwb = 0,Int_t col_lwb = 0,\n                 Int_t init = 0,Int_t nr_nonzeros = 0);\n\n  // Elementary constructors\n   void AMultB (const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0) {\n                const TMatrixTSparse<Element> bt(TMatrixTSparse::kTransposed,b); AMultBt(a,bt,constr); }\n   void AMultB (const TMatrixTSparse<Element> &a,const TMatrixT<Element>       &b,Int_t constr=0) {\n                const TMatrixTSparse<Element> bsp = b;\n                const TMatrixTSparse<Element> bt(TMatrixTSparse::kTransposed,bsp); AMultBt(a,bt,constr); }\n   void AMultB (const TMatrixT<Element>       &a,const TMatrixTSparse<Element> &b,Int_t constr=0) {\n                const TMatrixTSparse<Element> bt(TMatrixTSparse::kTransposed,b); AMultBt(a,bt,constr); }\n\n   void AMultBt(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);\n   void AMultBt(const TMatrixTSparse<Element> &a,const TMatrixT<Element>       &b,Int_t constr=0);\n   void AMultBt(const TMatrixT<Element>       &a,const TMatrixTSparse<Element> &b,Int_t constr=0);\n\n   void APlusB (const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);\n   void APlusB (const TMatrixTSparse<Element> &a,const TMatrixT<Element>       &b,Int_t constr=0);\n   void APlusB (const TMatrixT<Element>       &a,const TMatrixTSparse<Element> &b,Int_t constr=0) { APlusB(b,a,constr); }\n\n   void AMinusB(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);\n   void AMinusB(const TMatrixTSparse<Element> &a,const TMatrixT<Element>       &b,Int_t constr=0);\n   void AMinusB(const TMatrixT<Element>       &a,const TMatrixTSparse<Element> &b,Int_t constr=0);\n\npublic:\n\n   enum EMatrixCreatorsOp1 { kZero,kUnit,kTransposed,kAtA };\n   enum EMatrixCreatorsOp2 { kMult,kMultTranspose,kPlus,kMinus };\n\n   TMatrixTSparse() { fElements = 0; fRowIndex = 0; fColIndex = 0; }\n   TMatrixTSparse(Int_t nrows,Int_t ncols);\n   TMatrixTSparse(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb);\n   TMatrixTSparse(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros,\n                  Int_t *row, Int_t *col,Element *data);\n   TMatrixTSparse(const TMatrixTSparse<Element> &another);\n   TMatrixTSparse(const TMatrixT<Element>       &another);\n\n   TMatrixTSparse(EMatrixCreatorsOp1 op,const TMatrixTSparse<Element> &prototype);\n   TMatrixTSparse(const TMatrixTSparse<Element> &a,EMatrixCreatorsOp2 op,const TMatrixTSparse<Element> &b);\n   TMatrixTSparse(const TMatrixTSparse<Element> &a,EMatrixCreatorsOp2 op,const TMatrixT      <Element> &b);\n   TMatrixTSparse(const TMatrixT      <Element> &a,EMatrixCreatorsOp2 op,const TMatrixTSparse<Element> &b);\n\n   virtual ~TMatrixTSparse() { Clear(); }\n\n   virtual const Element *GetMatrixArray  () const;\n   virtual       Element *GetMatrixArray  ();\n   virtual const Int_t    *GetRowIndexArray() const;\n   virtual       Int_t    *GetRowIndexArray();\n   virtual const Int_t    *GetColIndexArray() const;\n   virtual       Int_t    *GetColIndexArray();\n\n   virtual TMatrixTBase<Element>   &SetRowIndexArray(Int_t *data) { memmove(fRowIndex,data,(this->fNrows+1)*sizeof(Int_t)); return *this; }\n   virtual TMatrixTBase<Element>   &SetColIndexArray(Int_t *data) { memmove(fColIndex,data,this->fNelems*sizeof(Int_t)); return *this; }\n\n           TMatrixTSparse<Element> &SetSparseIndex  (Int_t nelem_new);\n           TMatrixTSparse<Element> &SetSparseIndex  (const TMatrixTBase<Element> &another);\n           TMatrixTSparse<Element> &SetSparseIndexAB(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b);\n           TMatrixTSparse<Element> &SetSparseIndexAB(const TMatrixT      <Element> &a,const TMatrixTSparse<Element> &b);\n           TMatrixTSparse<Element> &SetSparseIndexAB(const TMatrixTSparse<Element> &a,const TMatrixT      <Element> &b)\n                                              { return SetSparseIndexAB(b,a); }\n\n   virtual void                     GetMatrix2Array (Element *data,Option_t * /*option*/ =\"\") const;\n   virtual TMatrixTBase<Element>   &SetMatrixArray  (const Element *data,Option_t * /*option*/=\"\")\n                                                    { memcpy(fElements,data,this->fNelems*sizeof(Element)); return *this; }\n   virtual TMatrixTBase<Element>   &SetMatrixArray  (Int_t nr_nonzeros,Int_t *irow,Int_t *icol,Element *data);\n   virtual TMatrixTBase<Element>   &InsertRow       (Int_t row,Int_t col,const Element *v,Int_t n=-1);\n   virtual void                     ExtractRow      (Int_t row,Int_t col,      Element *v,Int_t n=-1) const;\n\n   virtual TMatrixTBase<Element>   &ResizeTo(Int_t nrows,Int_t ncols,Int_t nr_nonzeros=-1);\n   virtual TMatrixTBase<Element>   &ResizeTo(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros=-1);\n   inline  TMatrixTBase<Element>   &ResizeTo(const TMatrixTSparse<Element> &m) {return ResizeTo(m.GetRowLwb(),m.GetRowUpb(),m.GetColLwb(),\n                                                                                                m.GetColUpb(),m.GetNoElements()); }\n\n   virtual void Clear(Option_t * /*option*/ =\"\") { if (this->fIsOwner) {\n                                                      if (fElements) { delete [] fElements; fElements = 0; }\n                                                      if (fRowIndex) { delete [] fRowIndex; fRowIndex = 0; }\n                                                      if (fColIndex) { delete [] fColIndex; fColIndex = 0; }\n                                                   }\n                                                   this->fNelems    = 0;\n                                                   this->fNrowIndex = 0;\n                                                 }\n\n           TMatrixTSparse<Element> &Use   (Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros,\n                                           Int_t *pRowIndex,Int_t *pColIndex,Element *pData);\n   const   TMatrixTSparse<Element> &Use   (Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros,\n                                           const Int_t *pRowIndex,const Int_t *pColIndex,const Element *pData) const\n                                            { return (const TMatrixTSparse<Element>&)\n                                                     ((const_cast<TMatrixTSparse<Element> *>(this))->Use(row_lwb,row_upb,col_lwb,col_upb,nr_nonzeros,\n                                                                                             const_cast<Int_t *>(pRowIndex),\n                                                                                             const_cast<Int_t *>(pColIndex),\n                                                                                             const_cast<Element *>(pData))); }\n           TMatrixTSparse<Element> &Use   (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,\n                                           Int_t *pRowIndex,Int_t *pColIndex,Element *pData);\n   const   TMatrixTSparse<Element> &Use   (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,\n                                           const Int_t *pRowIndex,const Int_t *pColIndex,const Element *pData) const;\n           TMatrixTSparse<Element> &Use   (TMatrixTSparse<Element> &a);\n   const   TMatrixTSparse<Element> &Use   (const TMatrixTSparse<Element> &a) const;\n\n   virtual TMatrixTBase<Element>   &GetSub(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,\n                                            TMatrixTBase<Element> &target,Option_t *option=\"S\") const;\n           TMatrixTSparse<Element>  GetSub(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Option_t *option=\"S\") const;\n   virtual TMatrixTBase<Element>   &SetSub(Int_t row_lwb,Int_t col_lwb,const TMatrixTBase<Element> &source);\n\n   virtual Bool_t IsSymmetric() const { return (*this == TMatrixTSparse<Element>(kTransposed,*this)); }\n   TMatrixTSparse<Element> &Transpose (const TMatrixTSparse<Element> &source);\n   inline TMatrixTSparse<Element> &T () { return this->Transpose(*this); }\n\n   inline void Mult(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b) { AMultB(a,b,0); }\n\n   virtual TMatrixTBase<Element> &Zero       ();\n   virtual TMatrixTBase<Element> &UnitMatrix ();\n\n   virtual Element RowNorm () const;\n   virtual Element ColNorm () const;\n   virtual Int_t   NonZeros() const { return this->fNelems; }\n\n   virtual TMatrixTBase<Element> &NormByDiag(const TVectorT<Element> &/*v*/,Option_t * /*option*/)\n                                              { MayNotUse(\"NormByDiag\"); return *this; }\n\n   // Either access a_ij as a(i,j)\n   Element  operator()(Int_t rown,Int_t coln) const;\n   Element &operator()(Int_t rown,Int_t coln);\n\n   // or as a[i][j]\n   inline const TMatrixTSparseRow_const<Element> operator[](Int_t rown) const { return TMatrixTSparseRow_const<Element>(*this,rown); }\n   inline       TMatrixTSparseRow      <Element> operator[](Int_t rown)       { return TMatrixTSparseRow      <Element>(*this,rown); }\n\n   TMatrixTSparse<Element> &operator=(const TMatrixT<Element>       &source);\n   TMatrixTSparse<Element> &operator=(const TMatrixTSparse<Element> &source);\n\n   TMatrixTSparse<Element> &operator= (Element val);\n   TMatrixTSparse<Element> &operator-=(Element val);\n   TMatrixTSparse<Element> &operator+=(Element val);\n   TMatrixTSparse<Element> &operator*=(Element val);\n\n   TMatrixTSparse<Element> &operator+=(const TMatrixTSparse<Element> &source) { TMatrixTSparse<Element> tmp(*this); Clear();\n                                                                                if (this == &source) APlusB (tmp,tmp,1);\n                                                                                else                 APlusB (tmp,source,1);\n                                                                                return *this; }\n   TMatrixTSparse<Element> &operator+=(const TMatrixT<Element>       &source) { TMatrixTSparse<Element> tmp(*this); Clear();\n                                                                                APlusB(tmp,source,1); return *this; }\n   TMatrixTSparse<Element> &operator-=(const TMatrixTSparse<Element> &source) { TMatrixTSparse<Element> tmp(*this); Clear();\n                                                                                if (this == &source) AMinusB (tmp,tmp,1);\n                                                                                else                 AMinusB(tmp,source,1);\n                                                                                return *this; }\n   TMatrixTSparse<Element> &operator-=(const TMatrixT<Element>       &source) { TMatrixTSparse<Element> tmp(*this); Clear();\n                                                                                AMinusB(tmp,source,1); return *this; }\n   TMatrixTSparse<Element> &operator*=(const TMatrixTSparse<Element> &source) { TMatrixTSparse<Element> tmp(*this); Clear();\n                                                                                if (this == &source) AMultB (tmp,tmp,1);\n                                                                                else                 AMultB (tmp,source,1);\n                                                                                return *this; }\n   TMatrixTSparse<Element> &operator*=(const TMatrixT<Element>       &source) { TMatrixTSparse<Element> tmp(*this); Clear();\n                                                                                AMultB(tmp,source,1);\n                                                                                return *this; }\n\n   virtual TMatrixTBase  <Element> &Randomize  (Element alpha,Element beta,Double_t &seed);\n   virtual TMatrixTSparse<Element> &RandomizePD(Element alpha,Element beta,Double_t &seed);\n\n   ClassDef(TMatrixTSparse,3) // Template of Sparse Matrix class\n};\n\n#ifndef __CINT__\n// When building with -fmodules, it instantiates all pending instantiations,\n// instead of delaying them until the end of the translation unit.\n// We 'got away with' probably because the use and the definition of the\n// explicit specialization do not occur in the same TU.\n//\n// In case we are building with -fmodules, we need to forward declare the\n// specialization in order to compile the dictionary G__Matrix.cxx.\ntemplate <> TClass *TMatrixTSparse<double>::Class();\n#endif // __CINT__\n\ntemplate <class Element> inline const Element *TMatrixTSparse<Element>::GetMatrixArray  () const { return fElements; }\ntemplate <class Element> inline       Element *TMatrixTSparse<Element>::GetMatrixArray  ()       { return fElements; }\ntemplate <class Element> inline const Int_t   *TMatrixTSparse<Element>::GetRowIndexArray() const { return fRowIndex; }\ntemplate <class Element> inline       Int_t   *TMatrixTSparse<Element>::GetRowIndexArray()       { return fRowIndex; }\ntemplate <class Element> inline const Int_t   *TMatrixTSparse<Element>::GetColIndexArray() const { return fColIndex; }\ntemplate <class Element> inline       Int_t   *TMatrixTSparse<Element>::GetColIndexArray()       { return fColIndex; }\n\ntemplate <class Element>\ninline       TMatrixTSparse<Element> &TMatrixTSparse<Element>::Use   (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,\n                                                                      Int_t *pRowIndex,Int_t *pColIndex,Element *pData)\n                                                                        { return Use(0,nrows-1,0,ncols-1,nr_nonzeros,pRowIndex,pColIndex,pData); }\ntemplate <class Element>\ninline const TMatrixTSparse<Element> &TMatrixTSparse<Element>::Use   (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,\n                                                                      const Int_t *pRowIndex,const Int_t *pColIndex,const Element *pData) const\n                                                                        { return Use(0,nrows-1,0,ncols-1,nr_nonzeros,pRowIndex,pColIndex,pData); }\ntemplate <class Element>\ninline       TMatrixTSparse<Element> &TMatrixTSparse<Element>::Use   (TMatrixTSparse<Element> &a)\n                                                                        { R__ASSERT(a.IsValid());\n                                                                           return Use(a.GetRowLwb(),a.GetRowUpb(),a.GetColLwb(),a.GetColUpb(),\n                                                                                      a.GetNoElements(),a.GetRowIndexArray(),\n                                                                                      a.GetColIndexArray(),a.GetMatrixArray()); }\ntemplate <class Element>\ninline const TMatrixTSparse<Element> &TMatrixTSparse<Element>::Use   (const TMatrixTSparse<Element> &a) const\n                                                                        { R__ASSERT(a.IsValid());\n                                                                           return Use(a.GetRowLwb(),a.GetRowUpb(),a.GetColLwb(),a.GetColUpb(),\n                                                                                      a.GetNoElements(),a.GetRowIndexArray(),\n                                                                                      a.GetColIndexArray(),a.GetMatrixArray()); }\n\ntemplate <class Element>\ninline       TMatrixTSparse<Element>  TMatrixTSparse<Element>::GetSub(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,\n                                                                      Option_t *option) const\n                                                                        {\n                                                                          TMatrixTSparse<Element> tmp;\n                                                                          this->GetSub(row_lwb,row_upb,col_lwb,col_upb,tmp,option);\n                                                                          return tmp;\n                                                                        }\n\ntemplate <class Element> TMatrixTSparse<Element>  operator+ (const TMatrixTSparse<Element> &source1,const TMatrixTSparse<Element> &source2);\ntemplate <class Element> TMatrixTSparse<Element>  operator+ (const TMatrixTSparse<Element> &source1,const TMatrixT<Element>       &source2);\ntemplate <class Element> TMatrixTSparse<Element>  operator+ (const TMatrixT<Element>       &source1,const TMatrixTSparse<Element> &source2);\ntemplate <class Element> TMatrixTSparse<Element>  operator+ (const TMatrixTSparse<Element> &source ,      Element                  val    );\ntemplate <class Element> TMatrixTSparse<Element>  operator+ (      Element                  val    ,const TMatrixTSparse<Element> &source );\ntemplate <class Element> TMatrixTSparse<Element>  operator- (const TMatrixTSparse<Element> &source1,const TMatrixTSparse<Element> &source2);\ntemplate <class Element> TMatrixTSparse<Element>  operator- (const TMatrixTSparse<Element> &source1,const TMatrixT<Element>       &source2);\ntemplate <class Element> TMatrixTSparse<Element>  operator- (const TMatrixT<Element>       &source1,const TMatrixTSparse<Element> &source2);\ntemplate <class Element> TMatrixTSparse<Element>  operator- (const TMatrixTSparse<Element> &source ,      Element                  val    );\ntemplate <class Element> TMatrixTSparse<Element>  operator- (      Element                  val    ,const TMatrixTSparse<Element> &source );\ntemplate <class Element> TMatrixTSparse<Element>  operator* (const TMatrixTSparse<Element> &source1,const TMatrixTSparse<Element> &source2);\ntemplate <class Element> TMatrixTSparse<Element>  operator* (const TMatrixTSparse<Element> &source1,const TMatrixT<Element>       &source2);\ntemplate <class Element> TMatrixTSparse<Element>  operator* (const TMatrixT<Element>       &source1,const TMatrixTSparse<Element> &source2);\ntemplate <class Element> TMatrixTSparse<Element>  operator* (      Element                  val    ,const TMatrixTSparse<Element> &source );\ntemplate <class Element> TMatrixTSparse<Element>  operator* (const TMatrixTSparse<Element> &source,       Element                  val    );\n\ntemplate <class Element> TMatrixTSparse<Element> &Add        (TMatrixTSparse<Element> &target,      Element                   scalar,\n                                                              const TMatrixTSparse<Element> &source);\ntemplate <class Element> TMatrixTSparse<Element> &ElementMult(TMatrixTSparse<Element> &target,const TMatrixTSparse<Element>  &source);\ntemplate <class Element> TMatrixTSparse<Element> &ElementDiv (TMatrixTSparse<Element> &target,const TMatrixTSparse<Element>  &source);\n\ntemplate <class Element> Bool_t AreCompatible(const TMatrixTSparse<Element> &m1,const TMatrixTSparse<Element> &m2,Int_t verbose=0);\n\n#endif\n", "meta": {"hexsha": "96dab7ddc611f497094f268ce56cd4a66aaac765", "size": 20311, "ext": "h", "lang": "C", "max_stars_repo_path": "resources/home/dnanexus/root/include/TMatrixTSparse.h", "max_stars_repo_name": "edawson/parliament2", "max_stars_repo_head_hexsha": "2632aa3484ef64c9539c4885026b705b737f6d1e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "resources/home/dnanexus/root/include/TMatrixTSparse.h", "max_issues_repo_name": "edawson/parliament2", "max_issues_repo_head_hexsha": "2632aa3484ef64c9539c4885026b705b737f6d1e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "resources/home/dnanexus/root/include/TMatrixTSparse.h", "max_forks_repo_name": "edawson/parliament2", "max_forks_repo_head_hexsha": "2632aa3484ef64c9539c4885026b705b737f6d1e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-28T23:01:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-28T23:01:44.000Z", "avg_line_length": 73.5905797101, "max_line_length": 149, "alphanum_fraction": 0.5656540791, "num_tokens": 4531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.35805593390095725}}
{"text": "/* specfunc/sinint.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n/* Author:  G. Jungman */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_trig.h>\n#include <gsl/gsl_sf_expint.h>\n\n#include \"error.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n/* based on SLATEC r9sifg.f, W. Fullerton */\n\n/*\n series for f1   on the interval  2.00000e-02 to  6.25000e-02\n                                        with weighted error   2.82e-17\n                                         log weighted error  16.55\n                               significant figures required  15.36\n                                    decimal places required  17.20\n*/\nstatic double f1_data[20] = {\n   -0.1191081969051363610,\n   -0.0247823144996236248,\n    0.0011910281453357821,\n   -0.0000927027714388562,\n    0.0000093373141568271,\n   -0.0000011058287820557,\n    0.0000001464772071460,\n   -0.0000000210694496288,\n    0.0000000032293492367,\n   -0.0000000005206529618,\n    0.0000000000874878885,\n   -0.0000000000152176187,\n    0.0000000000027257192,\n   -0.0000000000005007053,\n    0.0000000000000940241,\n   -0.0000000000000180014,\n    0.0000000000000035063,\n   -0.0000000000000006935,\n    0.0000000000000001391,\n   -0.0000000000000000282\n};\nstatic cheb_series f1_cs = {\n  f1_data,\n  19,\n  -1, 1,\n  10\n};\n\n/*\n\n series for f2   on the interval  0.00000e+00 to  2.00000e-02\n                                        with weighted error   4.32e-17\n                                         log weighted error  16.36\n                               significant figures required  14.75\n                                    decimal places required  17.10\n*/\nstatic double f2_data[29] = {\n   -0.0348409253897013234,\n   -0.0166842205677959686,\n    0.0006752901241237738,\n   -0.0000535066622544701,\n    0.0000062693421779007,\n   -0.0000009526638801991,\n    0.0000001745629224251,\n   -0.0000000368795403065,\n    0.0000000087202677705,\n   -0.0000000022601970392,\n    0.0000000006324624977,\n   -0.0000000001888911889,\n    0.0000000000596774674,\n   -0.0000000000198044313,\n    0.0000000000068641396,\n   -0.0000000000024731020,\n    0.0000000000009226360,\n   -0.0000000000003552364,\n    0.0000000000001407606,\n   -0.0000000000000572623,\n    0.0000000000000238654,\n   -0.0000000000000101714,\n    0.0000000000000044259,\n   -0.0000000000000019634,\n    0.0000000000000008868,\n   -0.0000000000000004074,\n    0.0000000000000001901,\n   -0.0000000000000000900,\n    0.0000000000000000432\n};\nstatic cheb_series f2_cs = {\n  f2_data,\n  28,\n  -1, 1,\n  14\n};\n\n/*\n\n series for g1   on the interval  2.00000e-02 to  6.25000e-02\n                                        with weighted error   5.48e-17\n                                         log weighted error  16.26\n                               significant figures required  15.47\n                                    decimal places required  16.92\n*/\nstatic double g1_data[21] = {\n   -0.3040578798253495954,\n   -0.0566890984597120588,\n    0.0039046158173275644,\n   -0.0003746075959202261,\n    0.0000435431556559844,\n   -0.0000057417294453025,\n    0.0000008282552104503,\n   -0.0000001278245892595,\n    0.0000000207978352949,\n   -0.0000000035313205922,\n    0.0000000006210824236,\n   -0.0000000001125215474,\n    0.0000000000209088918,\n   -0.0000000000039715832,\n    0.0000000000007690431,\n   -0.0000000000001514697,\n    0.0000000000000302892,\n   -0.0000000000000061400,\n    0.0000000000000012601,\n   -0.0000000000000002615,\n    0.0000000000000000548\n};\nstatic cheb_series g1_cs = {\n  g1_data,\n  20,\n  -1, 1,\n  13\n};\n\n/*\n\n series for g2   on the interval  0.00000e+00 to  2.00000e-02\n                                        with weighted error   5.01e-17\n                                         log weighted error  16.30\n                               significant figures required  15.12\n                                    decimal places required  17.07\n*/\nstatic double g2_data[34] = {\n   -0.0967329367532432218,\n   -0.0452077907957459871,\n    0.0028190005352706523,\n   -0.0002899167740759160,\n    0.0000407444664601121,\n   -0.0000071056382192354,\n    0.0000014534723163019,\n   -0.0000003364116512503,\n    0.0000000859774367886,\n   -0.0000000238437656302,\n    0.0000000070831906340,\n   -0.0000000022318068154,\n    0.0000000007401087359,\n   -0.0000000002567171162,\n    0.0000000000926707021,\n   -0.0000000000346693311,\n    0.0000000000133950573,\n   -0.0000000000053290754,\n    0.0000000000021775312,\n   -0.0000000000009118621,\n    0.0000000000003905864,\n   -0.0000000000001708459,\n    0.0000000000000762015,\n   -0.0000000000000346151,\n    0.0000000000000159996,\n   -0.0000000000000075213,\n    0.0000000000000035970,\n   -0.0000000000000017530,\n    0.0000000000000008738,\n   -0.0000000000000004487,\n    0.0000000000000002397,\n   -0.0000000000000001347,\n    0.0000000000000000801,\n   -0.0000000000000000501\n};\nstatic cheb_series g2_cs = {\n  g2_data,\n  33,\n  -1, 1,\n  20\n};\n\n\n/* x >= 4.0 */\nstatic void fg_asymp(const double x, gsl_sf_result * f, gsl_sf_result * g)\n{\n  /*\n      xbig = sqrt (1.0/r1mach(3))\n      xmaxf = exp (amin1(-alog(r1mach(1)), alog(r1mach(2))) - 0.01)\n      xmaxg = 1.0/sqrt(r1mach(1))\n      xbnd = sqrt(50.0)\n  */\n  const double xbig  = 1.0/GSL_SQRT_DBL_EPSILON;\n  const double xmaxf = 1.0/GSL_DBL_MIN;\n  const double xmaxg = 1.0/GSL_SQRT_DBL_MIN;\n  const double xbnd  = 7.07106781187;\n\n  const double x2 = x*x;\n\n  if(x <= xbnd) {\n    gsl_sf_result result_c1;\n    gsl_sf_result result_c2;\n    cheb_eval_e(&f1_cs, (1.0/x2-0.04125)/0.02125, &result_c1);\n    cheb_eval_e(&g1_cs, (1.0/x2-0.04125)/0.02125, &result_c2);\n    f->val = (1.0 + result_c1.val)/x;\n    g->val = (1.0 + result_c2.val)/x2;\n    f->err = result_c1.err/x  + 2.0 * GSL_DBL_EPSILON * fabs(f->val);\n    g->err = result_c2.err/x2 + 2.0 * GSL_DBL_EPSILON * fabs(g->val);\n  }\n  else if(x <= xbig) {\n    gsl_sf_result result_c1;\n    gsl_sf_result result_c2;\n    cheb_eval_e(&f2_cs, 100.0/x2-1.0, &result_c1);\n    cheb_eval_e(&g2_cs, 100.0/x2-1.0, &result_c2);\n    f->val = (1.0 + result_c1.val)/x;\n    g->val = (1.0 + result_c2.val)/x2;\n    f->err = result_c1.err/x  + 2.0 * GSL_DBL_EPSILON * fabs(f->val);\n    g->err = result_c2.err/x2 + 2.0 * GSL_DBL_EPSILON * fabs(g->val);\n  }\n  else {\n    f->val = (x < xmaxf ? 1.0/x  : 0.0);\n    g->val = (x < xmaxg ? 1.0/x2 : 0.0);\n    f->err = 2.0 * GSL_DBL_EPSILON * fabs(f->val);\n    g->err = 2.0 * GSL_DBL_EPSILON * fabs(g->val);\n  }\n\n  return;\n}\n\n\n/* based on SLATEC si.f, W. Fullerton\n\n series for si   on the interval  0.00000e+00 to  1.60000e+01\n                                        with weighted error   1.22e-17\n                                         log weighted error  16.91\n                               significant figures required  16.37\n                                    decimal places required  17.45\n*/\n\nstatic double si_data[12] = {\n  -0.1315646598184841929,\n  -0.2776578526973601892,\n   0.0354414054866659180,\n  -0.0025631631447933978,\n   0.0001162365390497009,\n  -0.0000035904327241606,\n   0.0000000802342123706,\n  -0.0000000013562997693,\n   0.0000000000179440722,\n  -0.0000000000001908387,\n   0.0000000000000016670,\n  -0.0000000000000000122\n};\n\nstatic cheb_series si_cs = {\n  si_data,\n  11,\n  -1, 1,\n  9\n};\n\n/*\n series for ci   on the interval  0.00000e+00 to  1.60000e+01\n                                        with weighted error   1.94e-18\n                                         log weighted error  17.71\n                               significant figures required  17.74\n                                    decimal places required  18.27\n*/\nstatic double ci_data[13] = {\n   -0.34004281856055363156,\n   -1.03302166401177456807,\n    0.19388222659917082877,\n   -0.01918260436019865894,\n    0.00110789252584784967,\n   -0.00004157234558247209,\n    0.00000109278524300229,\n   -0.00000002123285954183,\n    0.00000000031733482164,\n   -0.00000000000376141548,\n    0.00000000000003622653,\n   -0.00000000000000028912,\n    0.00000000000000000194\n};\nstatic cheb_series ci_cs = {\n  ci_data,\n  12,\n  -1, 1,\n  9\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_Si_e(const double x, gsl_sf_result * result)\n{\n  double ax = fabs(x);\n  \n  /* CHECK_POINTER(result) */\n\n  if(ax < GSL_SQRT_DBL_EPSILON) {\n    result->val = x;\n    result->err = 0.0;\n    return GSL_SUCCESS;\n  }\n  else if(ax <= 4.0) {\n    gsl_sf_result result_c;\n    cheb_eval_e(&si_cs, (x*x-8.0)*0.125, &result_c);\n    result->val  =  x * (0.75 + result_c.val);\n    result->err  = ax * result_c.err;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    /* Note there is no loss of precision\n     * here bcause of the leading constant.\n     */\n    gsl_sf_result f;\n    gsl_sf_result g;\n    fg_asymp(ax, &f, &g);\n    result->val  = 0.5 * M_PI - f.val*cos(ax) - g.val*sin(ax);\n    result->err  = f.err + g.err;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    if(x < 0.0) result->val = -result->val;\n    return GSL_SUCCESS;\n  }\n}\n\n\nint gsl_sf_Ci_e(const double x, gsl_sf_result * result)\n{\n  /* CHECK_POINTER(result) */\n\n  if(x <= 0.0) {\n    DOMAIN_ERROR(result);\n  }\n  else if(x <= 4.0) {\n    const double lx = log(x);\n    const double y  = (x*x-8.0)*0.125;\n    gsl_sf_result result_c;\n    cheb_eval_e(&ci_cs, y, &result_c);\n    result->val  = lx - 0.5 + result_c.val;\n    result->err  = 2.0 * GSL_DBL_EPSILON * (fabs(lx) + 0.5) + result_c.err;\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_SUCCESS;\n  }\n  else {\n    gsl_sf_result sin_result;\n    gsl_sf_result cos_result;\n    int stat_sin = gsl_sf_sin_e(x, &sin_result);\n    int stat_cos = gsl_sf_cos_e(x, &cos_result);\n    gsl_sf_result f;\n    gsl_sf_result g;\n    fg_asymp(x, &f, &g);\n    result->val  = f.val*sin_result.val - g.val*cos_result.val;\n    result->err  = fabs(f.err*sin_result.val);\n    result->err += fabs(g.err*cos_result.val);\n    result->err += fabs(f.val*sin_result.err);\n    result->err += fabs(g.val*cos_result.err);\n    result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n    return GSL_ERROR_SELECT_2(stat_sin, stat_cos);\n  }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_Si(const double x)\n{\n  EVAL_RESULT(gsl_sf_Si_e(x, &result));\n}\n\ndouble gsl_sf_Ci(const double x)\n{\n  EVAL_RESULT(gsl_sf_Ci_e(x, &result));\n}\n", "meta": {"hexsha": "76a88ea00fe8b3c2ff143b4dfe467796dc285a8c", "size": 11143, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/sinint.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/sinint.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/sinint.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 27.6501240695, "max_line_length": 81, "alphanum_fraction": 0.6201202549, "num_tokens": 3963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.3579666515764947}}
{"text": "/*\n *  gsl_binomial_randomdev.h\n *\n *  This file is part of NEST.\n *\n *  Copyright (C) 2004 The NEST Initiative\n *\n *  NEST 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 *  NEST 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 NEST.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n// Generated includes:\n#include \"config.h\"\n\n#ifndef GSL_BINOMIAL_RANDOMDEV_H\n#define GSL_BINOMIAL_RANDOMDEV_H\n\n// Includes from libnestutil:\n#include \"lockptr.h\"\n\n// Includes from librandom:\n#include \"gslrandomgen.h\"\n#include \"randomdev.h\"\n#include \"randomgen.h\"\n\n// Includes from sli:\n#include \"dictdatum.h\"\n\n#ifdef HAVE_GSL\n\n// External includes:\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_rng.h>\n\n\n/*BeginDocumentation\nName: rdevdict::gsl_binomial - GSL binomial random deviate generator\nDescription:\nThis function returns a random integer from the binomial distribution,\nthe number of successes in n independent trials with probability\np. The probability distribution for binomial variates is,\n\n   p(k) = (n! / k!(n-k)!) p^k (1-p)^(n-k)  , 0<=k<=n, n>0\n\nPlease note that the RNG used to initialize gsl_binomial has to be\nfrom the GSL (prefixed gsl_ in rngdict)\n\nParameters:\n   p - probability of success in a single trial (double)\n   n - number of trials (positive integer)\n\nSeeAlso: CreateRDV, RandomArray, rdevdict\nAuthor: Jochen Martin Eppler\n*/\n\n\nnamespace librandom\n{\n\n/**\n Class GSL_BinomialRandomDev\n\n Generates an RNG which returns Binomial(k;p;n)\n distributed random numbers out of an RNG which returns\n binomially distributed random numbers:\n\n    p(k) = (n! / k!(n-k)!) p^k (1-p)^(n-k)  , 0<=k<=n, n<0\n\n Arguments:\n  - pointer to an RNG\n  - parameter p (optional, default = 0.5)\n  - parameter n (optional, default = 1)\n\n @see\n http://www.gnu.org/software/gsl/manual/html_node/The-Binomial-Distribution.html\n @ingroup RandomDeviateGenerators\n*/\n\nclass GSL_BinomialRandomDev : public RandomDev\n{\npublic:\n  // accept only lockPTRs for initialization,\n  // otherwise creation of a lock ptr would\n  // occur as side effect---might be unhealthy\n  GSL_BinomialRandomDev( RngPtr, double p_s = 0.5, unsigned int n_s = 1 );\n  GSL_BinomialRandomDev( double p_s = 0.5, unsigned int n_s = 1 );\n\n  /**\n   * set parameters for p and n\n   * @parameters\n   * p - success probability for single trial\n   * n - number of trials\n   */\n  void set_p_n( double, unsigned int );\n  void set_p( double );       //!<set p\n  void set_n( unsigned int ); //!<set n\n\n  /**\n   * Import sets of overloaded virtual functions.\n   * We need to explicitly include sets of overloaded\n   * virtual functions into the current scope.\n   * According to the SUN C++ FAQ, this is the correct\n   * way of doing things, although all other compilers\n   * happily live without.\n   */\n  using RandomDev::operator();\n  using RandomDev::ldev;\n\n  long ldev();               //!< draw integer\n  long ldev( RngPtr ) const; //!< draw integer, threaded\n  bool\n  has_ldev() const\n  {\n    return true;\n  }\n\n  double operator()( RngPtr ) const; //!< return as double, threaded\n\n  //! set distribution parameters from SLI dict\n  void set_status( const DictionaryDatum& );\n\n  //! get distribution parameters from SLI dict\n  void get_status( DictionaryDatum& ) const;\n\nprivate:\n  double p_;       //!<probability p of binomial distribution\n  unsigned int n_; //!<parameter n in binomial distribution\n\n  gsl_rng* rng_;\n};\n\ninline double GSL_BinomialRandomDev::operator()( RngPtr rthrd ) const\n{\n  return static_cast< double >( ldev( rthrd ) );\n}\n}\n\n#endif\n\n#endif\n", "meta": {"hexsha": "599acb36350cc74a3ad1fb70d234901b02d8e6c6", "size": 3974, "ext": "h", "lang": "C", "max_stars_repo_path": "NEST-14.0-FPGA/librandom/gsl_binomial_randomdev.h", "max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z", "max_issues_repo_path": "NEST-14.0-FPGA/librandom/gsl_binomial_randomdev.h", "max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster", "max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z", "max_forks_repo_path": "NEST-14.0-FPGA/librandom/gsl_binomial_randomdev.h", "max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z", "avg_line_length": 26.1447368421, "max_line_length": 80, "alphanum_fraction": 0.7073477604, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.35791677626388546}}
{"text": "/*\n *  Player - One Hell of a Robot Server\n *  Copyright (C) 2000  Brian Gerkey   &  Kasper Stoy\n *                      gerkey@usc.edu    kaspers@robotics.usc.edu\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation; either\n *  version 2.1 of the License, or (at your option) any later version.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\n */\n/**************************************************************************\n * Desc: Useful pdf functions\n * Author: Andrew Howard\n * Date: 10 Dec 2002\n * CVS: $Id: pf_pdf.h 6345 2008-04-17 01:36:39Z gerkey $\n *************************************************************************/\n\n#ifndef PF_PDF_H\n#define PF_PDF_H\n\n#include \"nav2d_localizer/pf_vector.h\"\n\n//#include <gsl/gsl_rng.h>\n//#include <gsl/gsl_randist.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**************************************************************************\n * Gaussian\n *************************************************************************/\n\n// Gaussian PDF info\ntypedef struct\n{\n  // Mean, covariance and inverse covariance\n  pf_vector_t x;\n  pf_matrix_t cx;\n  //pf_matrix_t cxi;\n  double cxdet;\n\n  // Decomposed covariance matrix (rotation * diagonal)\n  pf_matrix_t cr;\n  pf_vector_t cd;\n\n  // A random number generator\n  //gsl_rng *rng;\n\n} pf_pdf_gaussian_t;\n\n\n// Create a gaussian pdf\npf_pdf_gaussian_t *pf_pdf_gaussian_alloc(pf_vector_t x, pf_matrix_t cx);\n\n// Destroy the pdf\nvoid pf_pdf_gaussian_free(pf_pdf_gaussian_t *pdf);\n\n// Compute the value of the pdf at some point [z].\n//double pf_pdf_gaussian_value(pf_pdf_gaussian_t *pdf, pf_vector_t z);\n\n// Draw randomly from a zero-mean Gaussian distribution, with standard\n// deviation sigma.\n// We use the polar form of the Box-Muller transformation, explained here:\n//   http://www.taygeta.com/random/gaussian.html\ndouble pf_ran_gaussian(double sigma);\n\n// Generate a sample from the the pdf.\npf_vector_t pf_pdf_gaussian_sample(pf_pdf_gaussian_t *pdf);\n\n\n#if 0\n\n/**************************************************************************\n * Discrete\n *************************************************************************/\n\n// Discrete PDF info\ntypedef struct\n{\n  // The list of discrete probs\n  int prob_count;\n  double *probs;\n\n  // A random number generator\n  gsl_rng *rng;\n\n  // The discrete prob generator\n  gsl_ran_discrete_t *ran;\n\n} pf_pdf_discrete_t;\n\n\n// Create a discrete pdf\npf_pdf_discrete_t *pf_pdf_discrete_alloc(int count, double *probs);\n\n// Destroy the pdf\nvoid pf_pdf_discrete_free(pf_pdf_discrete_t *pdf);\n\n// Compute the value of the probability of some element [i]\ndouble pf_pdf_discrete_value(pf_pdf_discrete_t *pdf, int i);\n\n// Generate a sample from the the pdf.\nint pf_pdf_discrete_sample(pf_pdf_discrete_t *pdf);\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "b7cbf8975c87b0cdc76a2116d8526a733d2a5624", "size": 3348, "ext": "h", "lang": "C", "max_stars_repo_path": "navigation_2d/nav2d_localizer/include/nav2d_localizer/pf_pdf.h", "max_stars_repo_name": "swsachith/tb3_rescue_bot", "max_stars_repo_head_hexsha": "cd2bb81bede9f740c3316783474d68ae7e0b480a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-17T11:13:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T11:13:01.000Z", "max_issues_repo_path": "src/nav2d_localizer/include/nav2d_localizer/pf_pdf.h", "max_issues_repo_name": "pplankton/MRSLAM", "max_issues_repo_head_hexsha": "0a16489a2cbd0c2d1511b506c540446cc670bde8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nav2d_localizer/include/nav2d_localizer/pf_pdf.h", "max_forks_repo_name": "pplankton/MRSLAM", "max_forks_repo_head_hexsha": "0a16489a2cbd0c2d1511b506c540446cc670bde8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-16T16:14:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-27T22:55:07.000Z", "avg_line_length": 27.4426229508, "max_line_length": 77, "alphanum_fraction": 0.6353046595, "num_tokens": 788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.3578200981685647}}
{"text": "#ifndef _PURSUIT_SHIP_H_\n#define _PURSUIT_SHIP_H_\n\n//-----------------------------------------------------------------------------\n\n#include <boost/shared_ptr.hpp>\n\n#include <Ravelin/Pose3d.h>\n#include <Ravelin/SpatialRBInertiad.h>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_multifit_nlin.h>\n\n#include <ompl/control/SpaceInformation.h>\n#include <ompl/base/goals/GoalState.h>\n#include <ompl/base/spaces/SE2StateSpace.h>\n#include <ompl/control/spaces/RealVectorControlSpace.h>\n#include <ompl/control/planners/rrt/RRT.h>\n#include <ompl/control/SimpleSetup.h>\n#include <ompl/config.h>\n#include <ompl/control/SimpleDirectedControlSampler.h>\n#include <ompl/control/ODESolver.h>\n\n#include \"experiment.h\"\n#include \"aabb.h\"\n#include \"control_space.h\"\n\n//-----------------------------------------------------------------------------\n\nclass space_c;\ntypedef boost::shared_ptr<space_c> space_p;\nclass ship_c;\ntypedef boost::shared_ptr<ship_c> ship_p;\n\n//-----------------------------------------------------------------------------\nclass ship_c {\npublic:\n\n  //---------------------------------------------------------------------------\n  // Members\n  //---------------------------------------------------------------------------\n\n  Ravelin::Pose3d _pose;\n  Ravelin::SVelocityd _velocity;\n\n  // the inertial mass matrix of the ship\n  Ravelin::SpatialRBInertiad _inertial;\n\n  space_p _space;\n  //----------\n\n  // the set of possible player types\n  enum role_e {\n    NONE = 0,\n    PREY,\n    PREDATOR\n  };\n\n  role_e role;\n\n  ship_p adversary;\n\n  double time;\n  double dtime;\n\n  double integration_step;\n  double controller_step;\n\n  // the ship's bounding box in the ship's frame of reference\n  aabb_c ship_frame_bb;\n\n   // whether or not a capture event has occurred\n  bool capture;\n  bool stopped;\n\n  //---------------------------------------------------------------------------\n  // Constructors\n  //---------------------------------------------------------------------------\n  ship_c( role_e role );\n  ship_c( ompl::base::StateSpace *_statespace );\n \n  //---------------------------------------------------------------------------\n  // Destructor\n  //---------------------------------------------------------------------------\n  virtual ~ship_c( void );\n\n  //---------------------------------------------------------------------------\n  // Base Class Definitions\n  //---------------------------------------------------------------------------\n  virtual bool open( void ) { return false; }\n  virtual bool read( std::vector<double>& q ) { return false; }\n  virtual bool write( const std::vector<double>& u ) { return false; }\n  virtual void reset( void ) { }\n\n  virtual bool read_ke( double& ke ) { return false; }\n\npublic:\n  static unsigned long compute_prey_command_seed( double time, double dtime );\n  static double compute_predator_time_randval( double time, double dtime );\n\n  // computes commands (forces) if the ship is prey\n  static void compute_prey_command( const std::vector<double>& pred_state, const std::vector<double>& prey_state, std::vector<double>& prey_u, const double& time, const double& dtime, space_c* space );\n\n  // normalizes the quaternion components of the state\n  static void renormalize_state_quat(std::vector<double>& q);\n\n  // compute the bounding box for the ship given a state\n  aabb_c aabb( const std::vector<double>& q );\n\n  // query whether a bounding box intersects another bounding box\n  //bool intersects_any_obstacle( const aabb_c& mybb, aabb_c& obstacle );\n\n  // query whether the ship intersects the world bounding box\n  bool intersects_world_bounds( const aabb_c& mybb );\n\n  // compute any force(field) that the boundary contributes to repel collision\n  static Ravelin::Vector3d boundary_force( space_c* space, const Ravelin::Vector3d& pos, const Ravelin::Vector3d& vel );\n\n  static Ravelin::SForced drag_force( Ravelin::SVelocityd& v, boost::shared_ptr<Ravelin::Pose3d> P_CoM );\n\n  // computes a repulsive force for a given distance\n  static double repulsive_force( double repulsion_factor, double dist );\n  static double flee_force( double repulsion_factor, double dist );\n\n  // - Feedback Control -\n  // compute the desired state based on the current command and current state\n  void compute_desired_state( const std::vector<double>& u, const std::vector<double>& x_current, std::vector<double>& x_desired );\n // computes the feedback command based on error in the current state\n  void compute_feedback( const std::vector<double>& x_current, std::vector<double>& x_desired, const std::vector<double>& u_current, std::vector<double>& u_feedback );\n\n  // - Dynamics -\n  // compute the inverse dynamics for the ship \n  static void inv_dyn( space_c* space,  const std::vector<double>& q, const std::vector<double>& qdot_des, std::vector<double>& u, const Ravelin::SpatialRBInertiad& inertial );\n\n  // ordinary differential equations for the ship\n  static void ode( space_c* space, const std::vector<double>& q, const std::vector<double>& u, std::vector<double>& dq, const Ravelin::SpatialRBInertiad& inertial );\n\n  // - OMPL --\n  // plans using the ompl rrt planner\n  //bool plan_rrt( const std::vector<double>& pred_q, const std::vector<double>& prey_q, std::vector<double>& u );\n\n  bool compute_predator_plan( const std::vector<double>& pred_q, const std::vector<double>& prey_q, std::vector< std::vector<double> >& us, std::vector<double>& durations, unsigned& control_count );\n\n // the reference to the statespace the planner has generated\n  ompl::base::StateSpace *_statespace;\n\n  // query whether or not the state generated by the planner is valid \n  bool is_state_valid(const ompl::control::SpaceInformation *si, const ompl::base::State *state);\n\n  // allocates the predator/prey control sampler for the planner\n  ompl::control::DirectedControlSamplerPtr allocate_pp_control_sampler( const ompl::control::SpaceInformation* si );\n\n  // ode.  called by the eular_integrator_c in integrator.h\n  void operator()( const ompl::base::State* state, const ompl::control::Control* control, std::vector<double>& dstate, const Ravelin::SpatialRBInertiad& inertial ) const;\n\n  // post integration update method\n  void update( ompl::base::State* state, const std::vector<double>& dstate ) const;\n\n  static double compute_distance( const std::vector<double>& pred_state, const std::vector<double>& prey_state );\n\n  private:\n    void get_predator_control(const std::vector<double>& last_pred_q, const std::vector<double>& new_prey_q, const Ravelin::SpatialRBInertiad& predJ, space_c* space, double DT, std::vector<double>& u);\n    void integrate_prey(const std::vector<double>& prey_q, const std::vector<double>& pred_q, const Ravelin::SpatialRBInertiad& Jprey, double time, space_c* space, double DT, std::vector<double>& qnew);\n    void integrate_predator(const std::vector<double>& q, const std::vector<double>& u, const Ravelin::SpatialRBInertiad& J, space_c* space, double DT, std::vector<double>& qnew);\n};\n\n#endif // _PURSUIT_SHIP_H_\n", "meta": {"hexsha": "8ca763bf9d895e23c0744960700e1f02c331c69a", "size": 7017, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/pursuit/ship.h", "max_stars_repo_name": "PositronicsLab/tcs", "max_stars_repo_head_hexsha": "c43bc3244b3c68cd1b42358afd18d5a0716d3e0f", "max_stars_repo_licenses": ["Apache-2.0"], "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/pursuit/ship.h", "max_issues_repo_name": "PositronicsLab/tcs", "max_issues_repo_head_hexsha": "c43bc3244b3c68cd1b42358afd18d5a0716d3e0f", "max_issues_repo_licenses": ["Apache-2.0"], "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/pursuit/ship.h", "max_forks_repo_name": "PositronicsLab/tcs", "max_forks_repo_head_hexsha": "c43bc3244b3c68cd1b42358afd18d5a0716d3e0f", "max_forks_repo_licenses": ["Apache-2.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.2764705882, "max_line_length": 202, "alphanum_fraction": 0.6481402309, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3570959370765473}}
{"text": "/*! \\file interp.h\n    \\brief Functions for interpolation to initialize the root solver\n */\n\n// used by the gsl interpolation functions\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_sort_double.h>\n\n#ifndef REAL_TYPEDEF\n#define REAL_TYPEDEF\n#ifndef single\t\t\t// compiler option determines variable size\ntypedef double REAL;\n#else\ntypedef float REAL;\n#endif\n#endif\n\n#define N_INTERP_POINTS 3\n#define NEAREST_TOL 1.0e-3\n\n#define MIN_IDX(indices,values) ((values[0] < values[1]) ? indices[0]:indices[1])\n#define DISTANCE(x1,y1,x2,y2) hypot(x1-x2,y1-y2)\n#define MAXIMUM(x,y) ((x) > (y) ? (x) : (y))\n\n\n\n// interpolation functions\nREAL interpBetw2ptsDist(REAL distx_x0,REAL f0,REAL f1,REAL distx1_x0);\nint cartesianToCylindrical(int npts,REAL R[],REAL Z[],REAL zeta[],REAL x[],REAL y[],REAL z[]);\nint interp2d(int nx,int nxi,REAL x[],REAL y[],REAL z[],REAL w[],REAL xi[],REAL yi[],REAL zi[],REAL wi[]);\nint find_nearestn(int nclosest,int nx,int nxi,size_t idx_closest[nx][nclosest],REAL x[],REAL y[],REAL xi[],REAL yi[]);\nint calc_slopes(double mx[],double my[],size_t idxs[],double x[],double y[],double z[]);\n\n// legacy functions used by previous versions of the root finder\nint interp(REAL y[],REAL xi[],REAL si[],int ny,int nxi);\nint interpxy(REAL x[],REAL y[],REAL xi[],REAL yi[],int nx,int nxi);\nint interpgsl(REAL x[],REAL y[],REAL xi[],REAL yi[],int nx,int nxi);\nint find_nearest(int nx,int xirows,int xicols,int xi_idx_below[],int yi_idx_below[],REAL x[],REAL y[],REAL xi[][xicols],REAL yi[][xicols]);\nint interpReg2d(int nx,int xirows,int xicols,REAL x[],REAL y[],REAL z[],REAL w[],REAL xi[][xicols],REAL yi[][xicols],REAL zi[][xicols],REAL wi[][xicols]);\n\n\n// ---  local function definitions\n\n//! Linear interpolation using two points to a third point\n/*! Uses the distance between the two known points ``distx1_x0'' = (x1-x0),\n    the distance between the unknown point to a known point ``distx_x0'' = (x-x0),\n    and the values of the function at x1 and x0 (f1 = f(x1),f2 = f(x2)),\n    to find the value at x: f= f(x).\n */\nREAL interpBetw2ptsDist(REAL distx_x0,REAL f0,REAL f1,REAL distx1_x0){\n  REAL f = (f1-f0)/distx1_x0*distx_x0 + f0;\n  return f;\n}\n\n//! Converts cartesian coordinates (x,y,z) to cylindrical coordinates (R,Z,zeta)\nint cartesianToCylindrical(int npts,REAL R[],REAL Z[],REAL zeta[],REAL x[],REAL y[],REAL z[]){\n  int i;\n  for(i=0;i<npts;i++){\n    R[i]=hypot(x[i],z[i]);\n    Z[i]=y[i];\n    zeta[i]=-atan2(z[i],x[i]);\t// negative because in forming right-hand coord system\n  }                               //  x: radially out, y: vertically up, z: toroidal\n                                  //  esi routines give theta going clockwise,\n                                  //  a: out in minor radius, gives z and theta antiparallel\n\n  return 0;\n}\n\n\n\n//! Finds the nearest n points on a grid of (xi,yi) for each point (x,y)\nint find_nearestn(int nclosest,int nx,int nxi,size_t idx_closest[nx][nclosest],REAL x[],REAL y[],REAL xi[],REAL yi[]){\n  double dist[nxi],d01,d02,d12,hyp;\n  int point,i,n_temp;\n  size_t *closest_pts;\n  size_t *idx_closest_pt;\n\n#if DEBUG\n  fprintf(stderr,\"point,   d01,    d02,   d12,    hyp,    collinear\\n\");\n#endif\n\n  for(point=0;point<nx;point++){\t\t// loop for each x,y\n\n    for(i=0;i<nxi;i++){\t// find the distance between (x,y) and all the (xi,yi)\n      //      dist[i]=sqrt((x[point]-xi[i])*(x[point]-xi[i])+(y[point]-yi[i])*(y[point]-yi[i]));\n      dist[i]=DISTANCE(x[point],y[point],xi[i],yi[i]);\n    }\n    idx_closest_pt=idx_closest[point];\n    gsl_sort_smallest_index(idx_closest_pt,nclosest,dist,1,nxi);// find the nearest xi\n\n    // make sure they aren't collinear\n    d01=DISTANCE(xi[idx_closest_pt[0]],yi[idx_closest_pt[0]],xi[idx_closest_pt[1]],yi[idx_closest_pt[1]]);\n    d02=DISTANCE(xi[idx_closest_pt[0]],yi[idx_closest_pt[0]],xi[idx_closest_pt[2]],yi[idx_closest_pt[2]]);\n    d12=DISTANCE(xi[idx_closest_pt[1]],yi[idx_closest_pt[1]],xi[idx_closest_pt[2]],yi[idx_closest_pt[2]]);\n    //    hyp = fmax(fmax(d01,d02),d12);\n    hyp = MAXIMUM(MAXIMUM(d01,d02),d12);\n    n_temp = nclosest;\n    while((d01+d02+d12-2.0*hyp < NEAREST_TOL) && (nclosest < nxi)){ // loop until the points aren't collinear\n      n_temp++;\n      closest_pts = (size_t *)malloc(sizeof(size_t)*n_temp);\n      gsl_sort_smallest_index(closest_pts,n_temp,dist,1,nxi);// find the nearest xi\n      idx_closest_pt[2]=closest_pts[n_temp-1];\n      d02=DISTANCE(xi[idx_closest_pt[0]],yi[idx_closest_pt[0]],xi[idx_closest_pt[2]],yi[idx_closest_pt[2]]);\n      d12=DISTANCE(xi[idx_closest_pt[1]],yi[idx_closest_pt[1]],xi[idx_closest_pt[2]],yi[idx_closest_pt[2]]);\n      //hyp = fmax(fmax(d01,d02),d12);\n      hyp = MAXIMUM(MAXIMUM(d01,d02),d12);\n\n      free(closest_pts);\n    }\n#if DEBUG\n    fprintf(stderr,\"%d, %g, %g, %g, %g, %g\\n\",point,d01,d02,d12,hyp,2.0*hyp-d01-d02-d12);\n#endif\n\t\n  }\n    //   for(i=0;i<xirows*xicols;i++){\n    //     fprintf(stderr,\"xi       yi\\n\");\n    //   fprintf(stderr,\"%g, %g\\n\",xi[0][i],yi[0][i]);\n    //   }\n    //   for(i=0;i<nx;i++){\n    //     fprintf(stderr,\"x,      xi_below,      y,    ,yi_below\\n\");\n    //     fprintf(stderr,\"%g, %g, %g, %g\\n\",x[i],xi[xi_idx_below[i]][0],y[i],yi[0][yi_idx_below[i]]);\n    //   }\n\n\n    return 0;\n }\n\n\n  //! Calculates the slopes (mx,my) for three points (x,y) which each have function value z\n  /*! these three points are have the indices idxs */\n  int calc_slopes(double mx[],double my[],size_t idxs[],double x[],double y[],double z[]){\n    size_t i,ip1,ip2,j,jp1,jp2;\n    double dx[N_INTERP_POINTS],dy[N_INTERP_POINTS],dz[N_INTERP_POINTS];\n\n    for(j=0;j<N_INTERP_POINTS;j++){\n      ip1 = idxs[(size_t)fmod(j+1,N_INTERP_POINTS)];\n      ip2 = idxs[(size_t)fmod(j+2,N_INTERP_POINTS)];\n      dx[j] = x[ip1]-x[ip2];\n      dy[j] = y[ip1]-y[ip2];\n      dz[j] = z[ip1]-z[ip2];\n    }\n    for(j=0;j<N_INTERP_POINTS;j++){\n      jp1 = (size_t)fmod(j+1,N_INTERP_POINTS);\n      jp2 = (size_t)fmod(j+2,N_INTERP_POINTS);\n      i = idxs[j];\n      ip1 = idxs[jp1];\n      ip2 = idxs[jp2];\n      mx[j] = -1.0*(y[i]*dz[j]+y[ip1]*dz[jp1]+y[ip2]*dz[jp2]);\n      mx[j]/=(x[i]*dy[j]+x[ip1]*dy[jp1]+x[ip2]*dy[jp2]);\n      my[j] = -1.0*(x[i]*dz[j]+x[ip1]*dz[jp1]+x[ip2]*dz[jp2]);\n      my[j]/=(y[i]*dx[j]+y[ip1]*dx[jp1]+y[ip2]*dx[jp2]);\n    }\n\n\n\n    return 0;\n  }\n\n//! High-level 2d interpolation function\n/*! Given values zi = f(xi,yi) and wi = g(xi,yi) on an arbitrary, irregular grid (xi,yi)\n    finds the values at (x,y).\n    The method is to find the nearest 3 grid points for each (x,y), then linearly interpolate (triangulation).\n */\n  int interp2d(int nx,int nxi,REAL x[],REAL y[],REAL z[],REAL w[],REAL xi[],REAL yi[],REAL zi[],REAL wi[]){\n    int point;\n    size_t *idxs;\n    double mxi[N_INTERP_POINTS],myi[N_INTERP_POINTS],a,b,c;\n\n    // find the indices of the 3 (xi,yi) closest to x,y\n    size_t idx_closest[nx][N_INTERP_POINTS];\n    find_nearestn(N_INTERP_POINTS,nx,nxi,idx_closest,x,y,xi,yi);\n\n    // loop around points\n    for(point=0;point<nx;point++){\n      idxs = idx_closest[point];\n      // first get z\n      // calculate the slopes (mx,my) for the nearest 3 points\n      calc_slopes(mxi,myi,idxs,xi,yi,zi);\n      // linear interp at each nearest point\n      a = zi[idxs[0]] + mxi[0]*(x[point]-xi[idxs[0]]) + myi[0]*(y[point]-yi[idxs[0]]);\n      b = zi[idxs[1]] + mxi[1]*(x[point]-xi[idxs[1]]) + myi[1]*(y[point]-yi[idxs[1]]);\n      c = zi[idxs[2]] + mxi[2]*(x[point]-xi[idxs[2]]) + myi[2]*(y[point]-yi[idxs[2]]);\n      // average to get the best guess\n      z[point] = (a+b+c)/3.0;\n\n      // next get w\n      // calculate the slopes (mx,my) for the nearest 3 points\n      calc_slopes(mxi,myi,idxs,xi,yi,wi);\n      // linear interp at each nearest point\n      a = wi[idxs[0]] + mxi[0]*(x[point]-xi[idxs[0]]) + myi[0]*(y[point]-yi[idxs[0]]);\n      b = wi[idxs[1]] + mxi[1]*(x[point]-xi[idxs[1]]) + myi[1]*(y[point]-yi[idxs[1]]);\n      c = wi[idxs[2]] + mxi[2]*(x[point]-xi[idxs[2]]) + myi[2]*(y[point]-yi[idxs[2]]);\n      // average to get the best guess\n      w[point] = (a+b+c)/3.0;\n\n    }\n\n    return 0;\n  }\n\n// --- legacy functions\n\nint interp(REAL y[],REAL xi[],REAL si[],int ny,int nxi){\n  int i,j;\n  //  printf(\"interp:\\n%10s,%10s,%10s,%10s,%10s\\n\",\"q_orig\",\"q_final\",\"q_i\",\"q_i+1\",\"s_i\");\n  for(i=0;i<ny;i++){\n    for(j=0;j<nxi-1;j++) if(xi[j+1] > y[i]) break;\n    //printf(\"%10g,\",y[i]);\n    y[i] = xi[j] + si[j]*(y[i]-xi[j]);\n    //printf(\"%10g,%10g,%10g,%10g\\n\",y[i],xi[j],xi[j+1],si[j]);\n  }\n  return 0;\n}\n\nint interpxy(REAL x[],REAL y[],REAL xi[],REAL yi[],int nx,int nxi){\n  int i,j;\n  REAL si[nxi-1];\n  // use linear interpolation\n  //printf(\"\\nstheta:\");\n  for(i=0;i<nxi-1;i++){\n    si[i] = (yi[i+1]-yi[i])/(xi[i+1]-xi[i]);\n    //printf(\"%g,\",si[i]);\n  }\n  si[nxi-2] = si[0];\n  //printf(\"\\n\");\n\n  //printf(\"interp:\\n%10s,%10s,%10s,%10s,%10s\\n\",\"q_orig\",\"q_final\",\"q_i\",\"q_i+1\",\"s_i\");\n  for(i=0;i<nx;i++){\n    for(j=0;j<nxi-1;j++) if(xi[j+1] > x[i]) break;\n    //printf(\"%10g,\",x[i]);\n    y[i] = yi[j] + si[j]*(x[i]-xi[j]);\n    //printf(\"%10g,%10g,%10g,%10g\\n\",y[i],xi[j],xi[j+1],si[j]);\n  }\n\n  return 0;\n}\n\n// interpolate the array x[] of size nx\n// on the grid xi[],y[i] of size nxi\nint interpgsl(REAL x[],REAL y[],REAL xi[],REAL yi[],int nx,int nxi){\n  // make sure periodic\n  //  yi[nxi-1]=yi[0];\n  // xi[nxi-1]=-xi[0];\n  gsl_interp_accel *acc = gsl_interp_accel_alloc ();\n  const gsl_interp_type *t = gsl_interp_cspline;\n  gsl_spline *spline = gsl_spline_alloc (t, nxi);\n\n  int i;\n  gsl_spline_init (spline, xi, yi, nxi);\n  //printf(\"\\ninterpgsl:\\n\");\n  for (i = 0; i < nx; i++)\n    {\n      y[i] = gsl_spline_eval (spline, x[i], acc);\n      //printf (\"%g, %g\\n\", x[i], y[i]);\n    }\n\n  gsl_spline_free (spline);\n  gsl_interp_accel_free (acc);\n\n  return 0;\n}\n\nint find_nearest1d(int nx,int nxi,int nnearest,int stride,size_t xi_idx[nx][nnearest],REAL x[],REAL xi[]){\n  int i,j;\n  REAL xerr[nxi];\n  for(i=0;i<nx;i++){\n    for(j=0;j<nxi;j++){\n      xerr[j]=fabs(x[i]-xi[j*stride]);\n    }\n    gsl_sort_smallest_index(xi_idx[i],nnearest,xerr,stride,nxi);// find the n nearest xi\n  }\n\n  return 0;\n}\n\n\n// xi varies slowly (each row), yi varies quickly (each col)\nint find_nearest(int nx,int xirows,int xicols,int xi_idx_below[],int yi_idx_below[],REAL x[],REAL y[],REAL xi[][xicols],REAL yi[][xicols]){\n  size_t nearest2_idxs[2];\n  double nearest2_vals[2],xerr[xirows],yerr[xirows];\n  int i,j;\n\n  for(i=0;i<nx;i++){\t\t// loop for each x,y\n\n    for(j=0;j<xirows;j++){\t// find the error between x and all the xi\n      xerr[j]=fabs(x[i]-xi[j][0]);\n    }\n    gsl_sort_smallest_index(nearest2_idxs,2,xerr,1,xirows);// find the two nearest xi\n    nearest2_vals[0] = xi[nearest2_idxs[0]][0];\n    nearest2_vals[1] = xi[nearest2_idxs[1]][0];\n    xi_idx_below[i] = MIN_IDX(nearest2_idxs,nearest2_vals); // this is the nearest xi less than x\n\n    for(j=0;j<xicols;j++){\t// find the error between y and all the yi\n      yerr[j]=fabs(y[i]-yi[0][j]);\n    }\n    gsl_sort_smallest_index(nearest2_idxs,2,yerr,1,xicols);// find the two nearest yi\n    nearest2_vals[0] = yi[0][nearest2_idxs[0]];\n    nearest2_vals[1] = yi[0][nearest2_idxs[1]];\n    yi_idx_below[i] = MIN_IDX(nearest2_idxs,nearest2_vals); // this is the nearest yi less than y\n  }\n\n  return 0;\n}\n\n// limitation: assumes regularly-spaced grids xi and yi\nint interpReg2d(int nx,int xirows,int xicols,REAL x[],REAL y[],REAL z[],REAL w[],REAL xi[][xicols],REAL yi[][xicols],REAL zi[][xicols],REAL wi[][xicols]){\n  int i,j;\n\n  // form the matrix of of slopes for y interpolation\n  double slopeziyi[xirows][xicols-1],slopewiyi[xirows][xicols-1];\n  double invdi;\n  for(i=0;i<xirows;i++){\n    for(j=0;j<xicols-1;j++){\n      invdi = 1.0/(yi[i][j+1]-yi[i][j]);\n      slopeziyi[i][j] = (zi[i][j+1]-zi[i][j])*invdi;\n      slopewiyi[i][j] = (wi[i][j+1]-wi[i][j])*invdi;\n    }\n  }\n\n  // find the indices of the nearest points (xi[i],yi[j]); note always exists (xi[i+1],yi[j+1])\n  int xi_idx_below[nx],yi_idx_below[nx];\n  find_nearest(nx,xirows,xicols,xi_idx_below,yi_idx_below,x,y,xi,yi);\n\n  // for fixed x, interpolate in y\n  double a,b,dist_y_yi,x_frac;\n  for(i=0;i<nx;i++){\n    dist_y_yi=y[i]-yi[0][yi_idx_below[i]];\n    x_frac = (x[i]-xi[xi_idx_below[i]][0])/(xi[xi_idx_below[i]+1][0]-xi[xi_idx_below[i]][0]);\n\n    // compute z[i]\n    // for fixed xi = i, interpolate in y between yi[j] and yi[j+1]\n    a = slopeziyi[xi_idx_below[i]][yi_idx_below[i]]*dist_y_yi + zi[xi_idx_below[i]][yi_idx_below[i]];\n    // for fixed xi = i+1, interpolate in y between yi[j] and yi[j+1]\n    b = slopeziyi[xi_idx_below[i]+1][yi_idx_below[i]]*dist_y_yi + zi[xi_idx_below[i]+1][yi_idx_below[i]];\n    // now interpolate in x between xi[i] and xi[i+1]\n    z[i] = (b-a)*x_frac + a;\n\n    // compute w[i]\n    // for fixed xi = i, interpolate in y between yi[j] and yi[j+1]\n    a = slopewiyi[xi_idx_below[i]][yi_idx_below[i]]*dist_y_yi + wi[xi_idx_below[i]][yi_idx_below[i]];\n    // for fixed xi = i+1, interpolate in y between yi[j] and yi[j+1]\n    b = slopewiyi[xi_idx_below[i]+1][yi_idx_below[i]]*dist_y_yi + wi[xi_idx_below[i]+1][yi_idx_below[i]];\n    // now interpolate in x between xi[i] and xi[i+1]\n    w[i] = (b-a)*x_frac + a;\n\n  }\n\n  return 0;\n}\n\n\n\n", "meta": {"hexsha": "21cfc1616cd0269155cfc0ccb62bc9772f9ec341", "size": 13095, "ext": "h", "lang": "C", "max_stars_repo_path": "src/python2/sdp/plasma/gts/C_src/interp.h", "max_stars_repo_name": "LeiShi/Synthetic-Diagnostics-Platform", "max_stars_repo_head_hexsha": "870120d3fd14b2a3c89c6e6e85625d1e9109a2de", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T22:08:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T02:47:05.000Z", "max_issues_repo_path": "src/python2/sdp/plasma/gts/C_src/interp.h", "max_issues_repo_name": "justthepython/Synthetic-Diagnostics-Platform", "max_issues_repo_head_hexsha": "5f1cb5c29d182490acbd4f3c167f0e09ec211236", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-05-11T12:58:00.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-11T17:18:36.000Z", "max_forks_repo_path": "src/python2/sdp/plasma/gts/C_src/interp.h", "max_forks_repo_name": "justthepython/Synthetic-Diagnostics-Platform", "max_forks_repo_head_hexsha": "5f1cb5c29d182490acbd4f3c167f0e09ec211236", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-04-29T12:35:59.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-10T03:38:30.000Z", "avg_line_length": 36.9915254237, "max_line_length": 154, "alphanum_fraction": 0.6171821306, "num_tokens": 4539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.357091485863527}}
{"text": "//CELL (~soma) stage: IIR filtering of each row or col of X according to dim.\n//The IIR filters are specified by an Nx(Q+1) or (Q+1)xN matrix A,\n//where Q is the IIR filter order (Q=0 means only a0; Q=1 means a0 and a1; etc.).\n\n//The calling program must ensure that the sizes are correct, the filter is stable, etc.\n\n//I just started this... finish later!! (Or skip.)\n\n#include <stdio.h>\n#include <cblas.h>\n\n#ifdef __cplusplus\nnamespace ov {\nextern \"C\" {\n#endif\n\nint iir_s (float *Y, const float *X, const float *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim);\nint iir_d (double *Y, const double *X, const double *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim);\nint iir_c (float *Y, const float *X, const float *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim);\nint iir_z (double *Y, const double *X, const double *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim);\n\nint iir_inplace_s (float *X, const float *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim);\nint iir_inplace_d (double *X, const double *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim);\nint iir_inplace_c (float *X, const float *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim);\nint iir_inplace_z (double *X, const double *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim);\n\n\nint iir_inplace_s (float *X, const float *A, const size_t N, const size_t T, const int Q, const char iscolmajor, const size_t dim)\n{\n    const size_t M = Q - 1;\n    int n, t;\n\n    //Checks\n    if (N<1) { fprintf(stderr,\"error in iir_s: N (num neurons) must be positive\\n\"); return 1; }\n    if (T<1) { fprintf(stderr,\"error in iir_s: T (num time points) must be positive\\n\"); return 1; }\n    if (Q<0) { fprintf(stderr,\"error in iir_s: Q (filter order) must be nonnegative\\n\"); return 1; }\n\n    if (N==1u)\n    {\n        if (A[0]!=1.0f) { cblas_sscal((int)T,1.0f/A[0],A,1); cblas_sscal((int)(N*T),1.0f/A[0],X,1); }\n        for (size_t t=1; t<M; ++t) { X[t] -= cblas_sdot(t,&A[M-t],1,&X[0],1); }\n        for (size_t t=M; t<T; ++t) { X[t] -= cblas_sdot(M,&A[0],1,&X[t-M],1); }\n    }\n    else if (dim==0u)\n    {\n        if (N<3)\n        {\n            if (iscolmajor)\n            {\n                for (size_t n=0u; n<N; ++n)\n                {\n                    if (A[n*Q1]!=1.0f) { cblas_sscal((int)T,1.0f/A[n*Q1],&A[n*Q1],1); }\n                }\n                for (size_t n=1; n<M; ++n)\n                {\n                    X[n] -= cblas_sdot(n,&A[M-n],1,&X[0],1);\n                    X[n+R] -= cblas_sdot(n,&A[M-n],1,&X[R],1);\n                }\n                for (size_t n=M; n<R; ++n)\n                {\n                    X[n] -= cblas_sdot(M,&A[0],1,&X[n-M],1);\n                    X[n+R] -= cblas_sdot(M,&A[0],1,&X[n-M+R],1);\n                }\n            }\n            else\n            {\n                for (size_t n=1; n<M; ++n)\n                {\n                    X[n*C] -= cblas_sdot(n,&A[M-n],1,&X[0],(int)C);\n                    X[1+n*C] -= cblas_sdot(n,&A[M-n],1,&X[1],(int)C);\n                }\n                for (size_t n=M; n<R; ++n)\n                {\n                    X[n*C] -= cblas_sdot(M,&A[0],1,&X[(n-M)*C],(int)C);\n                    X[1+n*C] -= cblas_sdot(M,&A[0],1,&X[1+(n-M)*C],(int)C);\n                }\n            }\n        }\n        else\n        {\n            if (iscolmajor)\n            {\n                for (size_t n=1; n<M; ++n) { cblas_sgemv(CblasColMajor,CblasTrans,n,(int)C,-1.0f,&X[0],(int)R,&A[M-n],1,1.0f,&X[n],(int)R); }\n                for (size_t n=M; n<R; ++n) { cblas_sgemv(CblasColMajor,CblasTrans,M,(int)C,-1.0f,&X[n-M],(int)R,&A[0],1,1.0f,&X[n],(int)R); }\n            }\n            else\n            {\n                for (size_t n=1; n<M; ++n) { cblas_sgemv(CblasRowMajor,CblasTrans,n,(int)C,-1.0f,&X[0],(int)C,&A[M-n],1,1.0f,&X[n*C],1); }\n                for (size_t n=M; n<R; ++n) { cblas_sgemv(CblasRowMajor,CblasTrans,M,(int)C,-1.0f,&X[(n-M)*C],(int)C,&A[0],1,1.0f,&X[n*C],1); }\n            }\n        }\n    }\n    else if (dim==1u)\n    {\n        if (R==1)\n        {\n            for (size_t n=1; n<M; ++n) { X[n] -= cblas_sdot(n,&A[M-n],1,&X[0],1); }\n            for (size_t n=M; n<C; ++n) { X[n] -= cblas_sdot(M,&A[0],1,&X[n-M],1); }\n        }\n        else if (R==2)\n        {\n            if (iscolmajor)\n            {\n                for (size_t n=1; n<M; ++n)\n                {\n                    X[n*R] -= cblas_sdot(n,&A[M-n],1,&X[0],(int)R);\n                    X[1+n*R] -= cblas_sdot(n,&A[M-n],1,&X[1],(int)R);\n                }\n                for (size_t n=M; n<C; ++n)\n                {\n                    X[n*R] -= cblas_sdot(M,&A[0],1,&X[(n-M)*R],(int)R);\n                    X[1+n*R] -= cblas_sdot(M,&A[0],1,&X[1+(n-M)*R],(int)R);\n                }\n            }\n            else\n            {\n                for (size_t n=1; n<M; ++n)\n                {\n                    X[n] -= cblas_sdot(n,&A[M-n],1,&X[0],1);\n                    X[n+C] -= cblas_sdot(n,&A[M-n],1,&X[C],1);\n                }\n                for (size_t n=M; n<C; ++n)\n                {\n                    X[n] -= cblas_sdot(M,&A[0],1,&X[n-M],1);\n                    X[n+C] -= cblas_sdot(M,&A[0],1,&X[n-M+C],1);\n                }\n            }\n        }\n        else\n        {\n            if (iscolmajor)\n            {\n                for (size_t n=1; n<M; ++n) { cblas_sgemv(CblasColMajor,CblasNoTrans,(int)R,n,-1.0f,&X[0],(int)R,&A[M-n],1,1.0f,&X[n*R],1); }\n                for (size_t n=M; n<C; ++n) { cblas_sgemv(CblasColMajor,CblasNoTrans,(int)R,M,-1.0f,&X[(n-M)*R],(int)R,&A[0],1,1.0f,&X[n*R],1); }\n            }\n            else\n            {\n                for (size_t n=1; n<M; ++n) { cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)R,n,-1.0f,&X[0],(int)C,&A[M-n],1,1.0f,&X[n],(int)C); }\n                for (size_t n=M; n<C; ++n) { cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)R,M,-1.0f,&X[n-M],(int)C,&A[0],1,1.0f,&X[n],(int)C); }\n            }\n        }\n    }\n    else\n    {\n        fprintf(stderr,\"error in iir_s: dim must be 0 or 1.\\n\"); return 1;\n    }\n\n    return 0;\n}\n\n\nint iir_d (double *X, const char iscolmajor, const size_t R, const size_t C, const double *A, const size_t N, const size_t dim)\n{\n    const size_t M = N - 1;\n    int n;\n\n    //Checks\n    if (R<1) { fprintf(stderr,\"error in iir_d: R (nrows X) must be positive\\n\"); return 1; }\n    if (C<1) { fprintf(stderr,\"error in iir_d: C (ncols X) must be positive\\n\"); return 1; }\n    if (N<1) { fprintf(stderr,\"error in iir_d: N (filter order) must be positive\\n\"); return 1; }\n\n    if (dim==0u)\n    {\n        if (C==1)\n        {\n            for (size_t n=1; n<M; ++n) { X[n] -= cblas_ddot(n,&A[M-n],1,&X[0],1); }\n            for (size_t n=M; n<R; ++n) { X[n] -= cblas_ddot(M,&A[0],1,&X[n-M],1); }\n        }\n        else if (C==2)\n        {\n            if (iscolmajor)\n            {\n                for (size_t n=1; n<M; ++n)\n                {\n                    X[n] -= cblas_ddot(n,&A[M-n],1,&X[0],1);\n                    X[n+R] -= cblas_ddot(n,&A[M-n],1,&X[R],1);\n                }\n                for (size_t n=M; n<R; ++n)\n                {\n                    X[n] -= cblas_ddot(M,&A[0],1,&X[n-M],1);\n                    X[n+R] -= cblas_ddot(M,&A[0],1,&X[n-M+R],1);\n                }\n            }\n            else\n            {\n                for (size_t n=1; n<M; ++n)\n                {\n                    X[n*C] -= cblas_ddot(n,&A[M-n],1,&X[0],(int)C);\n                    X[1+n*C] -= cblas_ddot(n,&A[M-n],1,&X[1],(int)C);\n                }\n                for (size_t n=M; n<R; ++n)\n                {\n                    X[n*C] -= cblas_ddot(M,&A[0],1,&X[(n-M)*C],(int)C);\n                    X[1+n*C] -= cblas_ddot(M,&A[0],1,&X[1+(n-M)*C],(int)C);\n                }\n            }\n        }\n        else\n        {\n            if (iscolmajor)\n            {\n                for (size_t n=1; n<M; ++n) { cblas_dgemv(CblasColMajor,CblasTrans,n,(int)C,-1.0,&X[0],(int)R,&A[M-n],1,1.0,&X[n],(int)R); }\n                for (size_t n=M; n<R; ++n) { cblas_dgemv(CblasColMajor,CblasTrans,M,(int)C,-1.0,&X[n-M],(int)R,&A[0],1,1.0,&X[n],(int)R); }\n            }\n            else\n            {\n                for (size_t n=1; n<M; ++n) { cblas_dgemv(CblasRowMajor,CblasTrans,n,(int)C,-1.0,&X[0],(int)C,&A[M-n],1,1.0,&X[n*C],1); }\n                for (size_t n=M; n<R; ++n) { cblas_dgemv(CblasRowMajor,CblasTrans,M,(int)C,-1.0,&X[(n-M)*C],(int)C,&A[0],1,1.0,&X[n*C],1); }\n            }\n        }\n    }\n    else if (dim==1u)\n    {\n        if (R==1)\n        {\n            for (size_t n=1; n<M; ++n) { X[n] -= cblas_ddot(n,&A[M-n],1,&X[0],1); }\n            for (size_t n=M; n<C; ++n) { X[n] -= cblas_ddot(M,&A[0],1,&X[n-M],1); }\n        }\n        else if (R==2)\n        {\n            if (iscolmajor)\n            {\n                for (size_t n=1; n<M; ++n)\n                {\n                    X[n*R] -= cblas_ddot(n,&A[M-n],1,&X[0],(int)R);\n                    X[1+n*R] -= cblas_ddot(n,&A[M-n],1,&X[1],(int)R);\n                }\n                for (size_t n=M; n<C; ++n)\n                {\n                    X[n*R] -= cblas_ddot(M,&A[0],1,&X[(n-M)*R],(int)R);\n                    X[1+n*R] -= cblas_ddot(M,&A[0],1,&X[1+(n-M)*R],(int)R);\n                }\n            }\n            else\n            {\n                for (size_t n=1; n<M; ++n)\n                {\n                    X[n] -= cblas_ddot(n,&A[M-n],1,&X[0],1);\n                    X[n+C] -= cblas_ddot(n,&A[M-n],1,&X[C],1);\n                }\n                for (size_t n=M; n<C; ++n)\n                {\n                    X[n] -= cblas_ddot(M,&A[0],1,&X[n-M],1);\n                    X[n+C] -= cblas_ddot(M,&A[0],1,&X[n-M+C],1);\n                }\n            }\n        }\n        else\n        {\n            if (iscolmajor)\n            {\n                for (size_t n=1; n<M; ++n) { cblas_dgemv(CblasColMajor,CblasNoTrans,(int)R,n,-1.0,&X[0],(int)R,&A[M-n],1,1.0,&X[n*R],1); }\n                for (size_t n=M; n<C; ++n) { cblas_dgemv(CblasColMajor,CblasNoTrans,(int)R,M,-1.0,&X[(n-M)*R],(int)R,&A[0],1,1.0,&X[n*R],1); }\n            }\n            else\n            {\n                for (size_t n=1; n<M; ++n) { cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)R,n,-1.0,&X[0],(int)C,&A[M-n],1,1.0,&X[n],(int)C); }\n                for (size_t n=M; n<C; ++n) { cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)R,M,-1.0,&X[n-M],(int)C,&A[0],1,1.0,&X[n],(int)C); }\n            }\n        }\n    }\n    else\n    {\n        fprintf(stderr,\"error in iir_d: dim must be 0 or 1.\\n\"); return 1;\n    }\n\n    return 0;\n}\n\n\nint iir_c (float *X, const char iscolmajor, const size_t R, const size_t C, const float *A, const size_t N, const size_t dim)\n{\n    const float a[2] = {-1.0f,0.0f}, b[2] = {1.0f,0.0f};\n    const size_t M = N - 1;\n    int n;\n\n    //Checks\n    if (R<1) { fprintf(stderr,\"error in iir_c: R (nrows X) must be positive\\n\"); return 1; }\n    if (C<1) { fprintf(stderr,\"error in iir_c: C (ncols X) must be positive\\n\"); return 1; }\n    if (N<1) { fprintf(stderr,\"error in iir_c: N (filter order) must be positive\\n\"); return 1; }\n\n    if (dim==0u)\n    {\n        if (iscolmajor)\n        {\n            for (size_t n=1; n<M; ++n) { cblas_cgemv(CblasColMajor,CblasTrans,n,(int)C,&a[0],&X[0],(int)R,&A[2*(M-n)],1,&b[0],&X[2*n],(int)R); }\n            for (size_t n=M; n<R; ++n) { cblas_cgemv(CblasColMajor,CblasTrans,M,(int)C,&a[0],&X[2*(n-M)],(int)R,&A[0],1,&b[0],&X[2*n],(int)R); }\n        }\n        else\n        {\n            for (size_t n=1; n<M; ++n) { cblas_cgemv(CblasRowMajor,CblasTrans,n,(int)C,&a[0],&X[0],(int)C,&A[2*(M-n)],1,&b[0],&X[2*n*C],1); }\n            for (size_t n=M; n<R; ++n) { cblas_cgemv(CblasRowMajor,CblasTrans,M,(int)C,&a[0],&X[2*(n-M)*C],(int)C,&A[0],1,&b[0],&X[2*n*C],1); }\n        }\n    }\n    else if (dim==1u)\n    {\n        if (iscolmajor)\n        {\n            for (size_t n=1; n<M; ++n) { cblas_cgemv(CblasColMajor,CblasNoTrans,(int)R,n,&a[0],&X[0],(int)R,&A[2*(M-n)],1,&b[0],&X[2*n*R],1); }\n            for (size_t n=M; n<C; ++n) { cblas_cgemv(CblasColMajor,CblasNoTrans,(int)R,M,&a[0],&X[2*(n-M)*R],(int)R,&A[0],1,&b[0],&X[2*n*R],1); }\n        }\n        else\n        {\n            for (size_t n=1; n<M; ++n) { cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)R,n,&a[0],&X[0],(int)C,&A[2*(M-n)],1,&b[0],&X[2*n],(int)C); }\n            for (size_t n=M; n<C; ++n) { cblas_cgemv(CblasRowMajor,CblasNoTrans,(int)R,M,&a[0],&X[2*(n-M)],(int)C,&A[0],1,&b[0],&X[2*n],(int)C); }\n        }\n    }\n    else\n    {\n        fprintf(stderr,\"error in iir_c: dim must be 0 or 1.\\n\"); return 1;\n    }\n\n    return 0;\n}\n\n\nint iir_z (double *X, const char iscolmajor, const size_t R, const size_t C, const double *A, const size_t N, const size_t dim)\n{\n    const double a[2] = {-1.0,0.0}, b[2] = {1.0,0.0};\n    const size_t M = N - 1;\n    int n;\n\n    //Checks\n    if (R<1) { fprintf(stderr,\"error in iir_z: R (nrows X) must be positive\\n\"); return 1; }\n    if (C<1) { fprintf(stderr,\"error in iir_z: C (ncols X) must be positive\\n\"); return 1; }\n    if (N<1) { fprintf(stderr,\"error in iir_z: N (filter order) must be positive\\n\"); return 1; }\n\n    if (dim==0u)\n    {\n        if (iscolmajor)\n        {\n            for (size_t n=1; n<M; ++n) { cblas_zgemv(CblasColMajor,CblasTrans,n,(int)C,&a[0],&X[0],(int)R,&A[2*(M-n)],1,&b[0],&X[2*n],(int)R); }\n            for (size_t n=M; n<R; ++n) { cblas_zgemv(CblasColMajor,CblasTrans,M,(int)C,&a[0],&X[2*(n-M)],(int)R,&A[0],1,&b[0],&X[2*n],(int)R); }\n        }\n        else\n        {\n            for (size_t n=1; n<M; ++n) { cblas_zgemv(CblasRowMajor,CblasTrans,n,(int)C,&a[0],&X[0],(int)C,&A[2*(M-n)],1,&b[0],&X[2*n*C],1); }\n            for (size_t n=M; n<R; ++n) { cblas_zgemv(CblasRowMajor,CblasTrans,M,(int)C,&a[0],&X[2*(n-M)*C],(int)C,&A[0],1,&b[0],&X[2*n*C],1); }\n        }\n    }\n    else if (dim==1u)\n    {\n        if (iscolmajor)\n        {\n            for (size_t n=1; n<M; ++n) { cblas_zgemv(CblasColMajor,CblasNoTrans,(int)R,n,&a[0],&X[0],(int)R,&A[2*(M-n)],1,&b[0],&X[2*n*R],1); }\n            for (size_t n=M; n<C; ++n) { cblas_zgemv(CblasColMajor,CblasNoTrans,(int)R,M,&a[0],&X[2*(n-M)*R],(int)R,&A[0],1,&b[0],&X[2*n*R],1); }\n        }\n        else\n        {\n            for (size_t n=1; n<M; ++n) { cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)R,n,&a[0],&X[0],(int)C,&A[2*(M-n)],1,&b[0],&X[2*n],(int)C); }\n            for (size_t n=M; n<C; ++n) { cblas_zgemv(CblasRowMajor,CblasNoTrans,(int)R,M,&a[0],&X[2*(n-M)],(int)C,&A[0],1,&b[0],&X[2*n],(int)C); }\n        }\n    }\n    else\n    {\n        fprintf(stderr,\"error in iir_z: dim must be 0 or 1.\\n\"); return 1;\n    }\n\n    return 0;\n}\n\n\n#ifdef __cplusplus\n}\n}\n#endif\n\n", "meta": {"hexsha": "70803d683e9474b510312a9d2f1b444d95b93675", "size": 14796, "ext": "c", "lang": "C", "max_stars_repo_path": "c/iir.c", "max_stars_repo_name": "erikedwards4/nn", "max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z", "max_issues_repo_path": "c/iir.c", "max_issues_repo_name": "erikedwards4/nn", "max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/iir.c", "max_forks_repo_name": "erikedwards4/nn", "max_forks_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7", "max_forks_repo_licenses": ["BSD-3-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.2065217391, "max_line_length": 146, "alphanum_fraction": 0.4530954312, "num_tokens": 5553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.35706473293954855}}
{"text": "#ifndef ALG_LOMV\n#define ALG_LOMV\n\n#include \"string.h\"\n#include \"assert.h\"\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_linalg.h>\n\ndouble linf(int d, gsl_vector * a, gsl_vector * b);\n\nvoid psi(int p, int q, gsl_vector * theta, gsl_matrix * B, gsl_matrix * V, gsl_vector * Delta, gsl_vector * x);\n\ngsl_vector * ffp(int p, int q, gsl_vector * theta, gsl_matrix * B, gsl_matrix * V, gsl_vector * Delta);\n\ngsl_vector * lo_minvar(int p, int q, gsl_matrix * B, gsl_matrix * V, gsl_vector * Delta);\n\ndouble * ffp_C_interface(int p, int q, double* theta, double** B, double** V, double* Delta);\n\ndouble* lo_minvar_C_interface(int p, int q, double**B, double** V, double* Delta);\n\ndouble* psi_C_interface(int p, int q, double**B, double** V, double* Delta);\n\n#endif\n", "meta": {"hexsha": "40812b81fb5785008b94a6a17504a5afb3873493", "size": 874, "ext": "h", "lang": "C", "max_stars_repo_path": "include/alg_lomv.h", "max_stars_repo_name": "alexbstl/ffp_minvar", "max_stars_repo_head_hexsha": "1ca18ea3f54583bf42ccdb79e0069b4190a0ac0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/alg_lomv.h", "max_issues_repo_name": "alexbstl/ffp_minvar", "max_issues_repo_head_hexsha": "1ca18ea3f54583bf42ccdb79e0069b4190a0ac0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/alg_lomv.h", "max_forks_repo_name": "alexbstl/ffp_minvar", "max_forks_repo_head_hexsha": "1ca18ea3f54583bf42ccdb79e0069b4190a0ac0e", "max_forks_repo_licenses": ["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.1379310345, "max_line_length": 111, "alphanum_fraction": 0.7059496568, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3569637649336057}}
{"text": "#ifndef TOPO_SL_H\n#define TOPO_SL_H\n\n#include <assert.h>\n\n#include <vector>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_spmatrix.h>\n#include <gsl/gsl_splinalg.h>\n\n#include <apf.h>\n#include <apfMDS.h>\n#include <apfMesh.h>\n#include <apfMesh2.h>\n\n#include <apfNumbering.h>\n#include <apfShape.h>\n\n#include \"topo_disp.h\"\n\n// Container for the gsl based linear solver:\nclass solv_kuprat {\n  private:\n    solv_kuprat(const solv_kuprat &obj);\n    solv_kuprat& operator=( const solv_kuprat& obj );\n  public:\n    apf::Mesh2* m;\n    field_calc* f_calc;\n\n    int n;\n    std::map<apf::MeshEntity*, int> v2id;\n    std::map<apf::MeshEntity*, bool> v_map;\n    std::map<int, apf::MeshEntity*> id2v;\n\n    std::vector<apf::MeshEntity*>* verts;\n\n    gsl_spmatrix* A;\n    gsl_spmatrix* C;\n    gsl_vector *f;\n    gsl_vector *u;\n\n    apf::GlobalNumbering* gn;\n\n    // Functions:\n    void numb_vert();\n    void numb_verts_in();\n    void dest_numb();\n    void add_forces(apf::MeshEntity* tri);\n\n    void collect_matrix_verts();\n    void collect_matrix();\n    void init(apf::Mesh2* m_in);\n    void init_verts(apf::Mesh2* m_in);\n    void clear();\n    double solve(const double tol);\n\n    solv_kuprat(apf::Mesh2* m, field_calc* f_calc_in);\n    solv_kuprat(apf::Mesh2* m, field_calc* f_calc_in, std::vector<apf::MeshEntity*>* verts);\n\n    ~solv_kuprat();\n\n    friend std::ostream& operator<<(std::ostream& s, const solv_kuprat& sl);\n\n};\n\n// Container for the gsl based linear solver:\nclass solv_kuprat_NBC {\n  private:\n    solv_kuprat_NBC(const solv_kuprat_NBC &obj);\n    solv_kuprat_NBC& operator=( const solv_kuprat_NBC& obj );\n  public:\n    apf::Mesh2* m;\n    field_calc* f_calc;\n\n    int n;\n    std::map<apf::MeshEntity*, int> v2id;\n    std::map<apf::MeshEntity*, bool> v_map;\n    std::map<int, apf::MeshEntity*> id2v;\n\n    std::map<apf::MeshEntity*, bool> v_sp;\n    std::vector<apf::MeshEntity*>* verts;\n\n    gsl_spmatrix* A;\n    gsl_spmatrix* C;\n    gsl_vector *f;\n    gsl_vector *u;\n\n    apf::GlobalNumbering* gn;\n\n    // Functions:\n    void numb_vert();\n    void numb_verts_in();\n    void dest_numb();\n    void add_forces(apf::MeshEntity* tri);\n\n    void collect_matrix_verts();\n    void collect_matrix();\n\n\t\tvoid process_ext_shell();\n\t\tvoid process_ext_shell_verts();\n\n    void init(apf::Mesh2* m_in);\n    void init_verts(apf::Mesh2* m_in);\n    void clear();\n    double solve(const double tol);\n\n    solv_kuprat_NBC(apf::Mesh2* m, field_calc* f_calc_in);\n    solv_kuprat_NBC(apf::Mesh2* m, field_calc* f_calc_in, std::vector<apf::MeshEntity*>* verts);\n\n    ~solv_kuprat_NBC();\n\n    friend std::ostream& operator<<(std::ostream& s, const solv_kuprat_NBC& sl);\n\n};\n#endif\n", "meta": {"hexsha": "1e3de8db16e1477610415da8c74352da799979dd", "size": 2736, "ext": "h", "lang": "C", "max_stars_repo_path": "src/topo_solvlin.h", "max_stars_repo_name": "erdemeren/VDlib", "max_stars_repo_head_hexsha": "23091adbea4ba26379eaf941be53d925304a0560", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/topo_solvlin.h", "max_issues_repo_name": "erdemeren/VDlib", "max_issues_repo_head_hexsha": "23091adbea4ba26379eaf941be53d925304a0560", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/topo_solvlin.h", "max_forks_repo_name": "erdemeren/VDlib", "max_forks_repo_head_hexsha": "23091adbea4ba26379eaf941be53d925304a0560", "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": 22.6115702479, "max_line_length": 96, "alphanum_fraction": 0.6670321637, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.3569637649336057}}
{"text": "#ifndef __INS_C_H__\n#define __INS_C_H__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Describe the INS Module On Board, Error equations based on Zipfel, Figure 10.27, space stabilized INS with GPS updates)\nLIBRARY DEPENDENCY:\n      ((../src/gnc_var.c)\n        (../src/Ins_c.c)\n        (../../cad/src/global_constants.c)\n        (../src/dm_delta_ut.c))\n*******************************************************************************/\n\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_vector.h>\n#include <math.h>\n#include <stdio.h>\n#include \"cad_utility_c.h\"\n#include \"math_utility_c.h\"\n#include \"time_utility_c.h\"\n\nextern const double __DM_sec2r;\nextern const double __DM_arcsec2r;\nextern const double __WEII3;\nextern const double __SMAJOR_AXIS;\nextern const double __GM;\nextern const double __WEII3;\nextern const double ___PI;\nextern const double __EPS;\nextern const double __DEG;\nextern const double __RAD;\n/** INS Variables **/\n/* Matrix */\nextern gsl_matrix *WEII;\nextern gsl_matrix *TBIC;\nextern gsl_matrix *TDCI;\nextern gsl_matrix *TEIC;\nextern gsl_matrix *TBDC;\nextern gsl_matrix *TBICI;\nextern gsl_matrix *TLI;\n\n/* Vector */\nextern gsl_vector *EVBI;\nextern gsl_vector *EVBID;\nextern gsl_vector *ESBI;\nextern gsl_vector *ESBID;\nextern gsl_vector *RICI;\nextern gsl_vector *RICID;\nextern gsl_vector *TBIC_Q;\nextern gsl_vector *TBIDC_Q;\nextern gsl_vector *SBIIC;\nextern gsl_vector *VBIIC;\nextern gsl_vector *SBEEC;\nextern gsl_vector *VBEEC;\nextern gsl_vector *WBICI;\nextern gsl_vector *EGRAVI;\nextern gsl_vector *VBECD;\nextern gsl_vector *INS_I_ATT_ERR;\nextern gsl_vector *TESTV;\nextern gsl_vector *TMP_old;\nextern gsl_vector *VBIIC_old;\nextern gsl_vector *POS_ERR;\nextern gsl_vector *GRAVGI;\nextern gsl_vector *TBDCQ;\nextern gsl_vector *VBIIC_old_old;\nextern gsl_vector *PHI_C;\nextern gsl_vector *DELTA_VEL_C;\nextern gsl_vector *PHI_LOW_C;\nextern gsl_vector *PHI_HIGH_C;\n\n/* Double */\nextern double dbic;\nextern double dvbec;\nextern double alphacx;\nextern double betacx;\nextern double thtvdcx;\nextern double psivdcx;\nextern double alppcx;\nextern double phipcx;\nextern double loncx;\nextern double latcx;\nextern double altc;\nextern double phibdcx;\nextern double thtbdcx;\nextern double psibdcx;\nextern double ins_pos_err;\nextern double ins_vel_err;\nextern double ins_tilt_err;\nextern double ins_pose_err;\nextern double ins_vele_err;\nextern double ins_phi_err;\nextern double ins_tht_err;\nextern double ins_psi_err;\n\n/* Unsigned int */\nextern unsigned int gpsupdate;\nextern unsigned int liftoff;\nextern unsigned int ideal;\n\nextern GPS_TIME gpstime;\nextern UTC_TIME utctime;\n/*******************/\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n    int load_location(double lonx, double latx, double alt);\n    int load_angle(double yaw, double roll, double pitch, GPS_TIME gps_time);\n    int load_geodetic_velocity(double alpha0x, double beta0x, double dvbe);\n    int calculate_INS_derived_TEI(GPS_TIME gps, gsl_matrix *TEIC);\n    int AccelHarmonic(const gsl_vector *SBII, double CS[21][21], int n_max, int m_max, const gsl_matrix *TEIC, gsl_vector *acc_out);\n    int DCM_2_Euler_angle(const gsl_matrix *TBD, double *phibdc, double *thtbdc, double *psibdc);\n    int calculate_INS_derived_phip(gsl_vector *VBECB, double *phipc);\n    int calculate_INS_derived_thtvd(gsl_vector *VBECD, double *thtvd);\n    int calculate_INS_derived_psivd(gsl_vector *VBECD, double *psivd);\n    int calculate_INS_derived_alpp(gsl_vector *VBECB, double *alpp);\n    int calculate_INS_derived_beta(gsl_vector *VBECB, double *beta);\n    int calculate_INS_derived_alpha(gsl_vector *VBECB, double *alpha);\n    int build_VBEB(double _alpha0x, double _beta0x, double _dvbe, gsl_vector *VBEB);\n    int INS_update(const double int_step, double *dvbec, unsigned int liftoff, double *alphacx, double *betacx\n                    , double *alppcx, double *phipcx, double *loncx, double *latcx, double *altc, double *psivdcx, double *thtvdcx\n                    , double *phibdc, double *thtbdc, double *psibdc\n                    , gsl_vector *PHI, gsl_vector *DELTA_VEL\n                    , gsl_vector *PHI_HIGH, gsl_vector *PHI_LOW, GPS_TIME gps, gsl_matrix *TEIC\n                    , gsl_vector *SBIIC, gsl_vector *VBIIC, gsl_vector *VBIIC_old, gsl_vector *GRAVGI, gsl_matrix *TBIC, gsl_vector *SBEEC\n                    , gsl_vector *VBEEC, gsl_matrix *WEII, gsl_matrix *TLI, gsl_matrix *TDCI\n                    , gsl_matrix *TBICI, gsl_matrix *TBDC, gsl_vector *TBDCQ);\n    int INS_init(GPS_TIME gps_time);\n    int INS_alloc();\n#ifdef __cplusplus\n}\n#endif\n#endif\n", "meta": {"hexsha": "f1fc4e904c6f0a96c65e1565e2db858bcf613323", "size": 4598, "ext": "h", "lang": "C", "max_stars_repo_path": "models/gnc/include/Ins_c.h", "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/gnc/include/Ins_c.h", "max_issues_repo_name": "cihuang123/Next-simulation", "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/gnc/include/Ins_c.h", "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T14:59:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:19:45.000Z", "avg_line_length": 34.5714285714, "max_line_length": 138, "alphanum_fraction": 0.7237929535, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.35692794501052194}}
{"text": "/*\n    Copyright (c) 2013, Taiga Nomi and the respective contributors\n    All rights reserved.\n\n    Use of this source code is governed by a BSD-style license that can be found\n    in the LICENSE file.\n*/\n#pragma once\n\n#include \"tiny_dnn/core/params/fully_params.h\"\n\n#ifdef CNN_USE_CBLAS\nextern \"C\" {\n#include <cblas.h>\n}\n#endif\n\nnamespace tiny_dnn {\nnamespace kernels {\n\ninline void fully_connected_op_cblas(const tensor_t &in_data,\n                                     const vec_t &W,\n                                     const vec_t &bias,\n                                     tensor_t &out_data,\n                                     const core::fully_params &params,\n                                     const bool layer_parallelize) {\n#ifdef CNN_USE_CBLAS\n  size_t out_size       = params.out_size_;\n  size_t in_size        = params.in_size_;\n  float_t alpha         = 1;\n  float_t beta          = 1;\n  const float_t *input  = in_data[0].data();\n  const float_t *weight = W.data();\n  float_t *output       = out_data[0].data();\n  if (bias.empty())\n    memset(output, 0, sizeof(float_t) * out_size);\n  else\n    memcpy(output, bias.data(), sizeof(float_t) * out_size);\n#ifdef CNN_USE_DOUBLE\n  cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1, out_size, in_size,\n              alpha, input, in_size, weight, out_size, beta, output, out_size);\n#else\n  cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1, out_size, in_size,\n              alpha, input, in_size, weight, out_size, beta, output, out_size);\n#endif\n\n#endif  // CNN_USE_CBLAS\n}\n\n}  // namespace kernels\n}  // namespace tiny_dnn\n", "meta": {"hexsha": "b9403e7ddc8a155ad515dd02bb48c1f6b6fe03fd", "size": 1603, "ext": "h", "lang": "C", "max_stars_repo_path": "tiny_dnn/core/kernels/fully_connected_op_cblas.h", "max_stars_repo_name": "tom01h/tiny-dnn", "max_stars_repo_head_hexsha": "4e6e151c464f47733e8f68c2b86dc32609d0c669", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "tiny_dnn/core/kernels/fully_connected_op_cblas.h", "max_issues_repo_name": "stillwater-sc/tiny-dnn", "max_issues_repo_head_hexsha": "ba452be4de67fa1d85d86f2425a3fa6e254205a4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "tiny_dnn/core/kernels/fully_connected_op_cblas.h", "max_forks_repo_name": "stillwater-sc/tiny-dnn", "max_forks_repo_head_hexsha": "ba452be4de67fa1d85d86f2425a3fa6e254205a4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 30.8269230769, "max_line_length": 80, "alphanum_fraction": 0.6169681847, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3568358405454589}}
{"text": "#ifndef _DSGLD_LDA_MODEL_H__\n#define _DSGLD_LDA_MODEL_H__\n\n#include <El.hpp>\n#include <gsl/gsl_rng.h>\n\n#include \"sgld_model.h\"\n\nusing std::string;\nusing std::vector;\n\nnamespace dsgld {\n\nclass LDAModel : public SGLDModel<double, int> {\n public:\n   LDAModel(\n       const El::Matrix<int>& X,\n       const int K,\n       const double alpha,\n       const double beta);\n\n  ~LDAModel() {};\n\n  El::Matrix<double> sgldEstimate(const El::Matrix<double>& theta) override;\n\n  El::Matrix<double> nablaLogPrior(const El::Matrix<double>& theta) const override;\n\n  void writePerplexities(const string& filename);\n\n  int NumGibbsSteps() const;\n  LDAModel* NumGibbsSteps(const int);\n\n protected:\n  void gibbsSample(\n      const El::Matrix<int>& doc,\n      const El::Matrix<double>& theta,\n      El::Matrix<int>& index_to_topic,\n      El::Matrix<int>& topic_counts) const;\n\n  double estimatePerplexity(\n      const El::Matrix<double>& theta,\n      const El::Matrix<double>& theta_sum_over_w,\n      const int num_words_in_doc,\n      const El::Matrix<int>& topic_counts) const;\n\n private:\n  const double alpha_;\n  const double beta_;\n  const int W;\n  const int K;\n  int numGibbsSteps_;\n  vector<double> perplexities_;\n  const gsl_rng* rng;\n};\n\n}  // namespace dsgld\n\n\n#endif  // _DSGLD_LDA_MODEL_H__\n\n", "meta": {"hexsha": "4302e04af7637837aad70ef5430057bec248a87a", "size": 1280, "ext": "h", "lang": "C", "max_stars_repo_path": "lda_model.h", "max_stars_repo_name": "feynmanliang/travelling-cluster-chain", "max_stars_repo_head_hexsha": "2442178679e8ec29ac8532205dd9640f546f87fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lda_model.h", "max_issues_repo_name": "feynmanliang/travelling-cluster-chain", "max_issues_repo_head_hexsha": "2442178679e8ec29ac8532205dd9640f546f87fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-04-20T05:06:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-20T05:06:53.000Z", "max_forks_repo_path": "lda_model.h", "max_forks_repo_name": "feynmanliang/travelling-cluster-chain", "max_forks_repo_head_hexsha": "2442178679e8ec29ac8532205dd9640f546f87fc", "max_forks_repo_licenses": ["Apache-2.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.9836065574, "max_line_length": 83, "alphanum_fraction": 0.690625, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.35679852250805627}}
{"text": "#ifndef __INTEGRAL_H__\n#define __INTEGRAL_H__\n#include \"integral.h\"\n#endif\n\n#ifndef __GSLEXTRA_H__\n#define __GSLEXTRA_H__\n#include \"../include/gslextra.h\"\n#endif\n\n#ifndef __GSLPRINT_H__\n#define __GSLPRINT_H__\n#include \"../include/gslprint.h\"\n#endif\n\n#include <gsl/gsl_eigen.h>\n\n// calculate the attraction energy matrix element (Z integral)\ndouble nuclear_attraction_energy_matrix_element(orbital * a, orbital * b, atomic_orbital * atom_HEAD);\n\n// calculate the single electron hamiltonian matrix (core hamiltonian matrix) element\ndouble single_electron_hamiltonian_matrix_element(orbital * a, orbital * b, atomic_orbital * atom_HEAD);\n\n// calculate the fock matrix element\ndouble fock_matrix_element(gsl_quad_tensor * v, gsl_matrix * density_matrix, gsl_matrix * h_matrix, int i, int j, int length);\n\n// calculate the Hartree-Fock energy of the system\ndouble HF_energy(gsl_quad_tensor * v, gsl_matrix * density_matrix, gsl_matrix * h_matrix, int length);\n\n// calculate the kinetic energy matrix \nvoid kinetic_energy_matrix(gsl_matrix * dest, orbital * HEAD, int length);\n\n// calculate the attraction energy matrix (Z integrals)\nvoid nuclear_attraction_energy_matrix(gsl_matrix * dest, orbital * HEAD, atomic_orbital * atom_HEAD, int length);\n\n// calculate the single electron hamiltonian matrix (core hamiltonian matrix)\nvoid core_hamiltonian_matrix(gsl_matrix * dest, orbital * HEAD, atomic_orbital * atom_HEAD, int length);\n\n//obtain the quad tensor of the two-electron Coulomb integrals \nvoid two_electron_quad_tensor(gsl_quad_tensor * dest, orbital * HEAD, int length);\n\n//obtain the fock matrix\nvoid fock_matrix(gsl_matrix * dest, gsl_quad_tensor * v, gsl_matrix * density_matrix, gsl_matrix * h_matrix, int length);\n\n// perform initial guess of the coefficient matrix by performing diagonalization of core hamiltonian matrix\nvoid initial_guess(gsl_matrix * dest, gsl_matrix * core_hamiltonian, gsl_matrix * S, int length);\n\n// calculate density matrix from coefficient matrix and the number of electrons\nvoid density_matrix(gsl_matrix * dest, gsl_matrix * coef, int el_num, int length);\n\n//perform RHF as well as printing information\nint RHF_SCF_print(double * tot_energy, gsl_vector * energy, gsl_matrix * coef, orbital * HEAD, atomic_orbital * atom_HEAD, int length, int el_num, int iteration_max, double errmax, int countmax, double alpha, int mixing_type, int SCF_INITIAL_FLAG, int SCF_FOCK_FLAG, int SCF_COEF_FLAG, int FOCK_FLAG);\n\n//calculate the nuclei repulsion energy\ndouble nuclei_repulsion(atomic_orbital * atomlist_HEAD);", "meta": {"hexsha": "7543a96b4e9681c54f1a84790f15e5a75721d91e", "size": 2540, "ext": "h", "lang": "C", "max_stars_repo_path": "include/RHF.h", "max_stars_repo_name": "Walter-Feng/Hartree-Fock", "max_stars_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-08-23T21:27:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T18:50:05.000Z", "max_issues_repo_path": "include/RHF.h", "max_issues_repo_name": "Walter-Feng/Hartree-Fock", "max_issues_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/RHF.h", "max_forks_repo_name": "Walter-Feng/Hartree-Fock", "max_forks_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-18T13:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T03:11:07.000Z", "avg_line_length": 46.1818181818, "max_line_length": 301, "alphanum_fraction": 0.7980314961, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3567653306616501}}
{"text": "#pragma once\n\n\n\n#ifndef _NOSNOPT\n#include <fstream>\n#include <iostream>\n#include \"BasicError.h\"\n#ifndef _NOGSL\n#include <gsl/gsl_vector.h>\n#else\n#include \"FakeGSL.h\"\n#endif\n#include \"OptSolver.h\"\n#include \"snopt.hh\"\n#include \"snoptProblem.hh\"\n\nusing namespace std;\n\n\nclass SnoptSolver : public OptSolver {\n\tsnoptProblem snoptProb;\n\t\n\tinteger n; integer neF; integer lenA; integer lenG;\n\t\n\tinteger *iAfun;\n\tinteger *jAvar;\n\tdoublereal *A;\n\t\n\tinteger *iGfun;\n\tinteger *jGvar;\n\t\n\tdoublereal *x;\n\tdoublereal *xlow;\n\tdoublereal *xupp;\n\tdoublereal *xmul;\n\tinteger *xstate;\n\t\n\tdoublereal *F;\n\tdoublereal *Flow;\n\tdoublereal *Fupp;\n\tdoublereal *Fmul;\n\tinteger *Fstate;\n\t\n\tinteger nxnames;\n\tinteger nFnames = 1;\n\tchar *xnames;\n\tchar *Fnames;\n\t\n\tgsl_vector* result;\n\tdouble objectiveVal;\n\t\n\tinteger Cold = 0, Basis = 1, Warm = 2;\npublic:\n\tSnoptSolver(integer n_, integer neF_, integer lenA_): n(n_), neF(neF_), lenA(lenA_) {\n\t\tiAfun = new integer[lenA];\n\t\tjAvar = new integer[lenA];\n\t\tA = new doublereal[lenA];\n\t\t\n\t\tlenG = n*neF;\n\t\tiGfun = new integer[lenG];\n\t\tjGvar = new integer[lenG];\n\t\t\n\t\tx = new doublereal[n];\n\t\txlow = new doublereal[n];\n\t\txupp = new doublereal[n];\n\t\txmul = new doublereal[n];\n\t\txstate = new integer[n];\n\t\t\n\t\tF = new doublereal[neF];\n\t\tFlow = new doublereal[neF];\n\t\tFupp = new doublereal[neF];\n\t\tFmul = new doublereal[neF];\n\t\tFstate = new integer[neF];\n\t\t\n\t\tnxnames = 1;\n\t\tnFnames = 1;\n\t\txnames = new char[nxnames*8];\n\t\tFnames = new char[nFnames*8];\n\t\t\n\t\tsnoptProb.setXNames(xnames, nxnames);\n\t\tsnoptProb.setFNames(Fnames, nFnames);\n\t\t\n\t\tresult = gsl_vector_alloc(n);\n\t}\n\t\n\t~SnoptSolver() {\n\t\tdelete []iAfun; delete []jAvar; delete []A;\n\t\tdelete []iGfun; delete []jGvar;\n\t\tdelete []x; delete []xlow; delete []xupp;\n\t\tdelete []xmul; delete []xstate;\n\t\tdelete []F; delete []Flow; delete []Fupp;\n\t\tdelete []Fmul; delete []Fstate;\n\t\tdelete []xnames; delete []Fnames;\n\t}\n\t\n\tvirtual void init(char* workspace, integer nef_, DFT df, integer ObjRow, doublereal ObjAdd, doublereal *xlow_, doublereal *xupp_, doublereal *Flow_, doublereal *Fupp_);\n\tbool optimize(gsl_vector* initState, bool suppressPrint = false);\n\t\n\tvirtual gsl_vector* getResults() {\n\t\treturn result;\n\t}\n\t\n\tvirtual double getObjectiveVal() {\n\t\treturn objectiveVal;\n\t}\n\t\n};\n\n\n#endif\n\n\n", "meta": {"hexsha": "b92fd49fafb7516eb6b0181216f882234ec5e15b", "size": 2255, "ext": "h", "lang": "C", "max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/Snopt.h", "max_stars_repo_name": "natebragg/sketch-backend", "max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_stars_repo_licenses": ["X11"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z", "max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/Snopt.h", "max_issues_repo_name": "natebragg/sketch-backend", "max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_issues_repo_licenses": ["X11"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z", "max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Optimizers/Snopt.h", "max_forks_repo_name": "natebragg/sketch-backend", "max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e", "max_forks_repo_licenses": ["X11"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z", "avg_line_length": 19.7807017544, "max_line_length": 169, "alphanum_fraction": 0.6833702882, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3567653162833177}}
{"text": "/**\n *\n * @file core_dgeqp3_tntpiv.c\n *\n *  PLASMA core_blas kernel\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated d Tue Jan  7 11:44:50 2014\n *\n **/\n#include <lapacke.h>\n#include \"common.h\"\n\n/***************************************************************************\n *\n * @ingroup CORE_double\n *\n *  CORE_dgeqp3_tntpiv computes a QR factorization with column pivoting of a\n *  matrix A:  A*P = Q*R  using Level 3 BLAS.\n *\n *  The matrix Q is represented as a product of elementary reflectors\n *\n *     Q = H(1) H(2) . . . H(k), where k = min(m,n).\n *\n *  Each H(i) has the form\n *\n *     H(i) = I - tau * v * v**T\n *\n *  where tau is a complex scalar, and v is a real/complex vector\n *  with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in\n *  A(i+1:m,i), and tau in TAU(i).\n *\n *******************************************************************************\n *\n *  Arguments:\n *  ==========\n *\n * @param[in] m\n *          The number of rows of the matrix A. M >= 0.\n *\n * @param[in] n\n *          The number of columns of the matrix A.  N >= 0.\n *\n * @param[in,out] A\n *          A is COMPLEX*16 array, dimension (LDA,N)\n *          On entry, the M-by-N matrix A.\n *          On exit, the upper triangle of the array contains the\n *          min(M,N)-by-N upper trapezoidal matrix R; the elements below\n *          the diagonal, together with the array TAU, represent the\n *          unitary matrix Q as a product of min(M,N) elementary\n *          reflectors.\n *\n * @param[in] lda\n *          The leading dimension of the array A. LDA >= max(1,M).\n *\n * @param[out] IPIV\n *          IPIV is INTEGER array, dimension min(M,N)\n *          The pivot indices; for 1 <= j <= min(M,N), column j of the\n *          tile was interchanged with column IPIV(j).\n *\n * @param[out] TAU\n *          TAU is COMPLEX*16 array, dimension (min(M,N))\n *          The scalar factors of the elementary reflectors.\n *\n * @param[in,out] iwork\n *          iwork is INTEGER array, dimension (N)\n *          On entry, if iwork(J).ne.0, the J-th column of A is permuted\n *          to the front of A*P (a leading column); if iwork(J)=0,\n *          the J-th column of A is a free column.\n *          On exit, if iwork(J)=K, then the J-th column of A*P was the\n *          the K-th column of A.\n *\n * @param[out] INFO\n *          = 0: successful exit.\n *          < 0: if INFO = -i, the i-th argument had an illegal value.\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *          \\retval <0 if -i, the i-th argument had an illegal value\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_dgeqp3_tntpiv = PCORE_dgeqp3_tntpiv\n#define CORE_dgeqp3_tntpiv PCORE_dgeqp3_tntpiv\n#endif\nint CORE_dgeqp3_tntpiv(int m, int n,\n                       double *A, int lda,\n                       int *IPIV, double *tau,\n                       int *iwork)\n{\n    int i, tmp, info;\n    memset(iwork, 0, n*sizeof(int));\n    info = LAPACKE_dgeqp3(LAPACK_COL_MAJOR, m, n, A, lda, iwork, tau );\n\n    /* Convert IPIV from permutation array, to pivot array\n     * WARNING: this is because this kernel is only used in\n     * tournament pivoting with rank revealing QR */\n    if (info == 0) {\n        for(i=0; i<min(m,n); i++) {\n            assert(iwork[i] != 0 );\n\n            tmp = iwork[i]-1;\n            while( tmp < i ) {\n                tmp = IPIV[ tmp ] - 1;\n            }\n            IPIV[i] = tmp+1;\n        }\n    }\n    return info;\n}\n", "meta": {"hexsha": "12f4778016d8b1ea991b2e948ed0ba905d0c3ac6", "size": 3750, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_dgeqp3_tntpiv.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas/core_dgeqp3_tntpiv.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas/core_dgeqp3_tntpiv.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.0512820513, "max_line_length": 80, "alphanum_fraction": 0.5202666667, "num_tokens": 1055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.35675309815803574}}
{"text": "#pragma once\n#include \"halley/maths/vector3.h\"\n#include <gsl/span>\n\nnamespace Halley\n{\n\tclass AudioListenerData;\n\n\tclass AudioChannelData\n\t{\n\tpublic:\n\t\tfloat pan; // TODO, do this right\n\t};\n\n\tclass AudioPosition\n\t{\n\tpublic:\n\t\tstatic AudioPosition makeUI(float pan = 0.0f); // -1.0f = left, 1.0f = right\n\t\tstatic AudioPosition makePositional(Vector2f pos, float referenceDistance = 200.0f, float maxDistance = 400.0f);\n\t\tstatic AudioPosition makePositional(Vector3f pos, float referenceDistance = 200.0f, float maxDistance = 400.0f);\n\t\tstatic AudioPosition makeFixed();\n\n\t\tvoid setMix(size_t srcChannels, gsl::span<const AudioChannelData> dstChannels, gsl::span<float, 16> dst, float gain, const AudioListenerData& listener) const;\n\n\t\tAudioPosition();\n\t\t\n\tprivate:\n\t\tVector3f pos;\n\t\tfloat referenceDistance;\n\t\tfloat maxDistance;\n\t\tbool isUI;\n\t\tbool isPannable;\n\t};\n}\n", "meta": {"hexsha": "47993c3b397b15332e18bdd608efe9e5189638fc", "size": 866, "ext": "h", "lang": "C", "max_stars_repo_path": "src/engine/audio/include/halley/audio/audio_position.h", "max_stars_repo_name": "Healthire/halley", "max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/audio/include/halley/audio/audio_position.h", "max_issues_repo_name": "Healthire/halley", "max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/audio/include/halley/audio/audio_position.h", "max_forks_repo_name": "Healthire/halley", "max_forks_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81", "max_forks_repo_licenses": ["Apache-2.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.7428571429, "max_line_length": 160, "alphanum_fraction": 0.7413394919, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.356682470185035}}
{"text": "/**************************************************************/\n/*! \\brief This file contains all .h files \n */\n/**************************************************************/\n\n\n#ifndef __SLIM_H__\n#define __SLIM_H__\n\n#define _GNU_SOURCE 1\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <time.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <math.h>\n#include <gsl/gsl_sf_gamma.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_cblas.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_eigen.h>\n#include <bcls.h>\n#include <GKlib.h>\n#include <def.h>\n#include <struct.h>\n#include <proto.h>\n#include <mpi.h>\n#include <omp.h>\n\n#endif\n", "meta": {"hexsha": "2d987578229007a6af26112a9128c35b4f161ef4", "size": 788, "ext": "h", "lang": "C", "max_stars_repo_path": "include/slim.h", "max_stars_repo_name": "echristakopoulou/glslim", "max_stars_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-16T01:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:45:41.000Z", "max_issues_repo_path": "include/slim.h", "max_issues_repo_name": "echristakopoulou/glslim", "max_issues_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/slim.h", "max_forks_repo_name": "echristakopoulou/glslim", "max_forks_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T07:46:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T13:00:19.000Z", "avg_line_length": 20.7368421053, "max_line_length": 64, "alphanum_fraction": 0.5939086294, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3566824701850349}}
{"text": "/**\n *\n * @file testing_dgemm.c\n *\n *  PLASMA testing routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Emmanuel Agullo\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated d Tue Jan  7 11:45:18 2014\n *\n **/\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\n#include <plasma.h>\n#include <cblas.h>\n#include <lapacke.h>\n#include <core_blas.h>\n#include \"testing_dmain.h\"\n\n#undef COMPLEX\n#define REAL\n\nstatic int check_solution(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K,\n                          double alpha, double *A, int LDA,\n                          double *B, int LDB,\n                          double beta, double *Cref, double *Cplasma, int LDC);\n\nint testing_dgemm(int argc, char **argv)\n{\n    /* Check for number of arguments*/\n    if ( argc != 8) {\n        USAGE(\"GEMM\", \"alpha beta M N K LDA LDB LDC\",\n              \"   - alpha  : alpha coefficient\\n\"\n              \"   - beta   : beta coefficient\\n\"\n              \"   - M      : number of rows of matrices A and C\\n\"\n              \"   - N      : number of columns of matrices B and C\\n\"\n              \"   - K      : number of columns of matrix A / number of rows of matrix B\\n\"\n              \"   - LDA    : leading dimension of matrix A\\n\"\n              \"   - LDB    : leading dimension of matrix B\\n\"\n              \"   - LDC    : leading dimension of matrix C\\n\");\n        return -1;\n    }\n\n    PLASMA_Set(PLASMA_TILE_SIZE, 128);\n    double alpha = (double) atol(argv[0]);\n    double beta = (double) atol(argv[1]);\n    int M     = atoi(argv[2]);\n    int N     = atoi(argv[3]);\n    int K     = atoi(argv[4]);\n    int LDA   = atoi(argv[5]);\n    int LDB   = atoi(argv[6]);\n    int LDC   = atoi(argv[7]);\n\n    double eps;\n    int info_solution;\n    int i, j, ta, tb;\n    int LDAxK = LDA*max(M,K);\n    int LDBxN = LDB*max(K,N);\n    int LDCxN = LDC*N;\n\n    double *A      = (double *)malloc(LDAxK*sizeof(double));\n\t#pragma omp register( [LDAxK]A )\n    double *B      = (double *)malloc(LDBxN*sizeof(double));\n\t#pragma omp register( [LDBxN]B )\n    double *C      = (double *)malloc(LDCxN*sizeof(double));\n\t#pragma omp register( [LDCxN]C )\n    double *Cinit  = (double *)malloc(LDCxN*sizeof(double));\n\t#pragma omp register( [LDCxN]Cinit )\n    double *Cfinal = (double *)malloc(LDCxN*sizeof(double));\n\t#pragma omp register( [LDCxN]Cfinal )\n\n    /* Check if unable to allocate memory */\n    if ((!A)||(!B)||(!Cinit)||(!Cfinal)){\n        printf(\"Out of Memory \\n \");\n        return -2;\n    }\n\n    eps = LAPACKE_dlamch_work('e');\n    printf(\"\\n\");\n    printf(\"------ TESTS FOR PLASMA DGEMM ROUTINE -------  \\n\");\n    printf(\"            Size of the Matrix %d by %d\\n\", M, N);\n    printf(\"\\n\");\n    printf(\" The matrix A is randomly generated for each test.\\n\");\n    printf(\"============\\n\");\n    printf(\" The relative machine precision (eps) is to be %e \\n\",eps);\n    printf(\" Computational tests pass if scaled residuals are less than 10.\\n\");\n\n    /*----------------------------------------------------------\n     *  TESTING DGEMM\n     */\n\n    /* Initialize A, B, C */\n    LAPACKE_dlarnv_work(IONE, ISEED, LDAxK, A);\n    LAPACKE_dlarnv_work(IONE, ISEED, LDBxN, B);\n    LAPACKE_dlarnv_work(IONE, ISEED, LDCxN, C);\n\n#ifdef COMPLEX\n    for (ta=0; ta<3; ta++) {\n        for (tb=0; tb<3; tb++) {\n#else\n    for (ta=0; ta<2; ta++) {\n        for (tb=0; tb<2; tb++) {\n#endif\n            for ( i = 0; i < M; i++)\n                for (  j = 0; j < N; j++)\n                    Cinit[LDC*j+i] = C[LDC*j+i];\n            for ( i = 0; i < M; i++)\n                for (  j = 0; j < N; j++)\n                    Cfinal[LDC*j+i] = C[LDC*j+i];\n\n            /* PLASMA DGEMM */\n            PLASMA_dgemm(trans[ta], trans[tb], M, N, K, alpha, A, LDA, B, LDB, beta, Cfinal, LDC);\n\n            /* Check the solution */\n            info_solution = check_solution(trans[ta], trans[tb], M, N, K, \n                                           alpha, A, LDA, B, LDB, beta, Cinit, Cfinal, LDC);\n\n            if (info_solution == 0) {\n                printf(\"***************************************************\\n\");\n                printf(\" ---- TESTING DGEMM (%s, %s) ............... PASSED !\\n\", transstr[ta], transstr[tb]);\n                printf(\"***************************************************\\n\");\n            }\n            else {\n                printf(\"************************************************\\n\");\n                printf(\" - TESTING DGEMM (%s, %s) ... FAILED !\\n\", transstr[ta], transstr[tb]);\n                printf(\"************************************************\\n\");\n            }\n        }\n    }\n#ifdef _UNUSED_\n    }}\n#endif\n    free(A); free(B); free(C);\n    free(Cinit); free(Cfinal);\n\n    return 0;\n}\n\n/*--------------------------------------------------------------\n * Check the solution\n */\n\nstatic int check_solution(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K,\n                          double alpha, double *A, int LDA,\n                          double *B, int LDB,\n                          double beta, double *Cref, double *Cplasma, int LDC)\n{\n    int info_solution;\n    double Anorm, Bnorm, Cinitnorm, Cplasmanorm, Clapacknorm, Rnorm, result;\n    double eps;\n    double beta_const;\n\n    double *work = (double *)malloc(max(K,max(M, N))* sizeof(double));\n    int Am, An, Bm, Bn;\n\n    beta_const  = -1.0;\n\n    if (transA == PlasmaNoTrans) {\n        Am = M; An = K;\n    } else {\n        Am = K; An = M;\n    }\n    if (transB == PlasmaNoTrans) {\n        Bm = K; Bn = N;\n    } else {\n        Bm = N; Bn = K;\n    }\n\n    Anorm       = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), Am, An, A,       LDA, work);\n    Bnorm       = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), Bm, Bn, B,       LDB, work);\n    Cinitnorm   = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M,  N,  Cref,    LDC, work);\n    Cplasmanorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M,  N,  Cplasma, LDC, work);\n\n    cblas_dgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, \n                (alpha), A, LDA, B, LDB, (beta), Cref, LDC);\n\n    Clapacknorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work);\n\n    cblas_daxpy(LDC * N, (beta_const), Cplasma, 1, Cref, 1);\n\n    Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work);\n\n    eps = LAPACKE_dlamch_work('e');\n\n    printf(\"Rnorm %e, Anorm %e, Bnorm %e, Cinitnorm %e, Cplasmanorm %e, Clapacknorm %e\\n\", \n           Rnorm, Anorm, Bnorm, Cinitnorm, Cplasmanorm, Clapacknorm);\n\n    result = Rnorm / ((Anorm + Bnorm + Cinitnorm) * N * eps);\n    printf(\"============\\n\");\n    printf(\"Checking the norm of the difference against reference DGEMM \\n\");\n    printf(\"-- ||Cplasma - Clapack||_oo/((||A||_oo+||B||_oo+||C||_oo).N.eps) = %e \\n\", \n           result);\n\n    if (  isnan(Rnorm) || isinf(Rnorm) || isnan(result) || isinf(result) || (result > 10.0) ) {\n         printf(\"-- The solution is suspicious ! \\n\");\n         info_solution = 1;\n    }\n    else {\n         printf(\"-- The solution is CORRECT ! \\n\");\n         info_solution= 0 ;\n    }\n\n    free(work);\n\n    return info_solution;\n}\n\nint timing_dgemm(int argc, char **argv)\n{\n\n\tint transa; int transb;\n\tint m, n, k;\n\tdouble alpha, beta;\n\tint lda, ldb, ldc;\n\tdouble *A, *B, *C;\n\tdouble *C0;\n\tint bs, rep;\n\tint i;\n\n\tdouble start, end;\n\tdouble elapsed;\n\tFILE *log;\n\tint num_threads;\n\n\n\t//gemm transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc\n\tif (argc != 12) {\n\t\tfprintf(stderr, \"GEMMs transa transb m n k alpha lda ldb beta ldc bs rep\\n\");\n\t\treturn 1;;\n\t}\n\n\tsscanf(argv[0], \"%d\", &transa);\n\tsscanf(argv[1], \"%d\", &transb);\n\n\tif ( !transa )\n\t\ttransa = PlasmaNoTrans;\n\telse\n\t\ttransa = PlasmaTrans;\n\tif ( !transb )\n\t\ttransb = PlasmaNoTrans;\n\telse\n\t\ttransb = PlasmaTrans;\n\n\tsscanf(argv[2], \"%d\", &m);\n\tsscanf(argv[3], \"%d\", &n);\n\tsscanf(argv[4], \"%d\", &k);\n\tsscanf(argv[5], \"%lf\", &alpha);\n\tsscanf(argv[6], \"%d\", &lda);\n\tsscanf(argv[7], \"%d\", &ldb);\n\tsscanf(argv[8], \"%lf\", &beta);\n\tsscanf(argv[9], \"%d\", &ldc);\n\tsscanf(argv[10], \"%d\", &bs);\n\tsscanf(argv[11], \"%d\", &rep);\n\n\tint dimA = max(m,k) * lda;\n\tint dimB = max(n,k) * ldb;\n\tint dimC = max(m,n) * ldc;\n\tA = malloc( dimA * sizeof(double));\n\t#pragma omp register ([dimA]A)\n\tB = malloc( dimB * sizeof(double));\n\t#pragma omp register ([dimB]B)\n\tC = malloc( dimC * sizeof(double));\n\t#pragma omp register ([dimC]C)\n\n\tLAPACKE_dlarnv(IONE, ISEED, dimA, A);\n\tLAPACKE_dlarnv(IONE, ISEED, dimB, B);\n\tLAPACKE_dlarnv(IONE, ISEED, dimC, C);\n\n\tPLASMA_Set( PLASMA_TILE_SIZE, bs);\n\n\telapsed = 0.0;\n\tfor ( i = 0; i < rep; i++ ) {\n\t\tstart = gtime();\n\t\tPLASMA_dgemm(transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);\n\t\tend = gtime();\n\t\telapsed += end - start;\n\t}\n\n\tnum_threads = omp_get_max_threads();\n\tdump_info(\"plasma_dgemm.log\", num_threads, elapsed, rep);\n\n\tfree(A); free(B); free(C);\n    return 0;\n}\n", "meta": {"hexsha": "e4f850b553d8257dad686fbc5fb910818c61b31b", "size": 9073, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/testing_dgemm.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/testing_dgemm.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/testing_dgemm.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.0719178082, "max_line_length": 113, "alphanum_fraction": 0.5354348066, "num_tokens": 2839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.3565858961122472}}
{"text": "/**\n * @file mcc_localizer.h\n * @brief grid search based localization\n * @author Kenichi Kumatani\n */\n\n#ifndef MCC_LOCALIZER_H\n#define MCC_LOCALIZER_H\n#include <stdio.h>\n#include <assert.h>\n#include <float.h>\n\n#include <gsl/gsl_block.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_complex.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_fft_real.h>\n#include <gsl/gsl_fft_complex.h>\n#include <common/refcount.h>\n#include \"common/jexception.h\"\n\n#include \"stream/stream.h\"\n#include \"feature/feature.h\"\n//#include \"modulated/modulated.h\"\n\n/**\n   @brief  construct a search grid for source localization and return the time delay corresponding to each position on the grid.\n   @note In order to do efficient grid-search for the source position which provides the maximum/minimum objective function, each cell size of a search grid has to be \"reasonable\".\n   @usage\n   After you construct an instance, you have to \n   1. set the geometry of the microphone array with setRadius(), setDistanceBtwMicrophones() or setPositionsOfMicrophones().\n   2. obtain the time delays at the source position with getTimeDelays(), and\n   3. go to the next search candidate on the grid with nextSearchGrid().\n */\nclass SearchGridBuilder {\n public:\n  SearchGridBuilder( int nChan, bool isFarField, unsigned int samplingFreq=16000);\n  virtual ~SearchGridBuilder();\n\n  const gsl_vector *getSearchPosition(){return(const gsl_vector *)_hypopos;}\n  float maxTimeDelay(){return _maxTimeDelay;}\n  size_t chanN(){return(_mpos->size1);}\n  unsigned int samplingFrequency(){return(_samplingFreq);}\n  void reset();\n\n  virtual const gsl_vector *getTimeDelays(){return NULL;}\n  virtual bool nextSearchGrid(){return false;}\n\nprotected:\n  virtual const gsl_vector *nextSearchGridFF(){return NULL;}\n  const gsl_vector *nextSearchGridNF();\n\nprotected:\n  const bool _isFarField; /* if _isFarField = true, the far-filed is assumed. Otherwise, the near-field is assumed. */\n  unsigned int _samplingFreq;\n  float _maxTimeDelay;\n  gsl_matrix* _mpos;\n  gsl_vector *_hypopos;\n  gsl_vector *_delays;  \n  float _constV;\n};\n\ntypedef refcount_ptr<SearchGridBuilder> SearchGridBuilderPtr;\n\nclass SGB4LinearArray : public SearchGridBuilder{\npublic:\n  SGB4LinearArray( int nChan, bool isFarField, unsigned int samplingFreq=16000);\n  void setDistanceBtwMicrophones( float distance );\n  void setPositionsOfMicrophones( const gsl_matrix* mpos );\n  virtual const gsl_vector *getTimeDelays();\n  virtual bool nextSearchGrid();\n\nprotected:\n  const gsl_vector *nextSearchGridFF();\n};\n\ntypedef Inherit<SGB4LinearArray, SearchGridBuilderPtr> SGB4LinearArrayPtr;\n\nclass SGB4CircularArray : public SearchGridBuilder {\npublic:\n  SGB4CircularArray( int nChan, bool isFarField, unsigned int samplingFreq=16000 );\n  void setRadius( float radius, float height=0.0 );\n  virtual const gsl_vector *getTimeDelays();\n  virtual bool nextSearchGrid();\n\nprotected:\n  const gsl_vector *nextSearchGridFF();\n};\n\ntypedef Inherit<SGB4CircularArray, SearchGridBuilderPtr> SGB4CircularArrayPtr;\n\n/**\n   @brief keeps samples in the previous block. \n          this object is used in order to fill the gap between previous and current block data.\n*/\nclass SampleHolder {\npublic:\n  SampleHolder( size_t chanN, size_t maxSampleDelay ):\n    _filledNum(0),_buffer(gsl_matrix_float_calloc(chanN,maxSampleDelay))\n  {}\n\n  ~SampleHolder()\n  {\n    gsl_matrix_float_free(_buffer);\n  }\n  \n  void setSamples( size_t chanX, gsl_vector_float *samples )\n  {\n    size_t maxSampleDelay = _buffer->size2;\n\n    if( samples->size >= maxSampleDelay ){\n      size_t frameY = samples->size - maxSampleDelay;\n      for(size_t frameX=0;frameX<maxSampleDelay;frameX++,frameY++){\n\tgsl_matrix_float_set( _buffer, chanX, frameX, gsl_vector_float_get( samples, frameY ) );\n      }\n      _filledNum = maxSampleDelay;\n    }\n    else{\n      // shift the elements of the buffer\n      size_t frameN = maxSampleDelay - samples->size;\n      for(size_t frameX=0;frameX<frameN;frameX++){\n\tgsl_matrix_float_set( _buffer, chanX, frameX, gsl_matrix_float_get( _buffer, chanX, frameX + samples->size ) );\n      }\n      // hold the samples of the current block\n      size_t frameY = 0;\n      for(size_t frameX=frameN;frameX<maxSampleDelay;frameX++,frameY++){\n\tgsl_matrix_float_set( _buffer, chanX, frameX, gsl_vector_float_get( samples, frameY ) );\n      }\n      _filledNum += samples->size;\n      if(  _filledNum > maxSampleDelay ) \n\t_filledNum = maxSampleDelay;\n    }\n  }\n\n  float getSample( int chanX, int minusFrameX )\n  {\n    return gsl_matrix_float_get( _buffer, chanX, _buffer->size2 + minusFrameX );\n  }\n\n  int nFilled(){ return _filledNum;}\n\nprivate:\n  int  _filledNum;\n  gsl_matrix_float *_buffer; /* the number of channels X samples */\n};\n\ntypedef refcount_ptr<SampleHolder> SampleHolderPtr;\n\n/**\n   @brief hold information for a position estimate.\n */\nclass SourceCandidate {\npublic:\n  SourceCandidate(size_t chanN, double costV=100000):\n    _costV(costV), _chanN(chanN){\n    _sampledelay = new int[chanN];\n    _position = gsl_vector_calloc( 3 );\n    _eigenvalues = gsl_vector_alloc( chanN );\n  }\n  ~SourceCandidate(){\n    delete [] _sampledelay;\n    gsl_vector_free(_position);\n    gsl_vector_free( _eigenvalues );\n  }\n  void setSourceInfo( int *tau, const gsl_vector *position, double costV, gsl_vector *eigenvalues ){\n    for(size_t i=0;i<_chanN;i++){_sampledelay[i]=tau[i];}\n    gsl_vector_memcpy(_position, (gsl_vector *)position);\n    _costV = costV;\n    gsl_vector_memcpy(_eigenvalues, eigenvalues);\n  }\n  void setConstV( double costV=100000 ){\n    _costV = costV;\n  }\n\n  double _costV; /* value of the cost function */\n  int *_sampledelay;\n  gsl_vector *_position;\n  gsl_vector *_eigenvalues;\nprivate:\n  size_t _chanN;\n};\n\n/**\n   @class estimate the source positions which provide the larger multi-channel cross correlation values. \n   @usage\n   1. setChannel()\n   2. next()\n   3. \n\n   @note The algorithm implemented here is described in:\n          J. Chen, J. Benesty and Y. Huang, \"Robust Time Delay Estimation Exploiting Redundancy Among Multiple Microphones\", IEEE Trans. SAP, vol.11, Sep. 2003.\n*/\n\nclass MCCLocalizer : public VectorFeatureStream {\npublic:\n  MCCLocalizer( SearchGridBuilderPtr &sgbPtr, size_t maxSource=1, const String& nm= \"MCCSourceLocalizer\" );\n  ~MCCLocalizer();\n  virtual const gsl_vector* next(int frameX = -5);\n  virtual void  reset();\n  //void setChannel(SampleFeaturePtr& chan);\n  void setChannel(VectorFloatFeatureStreamPtr& chan);\n  /*@brief obtain a relative delay at a microphone which corresponds to the best candidate */\n  int getDelayedSample( int chanX ){return _sourceCandidates[0]->_sampledelay[chanX];}\n  /*@brief obtain the maximum MCCC value */\n  double getMaxMCCC(){/* mistake: it was getMinMCCC() */\n#ifdef _NO_LOG_\n    return( 1 -_sourceCandidates[0]->_costV );\n#else\n    return( 1 -exp(_sourceCandidates[0]->_costV) );\n#endif\n  }\n  /*@brief obtain the best candidate of the position estimates */\n  const gsl_vector* getPosition(){return((const gsl_vector* )_sourceCandidates[0]->_position);}\n\n  /*@brief obtain a relative delay at a microphone which corresponds to the N-th best candidate */\n  int getNthBestDelayedSample( int nth, int chanX ){return _sourceCandidates[nth]->_sampledelay[chanX];}\n  /*@brief obtain the N-th best MCCC value */\n  double getNthBestMCCC( int nth ){\n#ifdef _NO_LOG_\n    return( 1 -_sourceCandidates[nth]->_costV );\n#else\n    return( 1 - exp(_sourceCandidates[nth]->_costV) );\n#endif\n  }\n  /*@brief obtain theN-th  best candidate of the position estimates */\n  const gsl_vector* getNthBestPosition( int nth ){return((const gsl_vector* )_sourceCandidates[nth]->_position);}\n\n  const gsl_vector* getEigenValues(){return ((const gsl_vector*)_sourceCandidates[0]->_eigenvalues);}\n  gsl_matrix *getR(){return _R;}\n\nprotected:\n  bool setIncomingData( int frameX );\n  void doEigenValueDecomposition();\n  double calcObjectiveFunction( bool normalizeVariance = true );\nprivate:\n  gsl_matrix *calcCovarianceMatrix();\n\nprivate:\n  gsl_vector* search( int frameX = -5 );\n\nprotected:\n  typedef list<VectorFloatFeatureStreamPtr>   _ChannelList; //typedef list<SampleFeaturePtr>   _ChannelList;\n  typedef _ChannelList::iterator   _ChannelIterator;\n  _ChannelList                     _channelList;\n\n  SearchGridBuilderPtr _sgbPtr;\n  vector<const gsl_vector_float *> _blockList;\n  int *_tau; /* sample delays */\n  gsl_vector *_x;\n  gsl_matrix *_R; /* covariance matrix */\n  gsl_matrix *_Rcopy;\n  double _detR;\n  void *_workspace;\n  gsl_vector *_eigenvalues;\n  SampleHolderPtr _shPtr; /* keep samples of the block processed at a prevous frame */\n  vector<SourceCandidate *> _sourceCandidates; /* _sourceCandidates[n] is the N-th best candidate */\n};\n\ntypedef Inherit<MCCLocalizer, VectorFeatureStreamPtr> MCCLocalizerPtr;\n\n/**\n   @class calculate multichannel cross correlation coefficient givin a position or time delays.\n*/\nclass MCCCalculator : public MCCLocalizer {\npublic:\n  MCCCalculator( SearchGridBuilderPtr &sgbPtr, bool normalizeVariance=true, const String& nm= \"MCCCalculator\" );\n  ~MCCCalculator();\n  void setTimeDelays( gsl_vector *delays );\n  double getMCCC();\n  double getCostV();\n  virtual const gsl_vector* next(int frameX = -5);\n  virtual void  reset();\nprivate:\n  gsl_matrix *calcCovarianceMatrix( gsl_vector *delays );\n\nprivate:\n  gsl_vector *_delays;\n  bool        _normalizeVariance;\n};\n\ntypedef Inherit<MCCCalculator, MCCLocalizerPtr> MCCCalculatorPtr;\n\n/**\n   @class recursively estimate the source position which provides the multi-channel cross correlation.\n   @usage\n\n   @note The algorithm implemented here is described in:\n         J. Benesty, J. Chen and Y. Huang, \"Time-Delay Estimation via Linear Interpolation and Cross Correlation\", IEEE Trans. SAP, vol.12, Sep. 2004.\n*/\nclass RMCCLocalizer : public MCCLocalizer {\npublic:\n  RMCCLocalizer( SearchGridBuilderPtr &sgbPtr, float lambda, size_t maxSource=1, const String& nm= \"RMCCSourceLocalizer\" );\n  ~RMCCLocalizer();\n  virtual const gsl_vector* next(int frameX = -5);\n  virtual void  reset();\n\nprivate:\n  void calcInverseMatrix();\n  void updateParameters();\n\n  gsl_matrix *_invR; /* an inverse matrix of the covariance matrix */\n  gsl_vector *_kd; /* a priori Kalman gain vector */\n\n  //gsl_vector *_old_x;\n  gsl_matrix *_old_R; /* covariance matrix at a previous frame */\n  gsl_matrix *_old_invR;\n  gsl_vector *_old_kd; /* a priori Kalman gain vector at a previous frame */\n};\n\ntypedef Inherit<RMCCLocalizer, MCCLocalizerPtr> RMCCLocalizerPtr;\n\n#endif\n", "meta": {"hexsha": "9ab97bbf46c78338266f33917b940d9e5fb29b29", "size": 10516, "ext": "h", "lang": "C", "max_stars_repo_path": "btk20_src/localization/mcc_localizer.h", "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 136.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_issues_repo_path": "btk20_src/localization/mcc_localizer.h", "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_forks_repo_path": "btk20_src/localization/mcc_localizer.h", "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 68.0, "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "avg_line_length": 33.4904458599, "max_line_length": 180, "alphanum_fraction": 0.7377329783, "num_tokens": 2755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321964553658, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3561160982276829}}
{"text": "\n#ifdef USING_FFTW\n\n#include <fftw.h>\n\n#elif defined USING_FFTW3\n\n#include <fftw3.h>\n\n#else\n\ntypedef double fftw_real;\ntypedef struct {\n     fftw_real re, im;\n} fftw_complex_orig;\ntypedef fftw_real HPCC_Complex[2];\ntypedef HPCC_Complex fftw_complex;\n#endif\ntypedef enum {\n     FFTW2_FORWARD = -1, FFTW2_BACKWARD = 1\n} fftw_direction;\n\n\nstruct hpcc_fftw_plan_struct {\n  fftw_complex *w1, *w2, *ww1, *ww2, *ww3, *ww4, *c, *d;\n  int n, c_size, d_size;\n  int flags;\n  fftw_direction dir;\n};\ntypedef struct hpcc_fftw_plan_struct *hpcc_fftw_plan;\n\nextern hpcc_fftw_plan HPCC_fftw_create_plan(int n, fftw_direction dir, int flags);\nextern void HPCC_fftw_destroy_plan(hpcc_fftw_plan plan);\nextern void HPCC_fftw_one(hpcc_fftw_plan plan, fftw_complex *in, fftw_complex *out);\n\n\n#ifdef USING_FFTW\n\n#elif defined USING_FFTW3\n\n#define c_re(c)  ((c)[0])\n#define c_im(c)  ((c)[1])\n\n#else\n\ntypedef struct hpcc_fftw_plan_struct *fftw_plan;\n\n#define c_re(c)  ((c)[0])\n#define c_im(c)  ((c)[1])\n\n#define fftw_malloc malloc\n#define fftw_free free\n/* flags for the planner */\n#define  FFTW_ESTIMATE (0)\n#define  FFTW_MEASURE  (1)\n\n#define FFTW_OUT_OF_PLACE (0)\n#define FFTW_IN_PLACE (8)\n#define FFTW_USE_WISDOM (16)\n\n#define fftw_create_plan HPCC_fftw_create_plan\n#define fftw_destroy_plan HPCC_fftw_destroy_plan\n#define fftw_one HPCC_fftw_one\n\n#endif\n", "meta": {"hexsha": "ead5d698c3db6b47471d849c2268aa0a27fcc1fb", "size": 1332, "ext": "h", "lang": "C", "max_stars_repo_path": "FFT/wrapfftw.h", "max_stars_repo_name": "Ringbo/HPCC_optimization", "max_stars_repo_head_hexsha": "48d05ae8aedfc4c6ed68835f1d440e151230a6df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-14T01:29:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T01:29:58.000Z", "max_issues_repo_path": "FFT/wrapfftw.h", "max_issues_repo_name": "Ringbo/HPCC_optimization", "max_issues_repo_head_hexsha": "48d05ae8aedfc4c6ed68835f1d440e151230a6df", "max_issues_repo_licenses": ["MIT"], "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/wrapfftw.h", "max_forks_repo_name": "Ringbo/HPCC_optimization", "max_forks_repo_head_hexsha": "48d05ae8aedfc4c6ed68835f1d440e151230a6df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-14T01:30:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T01:30:03.000Z", "avg_line_length": 20.1818181818, "max_line_length": 84, "alphanum_fraction": 0.7567567568, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3561160921194734}}
{"text": "// Authors: David Blei (blei@cs.princeton.edu)\n//          Sean Gerrish (sgerrish@cs.princeton.edu)\n//\n// Copyright 2011 Sean Gerrish and David Blei\n// All Rights Reserved.\n//\n// See the README for this package for details about modifying or\n// distributing this software.\n\n#ifndef LDASEQ_H\n#define LDASEQ_H\n\n#include <sys/stat.h>\n#include <sys/types.h>\n\n#include \"gsl-wrappers.h\"\n#include \"lda.h\"\n\n#define LDA_SEQ_EM_THRESH 1e-4\n#define SAVE_LAG 10\n\n/*\n * an lda sequence is a collection of simplex sequences for K topics\n * and an alpha vector\n *\n */\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <stdlib.h>\n#include <assert.h>\n\n#include \"param.h\"\n#include \"ss-lm.h\"\n#include \"data.h\"\n#include \"lda.h\"\n\n#define LDA_SEQ_EM_THRESHOLD 1e-5;\n\n// lda sequence variational posterior distribution\n\n\n// === allocation and initialization ===\n\ninf_var* inf_var_alloc(int number_topics,\n\t\t       corpus_seq_t* corpus_seq);\nvoid inf_var_free(inf_var* ptr);\n\n// initialize lda sequence from lda model topics\n\nvoid init_lda_seq_from_ss(lda_seq* model,\n                          double topic_chain_variance,\n                          double topic_obs_variance,\n                          double alpha,\n                          gsl_matrix* init_suffstats);\n\n// === fitting ===\n\n\n// infer a corpus with an lda-seq\n\ndouble update_inf_var(lda_seq* seq,\n\t\t      const corpus_seq_t* data,\n\t\t      gsl_matrix** phi,\n\t\t      size_t t,\n\t\t      const char* root);\ndouble update_inf_var_multiple(lda_seq* seq,\n\t\t\t       const corpus_seq_t* data,\n\t\t\t       gsl_matrix** phi,\n\t\t\t       size_t t,\n\t\t\t       const char* root);\nvoid update_inf_reg(lda_seq* seq,\n\t\t    const corpus_seq_t* data,\n\t\t    gsl_matrix** phi,\n\t\t    size_t t,\n\t\t    const char* root);\n\ndouble lda_seq_infer(lda_seq* model,\n                     const corpus_seq_t* data,\n                     gsl_matrix** suffstats,\n                     gsl_matrix* gammas,\n                     gsl_matrix* lhoods,\n\t\t     int iter,\n\t\t     const char* file_root);\n\n// fit lda sequence from sufficient statistics\n\ndouble fit_lda_seq(lda_seq* m,\n                   const corpus_seq_t* data,\n                   const corpus_seq_t* heldout,\n                   const char* file_root);\n\nvoid update_lda_seq_ss(int time,\n                       const doc_t* doc,\n                       const lda_post* post,\n                       gsl_matrix** ss);\n\ndouble fit_lda_seq_topics(lda_seq* model,\n                          gsl_matrix** ss);\n\n\n// === reading and writing ===\n\n\n// read and write a lda sequence\n\nvoid write_lda_seq(const lda_seq* m, const char* root);\n\nlda_seq* read_lda_seq(const char* root, corpus_seq_t* data);\n\n// write lda sequence sufficient statistics\n\nvoid write_lda_seq_suffstats(lda_seq* m,\n                             gsl_matrix** topic_ss,\n                             const char* root);\n\n// new lda sequence\n\nlda_seq* new_lda_seq(corpus_seq_t* data,\n\t\t     int W,\n\t\t     int T,\n\t\t     int K);\n\nvoid make_lda_from_seq_slice(lda* lda_m,\n                             lda_seq* lda_seq_m,\n                             int time);\n\n#endif\n", "meta": {"hexsha": "23df02e61b42540d91327b5afdd9ef2dae29fd43", "size": 3093, "ext": "h", "lang": "C", "max_stars_repo_path": "scripts/lib/DTM/dtm/lda-seq.h", "max_stars_repo_name": "iwangjian/dtm-lab", "max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z", "max_issues_repo_path": "scripts/lib/DTM/dtm/lda-seq.h", "max_issues_repo_name": "iwangjian/topic-extractor", "max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_issues_repo_licenses": ["MIT"], "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/lib/DTM/dtm/lda-seq.h", "max_forks_repo_name": "iwangjian/topic-extractor", "max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z", "avg_line_length": 23.976744186, "max_line_length": 68, "alphanum_fraction": 0.6068541869, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3561160921194734}}
{"text": "// @file kn2row_conv.c\n//\n//  \\date Created on: Sep 23, 2017\n//  \\author Gopalakrishna Hegde\n//\n//   Description:\n//\n//\n//\n#include <assert.h>\n#include <stdbool.h>\n#include <stdlib.h>\n#include <string.h>\n#include <cblas.h>\n#include \"common_types.h\"\n#include \"data_reshape.h\"\n#include \"utils.h\"\n\n//\n// col_shift : +ve --> shift left overlap mat , -ve --> shift right overlap mat\n// or shift left base mat and keep overlap mat as it is.\n//\n//\n// row_shift : +ve (coeff is down the center coeff) --> shift up overlap mat ,\n// -ve --> shift down overlap mat or shift up the base mat.\nvoid MatrixShiftAdd(float *base_mat,\n                     int base_no_rows, int base_no_cols,\n                     float *overlap_mat,\n                     int ov_no_rows, int ov_no_cols,\n                     int row_shift, int col_shift) {\n  if (row_shift == 0 && col_shift == 0 && (base_no_rows == ov_no_rows) &&\n      (base_no_cols == ov_no_cols)) {\n    // normal matrix add\n    cblas_saxpy(base_no_rows * base_no_cols, 1.0, overlap_mat, 1, base_mat, 1);\n    return;\n  }\n  int rows_to_add, cols_to_add;\n  int base_row_start, base_col_start;\n  int ov_row_start, ov_col_start;\n  // without padding case\n  if (ov_no_rows > base_no_rows) {\n    rows_to_add = base_no_rows;\n    cols_to_add = base_no_cols;\n    base_row_start = 0;\n    base_col_start = 0;\n    ov_row_start = row_shift < 0? -row_shift : 0;\n    ov_col_start = col_shift < 0? -col_shift : 0;\n\n  } else {\n    rows_to_add = ov_no_rows - abs(row_shift);\n    cols_to_add = ov_no_cols - abs(col_shift);\n\n    ov_col_start = col_shift > 0? col_shift : 0;\n    ov_row_start = row_shift > 0? row_shift : 0;\n    base_row_start = row_shift < 0? -row_shift : 0;\n    base_col_start = col_shift < 0? -col_shift : 0;\n  }\n\n  for (int r = 0; r < rows_to_add; ++r) {\n    int base_mat_offset = (r + base_row_start) * base_no_cols + base_col_start;\n    int overlap_mat_offset = (r + ov_row_start) * ov_no_cols + ov_col_start;\n    cblas_saxpy(cols_to_add, 1.0, overlap_mat + overlap_mat_offset, 1,\n                base_mat + base_mat_offset, 1);\n  }\n}\n\n/* Ker2Row convolution implementations.\n *\n * Assumptions:\n * 1. in_data is in NCHW format.\n * 2. filters are in MCKK format where M is the no of output maps.\n * 3. Stride will always be 1.\n * 4. pad will be zero or kernel_size / 2\n *\n * Output will be in NCHW format.\n */\nbool Kn2RowConvLayer(const float *in_data, const float *filters,\n                         const float *bias, TensorDim in_dim,\n                         TensorDim filt_dim, int stride, int pad, int group,\n                         float *output) {\n  // Currently we have limited support.\n  assert(group == 1);\n  assert((pad == 0) || (pad == filt_dim.w / 2));\n  assert(in_dim.n == 1);\n  assert(filt_dim.h == filt_dim.w);\n  assert(stride == 1);\n\n  // Output dimensions.\n  TensorDim out_dim;\n  out_dim.w = (in_dim.w + (pad + pad) - filt_dim.w) / stride + 1;\n  out_dim.h = (in_dim.h + (pad + pad) - filt_dim.h) / stride + 1;\n  out_dim.c = filt_dim.n;\n  out_dim.n = in_dim.n;\n\n  // Re-arrange filters in the  k x k x no_out_maps x no_in_maps.\n  // We can avoid this if the filters are already reshaped in this format.\n  float *kkmc_filters = malloc(filt_dim.n * filt_dim.c * filt_dim.h *\n                               filt_dim.w * sizeof(float));\n  NCHW2HWNC(filters, filt_dim.n, filt_dim.c, filt_dim.h, filt_dim.w,\n            kkmc_filters);\n\n  // Just for convenience\n  int H = in_dim.h;\n  int W = in_dim.w;\n  float alpha = 1.0;\n  float beta = 0.0;\n\n  // We need separate buffer because GEMM output will have width = H*W even\n  // if there is no padding (pad = 0).\n  float *gemm_output = malloc(out_dim.c * H * W * sizeof(float));\n\n  // Prefill output buffer with bias if present else set to zero.\n  if (bias) {\n    for (int m = 0; m < out_dim.c; ++m) {\n      for (int a = 0; a < out_dim.h * out_dim.w; ++a) {\n        output[m * out_dim.h * out_dim.w + a] = bias[m];\n      }\n      // For batch size > 1\n      for (int b = 1; b < out_dim.n; ++b) {\n        memcpy(output + b * out_dim.c * out_dim.h * out_dim.w,\n               output, out_dim.c * out_dim.h * out_dim.w * sizeof(float));\n      }\n    }\n  } else {\n    memset(output, 0, out_dim.n * out_dim.c * out_dim.h * out_dim.w *\n           sizeof(float));\n  }\n\n  for (int kr = 0; kr < filt_dim.h; kr++) {\n    int row_shift = kr - filt_dim.h / 2;\n    for (int kc = 0; kc < filt_dim.w; kc++) {\n      int group_no = kr * filt_dim.w + kc;\n      int col_shift = kc - filt_dim.w / 2;\n      // Matrix dimensions - A -> mxk B -> kxn  C --> mxn\n      int m = filt_dim.n;\n      int k = filt_dim.c;\n      int n = in_dim.h * in_dim.w;\n      // This is just 1x1 convolution\n      cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n                  m, n, k, alpha, kkmc_filters + group_no * m * k,\n                  k, in_data, n, beta, gemm_output, n);\n      // Slide the resulting matrix which has contribution from one of the\n      // KxK kernel coefficients and add to the output.\n      for (int omap = 0; omap < filt_dim.n; omap++) {\n        MatrixShiftAdd(output + omap * out_dim.h * out_dim.w,\n                        out_dim.h, out_dim.w,\n                        gemm_output + omap * H * W,\n                        H, W, row_shift, col_shift);\n      }\n    }\n  }\n  free(kkmc_filters);\n  free(gemm_output);\n  return true;\n}\n", "meta": {"hexsha": "20ff16aab7b061f00cfa0f70a161778822c7558a", "size": 5311, "ext": "c", "lang": "C", "max_stars_repo_path": "src/kn2row_conv.c", "max_stars_repo_name": "gplhegde/convolution-flavors", "max_stars_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2017-10-03T18:10:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T06:38:50.000Z", "max_issues_repo_path": "src/kn2row_conv.c", "max_issues_repo_name": "chayitw/convolution-flavors", "max_issues_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-16T02:49:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T02:49:23.000Z", "max_forks_repo_path": "src/kn2row_conv.c", "max_forks_repo_name": "chayitw/convolution-flavors", "max_forks_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2017-10-24T05:17:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T14:16:14.000Z", "avg_line_length": 34.0448717949, "max_line_length": 79, "alphanum_fraction": 0.601581623, "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177488, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.35573248940616736}}
{"text": "/* Leaf bindings for the GNU Scientific Library\n\n   Note that the GSL is GPL, not LGPL!.  If you include this code in\n   the libprim build, the result will be covered under the GPL.\n */\n\n#ifndef _LEAF_GSL_H_\n#define _LEAF_GSL_H_\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_poly.h>\n#include <leaf/grid.h>\n\n/* Direct gsl_ -> grid_ adapters. */\nint grid_linalg_SV_decomp(grid *A, grid *V, grid *S, grid *work); \nint grid_linalg_SV_solve(grid *gU, grid *gV, grid *gS, grid *gb, grid *gx);\n\nint grid_blas_dgemv(int transA, double alpha, grid *gA, grid *gx, double beta, grid *gy);\nint grid_blas_dgemm(int transA, int transB, double alpha, grid *gA, grid *gB, double beta, grid *gC);\nint grid_unfold(grid *gA, grid *gx, grid *gout);\n\n#endif\n", "meta": {"hexsha": "e39ee3779582a7242433990533213a8a3833bdf9", "size": 818, "ext": "h", "lang": "C", "max_stars_repo_path": "zl/gsl.h", "max_stars_repo_name": "zwizwa/libprim", "max_stars_repo_head_hexsha": "22df73f8cf2e848559a879ea9139abdc1b5d2239", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "zl/gsl.h", "max_issues_repo_name": "zwizwa/libprim", "max_issues_repo_head_hexsha": "22df73f8cf2e848559a879ea9139abdc1b5d2239", "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": "zl/gsl.h", "max_forks_repo_name": "zwizwa/libprim", "max_forks_repo_head_hexsha": "22df73f8cf2e848559a879ea9139abdc1b5d2239", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4615384615, "max_line_length": 101, "alphanum_fraction": 0.7188264059, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3556380045051593}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_chebyshev.h>\n\ndouble\nf (double x, void *p)\n{\n  p = 0;\n  if (x < 0.5)\n    return 0.25;\n  else\n    return 0.75;\n}\n\n\nint\nmain (void)\n{\n  double x;\n\n  gsl_cheb_series *cs = gsl_cheb_alloc (40);\n\n  gsl_function F;\n\n  F.function = f;\n  F.params = 0;\n\n  gsl_cheb_init (cs, &F, 0.0, 1.0);\n\n  for (x = -1; x < 2; x += 0.001)\n    {\n      double r10 = gsl_cheb_eval_n (cs, 10, x);\n      double r40 = gsl_cheb_eval (cs, x);\n      printf (\"%g %g %g %g\\n\", x, GSL_FN_EVAL (&F, x), r5, r40);\n    }\n\n  gsl_cheb_free (cs);\n}\n", "meta": {"hexsha": "df32f7325363fcc9c30979123ec6b64211a07a9b", "size": 571, "ext": "c", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/cheb/demo.c", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/cheb/demo.c", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/cheb/demo.c", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 14.641025641, "max_line_length": 64, "alphanum_fraction": 0.5551663748, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.35545832388382004}}
{"text": "/** \n * Simple and fast kmeans-implementation making use of multithreading.\n *\n * Author: Anders Bennehag\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Anders Bennehag\n *\n */\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <pthread.h>\n#include <assert.h>\n#include <gsl/gsl_rng.h>\n#include \"fastkmeans/fastkmeans.h\"\n\ntypedef enum {\n    SUCCESS=0,\n    ALLOCATION_ERROR,\n} fkm_error;\n\ntypedef enum {\n    WAIT,\n    RELEASED,\n    EXIT,\n} barrier_status;\n\ntypedef struct {\n    const gsl_matrix* points;\n    gsl_matrix* clusters;\n    const size_t num_points;\n    const size_t dim;\n    const size_t k;\n    unsigned* owner_of;\n} targs;\n\ntypedef struct {\n    pthread_mutex_t lock;\n    pthread_cond_t cond;\n    int count;\n    int goal;\n    barrier_status status;\n} tbarrier;\n\ntypedef struct {\n    targs* args;\n    size_t thread_id;\n    pthread_t pthread_id;\n    size_t num_threads;\n    tbarrier* bar_start;\n    tbarrier* bar_finish;\n} thread_meta;\n\ntypedef struct {\n    thread_meta* threads;\n    const size_t num_threads;\n    tbarrier bar_start;\n    tbarrier bar_finish;\n} thread_pool;\n\nint fkm_clusters_assignment(const thread_pool* tpool);\ndouble fkm_clusters_update(const targs* args);\ndouble fkm_matrix_diff(gsl_matrix* a, gsl_matrix* b);\nint fkm_threads_init(thread_pool* tpool);\nint fkm_threads_join(thread_pool* tpool);\nint barrier_finish(tbarrier* bar);\n\nint fkm_kmeans(const gsl_matrix* points, gsl_matrix* clusters,\n               size_t max_iter, int num_threads) {\n\n    if (num_threads<0) {\n        printf(\"Invalid number of threads\\n\");\n        return 1;\n    }\n\n    size_t num_points = points->size1;\n    unsigned owner_of[num_points];\n    targs args = {\n        .points=points,\n        .clusters=clusters,\n        .num_points=num_points,\n        .dim=points->size2,\n        .k=clusters->size1,\n        .owner_of=owner_of,\n    };\n\n    thread_meta tmeta[num_threads];\n    thread_pool tpool = {\n        .num_threads=num_threads,\n        .threads=tmeta,\n        .bar_start={\n            .lock=PTHREAD_MUTEX_INITIALIZER,\n            .cond=PTHREAD_COND_INITIALIZER,\n            .goal=num_threads+1,\n        },\n        .bar_finish={\n            .lock=PTHREAD_MUTEX_INITIALIZER,\n            .cond=PTHREAD_COND_INITIALIZER,\n            .goal=num_threads+1,\n        },\n    };\n    for (int i=0; i<num_threads; ++i) {\n        tmeta[i].args = &args;\n        tmeta[i].pthread_id = 0;\n        tmeta[i].thread_id = i;\n        tmeta[i].num_threads = num_threads;\n        tmeta[i].bar_start=&tpool.bar_start;\n        tmeta[i].bar_finish=&tpool.bar_finish;\n    }\n    fkm_threads_init(&tpool);\n    gsl_rng* rng = gsl_rng_alloc(gsl_rng_mt19937);\n    gsl_rng_set(rng, time(NULL));\n\n    // Randomize which center each point belongs to\n    for (size_t p=0; p < args.num_points; ++p) {\n        // TODO: Make sure every cluster gets assigned\n        owner_of[p] = gsl_rng_uniform_int(rng, args.k);\n        /*FKM_DEBUGFMT(\"Made %u owner of %lu\", owner_of[p], p);*/\n    }\n\n    // Initiate clusters to random point in input\n    for (size_t m=0; m<args.k; m++) {\n        size_t rand_p = gsl_rng_uniform_int(rng, args.num_points);\n        for (size_t j=0; j<args.dim; ++j) {\n            double val = gsl_matrix_get(points,\n                                        rand_p,\n                                        j);\n            gsl_matrix_set(clusters, m, j, val);\n        }\n    }\n\n    for (size_t it=0; it<max_iter; ++it) {\n        FKM_DEBUGFMT(\"iter %lu num_points %lu dim %lu, k %lu num_threads %i\", \n                it, args.num_points, args.dim, args.k, num_threads);\n        /*for (size_t p=0; p<num_points;++p) {*/\n            /*printf(\"%lu:%u \", p, owner_of[p]);*/\n        /*}*/\n        /*printf(\"\\n\");*/\n        fkm_clusters_assignment(&tpool);\n        double diff = fkm_clusters_update(&args);\n        FKM_DEBUGFMT(\"Diff: %f\", diff);\n        if (fabs(diff) < 1e-10) {\n            FKM_DEBUG(\"Break since no progress\");\n            break;\n        }\n    }\n    barrier_finish(&tpool.bar_start);\n    int err = fkm_threads_join(&tpool);\n    return 0;\n}\n\nint barrier_wait(tbarrier* bar) {\n    pthread_mutex_lock(&bar->lock);\n    FKM_DEBUGFMT(\"barrier_wait: count:%i goal:%i status:%i\", bar->count,\n                                                      bar->goal,\n                                                      bar->status);\n    assert(bar->goal > 0);\n    bar->count += 1;\n    if (bar->goal == bar->count) {\n        bar->status = RELEASED;\n        bar->count = 0;\n        FKM_DEBUG(\"Goal reached in barrier, broadcasting release\");\n        pthread_cond_broadcast(&bar->cond);\n        pthread_mutex_unlock(&bar->lock);\n        return 0;\n    }\n    pthread_mutex_unlock(&bar->lock);\n    for (;;) {\n        pthread_cond_wait(&bar->cond, &bar->lock);\n        if (bar->status == RELEASED) {\n            FKM_DEBUG(\"Barrier released\");\n            pthread_mutex_unlock(&bar->lock);\n            return 0;\n        } else if (bar->status == EXIT) {\n            FKM_DEBUG(\"Barrier signals FINISHED\");\n            pthread_mutex_unlock(&bar->lock);\n            return 1;\n        } else {\n            // Spurious wakeup\n            FKM_DEBUG(\"Spurious wakeup\");\n        }\n    }\n}\n\nint barrier_finish(tbarrier* bar) {\n    int err = pthread_mutex_lock(&bar->lock);\n    if (err) {\n        FKM_ERROR(\"Could not acquire mutex\");\n        return 1;\n    }\n    bar->status = EXIT;\n    err = pthread_mutex_unlock(&bar->lock);\n    if (err) {\n        FKM_ERROR(\"Could not release mutex\");\n        return 1;\n    }\n    err = pthread_cond_broadcast(&bar->cond);\n    if (err) {\n        FKM_ERROR(\"Could not broadcast cond-variable\");\n        return 1;\n    }\n    return 0;\n}\nint fkm_clusters_assignment_single(targs* args,\n                                     size_t offset,\n                                     size_t stride);\n\nvoid* fkm_thread_manage(void* data) {\n    thread_meta* tmeta = data;\n    targs* args = tmeta->args;\n\n    int stop=0;\n    for (;;) {\n        stop = barrier_wait(tmeta->bar_start);\n        if (stop) {\n            return 0;\n        }\n        fkm_clusters_assignment_single(args, \n                                       tmeta->thread_id, \n                                       tmeta->num_threads);\n        stop = barrier_wait(tmeta->bar_finish);\n        if (stop) {\n            return 0;\n        }\n    }\n}\n\nint fkm_clusters_assignment_single(targs* args,\n                                     size_t offset,\n                                     size_t stride) {\n    for (size_t p=offset; p<args->num_points; p+=stride) {\n        double min_err = 1e308;\n        for (size_t m=0; m<args->k; ++m) {\n            double err = 0;\n            for (size_t j=0; j<args->dim; ++j) {\n                double a = fabs(gsl_matrix_get(args->clusters, m, j)\n                                - gsl_matrix_get(args->points, p, j));\n                err += a*a;\n            }\n            if (err < min_err) {\n                min_err = err;\n                args->owner_of[p] = m;\n            }\n        }\n    }\n    return 0;\n}\n\nint fkm_threads_init(thread_pool* tpool) {\n\n    for (size_t thr=0; thr<tpool->num_threads;++thr) {\n        thread_meta* tdata = &tpool->threads[thr];\n        int err = pthread_create(&tdata->pthread_id,\n                                 NULL, \n                                 &fkm_thread_manage,\n                                 tdata);\n        if (err) {\n            FKM_ERRORFMT(\"pthread_create-error %i\", err);\n            return 1;\n        }\n    }\n    return 0;\n}\nint fkm_threads_join(thread_pool* tpool) {\n    for (size_t thr=0; thr<tpool->num_threads;++thr) {\n        thread_meta* tdata = &tpool->threads[thr];\n        int err = pthread_join(tdata->pthread_id, NULL);\n        if (err) {\n            FKM_ERRORFMT(\"pthread_join-error %i\", err);\n        }\n        return 1;\n    }\n    return 0;\n}\n\nint fkm_clusters_assignment(const thread_pool* tpool) {\n    tbarrier* bar_start = tpool->threads[0].bar_start;\n    FKM_DEBUGFMT(\"bar_start: count:%i goal:%i status:%i\", bar_start->count,\n                                                      bar_start->goal,\n                                                      bar_start->status);\n    int err = barrier_wait(bar_start);\n    if (err) {\n        FKM_ERROR(\"barrier_wait failed\");\n        return 1;\n    }\n    tbarrier* bar_finish = tpool->threads[0].bar_finish;\n    FKM_DEBUGFMT(\"bar_finish: count:%i goal:%i status:%i\", bar_finish->count,\n                                                      bar_finish->goal,\n                                                      bar_finish->status);\n    err = barrier_wait(tpool->threads[0].bar_finish);\n    if (err) {\n        FKM_ERROR(\"barrier_wait failed\");\n        return 1;\n    }\n    return 0;\n}\n\n/**\n * Update clusters.\n *\n *\n */\ndouble fkm_clusters_update(const targs* args) {\n    /*printf(\"DEBUG: num_points %lu dim %lu, k %lu\\n\", num_points, dim, k);*/\n    unsigned cluster_size[args->k];\n    for (size_t m=0; m<args->k; ++m) {\n        cluster_size[m] = 0;\n    }\n    gsl_matrix* mean_sums = gsl_matrix_calloc(args->k, args->dim);\n    for (size_t p=0; p<args->num_points; ++p) {\n        unsigned m = args->owner_of[p];\n        assert(m < args->k);\n        cluster_size[m] += 1;\n        /*LOGFMT(\"p:%lu belongs to %u. Children %u\", p, m, cluster_size[m]);*/\n        for (size_t j=0; j<args->dim; ++j) {\n            double val = gsl_matrix_get(mean_sums, m, j)\n                + gsl_matrix_get(args->points, p, j);\n            gsl_matrix_set(mean_sums, m, j, val);\n        }\n    }\n    double diff = 0;\n    for (size_t m=0; m<args->k; ++m) {\n        /*printf(\"Updating cluster %lu to\", m);*/\n        for (size_t j=0; j<args->dim; ++j) {\n            double val = gsl_matrix_get(mean_sums, m, j);\n            val /= cluster_size[m];\n            diff += val - gsl_matrix_get(args->clusters, m, j);\n            gsl_matrix_set(args->clusters, m, j, val);\n            /*printf(\" %u %f\", cluster_size[m], val);*/\n        }\n        /*printf(\"\\n\");*/\n    }\n    gsl_matrix_free(mean_sums);\n    return diff;\n}\n\ntypedef double (*elem_func)(double, double);\n\ndouble fkm_matrix_elem_func(gsl_matrix* a, gsl_matrix* b, elem_func f) {\n    double v = 0;\n    for (size_t i=0; i<a->block->size; ++i) {\n        v += f(a->block->data[i], b->block->data[i]);\n    }\n    return v;\n}\n\ndouble diff(double a, double b) {\n    return fabs(a - b);\n}\n\ndouble fkm_matrix_diff(gsl_matrix* a, gsl_matrix* b) {\n    return fkm_matrix_elem_func(a, b, diff);\n}\n\nvoid print_matrix(gsl_matrix* a) {\n    for (size_t i=0; i<5 && i<a->block->size; ++i) {\n        printf(\"%lu: %f\\n\", i, a->block->data[i]);\n    }\n}\n\ngsl_matrix* fkm_matrix_load(FILE* fin) {\n    size_t rows, cols;\n    int err = fscanf(fin, \"%lu %lu\", &rows, &cols);\n    if (err == EOF) {\n        printf(\"ERROR: Could not parse matrix dimensions\\n\");\n        return 0;\n    }\n    gsl_matrix* mat = gsl_matrix_alloc(rows, cols);\n    err = gsl_matrix_fscanf(fin, mat);\n    if (err) {\n        printf(\"ERROR: Could not parse matrix data\\n\");\n        return 0;\n    }\n    printf(\"Loaded %lu rows, %lu columns matrix\\n\", rows, cols);\n    return mat;\n}\n\nint fkm_matrix_save(FILE* fout, gsl_matrix* mat) {\n    int err = 0;\n    fprintf(fout, \"%zu %zu\\n\", mat->size1, mat->size2);\n    for (size_t i=0; i<mat->block->size; ++i) {\n        if (i && i % mat->size2 == 0) {\n            err = fprintf(fout, \"\\n\");\n            if (err<0) {\n                FKM_ERRORFMT(\"fprintf returned %i\", err);\n            }\n        }\n        int err = fprintf(fout, \"%f \", mat->block->data[i]);\n        if (err<0) {\n            FKM_ERRORFMT(\"fprintf returned %i\", err);\n        }\n    }\n    return err;\n}\n\n", "meta": {"hexsha": "e0b39292c9e4758e3edad4c0e329928f0811eb62", "size": 11625, "ext": "c", "lang": "C", "max_stars_repo_path": "src/fastkmeans/fastkmeans.c", "max_stars_repo_name": "PureW/fast-kmeans", "max_stars_repo_head_hexsha": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fastkmeans/fastkmeans.c", "max_issues_repo_name": "PureW/fast-kmeans", "max_issues_repo_head_hexsha": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fastkmeans/fastkmeans.c", "max_forks_repo_name": "PureW/fast-kmeans", "max_forks_repo_head_hexsha": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd", "max_forks_repo_licenses": ["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.0625, "max_line_length": 78, "alphanum_fraction": 0.5416774194, "num_tokens": 3056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.35539823064010906}}
{"text": "//\n// Author: Valerio Bertone: valerio.bertone@cern.ch\n//\n\n#pragma once\n\n#include <string>\n#include <vector>\n#include <utility>\n\n#include <apfel/apfelxx.h>\n#include <yaml-cpp/yaml.h>\n#include <gsl/gsl_rng.h>\n\nnamespace NangaParbat\n{\n  /**\n   * @brief The \"DataHandler\" class provides a common interface to all\n   * datasets. It provides methods to get kinematics, central values,\n   * uncertainties, etc.\n   */\n  class DataHandler\n  {\n  public:\n\n    /**\n     * @brief The process enumerator\n     */\n    enum Process: int {UnknownProcess = -1, DY = 0, SIDIS = 1, SIA = 2, DIA = 3};\n\n    /**\n     * @brief The observable enumerator\n     */\n    enum Observable: int {UnknownObservable = -1, dsigma_dxdydz = 0, dsigma_dxdQdz = 1, multiplicity = 2};\n\n    /**\n     * @brief Structure containing the kinematic information of one\n     * single data set.\n     */\n    struct Kinematics\n    {\n      Kinematics();\n      bool empty() const;\n      int                                    ndata;    //!< Number of data points\n      double                                 Vs;       //!< Center of mass energy\n      std::vector<double>                    qTv;      //!< Vector of qT values\n      std::vector<std::pair<double, double>> qTmap;    //!< Map of qT bounds to associate to the single bins\n      std::vector<double>                    qTfact;   //!< Possible bin-by-bin prefactors to multiply the theoretical predictions\n      std::pair<double, double>              var1b;    //!< Variable 1 integration bounds\n      std::pair<double, double>              var2b;    //!< Variable 2 integration bounds\n      std::pair<double, double>              var3b;    //!< Variable 3 integration bounds\n      bool                                   IntqT;    //!< Whether the bins in qTv are integrated over\n      bool                                   Intv1;    //!< Whether the bins variable 1 are integrated over\n      bool                                   Intv2;    //!< Whether the bins variable 2 are integrated over\n      bool                                   Intv3;    //!< Whether the bins variable 3 are integrated over\n      bool                                   PSRed;    //!< Whether there is a final-state PS reduction\n      double                                 pTMin;    //!< Minimum pT of the final-state leptons\n      std::pair<double, double>              etaRange; //!< Allowed range in eta of the final-state leptons\n    };\n\n    /**\n     * @brief Structure containing the single bin information. This is\n     * currently used only for the FF_SIDIS project.\n     * @todo Integrate it better in the rest of the class.\n     */\n    struct Binning\n    {\n      Binning();\n      double zmin;\n      double zmax;\n      double zav;\n      bool Intz;\n      double xmin;\n      double xmax;\n      double xav;\n      bool Intx;\n      double Qmin;\n      double Qmax;\n      double Qav;\n      bool IntQ;\n      double ymin;\n      double ymax;\n      double yav;\n      bool Inty;\n    };\n\n    /**\n     * @brief The \"DataHandler\" copy constructor.\n     */\n    DataHandler(DataHandler const &DH);\n\n    /**\n     * @brief The \"DataHandler\" constructor.\n     * @param name: the name associated to the data set\n     * @param datafile: the YAML:Node with the interpolation table\n     * @param rng: GSL random number object\n     * @param fluctuation: ID of the fluctuation (i.e. Monte-Carlo replica ID) (default: 0, i.e. no fluctuations)\n     * @param t0: vector of predictions to be used for the t0-prescription\n     */\n    DataHandler(std::string const& name, YAML::Node const& datafile, gsl_rng* rng = nullptr, int const& fluctuation = 0, std::vector<double> const& t0 = {});\n\n    /**\n     * @brief Function that fluctuates data\n     * @param rng: GSL random number object\n     * @param fluctuation: ID of the fluctuation (i.e. Monte-Carlo replica ID) (default: 0, i.e. no fluctuations)\n     */\n    void FluctuateData(gsl_rng *rng, int const &fluctuation);\n\n    /**\n     * @brief Function that sets the data central values replacing that\n     * introduced in the constructor.\n     * @param means: the new means\n     */\n    void SetMeans(std::vector<double> const& means, gsl_rng* rng = nullptr, int const& fluctuation = 0);\n\n    /**\n     * @brief Function that returns the name of the dataset\n     */\n    std::string GetName() const { return _name; };\n\n    /**\n     * @brief Function that returns the datafile in YAML format\n     */\n    YAML::Node GetDataFile() const { return _datafile; };\n\n    /**\n     * @brief Function that returns the process code\n     */\n    Process GetProcess() const { return _proc; };\n\n    /**\n     * @brief Function that returns the observable code\n     */\n    Observable GetObservable() const { return _obs; };\n\n    /**\n     * @brief Function that returns the target isoscalarity\n     * @note The code always assumes that one of the hadrons has\n     * isoscalarity 1, meaning that it's a single hadron whose\n     * distributions don't need to be manipulated.\n     */\n    double GetTargetIsoscalarity() const { return _targetiso; };\n\n    /**\n     * @brief Function that returns the possible identified hadron\n     * species in the final state.\n     */\n    std::string GetHadron() const { return _hadron; };\n\n    /**\n     * @brief Function that returns the charge of the identified final\n     * state.\n     */\n    int GetCharge() const { return _charge; };\n\n    /**\n     * @brief Function that returns the quark-tagged compoments. Zero\n     * corresponds to total.\n     */\n    std::vector<apfel::QuarkFlavour> GetTagging() const { return _tagging; };\n\n    /**\n     * @brief Function that returns any possible constant prefactor to\n     * be used to multiply the theoretical predictions.\n     */\n    double GetPrefactor() const { return _prefact; };\n\n    /**\n     * @brief Function that returns the kinematic object\n     */\n    Kinematics GetKinematics() const { return _kin; };\n\n    /**\n     * @brief Function that returns the mean values\n     */\n    std::vector<double> GetMeanValues() const { return _means; };\n\n    /**\n     * @brief Function that returns the fluctuated data\n     */\n    std::vector<double> GetFluctutatedData() const { return _fluctuations; };\n\n    /**\n     * @brief Function that returns the sum in quadrature of the\n     * uncorrelated uncertainties.\n     */\n    std::vector<double> GetUncorrelatedUnc() const { return _uncor; };\n\n    /**\n     * @brief Function that returns the additive correlated systematic\n     * uncertainties.\n     */\n    std::vector<std::vector<double>> GetAddCorrelatedUnc() const { return _corra; };\n\n    /**\n     * @brief Function that returns the multiplicative correlated\n     * systematic uncertainties.\n     */\n    std::vector<std::vector<double>> GetMultCorrelatedUnc() const { return _corrm; };\n\n    /**\n     * @brief Function that returns the all the correlated systematic\n     * uncertainties (additive first and multiplicative second).\n     */\n    std::vector<std::vector<double>> GetCorrelatedUnc() const { return _corr; };\n\n    /**\n     * @brief Function that returns the covariance matrix of the\n     * correlated uncertainties.\n     */\n    apfel::matrix<double> GetCovarianceMatrix() const { return _covmat; };\n\n    /**\n     * @brief Function that returns the Cholesky decomposition of the\n     * covariance matrix.\n     */\n    apfel::matrix<double> GetCholeskyDecomposition() const { return _CholL; };\n\n    /**\n     * @brief Function that returns the set of t0 predictions\n     */\n    std::vector<double> GetT0() const { return _t0; };\n\n    /**\n     * @brief Function that returns the plotting labels.\n     */\n    std::map<std::string, std::string> GetLabels() const { return _labels; };\n\n    /**\n     * @brief Get vector of bins. This is currently used only for the\n     * FF_SIDIS project.\n     * @todo Integrate it better in the rest of the\n     * class.\n     */\n    std::vector<Binning> GetBinning() const { return _bins; }\n\n  protected:\n\n    std::string                        _name;         //!< Name of the dataset\n    YAML::Node                         _datafile;     //!< Datafile in YAML\n    Process                            _proc;         //!< The process\n    Observable                         _obs;          //!< The observable\n    double                             _targetiso;    //!< Isoscalarity of the target\n    std::string                        _hadron;       //!< Hadron species identified in the final state\n    double                             _charge;       //!< Charge of the identified final state\n    std::vector<apfel::QuarkFlavour>   _tagging;      //!< Possible quark-tagged components\n    double                             _prefact;      //!< Possible overall prefactor to multiply the theoretical predictions\n    Kinematics                         _kin;          //!< Kinematics block\n    std::vector<double>                _means;        //!< Vector of central values\n    std::vector<double>                _uncor;        //!< Vector of uncorrelated uncertainties\n    std::vector<std::vector<double>>   _corra;        //!< Additive correlated uncertainties\n    std::vector<std::vector<double>>   _corrm;        //!< Multiplicative correlated uncertainties\n    std::vector<std::vector<double>>   _corr;         //!< All correlated uncertainties\n    apfel::matrix<double>              _covmat;       //!< Covariance matrix\n    apfel::matrix<double>              _CholL;        //!< Cholesky decomposition of the covariance matrix\n    std::map<std::string, std::string> _labels;       //!< Labels used for plotting\n    std::vector<double>                _fluctuations; //!< Vector of fluctuated data\n    std::vector<double>                _t0;           //!< Vector of t0-predictions\n    std::vector<Binning>               _bins;         //!< Vector of bins (currently used only for the FF_SIDIS project)\n\n    friend std::ostream& operator << (std::ostream& os, DataHandler const& DH);\n  };\n\n  std::ostream& operator << (std::ostream &os, DataHandler const& DH);\n}\n", "meta": {"hexsha": "6aaae932b1188cfc7ae5571d68eea8b3ef49aed3", "size": 9964, "ext": "h", "lang": "C", "max_stars_repo_path": "inc/NangaParbat/datahandler.h", "max_stars_repo_name": "vbertone/NangaParbat", "max_stars_repo_head_hexsha": "49529d0a2e810dfe0ec676c8e96081be39a8800d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-16T17:15:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T10:59:39.000Z", "max_issues_repo_path": "inc/NangaParbat/datahandler.h", "max_issues_repo_name": "vbertone/NangaParbat", "max_issues_repo_head_hexsha": "49529d0a2e810dfe0ec676c8e96081be39a8800d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/NangaParbat/datahandler.h", "max_forks_repo_name": "vbertone/NangaParbat", "max_forks_repo_head_hexsha": "49529d0a2e810dfe0ec676c8e96081be39a8800d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-01-18T22:10:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-01T18:42:36.000Z", "avg_line_length": 37.4586466165, "max_line_length": 157, "alphanum_fraction": 0.5933360096, "num_tokens": 2331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3553154639737584}}
{"text": "/*\n * library_def.h\n *\n *  Created on: 2019. 9. 3.\n *      Author: Misun Yu, Dongsik Choi\n */\n\n#ifndef LIBRARY_H_\n#define LIBRARY_H_\n\n//#define _DEBUG\n//#define THREAD_MATMUL\n//#define _USE_OPENBLAS_MATMUL\n//#define _USE_OPENBLAS_CONV\n\n//#define _CONV_ORIGINAL\n//#define _CONV_GROUP_ORIGINAL\n//#define _USE_LLVM 1\n\n#ifdef __MACH__\n#include <stdlib.h>\n#else\n#include <malloc.h>\n#endif\n\n\n#include <vector>\n#include <string.h>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n\n#include <algorithm>\n#include <vector>\n#include <iostream>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n//#include <omp.h>\n#include <time.h>\n#include <assert.h>\n\n#ifdef _USE_OPENBLAS_MATMUL\n#include <cblas.h>\n#else\n\n#ifdef _USE_OPENBLAS_CONV\n#include <cblas.h>\n#else\n\n#endif\n\n#endif\n\n\n#ifdef __MACH__\n#include <dispatch/dispatch.h>\n#else\n#include <semaphore.h>\n#endif\n\n\nusing namespace std;\n\n//#define FLOAT    0\n//#define DOUBLE   1\n//#define INT      2\n//#define CHAR     3\n\ntypedef int8_t i8;\ntypedef uint8_t ui8;\ntypedef int16_t i16;\ntypedef int32_t i32;\n\n#if defined(__MACH__) || defined(_USE_LLVM)\n#define MAX_PAD_SIZE 3 //msyu\n#endif\n\nusing namespace std;\n\nvoid read_vector(vector<size_t>* vec, ifstream* readFileBin);\n\n/*\n *\n *\n * Batch Normalization\n *\n *\n */\n\n\ntemplate <typename T1, size_t N1, size_t N2, size_t N3, size_t N4,\n        typename T2>\nvoid splat(T1 (&in1)[N1][N2][N3][N4], int axis, T2 (&result)[N1][N2][N3][N4])\n{\n#ifdef _DEBUG\n    cout << \"splat()-4D\" << endl;\n#endif\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n}\n\ntemplate <typename T1, size_t K1, size_t L1, size_t M1, size_t N1,\n        typename T2, size_t K2, size_t L2, size_t M2, size_t N2,\n        typename T3, size_t K3, size_t L3, size_t M3, size_t N3>\nvoid concat(int axis, T1 (&in1)[N1][M1][K1][L1], T2 (&in2)[N2][M2][K2][L2], T3 (&result)[N3][M3][K3][L3])\n{\n#ifdef _DEBUG\n    cout << \"concat()-4D\" << endl;\n    cout << \"axis: \" << axis << endl;\n#endif\n    if(axis == 3) {\n        for(size_t i = 0; i < N3; i++) {\n            for(size_t j = 0; j < M3; j++) {\n                for(size_t k = 0; k < K3; k++) {\n                    for(size_t l = 0; l < L3; l++) {\n                        if(l < L1) {\n                            result[i][j][k][l] = in1[i][j][k][l];\n                        } else {\n                            result[i][j][k][l] = in2[i][j][k][l-L1];\n                        }\n                    }\n                }\n            }\n        }\n    } else {\n        cout << \"Not supported. \" << axis << endl;\n    }\n    //\tend = clock();\n    //    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n}\n\ntemplate <typename T1, size_t N, size_t M, size_t K, size_t L>\nvoid batchNorm(T1 (&in)[N][M][K][L], T1 (&scale)[M], T1 (&bias)[M], T1 (&mean)[M], T1 (&var)[M], unsigned int channelIdx, T1 epsilon, T1 momentum, T1 (&result)[N][M][K][L])\n{\n    //NCHW\n//\n#ifdef _DEBUG\n    cout << \"batchNorm() - 1\" << endl;\n  cout << \"channel: \" << channelIdx << endl;\n  cout << \"N: \" << N << endl;\n  cout << \"M: \" << M << endl;\n  cout << \"K: \" << K << endl;\n  cout << \"L: \" << L << endl;\n#endif\n\n    for(size_t i = 0; i < N; i++) {\n        for(size_t j = 0; j < M; j++) {\n            for(size_t k = 0; k < K; k++) {\n                for(size_t l = 0; l < L; l++) {\n                    float norm = (in[i][j][k][l] - mean[j])/sqrtf(epsilon + var[j]);\n                    result[i][j][k][l] = scale[j]* norm + bias[j];\n                }\n            }\n        }\n    }\n}\n\ntemplate <typename T1, size_t N, size_t M, size_t K, size_t L>\nvoid batchNorm(T1 (&in)[N][L][K][M], T1 (&scale)[M], T1 (&bias)[M], T1 (&mean)[M], T1 (&var)[M], unsigned int channelIdx, T1 epsilon, T1 momentum, T1 (&result)[N][L][K][M])\n{\n    //NCHW\n//\n#ifdef _DEBUG\n    cout << \"batchNorm() - 2\" << endl;\n    cout << \"channel: \" << channelIdx << endl;\n    cout << \"N: \" << N << endl;\n    cout << \"L: \" << L << endl;\n    cout << \"K: \" << K << endl;\n    cout << \"M: \" << M << endl;\n\n#endif\n\n    for(size_t i = 0; i < N; i++) {\n        for(size_t j = 0; j < L; j++) {\n            for(size_t k = 0; k < K; k++) {\n                for(size_t l = 0; l < M; l++) {\n                    float norm = (in[i][j][k][l] - mean[l])/sqrtf(epsilon + var[l]);\n                    result[i][j][k][l] = scale[l]* norm + bias[l];\n                }\n            }\n        }\n    }\n}\n\n/*\n *\n *\n * Convolution\n *\n *\n */\n\nextern int conv_idx;\n\n#ifdef _CONV_ORIGINAL\n\ntemplate <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL,\n        typename T2, size_t FILTER_SIZE, size_t FILTER_HEIGHT, size_t FILTER_WIDTH, size_t FILTER_CHANNEL,\n        typename T3, size_t N2,\n        typename T4, size_t N3, size_t M3, size_t K3, size_t L3>\nvoid conv(T1 (&in1)[BATCH][HEIGHT][WIDTH][CHANNEL], T2 (&filter)[FILTER_SIZE][FILTER_HEIGHT][FILTER_WIDTH][FILTER_CHANNEL], vector<size_t> filter_dim, T3 (&bias)[N2], \\\n\tvector<size_t> stride, vector<size_t> pad, int group, T4 (&result)[N3][M3][K3][L3])\n{\n#ifdef _DEBUG\n    cout << conv_idx++ << \": conv()-original\" << endl;\n\n    cout << \"BATCH: \" << BATCH << endl;\n    cout << \"HEIGHT: \" << HEIGHT << endl;\n    cout << \"WIDTH: \" << WIDTH << endl;\n    cout << \"CHANNEL: \" << CHANNEL << endl;\n    cout << \"pad: \" << pad.at(0) << endl;\n    cout << \"stride: \" << stride.at(0) << endl;\n    cout << \"FILTER_HEIGHT: \" << FILTER_HEIGHT << endl;\n    cout << \"FILTER_WIDTH: \" << FILTER_WIDTH << endl;\n    cout << \"FILTER_CHANNEL: \" << FILTER_CHANNEL << endl;\n    //N, H, W, C\n    //N == 1\n    //group == 1\n#endif\n\n    int pad_xleft = pad.at(0);\n    int pad_xright = pad.at(1);\n    int pad_ytop = pad.at(2);\n    int pad_ybottom = pad.at(3);\n    int xadd = pad_xleft + pad_xright;\n    int yadd = pad_ytop + pad_ybottom;\n\n    int stride_size = stride.at(0);\n\n    int filter_h = filter_dim.at(1);\n    int filter_w = filter_dim.at(2);\n    int filter_size = filter_dim.at(0);\n\n    int out_h = (HEIGHT + yadd - filter_h)/stride_size + 1;\n    int out_w = (WIDTH + xadd - filter_w)/stride_size + 1;\n\n#ifdef _DEBUG\n    cout << \"FILTER_SIZE: \" << FILTER_SIZE << endl;\n    cout << \"out_h: \" << out_h << endl;\n    cout << \"out_w: \" << out_w << endl;\n\n    struct timespec tp, ep;\n    double timeCheck;\n    clock_gettime(CLOCK_MONOTONIC, &tp);\n#endif\n\n\n#if defined(__MACH__) || defined(_USE_LLVM)\n    float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL];\n    newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n    memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n#else\n    float (* newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL];\n    newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n    memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n#endif\n\n    for (int b = 0; b < BATCH; b++){\n        for (size_t c = 0; c < CHANNEL; c++){\n            for (int h = 0; h < HEIGHT; h++){\n                for (int w = 0; w < WIDTH; w++){\n                    (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in1[b][h][w][c];\n                }\n            }\n        }\n    }\n\n    int new_h_idx = 0, new_w_idx = 0;\n    for (int b = 0; b < BATCH; b++){\n        for(int fc = 0; fc < filter_size; fc++) {\n            for(int i = 0; i <out_h; i++) {\n                for(int j = 0; j <out_w; j++) {\n\n                    float total = 0.0;\n                    for(int fh = 0; fh <filter_h; fh++) {\n                        for(int fw = 0; fw <filter_w; fw++) {\n                            for(size_t f = 0; f < CHANNEL; f++) {\n                                total = total + (*newin)[b][new_h_idx+fh][new_w_idx+fw][f]*filter[fc][fh][fw][f];\n                            }\n                        }\n                    }\n                    result[b][i][j][fc] = total + bias[fc];\n                    new_w_idx += stride_size;\n                }\n                new_h_idx += stride_size;\n                new_w_idx = 0;\n            }\n            new_h_idx = 0;\n        }\n    }\n\n#ifdef _DEBUG\n    free(newin);\n    clock_gettime(CLOCK_MONOTONIC, &ep);\n    timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0);\n    cout << \"==================== \" + to_string(conv_idx++) + \" convolution time : \" << timeCheck <<\" seconds  ====================\" << endl << endl;\n#endif\n}\n#else\n\n#ifdef __MACH__\nextern dispatch_semaphore_t    semaphore;\n#else\nextern    sem_t  semaphore;\n#endif\n\n// \uc2a4\ub808\ub4dc \uc218 \uc815\uc758\n#define MAX_THREAD 2\n\n//\uc2a4\ub808\ub4dc\ub97c \uc0ac\uc6a9\ud558\uae30 \uc704\ud55c \uad6c\uc870\uccb4.\ntemplate <typename T1, typename T2, typename T3, int tN, int tM, int tM1>\nstruct tTHREAD{\n    T1(*arrr)[tM];\n    T2(*brrr1)[tM][tM1];\n    T3(*crrr1)[tN][tM1];\n    int b;\n    int cnt;\n};\n// \uc2a4\ub808\ub4dc \ud568\uc218\ntemplate <typename T1, typename T2, typename T3, int tN, int tM, int tM1>\nvoid *multi(void *num)\n{\n    struct tTHREAD<float, float, float, tN, tM, tM1> *numMul = (struct tTHREAD<float, float, float, tN, tM, tM1> *)num;\n    // cnt\ub294 \ud604\uc7ac \uc0ac\uc6a9\ub418\ub824\ub294 \uc2a4\ub808\ub4dc \ubc88\ud638.\n    int core = numMul->cnt;\n    int B = numMul->b;\n\n    int mN = tN / MAX_THREAD * (core + 1);\n    if (core == MAX_THREAD - 1) mN = tN;\n\n    for (int i = core * (tN / MAX_THREAD); i < mN; i++) {// \uac01 \uc2a4\ub808\ub4dc\ub294 \ud589\ub82c \ud589 \uae30\uc900\uc73c\ub85c \uc2a4\ub808\ub4dc \uac1c\uc218\ub9cc\ud07c \ub098\ub220\uc11c \uc5f0\uc0b0\n        for (int k = 0; k < tM; k++) {\n            for (int j = 0; j < tM1; j++) {\n                numMul->crrr1[B][i][j] += numMul->arrr[i][k] * numMul->brrr1[B][k][j];\n            }\n        }\n    }\n\n#ifdef __MACH__\n    dispatch_semaphore_signal(semaphore);\n#else\n    sem_post(&semaphore);\n#endif\n\n    return nullptr;\n}\n\n\n\n#ifdef _CONV_GROUP_ORIGINAL\n\ntemplate <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL,\n        typename T2, size_t FILTER_SIZE, size_t FILTER_HEIGHT, size_t FILTER_WIDTH, size_t FILTER_CHANNEL,\n        typename T3, size_t N2,\n        typename T4, size_t N3, size_t M3, size_t K3, size_t L3>\nvoid conv_group(T1 (&in1)[BATCH][HEIGHT][WIDTH][CHANNEL], T2 (&filter)[FILTER_SIZE][FILTER_HEIGHT][FILTER_WIDTH][FILTER_CHANNEL], vector<size_t> kernel_dim, T3 (&bias)[N2], \\\n\tvector<size_t> stride, vector<size_t> pad, int group, T4 (&result)[N3][M3][K3][L3])\n{\n#ifdef _DEBUG\n    cout << \"conv_group()-original\" << endl;\n\n    cout << \"BATCH: \" << BATCH << endl;\n    cout << \"HEIGHT: \" << HEIGHT << endl;\n    cout << \"WIDTH: \" << WIDTH << endl;\n    cout << \"CHANNEL: \" << CHANNEL << endl;\n    cout << \"pad: \" << pad.at(0) << endl;\n    cout << \"stride: \" << stride.at(0) << endl;\n    cout << \"FILTER_SIZE: \" << FILTER_SIZE << endl;\n    cout << \"FILTER_HEIGHT: \" << FILTER_HEIGHT << endl;\n    cout << \"FILTER_WIDTH: \" << FILTER_WIDTH << endl;\n    cout << \"FILTER_CHANNEL: \" << FILTER_CHANNEL << endl;\n\n    cout << \"OUT BATCH: \" << N3 << endl;\n    cout << \"OUT HEIGHT: \" << M3 << endl;\n    cout << \"OUT WIDTH: \" << K3 << endl;\n    cout << \"OUT CHANNEL: \" << L3 << endl;\n\n    cout << \"group: \" << group << endl;\n    //N, H, W, C\n    //N == 1\n    //group == 1\n#endif\n\n    int pad_xleft = pad.at(0);\n    int pad_xright = pad.at(1);\n    int pad_ytop = pad.at(2);\n    int pad_ybottom = pad.at(3);\n    int xadd = pad_xleft + pad_xright;\n    int yadd = pad_ytop + pad_ybottom;\n\n    int stride_size = stride.at(0);\n\n    int kernel_h = kernel_dim.at(1);\n    int kernel_w = kernel_dim.at(2);\n    int kernel_size = kernel_dim.at(0);\n\n    int out_h = (HEIGHT + yadd - kernel_h)/stride_size + 1;\n    int out_w = (WIDTH + xadd - kernel_w)/stride_size + 1;\n\n#ifdef _DEBUG\n    cout << \"FILTER_SIZE: \" << FILTER_SIZE << endl;\n    cout << \"out_h: \" << out_h << endl;\n    cout << \"out_w: \" << out_w << endl;\n    cout << \"kernel_h: \" << kernel_h << endl;\n    cout << \"kernel_w: \" << kernel_w << endl;\n    cout << \"kernel_size: \" << kernel_size << endl;\n\n    struct timespec tp, ep;\n    double timeCheck;\n    clock_gettime(CLOCK_MONOTONIC, &tp);\n#endif\n\n\n#if defined(__MACH__) || defined(_USE_LLVM)\n    float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL];\n    newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n    memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n#else\n    float (* newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL];\n    newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n    memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n#endif\n\n\n    for (int b = 0; b < BATCH; b++){\n        for (size_t c = 0; c < CHANNEL; c++){\n            for (int h = 0; h < HEIGHT; h++){\n                for (int w = 0; w < WIDTH; w++){\n                    (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in1[b][h][w][c];\n                }\n            }\n        }\n    }\n\n    int splitKernelSize = kernel_size/group;\n    int new_h_idx = 0, new_w_idx = 0;\n\n    for (int b = 0; b < BATCH; b++) {\n        for(int g = 0; g < group; g++) {\n            for (int fc = 0; fc < splitKernelSize; fc++) {\n                for (int i = 0; i < out_h; i++) {\n                    for (int j = 0; j < out_w; j++) {\n\n                        float total = 0.0;\n                        for (int fh = 0; fh < kernel_h; fh++) {\n                            for (int fw = 0; fw < kernel_w; fw++) {\n                                for (size_t f = 0; f < FILTER_CHANNEL; f++) {\n                                    total = total + (*newin)[b][new_h_idx + fh][new_w_idx + fw][g*FILTER_CHANNEL + f] *\n                                                    filter[g*splitKernelSize + fc][fh][fw][f];\n                                }\n                            }\n                        }\n                        result[b][i][j][g*splitKernelSize + fc] = total + bias[g*splitKernelSize + fc];\n                        new_w_idx += stride_size;\n                    }\n                    new_h_idx += stride_size;\n                    new_w_idx = 0;\n                }\n                new_h_idx = 0;\n            }\n        }\n    }\n\n\n\n#ifdef _DEBUG\n    free(newin);\n    clock_gettime(CLOCK_MONOTONIC, &ep);\n    timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0);\n    cout << \"==================== \" + to_string(conv_idx++) + \" convolution time : \" << timeCheck <<\" seconds  ====================\" << endl << endl;\n#endif\n}\n#else\n//\n//convolution image to columns\ntemplate <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL,\n        typename T2, size_t FILTER_SIZE, size_t FILTER_HEIGHT, size_t FILTER_WIDTH, size_t FILTER_CHANNEL,\n        typename T3, size_t N2,\n        typename T4, size_t N3, size_t M3, size_t K3, size_t L3>\nvoid conv_group(T1 (&in1)[BATCH][HEIGHT][WIDTH][CHANNEL], T2 (&filter)[FILTER_SIZE][FILTER_HEIGHT][FILTER_WIDTH][FILTER_CHANNEL], vector<size_t> filter_dim, T3 (&bias)[N2], \\\n\tvector<size_t> stride, vector<size_t> pad, size_t group, T4 (&result)[N3][M3][K3][L3])\n{\n //   cout <<  \"-- conv() group: \" << group << endl;\n\n#ifdef _DEBUG\n    cout <<  \"-- conv() -- \" << endl;\n\n  cout << \"BATCH: \" << BATCH << endl;\n  cout << \"HEIGHT: \" << HEIGHT << endl;\n  cout << \"WIDTH: \" << WIDTH << endl;\n  cout << \"CHANNEL: \" << CHANNEL << endl;\n  cout << \"pad: \" << pad.at(0) << endl;\n  cout << \"stride: \" << stride.at(0) << endl;\n  cout << \"FILTER_HEIGHT: \" << FILTER_HEIGHT << endl;\n  cout << \"FILTER_WIDTH: \" << FILTER_WIDTH << endl;\n  cout << \"FILTER_CHANNEL: \" << FILTER_CHANNEL << endl;\n  cout << \"BIAS LEN: \" << N2 << endl;\n#endif\n\n    int pad_xleft = pad.at(0);\n    int pad_xright = pad.at(1);\n    int pad_ytop = pad.at(2);\n    int pad_ybottom = pad.at(3);\n    int xadd = pad_xleft + pad_xright;\n    int yadd = pad_ytop + pad_ybottom;\n\n    int stride_size = stride.at(0);\n\n    int out_h = (HEIGHT + yadd - FILTER_HEIGHT)/stride_size + 1;\n    int out_w = (WIDTH + xadd - FILTER_WIDTH)/stride_size + 1;\n\n#ifdef _DEBUG\n    cout << \"FILTER_SIZE: \" << FILTER_SIZE << endl;\n  cout << \"out_h: \" << out_h << endl;\n  cout << \"out_w: \" << out_w << endl;\n\n  struct timespec tp, ep;\n  double timeCheck;\n  clock_gettime(CLOCK_MONOTONIC, &tp);\n#endif\n\n#if defined(__MACH__) || defined(_USE_LLVM)\n    float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL];\n    newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n    memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n#else\n    float (* newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL];\n  newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n  memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n#endif\n\n    //step 1. \ud328\ub529\n\n    //int jp, kp;\n    //printf(\"\ud328\ub529 \ubcc0\ud658 \uc911\\n\");\n    for (int b = 0; b < BATCH; b++){\n        for (int h = 0; h < HEIGHT; h++){\n            for (int w = 0; w < WIDTH; w++){\n                for (size_t c = 0; c < CHANNEL; c++){\n                    (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in1[b][h][w][c];\n                }\n            }\n        }\n    }\n\n    //step 2. \uc785\ub825\uac12 \ucc28\uc6d0 \ubcc0\ud658\n    //printf(\"\uc785\ub825\uac12 \ucc28\uc6d0 \ubcc0\ud658 \uc911 \\n\");\n    float (*newin2)[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3];\n    newin2 = (float(*)[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3])malloc(sizeof(float[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3]));\n    //\ud558\ub098\uc758 \uc2a4\ud2b8\ub77c\uc774\ud2b8\uc5d0 \uac01 \ucc44\ub110\ub4e4\uc744 \ud558\ub098\uc758 \ud589\uc73c\ub85c \uad6c\uc131\n    for (int b = 0, p = 0; b < BATCH; b++, p = 0)\n        for (int i = 0; i < out_h; i++)\n            for (int j = 0, q = 0; j < out_w; j++, q = 0, p++)\n                for (int c = 0; c < CHANNEL; c++)\n                    for (int ii = i * stride_size; ii < i * stride_size + FILTER_HEIGHT; ii++)\n                        for (int jj = j * stride_size; jj < j * stride_size + FILTER_WIDTH; jj++)\n                            (*newin2)[b][q++][p] = (*newin)[b][ii][jj][c];\n\n    free(newin);\n\n    // step 3. \ud544\ud130 \ud3c9\ud65c\ud654\n    //printf(\"\ud544\ud130 \ud3c9\ud65c\ud654 \uc911\\n\");\n\n    float (*transFilter)[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL]; //\ud328\ub529 \ubc30\uc5f4\n    transFilter = (float(*)[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL])malloc(sizeof(float[FILTER_SIZE][FILTER_WIDTH*FILTER_HEIGHT*FILTER_CHANNEL]));\n    memset(transFilter, 0x00, sizeof(float[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL]));\n\n    for (int i1 = 0, q = 0; i1 < FILTER_SIZE; i1++, q = 0)\n        for (int i2 = 0; i2 < FILTER_CHANNEL; i2++)\n            for (int i3 = 0; i3 < FILTER_HEIGHT; i3++)\n                for (int i4 = 0; i4 < FILTER_WIDTH; i4++)\n                    (*transFilter)[i1][q++] = filter[i1][i3][i4][i2];\n\n\n\n    // step 4. \ud589\ub82c \uacf1.\n    float (*finalResult)[BATCH][FILTER_SIZE][M3*K3];\n    finalResult = (float (*)[BATCH][FILTER_SIZE][M3*K3])malloc(sizeof(float[BATCH][FILTER_SIZE][M3*K3]));\n    memset(finalResult, 0x00, sizeof(float[BATCH][FILTER_SIZE][M3*K3]));\n\n    int div = out_h * out_w; // B * out_h * out_w\n    //int total2 = BATCH * CHANNEL * FILTER_HEIGHT * FILTER_WIDTH * out_h * out_w;\n    int total2 = BATCH * FILTER_CHANNEL * FILTER_HEIGHT * FILTER_WIDTH * out_h * out_w;\n    int total3 = total2 / div;\n    //printf(\"\ud589\ub82c \uacf1 \uc911\\n\");\n#ifdef _USE_OPENBLAS_CONV\n  size_t m1len = FILTER_SIZE*total3, m2len = total3*div, m3len = FILTER_SIZE*div;\n    float *m1, *m2, *m3;\n\n    m1 = (float *)malloc(sizeof(float)*m1len);\n    m2 = (float *)malloc(sizeof(float)*m2len);\n    m3 = (float *)malloc(sizeof(float)*m3len);\n\n    for (int b = 0; b < BATCH; b++) {\n        for (int i = 0; i < m1len; i++) {\n            m1[i] = (*transFilter)[i/total3][i % total3];\n        }\n\n        for (int i = 0; i < m2len; i++) {\n            m2[i] = (*newin2)[b][i/div][i % div];\n        }\n\n        cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, FILTER_SIZE, div, total3, 1.0, m1, total3, m2, div, 0.0, m3, div);\n\n        for (int i = 0; i < m3len; i++) {\n            (*finalResult)[b][i/div][i % div] = m3[i];\n        }\n    }\n    free(m1);\n    free(m2);\n    free(m3);\n\n#else\n\n#ifdef THREAD_MATMUL\n\n    //printf(\"\ud589\ub82c \uacf1 \uc911\\n\");\n    struct tTHREAD<float,float,float, FILTER_SIZE, BATCH*FILTER_CHANNEL*FILTER_HEIGHT*FILTER_WIDTH, M3*K3> p;\n\n    // \uc2a4\ub808\ub4dc\uc5d0 \uc5f0\uc0b0\ud560 \uba54\ubaa8\ub9ac \ubcf5\uc0ac\n    pthread_t threads[MAX_THREAD];\n    p.arrr = (*transFilter);\n    p.brrr1 =(*newin2);\n    p.crrr1 =(*finalResult);\n\n#ifdef __MACH__\n    semaphore = dispatch_semaphore_create(1);\n#else\n    sem_init(&semaphore, 0, 1);\n#endif\n\n    for(int b = 0; b < BATCH; b++){\n        for (int i = 0; i < MAX_THREAD; i++) {\n#ifdef __MACH__\n            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);\n#else\n            //sem_wait(&semaphore);\n            int r;\n\n            do {\n                r = sem_wait(&semaphore);\n            } while (r == -1 && errno == EINTR);\n#endif\n\n            p.cnt = i;\n            p.b = b; // \ubc30\uce58 \uac12\n\n            pthread_create(&threads[i], NULL, multi<float, float, float, FILTER_SIZE, BATCH*FILTER_CHANNEL*FILTER_HEIGHT*FILTER_WIDTH, M3*K3>, (void *)&p); // filter_size, total3, div\n        }\n\n        for (int t = 0; t < MAX_THREAD; t++)\n            pthread_join(threads[t], NULL); // \ubaa8\ub4e0 \uc2a4\ub808\ub4dc\uac00 \ub05d\ub0a0 \ub54c\uae4c\uc9c0 \uacb0\ud569 \ubc0f \ub300\uae30\n    }\n\n#ifdef __MACH__\n    dispatch_release(semaphore);\n#else\n    // sem_distroy(&semaphore);\n#endif\n\n\n#else\n\n//total3:  BATCH * FILTER_CHANNEL * FILTER_HEIGHT * FILTER_WIDTH\n//div: out_w * out_h\n    int splitedKernelSize = FILTER_SIZE/group;\n    // k for\ubb38\uacfc j for \ubb38\uc744 \ubcc0\uacbd\ud568\uc73c\ub85c\uc368, \uc9c0\uc5ed\uc131 \ud5a5\uc0c1.\n    for (int b = 0; b < BATCH; b++) {\n        for (int i = 0; i < splitedKernelSize; i++) {\n            for(int g = 0; g < group; g++) {\n                for (int k = 0; k < total3; k++) {\n                    for (int j = 0; j < div; j++) {\n                        (*finalResult)[b][g*splitedKernelSize + i][j] += (*transFilter)[g*splitedKernelSize + i][k] * (*newin2)[b][g*FILTER_CHANNEL*FILTER_WIDTH*FILTER_HEIGHT + k][j];\n                    }\n                }\n            }\n        }\n    }\n#endif\n\n#endif\n    // step 5. \uacb0\uacfc \ucc28\uc6d0 \ubcc0\ud658\ubc0f \ud3b8\ud5a5 \ud569\n    //printf(\"\ub9c8\uc9c0\ub9c9 \ucc28\uc6d0 \ubcc0\ud658 \uc911\\n\");\n    //int putout_c = (FILTER_SIZE) / (BATCH);\n\n\n    for (int i1 = 0; i1 < BATCH; i1++) {\n        for(int g = 0; g < group; g++) {\n            for (int i4 = 0; i4 < splitedKernelSize; i4++) {\n                size_t q = 0;\n                for (int i2 = 0; i2 < out_h; i2++) {\n                    for (int i3 = 0; i3 < out_w; i3++) {\n                        result[i1][i2][i3][g*splitedKernelSize + i4] = (*finalResult)[i1][g*splitedKernelSize + i4][q++] + bias[g*splitedKernelSize + i4];\n                    }\n                }\n                //cout << (float)bias[i4] << \"\\t\" << endl;\n            }\n        }\n    }\n\n    free(newin2);\n    free(transFilter);\n    free(finalResult);\n\n#ifdef _DEBUG\n    clock_gettime(CLOCK_MONOTONIC, &ep);\n  timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0);\n  cout << \"==================== \" + to_string(conv_idx++) + \" convolution time : \" << timeCheck <<\" seconds  ====================\" << endl << endl;\n#endif\n}\n\n#endif\n\n//\n//convolution image to columns\ntemplate <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL,\n        typename T2, size_t FILTER_SIZE, size_t FILTER_HEIGHT, size_t FILTER_WIDTH, size_t FILTER_CHANNEL,\n        typename T3, size_t N2,\n        typename T4, size_t N3, size_t M3, size_t K3, size_t L3>\nvoid conv(T1 (&in1)[BATCH][HEIGHT][WIDTH][CHANNEL], T2 (&filter)[FILTER_SIZE][FILTER_HEIGHT][FILTER_WIDTH][FILTER_CHANNEL], vector<size_t> filter_dim, T3 (&bias)[N2], \\\n\tvector<size_t> stride, vector<size_t> pad, size_t group, T4 (&result)[N3][M3][K3][L3])\n{\n    cout <<  \"-- conv() group: \" << group << endl;\n\n#ifdef _DEBUG\n    cout <<  \"-- conv() -- \" << endl;\n\n  cout << \"BATCH: \" << BATCH << endl;\n  cout << \"HEIGHT: \" << HEIGHT << endl;\n  cout << \"WIDTH: \" << WIDTH << endl;\n  cout << \"CHANNEL: \" << CHANNEL << endl;\n  cout << \"pad: \" << pad.at(0) << endl;\n  cout << \"stride: \" << stride.at(0) << endl;\n  cout << \"FILTER_HEIGHT: \" << FILTER_HEIGHT << endl;\n  cout << \"FILTER_WIDTH: \" << FILTER_WIDTH << endl;\n  cout << \"FILTER_CHANNEL: \" << FILTER_CHANNEL << endl;\n  cout << \"BIAS LEN: \" << N2 << endl;\n#endif\n\n    int pad_xleft = pad.at(0);\n    int pad_xright = pad.at(1);\n    int pad_ytop = pad.at(2);\n    int pad_ybottom = pad.at(3);\n    int xadd = pad_xleft + pad_xright;\n    int yadd = pad_ytop + pad_ybottom;\n\n    int stride_size = stride.at(0);\n\n    int out_h = (HEIGHT + yadd - FILTER_HEIGHT)/stride_size + 1;\n    int out_w = (WIDTH + xadd - FILTER_WIDTH)/stride_size + 1;\n\n#ifdef _DEBUG\n    cout << \"FILTER_SIZE: \" << FILTER_SIZE << endl;\n  cout << \"out_h: \" << out_h << endl;\n  cout << \"out_w: \" << out_w << endl;\n\n  struct timespec tp, ep;\n  double timeCheck;\n  clock_gettime(CLOCK_MONOTONIC, &tp);\n#endif\n\n#if defined(__MACH__) || defined(_USE_LLVM)\n    float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL];\n    newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n    memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n#else\n    float (* newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL];\n    newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n    memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n#endif\n\n    //step 1. \ud328\ub529\n\n    //int jp, kp;\n    //printf(\"\ud328\ub529 \ubcc0\ud658 \uc911\\n\");\n    for (int b = 0; b < BATCH; b++){\n        for (int h = 0; h < HEIGHT; h++){\n            for (int w = 0; w < WIDTH; w++){\n                for (size_t c = 0; c < CHANNEL; c++){\n                    (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in1[b][h][w][c];\n                }\n            }\n        }\n    }\n\n    //step 2. \uc785\ub825\uac12 \ucc28\uc6d0 \ubcc0\ud658\n    //printf(\"\uc785\ub825\uac12 \ucc28\uc6d0 \ubcc0\ud658 \uc911 \\n\");\n    float (*newin2)[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3];\n    newin2 = (float(*)[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3])malloc(sizeof(float[BATCH][CHANNEL*FILTER_HEIGHT*FILTER_WIDTH][M3*K3]));\n    //\ud558\ub098\uc758 \uc2a4\ud2b8\ub77c\uc774\ud2b8\uc5d0 \uac01 \ucc44\ub110\ub4e4\uc744 \ud558\ub098\uc758 \ud589\uc73c\ub85c \uad6c\uc131\n    for (int b = 0, p = 0; b < BATCH; b++, p = 0)\n        for (int i = 0; i < out_h; i++)\n            for (int j = 0, q = 0; j < out_w; j++, q = 0, p++)\n                for (int c = 0; c < CHANNEL; c++)\n                    for (int ii = i * stride_size; ii < i * stride_size + FILTER_HEIGHT; ii++)\n                        for (int jj = j * stride_size; jj < j * stride_size + FILTER_WIDTH; jj++)\n                            (*newin2)[b][q++][p] = (*newin)[b][ii][jj][c];\n\n    free(newin);\n\n    // step 3. \ud544\ud130 \ud3c9\ud65c\ud654\n    //printf(\"\ud544\ud130 \ud3c9\ud65c\ud654 \uc911\\n\");\n\n    float (*transFilter)[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL]; //\ud328\ub529 \ubc30\uc5f4\n    transFilter = (float(*)[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL])malloc(sizeof(float[FILTER_SIZE][FILTER_WIDTH*FILTER_HEIGHT*FILTER_CHANNEL]));\n    memset(transFilter, 0x00, sizeof(float[FILTER_SIZE][FILTER_HEIGHT*FILTER_WIDTH*FILTER_CHANNEL]));\n\n    for (int i1 = 0, q = 0; i1 < FILTER_SIZE; i1++, q = 0)\n        for (int i2 = 0; i2 < FILTER_CHANNEL; i2++)\n            for (int i3 = 0; i3 < FILTER_HEIGHT; i3++)\n                for (int i4 = 0; i4 < FILTER_WIDTH; i4++)\n                    (*transFilter)[i1][q++] = filter[i1][i3][i4][i2];\n\n\n\n    // step 4. \ud589\ub82c \uacf1.\n    float (*finalResult)[BATCH][FILTER_SIZE][M3*K3];\n    finalResult = (float (*)[BATCH][FILTER_SIZE][M3*K3])malloc(sizeof(float[BATCH][FILTER_SIZE][M3*K3]));\n    memset(finalResult, 0x00, sizeof(float[BATCH][FILTER_SIZE][M3*K3]));\n\n    int div = out_h * out_w; // B * out_h * out_w\n    int total2 = BATCH * CHANNEL * FILTER_HEIGHT * FILTER_WIDTH * out_h * out_w;\n    int total3 = total2 / div;\n    //printf(\"\ud589\ub82c \uacf1 \uc911\\n\");\n#ifdef _USE_OPENBLAS_CONV\n  size_t m1len = FILTER_SIZE*total3, m2len = total3*div, m3len = FILTER_SIZE*div;\n    float *m1, *m2, *m3;\n\n    m1 = (float *)malloc(sizeof(float)*m1len);\n    m2 = (float *)malloc(sizeof(float)*m2len);\n    m3 = (float *)malloc(sizeof(float)*m3len);\n\n    for (int b = 0; b < BATCH; b++) {\n        for (int i = 0; i < m1len; i++) {\n            m1[i] = (*transFilter)[i/total3][i % total3];\n        }\n\n        for (int i = 0; i < m2len; i++) {\n            m2[i] = (*newin2)[b][i/div][i % div];\n        }\n\n        cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, FILTER_SIZE, div, total3, 1.0, m1, total3, m2, div, 0.0, m3, div);\n\n        for (int i = 0; i < m3len; i++) {\n            (*finalResult)[b][i/div][i % div] = m3[i];\n        }\n    }\n    free(m1);\n    free(m2);\n    free(m3);\n\n#else\n\n#ifdef THREAD_MATMUL\n\n    //printf(\"\ud589\ub82c \uacf1 \uc911\\n\");\n    struct tTHREAD<float,float,float, FILTER_SIZE, BATCH*FILTER_CHANNEL*FILTER_HEIGHT*FILTER_WIDTH, M3*K3> p;\n\n    // \uc2a4\ub808\ub4dc\uc5d0 \uc5f0\uc0b0\ud560 \uba54\ubaa8\ub9ac \ubcf5\uc0ac\n    pthread_t threads[MAX_THREAD];\n    p.arrr = (*transFilter);\n    p.brrr1 =(*newin2);\n    p.crrr1 =(*finalResult);\n\n#ifdef __MACH__\n    semaphore = dispatch_semaphore_create(1);\n#else\n    sem_init(&semaphore, 0, 1);\n#endif\n\n    for(int b = 0; b < BATCH; b++){\n        for (int i = 0; i < MAX_THREAD; i++) {\n#ifdef __MACH__\n            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);\n#else\n            //sem_wait(&semaphore);\n            int r;\n\n            do {\n                r = sem_wait(&semaphore);\n            } while (r == -1 && errno == EINTR);\n#endif\n\n            p.cnt = i;\n            p.b = b; // \ubc30\uce58 \uac12\n\n            pthread_create(&threads[i], NULL, multi<float, float, float, FILTER_SIZE, BATCH*FILTER_CHANNEL*FILTER_HEIGHT*FILTER_WIDTH, M3*K3>, (void *)&p); // filter_size, total3, div\n        }\n\n        for (int t = 0; t < MAX_THREAD; t++)\n            pthread_join(threads[t], NULL); // \ubaa8\ub4e0 \uc2a4\ub808\ub4dc\uac00 \ub05d\ub0a0 \ub54c\uae4c\uc9c0 \uacb0\ud569 \ubc0f \ub300\uae30\n    }\n\n#ifdef __MACH__\n    dispatch_release(semaphore);\n#else\n    // sem_distroy(&semaphore);\n#endif\n\n\n#else\n    // k for\ubb38\uacfc j for \ubb38\uc744 \ubcc0\uacbd\ud568\uc73c\ub85c\uc368, \uc9c0\uc5ed\uc131 \ud5a5\uc0c1.\n    for (int b = 0; b < BATCH; b++) {\n        for (int i = 0; i < FILTER_SIZE; i++) {\n            for (int k = 0; k < total3; k++) {\n                for (int j = 0; j < div; j++) {\n                    (*finalResult)[b][i][j] += (*transFilter)[i][k] * (*newin2)[b][k][j];\n                }\n            }\n        }\n    }\n#endif\n\n#endif\n    // step 5. \uacb0\uacfc \ucc28\uc6d0 \ubcc0\ud658\ubc0f \ud3b8\ud5a5 \ud569\n    //printf(\"\ub9c8\uc9c0\ub9c9 \ucc28\uc6d0 \ubcc0\ud658 \uc911\\n\");\n    //int putout_c = (FILTER_SIZE) / (BATCH);\n\n    for (int i1 = 0; i1 < BATCH; i1++) {\n        for (int i4 = 0; i4 < FILTER_SIZE; i4++) {\n            size_t q = 0;\n            for (int i2 = 0; i2 < out_h; i2++) {\n                for (int i3 = 0; i3 < out_w; i3++) {\n                    result[i1][i2][i3][i4] = (*finalResult)[i1][i4][q++] + bias[i4];\n                }\n            }\n            //cout << (float)bias[i4] << \"\\t\" << endl;\n        }\n    }\n\n    free(newin2);\n    free(transFilter);\n    free(finalResult);\n\n#ifdef _DEBUG\n    clock_gettime(CLOCK_MONOTONIC, &ep);\n  timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0);\n  cout << \"==================== \" + to_string(conv_idx++) + \" convolution time : \" << timeCheck <<\" seconds  ====================\" << endl << endl;\n#endif\n}\n\n#endif\n\n/*\n *\n *\n * Average Pooling\n *\n *\n */\n\ntemplate <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL,\n        typename T2, size_t N2, size_t M2, size_t K2, size_t L2>\nvoid avgpool(T1 (&in)[BATCH][HEIGHT][WIDTH][CHANNEL], vector<size_t> windows_dim, vector<size_t> stride, vector<size_t> pad, T2 (&result)[N2][M2][K2][L2])\n{\n    //\ttime_t istart,iend;\n//\ttime (&istart);\n\n    //N, H, W, C\n    //N == 1\n    //group == 1\n\n    int pad_xleft = pad.at(0);\n    int pad_xright = pad.at(1);\n    int pad_ytop = pad.at(2);\n    int pad_ybottom = pad.at(3);\n    int xadd = pad_xleft + pad_xright;\n    int yadd = pad_ytop + pad_ybottom;\n\n    int stride_size = stride.at(0);\n\n    int window_h = windows_dim.at(0);\n    int window_w = windows_dim.at(1);\n\n    int out_h = (HEIGHT + yadd - window_h)/stride_size + 1;\n    int out_w = (WIDTH + xadd - window_w)/stride_size + 1;\n\n    const int new_height = HEIGHT + pad.at(0) + pad.at(1);\n    const int new_width = WIDTH +  pad.at(2) + pad.at(3);\n\n#ifdef _DEBUG\n    cout << \"avgpool()\" <<endl;\n\n//  cout << \"BATCH: \" << BATCH << endl;\n//  cout << \"HEIGHT: \" << HEIGHT << endl;\n//  cout << \"WIDTH: \" << WIDTH << endl;\n//  cout << \"CHANNEL: \" << CHANNEL << endl;\n//  cout << \"pad: \" << pad.at(0) << endl;\n//  cout << \"stride: \" << stride.at(0) << endl;\n//  cout << \"WINDOW_HEIGHT: \" << window_h << endl;\n//  cout << \"WINDOW_WIDTH: \" << window_w << endl;\n#endif\n\n\n#if defined(__MACH__) || defined(_USE_LLVM)\n    float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL];\n    newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n    memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n#else\n    float (*newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL];\n    newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n    memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n#endif\n\n\n//    float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE][WIDTH+MAX_PAD_SIZE][CHANNEL];\n//    newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE][WIDTH+MAX_PAD_SIZE][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE][WIDTH+MAX_PAD_SIZE][CHANNEL]));\n\n    for (int b = 0; b < BATCH; b++){\n        for (size_t h = 0; h < HEIGHT; h++){\n            for (size_t w = 0; w < WIDTH; w++){\n                for (int c = 0; c < CHANNEL; c++){\n                    (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in[b][h][w][c];\n                }\n            }\n        }\n    }\n\n    int wnum = window_h*window_w;\n    int new_h_idx = 0, new_w_idx = 0;\n    for (int b = 0; b < BATCH; b++){\n        for(int c = 0; c < CHANNEL; c++) {\n\n            for(int i = 0; i <out_h; i++) {\n                for(int j = 0; j <out_w; j++) {\n\n                    int pad_cnt = 0;\n                    float total = 0.0;\n                    for(int fh = 0; fh <window_h; fh++) {\n                        for(int fw = 0; fw <window_w; fw++) {\n\n                            int h_idx = new_h_idx+fh, w_idx = new_w_idx+fw;\n\n                            if(h_idx < pad_ytop || w_idx < pad_xleft || h_idx >= (new_height - pad_ybottom)|| w_idx >= (new_width - pad_xright)) {\n                                pad_cnt++;\n                            }\n\n                            total = total + (*newin)[b][h_idx][w_idx][c];\n                        }\n                    }\n\n                    //cout << \"pad_cnt = \" << pad_cnt << endl;\n\n                    result[b][i][j][c] = total/(wnum-pad_cnt);\n                    new_w_idx += stride_size;\n                }\n                new_h_idx += stride_size;\n                new_w_idx = 0;\n            }\n            new_h_idx = 0;\n        }\n    }\n\n    free(newin);\n\n//    time (&iend);\n//    double dif = difftime (iend,istart);\n//    printf (\"==> [Avg. pooling time] %.4lf seconds.\\n\", dif );\n\n}\n\n\n//N H W C\n/*\n *\n *\n * Max Pooling\n *\n *\n */\n\ntemplate <typename T1, size_t BATCH, size_t HEIGHT, size_t WIDTH, size_t CHANNEL,\n        typename T3, size_t N2, size_t M2, size_t K2, size_t L2>\nvoid maxpool(T1 (&in1)[BATCH][HEIGHT][WIDTH][CHANNEL], vector<size_t> windows_dim, vector<size_t> stride, vector<size_t> pad, T3 (&result)[N2][M2][K2][L2])\n{\n\n#ifdef _DEBUG\n    cout << \"maxpool()\" << endl;\n#endif\n//\ttime_t istart,iend;\n//\ttime (&istart);\n\n\n    //N, H, W, C\n    //N == 1\n    //group == 1\n\n\n    int pad_xleft = pad.at(0);\n    int pad_xright = pad.at(1);\n    int pad_ytop = pad.at(2);\n    int pad_ybottom = pad.at(3);\n    int xadd = pad_xleft + pad_xright;\n    int yadd = pad_ytop + pad_ybottom;\n\n    int stride_size = stride.at(0);\n\n    int window_h = windows_dim.at(0);\n    int window_w = windows_dim.at(1);\n\n    int out_h = (HEIGHT + yadd - window_h)/stride_size + 1;\n    int out_w = (WIDTH + xadd - window_w)/stride_size + 1;\n\n\n\n#if defined(__MACH__) || defined(_USE_LLVM)\n    float (* newin)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL];\n    newin = (float (*)[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n    memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+MAX_PAD_SIZE*2][WIDTH+MAX_PAD_SIZE*2][CHANNEL]));\n#else\n    float (* newin)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL];\n  newin = (float (*)[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL])malloc(sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n  memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n#endif\n\n    // memset(newin, 0x00, sizeof(float[BATCH][HEIGHT+yadd][WIDTH+xadd][CHANNEL]));\n\n    for (int b = 0; b < BATCH; b++){\n        for (size_t h = 0; h < HEIGHT; h++){\n            for (size_t w = 0; w < WIDTH; w++){\n                for (int c = 0; c < CHANNEL; c++){\n                    (*newin)[b][pad_ytop+h][pad_xleft+w][c] = in1[b][h][w][c];\n                }\n            }\n        }\n    }\n\n    int new_h_idx = 0, new_w_idx = 0;\n    for (int b = 0; b < BATCH; b++){\n        for(int c = 0; c < CHANNEL; c++) {\n\n            for(int i = 0; i <out_h; i++) {\n                for(int j = 0; j <out_w; j++) {\n\n                    float max = -INFINITY;;\n                    for(int fh = 0; fh <window_h; fh++) {\n                        for(int fw = 0; fw <window_w; fw++) {\n\n                            float value = (*newin)[b][new_h_idx+fh][new_w_idx+fw][c];\n\n                            if(max < value)\n                                max = value;\n                        }\n                    }\n\n                    result[b][i][j][c] = max;\n                    new_w_idx += stride_size;\n                }\n                new_h_idx += stride_size;\n                new_w_idx = 0;\n            }\n            new_h_idx = 0;\n\n        }\n    }\n\n\n//    if(pad_size > 0)\n    free(newin);\n\n//    time (&iend);\n//    double dif = difftime (iend,istart);\n//    printf (\"==> [Max. pooling time] %.4lf seconds.\\n\", dif );\n} // end maxpool\n\n\n\n/*\n *\n *\n * Softmax 2D\n *\n *\n */\ntemplate <typename T1, size_t N, size_t M, typename T2>\nvoid softmax(T1 (&in1)[N][M], int axis, T2 (&result)[N][M])\n{\n\n#ifdef _DEBUG\n    cout << \"softmax()-2D\" << endl;\n#endif\n    //axis\n\n    // clock_t start, end;\n    // start = clock();\n\n    if(axis == 1) {\n\n        float max[N];\n        for(size_t i = 0; i < N; i++) {\n            max[i] = -INFINITY;\n        }\n\n        for (size_t i = 0; i < N; i++) {\n            for (size_t j = 0; j < M; j++) {\n                if (in1[i][j] > max[i]) {\n                    max[i] = in1[i][j];\n                }\n            }\n        }\n\n        float sum[N];\n        memset(sum, 0x00, sizeof(float)*N);\n        for (size_t i = 0; i < N; i++) {\n            for (size_t j = 0; j < M; j++) {\n                sum[i] += expf(in1[i][j]- max[i]);\n            }\n        }\n\n        for (size_t i = 0; i < N; i++) {\n            for (size_t j = 0; j < M; j++) {\n                result[i][j] = expf(in1[i][j]-max[i])/sum[i];\n            }\n        }\n    } else {\n\n        float max = -INFINITY;\n        float sum = 0.0;\n\n\n        for (size_t i = 0; i < N; i++) {\n            for (size_t j = 0; j < M; j++) {\n                if (in1[i][j] > max) {\n                    max = in1[i][j];\n                }\n            }\n        }\n\n        for (size_t i = 0; i < N; i++) {\n            for (size_t j = 0; j < M; j++) {\n                sum += expf(in1[i][j]- max);\n            }\n        }\n\n        for (size_t i = 0; i < N; i++) {\n            for (size_t j = 0; j < M; j++) {\n                result[i][j] = expf(in1[i][j]-max)/sum;\n            }\n        }\n    }\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n}\n\n\n\n/*\n *\n *\n * Softmax 3D\n *\n *\n *\n */\n\ntemplate <typename T1, size_t N1, size_t N2, size_t N3,\n        typename T2>\nvoid softmax(T1 (&in1)[N1][N2][N3], int axis, T2 (&result)[N1][N2][N3])\n{\n#ifdef _DEBUG\n    cout << \"softmax()-3D\" << endl;\n#endif\n    //cout << \"axis = \" << axis << endl;\n\n    //clock_t start, end;\n    //start = clock();\n\n    if(axis == 1) {\n\n        float max[N1];\n        for(int i = 0; i < N1; i++) {\n            max[i] = -INFINITY;\n        }\n\n        for (size_t i = 0; i < N1; i++) {\n            for (size_t k = 0; k < N3; k++) {\n                for (size_t j = 0; j < N2; j++) {\n                    if (in1[i][j][k] > max[i]) {\n                        max[i] = in1[i][j][k];\n                    }\n                }\n            }\n        }\n\n        float sum[N1];\n        memset(sum, 0x00, sizeof(float)*N1);\n        for (size_t i = 0; i < N1; i++) {\n            for (size_t j = 0; j < N2; j++) {\n                for (size_t k = 0; k < N3; k++) {\n                    sum[i] += expf(in1[i][j][k]- max[i]);\n                }\n            }\n        }\n\n        for (size_t i = 0; i < N1; i++) {\n            for (size_t j = 0; j < N2; j++) {\n                for (size_t k = 0; k < N3; k++) {\n                    result[i][j][k] = expf(in1[i][j][k]-max[i])/sum[i];\n                }\n            }\n        }\n    } else {\n\n        float max = -INFINITY;\n        float sum = 0.0;\n\n\n        for (size_t i = 0; i < N1; i++) {\n            for (size_t k = 0; k < N3; k++) {\n                for (size_t j = 0; j < N2; j++) {\n                    if (in1[i][j][k] > max) {\n                        max = in1[i][j][k];\n                    }\n                }\n            }\n        }\n\n        for (size_t i = 0; i < N1; i++) {\n            for (size_t j = 0; j < N2; j++) {\n                for (size_t k = 0; k < N3; k++) {\n                    sum += expf(in1[i][j][k]- max);\n                }\n            }\n        }\n\n        for (size_t i = 0; i < N1; i++) {\n            for (size_t j = 0; j < N2; j++) {\n                for (size_t k = 0; k < N3; k++) {\n                    result[i][j][k] = expf(in1[i][j][k]-max)/sum;\n                }\n            }\n        }\n    }\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n}\n\n\n/*\n *\n *\n * Relu 4D\n *\n *\n *\n */\n\ntemplate <typename T1, size_t N, size_t M, size_t K, size_t L>\nvoid relu(T1 (&in1)[N][M][K][L])\n{\n#ifdef _DEBUG\n    cout << \"relu()-4D\" << endl;\n#endif\n    //  clock_t start, end;\n//\tstart = clock();\n\n    for (size_t i = 0; i < N; i++){\n        for (size_t j=0; j<M; j++){\n            for (size_t k=0; k<K; k++){\n                for (size_t l=0; l<L; l++)\n                {\n                    if (in1[i][j][k][l] < 0.0)\n                        in1[i][j][k][l] = 0.0;\n\n                }\n            }\n        }\n    }\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n} //end relu\n\n\n\n\n/*\n *\n *\n * Relu 2D\n *\n *\n */\ntemplate <typename T1, size_t N, size_t M>\nvoid relu(T1 (&in1)[N][M])\n{\n#ifdef _DEBUG\n    cout << \"relu()-2D\" << endl;\n#endif\n    //    clock_t start, end;\n//\tstart = clock();\n\n\n    for (size_t i=0; i < N; i++) {\n        for (size_t j=0; j<M; j++){\n            if (in1[i][j] <= 0.0)\n                in1[i][j] = 0.0;\n        }\n    }\n\n//\tend = clock();\n//\tcout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n} //end relu\n\n\n\n/*\n *\n *\n * Add 2D + 2D\n *\n *\n */\n\ntemplate <typename T1, size_t N, size_t M>\nvoid add(T1 (&in1)[N][M], T1 (&in2)[N][M], T1 (&result)[N][M])\n{\n\n#ifdef _DEBUG\n    cout << \"add()-2D + 2D\" << endl;\n#endif\n    //    clock_t start, end;\n//\tstart = clock();\n\n    for (size_t i = 0; i < N; i++){\n        for (size_t j = 0; j < M; j++){\n            result[i][j] = in1[i][j] + in2[i][j];\n        }\n    }\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n    //cout << \"[LIB] add end\" << endl;\n\n}\n\n/*\n *\n *\n * Add 2D + 1D\n *\n *\n */\ntemplate <typename T1, size_t N, size_t M>\nvoid add(T1 (&in1)[N][M], T1 (&in2)[M], T1 (&result)[N][M])\n{\n#ifdef _DEBUG\n    cout << \"add()-2D + 1D\" << endl;\n#endif\n    //    clock_t start, end;\n//\tstart = clock();\n\n    for (size_t i = 0; i < N; i++){\n        for (size_t j = 0; j < M; j++){\n            result[i][j] = in1[i][j] + in2[j];\n        }\n    }\n\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n    //cout << \"[LIB] add end\" << endl;\n\n}\n\n/*\n *\n *\n * Add 2D + 2D\n *\n *\n */\ntemplate <typename T1, size_t N, size_t M>\nvoid add(T1 (&in1)[N][M], T1 (&in2)[N][M])\n{\n#ifdef _DEBUG\n    cout << \"add()-2D + 2D\" << endl;\n#endif\n    //    clock_t start, end;\n//\tstart = clock();\n\n    for (size_t i = 0; i < N; i++){\n        for (size_t j = 0; j < M; j++){\n            in1[i][j] = in1[i][j] + in2[i][j];\n        }\n    }\n}\n\n/*\n *\n *\n * Add 2D + 1D\n *\n *\n */\ntemplate <typename T1, size_t N, size_t M>\nvoid add(T1 (&in1)[N][M], T1 (&in2)[M])\n{\n#ifdef _DEBUG\n    cout << \"add()-2D + 1D\" << endl;\n#endif\n    //    clock_t start, end;\n//\tstart = clock();\n\n    for (size_t i = 0; i < N; i++){\n        for (size_t j = 0; j < M; j++){\n            in1[i][j] = in1[i][j] + in2[j];\n        }\n    }\n\n\n}\n\n\n/*\n *\n *\n * Add 4D + 1D\n *\n *\n */\ntemplate <typename T1, size_t N1, size_t N2, size_t N3, size_t N4,\n        typename T2, size_t M>\nvoid add(T1 (&in1)[N1][N2][N3][N4], T2 (&in2)[M], T1 (&result)[N1][N2][N3][N4])\n{\n#ifdef _DEBUG\n    cout << \"add()-2D + 1D\" << endl;\n#endif\n    //clock_t start, end;\n    //start = clock();\n\n    for (int i1 = 0; i1 < N1; i1++){\n        for (int i2 = 0; i2 < N2; i2++){\n            for (int i3 = 0; i3 < N3; i3++){\n                for (int i4 = 0; i4 < N4; i4++){\n\n                    result[i1][i2][i3][i4] = in1[i1][i2][i3][i4] + in2[i2];\n                }\n            }\n        }\n    }\n\n}\n\n/*\n *\n *\n * Add 4D + 1D\n *\n *\n */\ntemplate <typename T1, size_t N1, size_t N2, size_t N3, size_t N4,\n        typename T2, size_t M>\nvoid add(T1 (&in1)[N1][N2][N3][N4], T2 (&in2)[M])\n{\n#ifdef _DEBUG\n    cout << \"add()-2D + 1D\" << endl;\n#endif\n    //clock_t start, end;\n    //start = clock();\n\n    for (int i1 = 0; i1 < N1; i1++){\n        for (int i2 = 0; i2 < N2; i2++){\n            for (int i3 = 0; i3 < N3; i3++){\n                for (int i4 = 0; i4 < N4; i4++){\n\n                    in1[i1][i2][i3][i4] = in1[i1][i2][i3][i4] + in2[i2];\n                }\n            }\n        }\n    }\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n    //cout << \"[LIB] add end\" << endl;\n\n}\n\n\n/*\n *\n *\n * Add 4D + 4D\n *\n *\n */\ntemplate <typename T1, size_t N, size_t M, size_t K, size_t L>\nvoid add(T1 (&in1)[N][M][K][L], T1 (&in2)[N][M][K][L], T1 (&result)[N][M][K][L])\n{\n#ifdef _DEBUG\n    cout << \"add()\" << endl;\n#endif\n    //    clock_t start, end;\n//\tstart = clock();\n\n    for (int i = 0; i < N; i++){\n        for (int j = 0; j < M; j++){\n            for (int k = 0; k < K; k++){\n                for (int l = 0; l < L; l++){\n                    result[i][j][k][l] = in1[i][j][k][l] + in2[i][j][k][l];\n                }\n            }\n        }\n    }\n\n//\tend = clock();\n//\tcout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n\n\n} //end add\n\n\n/*\n *\n *\n * Add 4D + 4D\n *\n *\n */\ntemplate <typename T1, size_t N, size_t M, size_t K, size_t L>\nvoid add(T1 (&in1)[N][M][K][L], T1 (&in2)[N][M][K][L])\n{\n#ifdef _DEBUG\n    cout << \"add()- 4D +4D\" << endl;\n#endif\n    //    clock_t start, end;\n//\tstart = clock();\n\n    for (size_t i = 0; i < N; i++){\n        for (size_t j = 0; j < M; j++){\n            for (size_t k = 0; k < K; k++){\n                for (size_t l = 0; l < L; l++){\n                    in1[i][j][k][l] = in1[i][j][k][l] + in2[i][j][k][l];\n                }\n            }\n        }\n    }\n\n//\tend = clock();\n//\tcout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n//\n//\n\n}\n\ntemplate <typename T1, size_t N1, size_t M1, typename T2, size_t N2, size_t M2, typename T3, size_t N3, typename T4, size_t N4, size_t M4>\nvoid gemm(T1 (&a)[N1][M1], T2 (&b)[N2][M2], T3 (&c)[N3], float alpha, float beta, int transA, int transB, T4 (&result)[N4][M4]) {\n\n#ifdef _DEBUG\n    cout << \"gemm()\" << endl;\n//  cout << \"N: \" << N << endl;\n//  cout << \"K: \" << K << endl;\n//  cout << \"M: \" << M << endl;\n\n    struct timespec tp, ep;\n    double timeCheck;\n    clock_gettime(CLOCK_MONOTONIC, &tp);\n#endif\n\n//#ifdef _USE_OPENBLAS_MATMUL\n//    size_t m1len = N*K, m2len = K*M, m3len = N*M;\n//    float *m1, *m2, *m3;\n//\n//    m1 = (float *)malloc(sizeof(float)*m1len);\n//    m2 = (float *)malloc(sizeof(float)*m2len);\n//    m3 = (float *)malloc(sizeof(float)*m3len);\n//\n//    for(int i = 0; i < m1len; i++) {\n//        m1[i] = in1[i/K][i%K];\n//    }\n//\n//    for(int i = 0; i < m2len; i++) {\n//        m2[i] = weight[i/M][i%M];\n//    }\n//\n//    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, M, K, 1, m1, K, m2, M, 0, m3, M);\n//\n//    for(int i = 0; i < m3len; i++) {\n//        result[i/M][i%M] = m3[i] + bias[i];\n//    }\n//\n//    free(m1);\n//    free(m2);\n//    free(m3);\n//\n//#else\n\n//    cout << \"transA = \" << transA << \" transB = \" << transB << endl;\n    if(transA == 0 && transB == 0) {\n        for (size_t i = 0; i < N1; i++){\n            for (size_t j = 0;  j <M1; j++){\n                for (size_t k = 0; k < M2; k++){\n                    result[i][j] += a[i][k]*b[k][j];\n                }\n            }\n        }\n    } else if (transA == 0 && transB == 1) {\n\n        float transposedB[M2][N2];\n        for (size_t i = 0; i < N2; i++) {\n            for (size_t j = 0; j < M2; j++) {\n                transposedB[j][i] = b[i][j];\n            }\n        }\n\n        for (size_t i = 0; i < N1; i++){\n            for (size_t j = 0;  j <M2; j++){\n                for (size_t k = 0; k < M1; k++){\n                    result[i][j] += a[i][k]*transposedB[k][j];\n                }\n            }\n        }\n    }  else if (transA == 1 && transB == 0) {\n        float transposedA[M1][N1];\n        for (size_t i = 0; i < N1; i++) {\n            for (size_t j = 0; j < M1; j++) {\n                transposedA[j][i] = a[i][j];\n            }\n        }\n\n        for (size_t i = 0; i < M1; i++){\n            for (size_t j = 0;  j <M2; j++){\n                for (size_t k = 0; k < N1; k++){\n                    result[i][j] += transposedA[i][k]*b[k][j];\n                }\n            }\n        }\n    }\n\n    for (size_t i = 0; i < N4; i++){\n        for (size_t j = 0; j < M4; j++){\n            result[i][j] = result[i][j] + c[j];\n        }\n    }\n\n//#endif\n\n#ifdef _DEBUG\n    clock_gettime(CLOCK_MONOTONIC, &ep);\n    timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0);\n    cout << \"====================  gemm time : \" << timeCheck <<\" seconds  ====================\" << endl << endl;\n#endif\n}\n\n//void cblas_sgemm(const enum CBLAS_ORDER __Order, const enum CBLAS_TRANSPOSE __TransA, const enum CBLAS_TRANSPOSE __TransB,\n// const int __M, const int __N, const int __K, const float __alpha, const float *__A, const int __lda, const float *__B, const int __ldb, const float __beta, float *__C, const int __ldc);\n\ntemplate <typename T1, size_t N, size_t K, typename T2, size_t M, typename T3, typename T4>\nvoid fullyconnected(T1 (&in1)[N][K], T2 (&weight)[K][M], T3 (&bias)[M], T4 (&result)[N][M]) {\n\n#ifdef _DEBUG\n    cout << \"fullyconnected()\" << endl;\n//  cout << \"N: \" << N << endl;\n//  cout << \"K: \" << K << endl;\n//  cout << \"M: \" << M << endl;\n\n  struct timespec tp, ep;\n  double timeCheck;\n  clock_gettime(CLOCK_MONOTONIC, &tp);\n#endif\n\n#ifdef _USE_OPENBLAS_MATMUL\n    size_t m1len = N*K, m2len = K*M, m3len = N*M;\n    float *m1, *m2, *m3;\n\n    m1 = (float *)malloc(sizeof(float)*m1len);\n    m2 = (float *)malloc(sizeof(float)*m2len);\n    m3 = (float *)malloc(sizeof(float)*m3len);\n\n    for(int i = 0; i < m1len; i++) {\n        m1[i] = in1[i/K][i%K];\n    }\n\n    for(int i = 0; i < m2len; i++) {\n        m2[i] = weight[i/M][i%M];\n    }\n\n    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, M, K, 1, m1, K, m2, M, 0, m3, M);\n\n    for(int i = 0; i < m3len; i++) {\n        result[i/M][i%M] = m3[i] + bias[i];\n    }\n\n    free(m1);\n    free(m2);\n    free(m3);\n\n#else\n    for (size_t i = 0; i < N; i++){\n        for (size_t j = 0;  j <M; j++){\n            for (size_t k = 0; k < K; k++){\n                result[i][j] += in1[i][k]*weight[k][j];\n            }\n        }\n    }\n\n    for (size_t i = 0; i < N; i++){\n        for (size_t j = 0; j < M; j++){\n            result[i][j] = result[i][j] + bias[j];\n        }\n    }\n\n#endif\n\n#ifdef _DEBUG\n    clock_gettime(CLOCK_MONOTONIC, &ep);\n  timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0);\n  cout << \"====================  fullyconnected time : \" << timeCheck <<\" seconds  ====================\" << endl << endl;\n#endif\n}\n\ntemplate <typename T1, size_t N, size_t K, typename T2, size_t M, typename T3, typename T4>\nvoid fullyconnected(T1 (&in1)[N][K], T2 (&weight)[K][M], T3 (&bias)[N][M], T4 (&result)[N][M]) {\n\n#ifdef _DEBUG\n    cout << \"fullyconnected()\" << endl;\n//  cout << \"N: \" << N << endl;\n//  cout << \"K: \" << K << endl;\n//  cout << \"M: \" << M << endl;\n\n  struct timespec tp, ep;\n  double timeCheck;\n  clock_gettime(CLOCK_MONOTONIC, &tp);\n#endif\n\n#ifdef _USE_OPENBLAS_MATMUL\n    size_t m1len = N*K, m2len = K*M, m3len = N*M;\n    float *m1, *m2, *m3;\n\n    m1 = (float *)malloc(sizeof(float)*m1len);\n    m2 = (float *)malloc(sizeof(float)*m2len);\n    m3 = (float *)malloc(sizeof(float)*m3len);\n\n    for(int i = 0; i < m1len; i++) {\n        m1[i] = in1[i/K][i%K];\n    }\n\n    for(int i = 0; i < m2len; i++) {\n        m2[i] = weight[i/M][i%M];\n    }\n\n    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, M, K, 1, m1, K, m2, M, 0, m3, M);\n\n    for(int i = 0; i < m3len; i++) {\n        result[i/M][i%M] = m3[i] + bias[i];\n    }\n\n    free(m1);\n    free(m2);\n    free(m3);\n\n#else\n    for (size_t i = 0; i < N; i++){\n        for (size_t j = 0;  j <M; j++){\n            for (size_t k = 0; k < K; k++){\n                result[i][j] += in1[i][k]*weight[k][j];\n            }\n        }\n    }\n\n    for (size_t i = 0; i < N; i++){\n        for (size_t j = 0; j < M; j++){\n            result[i][j] = result[i][j] + bias[i][j];\n        }\n    }\n\n#endif\n\n#ifdef _DEBUG\n    clock_gettime(CLOCK_MONOTONIC, &ep);\n  timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0);\n  cout << \"====================  fullyconnected time : \" << timeCheck <<\" seconds  ====================\" << endl << endl;\n#endif\n}\n\ntemplate <typename T1, size_t N, size_t K,\n        typename T2, size_t N1, size_t M1,\n        typename T3, size_t N2, size_t M2>\nvoid matmul(T1 (&in1)[N][K], T2 (&in2)[N1][M1], T3 (&result)[N2][M2]) {\n\n#ifdef _DEBUG\n    cout << \"N: \" << N << endl;\n  cout << \"K: \" << K << endl;\n  cout << \"M: \" << M1 << endl;\n\n  struct timespec tp, ep;\n  double timeCheck;\n  clock_gettime(CLOCK_MONOTONIC, &tp);\n#endif\n\n#ifdef _USE_OPENBLAS_MATMUL\n    size_t m1len = N*K, m2len = N1*M1, m3len = N2*M2;\n    float *m1, *m2, *m3;\n\n    m1 = (float *)malloc(sizeof(float)*m1len);\n    m2 = (float *)malloc(sizeof(float)*m2len);\n    m3 = (float *)malloc(sizeof(float)*m3len);\n\n    for(int i = 0; i < m1len; i++) {\n        m1[i] = in1[i/K][i%K];\n    }\n\n    for(int i = 0; i < m2len; i++) {\n        m2[i] = in2[i/M1][i%M1];\n    }\n\n    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, N, M1, K, 1, m1, K, m2, M1, 0, m3, M1);\n\n    for(int i = 0; i < m3len; i++) {\n        result[i/M2][i%M2] = m3[i];\n    }\n\n    free(m1);\n    free(m2);\n    free(m3);\n\n#else\n    for (size_t i = 0; i < N; i++){\n//        for (size_t k = 0; k < M; k++){\n        for (size_t j = 0;  j <M1; j++){\n            for (size_t k = 0; k < K; k++){\n                result[i][j] += in1[i][k]*in2[k][j];\n            }\n        }\n    }\n\n#endif\n\n#ifdef _DEBUG\n    clock_gettime(CLOCK_MONOTONIC, &ep);\n  timeCheck = ((ep.tv_sec - tp.tv_sec) + (ep.tv_nsec - tp.tv_nsec) / 1000000000.0);\n  cout << \"====================  matmul time : \" << timeCheck <<\" seconds  ====================\" << endl << endl;\n#endif\n}\n\n\n\n/*\n *\n *\n * Transpose 2D\n *\n *\n */\ntemplate <typename T1, size_t N, size_t M, typename T2, size_t N1, size_t M1>\nvoid transpose(T1 (&in1)[N][M], vector<size_t> shuffle, T2 (&result)[N1][M1])\n{\n#ifdef _DEBUG\n    cout << \"transpose()-2D-2D\" << endl;\n#endif\n    //  clock_t start, end;\n//\tstart = clock();\n\n    for (size_t i=0; i<N; i++){\n        for (size_t j=0; j<M; j++){\n            result[j][i] = in1[i][j];\n        }\n    }\n\n//\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n}\n\n/*\n *\n *\n * Transpose 3D\n *\n *\n */\ntemplate <typename T1, size_t M, size_t K, size_t L,\n        typename T2, size_t M1, size_t K1, size_t L1>\nvoid transpose(T1 (&in1)[M][K][L], vector<size_t> shuffle, T2 (&result)[M1][K1][L1])\n{\n#ifdef _DEBUG\n    cout << \"transpose()-3D\" << endl;\n#endif\n    //\n//    clock_t start, end;\n//    start = clock();\n\n    int shuffleType = 0;\n //   int shuffle0 = shuffle.at(0);\n    int shuffle1 = shuffle.at(1);\n    int shuffle2 = shuffle.at(2);\n    int shuffle3 = shuffle.at(3);\n\n\n    if(shuffle1 == 1 && shuffle2 == 2 && shuffle3  == 0) {\n        shuffleType = 120;\n    } else if(shuffle1 == 2 && shuffle2 == 0 && shuffle3  == 1) {\n        shuffleType = 201;\n    } else if(shuffle1 == 0 && shuffle2 == 2 && shuffle3  == 1) {\n        shuffleType = 021;\n    } else if(shuffle1 == 1 && shuffle2 == 0 && shuffle3  == 2) {\n        shuffleType = 102;\n    }\n\n    cout << shuffleType <<endl;\n    for (int j=0; j<M; j++){\n        for (int k=0; k<K; k++){\n            for (int l=0; l<L; l++){\n                if(shuffleType == 120) {\n                    result[k][l][j] = in1[j][k][l]; // 1, 2, 0\n                } else if (shuffleType == 201) {\n                    result[l][j][k] = in1[j][k][l]; // 2, 0, 1\n                } else if (shuffleType == 021) {\n                    result[j][l][k] = in1[j][k][l]; // 0, 2, 1\n                } else if (shuffleType == 102) {\n                    result[k][j][l] = in1[j][k][l]; // 1, 0, 2\n                } else {\n                    cout << \"No!!!!!!!!!!!!\";\n                }\n            }\n            // cout <<endl;\n        }\n        //cout <<endl;\n    }\n    //cout <<endl;\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n\n} // end transpose\n\n\n/*\n *\n *\n * Transpose 6D\n *\n *\n */\ntemplate <typename T1, size_t N1, size_t N2, size_t N3, size_t N4, size_t N5, size_t N6,\n        typename T2, size_t M1, size_t M2, size_t M3, size_t M4, size_t M5, size_t M6>\nvoid transpose( T1 (&in1)[N1][N2][N3][N4][N5][N6], vector<size_t> shuffle, T2 (&result)[M1][M2][M3][M4][M5][M6])\n{\n#ifdef _DEBUG\n    cout << \"transpose-6D\" << endl;\n#endif\n    //\n//    clock_t start, end;\n//    start = clock();\n\n    int shuffleType = 0;\n    int shuffle0 = shuffle.at(0);\n    int shuffle1 = shuffle.at(1);\n    int shuffle2 = shuffle.at(2);\n    int shuffle3 = shuffle.at(3);\n    int shuffle4 = shuffle.at(4);\n    int shuffle5 = shuffle.at(5);\n\n    if(shuffle0 == 0 &&shuffle1 == 1 && shuffle2 == 4 && shuffle3  == 2 && shuffle4  == 5 && shuffle5  == 3) {\n        shuffleType = 14253;\n    }\n\n\n    //  cout << shuffleType <<endl;\n//#pragma omp parallel for\n    for (int i1 = 0; i1 < N1; i1++){\n        for (int i2 = 0; i2 < N2; i2++){\n            for (int i3 = 0; i3 < N3; i3++){\n                for (int i4 = 0; i4 < N4; i4++){\n                    for (int i5 = 0; i5 < N5; i5++){\n                        for (int i6 = 0; i6 < N6; i6++){\n\n                            if(shuffleType == 14253) {\n                                result[i1][i2][i5][i3][i6][i4] = in1[i1][i2][i3][i4][i5][i6]; // 0, 1, 4, 2, 5, 3\n                            }\n\n                        }\n\n                    }\n                }\n                // cout <<endl;\n            }\n            //cout <<endl;\n        }\n        //cout <<endl;\n    }\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n}\n\n\n/*\n *\n *\n * Transpose 4D\n *\n *\n */\ntemplate <typename T1, size_t N1, size_t N2, size_t N3, size_t N4,\n        typename T2, size_t M1, size_t M2, size_t M3, size_t M4>\nvoid transpose( T1 (&in1)[N1][N2][N3][N4], vector<size_t> shuffle, T2 (&result)[M1][M2][M3][M4])\n{\n#ifdef _DEBUG\n    cout << \"transpose()-4D\" << endl;\n#endif\n//    clock_t start, end;\n//    start = clock();\n\n    int shuffleType = 0;\n//    int shuffle0 = shuffle.at(0);\n    int shuffle1 = shuffle.at(1);\n    int shuffle2 = shuffle.at(2);\n    int shuffle3 = shuffle.at(3);\n\n    if(shuffle1 == 2 && shuffle2 == 3 && shuffle3  == 1) {\n        shuffleType = 231;\n    } else if(shuffle1 == 3 && shuffle2 == 1 && shuffle3  == 2) {\n        shuffleType = 312;\n    } else if(shuffle1 == 1 && shuffle2 == 3 && shuffle3  == 2) {\n        shuffleType = 132;\n    } else if(shuffle1 == 2 && shuffle2 == 1 && shuffle3  == 3) {\n        shuffleType = 213;\n    } else if(shuffle1 == 3 && shuffle2 == 2 && shuffle3  == 1) {\n        shuffleType = 321;\n    }else if(shuffle1 == 1 && shuffle2 == 3 && shuffle3  == 2) {\n        shuffleType = 132;\n    }\n\n//   cout << \"shuffle type = \" << shuffleType <<endl;\n//#pragma omp parallel for\n    for (size_t i1 = 0; i1 < N1; i1++){\n        for (size_t i2 = 0; i2< N2; i2++){\n            for (size_t i3 = 0; i3 < N3; i3++){\n                for (size_t i4 = 0; i4 < N4; i4++){\n                    if(shuffleType == 231) {\n                        result[i1][i3][i4][i2] = in1[i1][i2][i3][i4]; // 0, 2, 3, 1\n                    } else if (shuffleType == 312) {\n                        result[i1][i4][i2][i3] = in1[i1][i2][i3][i4]; // 0, 3, 1, 2\n                    } else if (shuffleType == 132) {\n                        result[i1][i2][i4][i3] = in1[i1][i2][i3][i4]; // 0, 1, 3, 2\n                    } else if (shuffleType == 213) {\n                        result[i1][i3][i2][i4] = in1[i1][i2][i3][i4]; // 0, 2, 1, 3\n                    }else if (shuffleType == 321) {\n                        result[i1][i4][i3][i2] = in1[i1][i2][i3][i4]; // 0, 2, 1, 3\n                    }else if (shuffleType == 132) {\n                        result[i1][i2][i4][i3] = in1[i1][i2][i3][i4]; // 0, 2, 1, 3\n                    }\n                    else {\n                        cout << \"No!!!!!!!!!!!!\";\n                    }\n                }\n                // cout <<endl;\n            }\n            //cout <<endl;\n        }\n        //cout <<endl;\n    }\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n\n}\n\n\n/*\n *\n *\n * Reshape 4D => 2D\n *\n *\n */\ntemplate <typename T1, size_t N, size_t M, size_t L, size_t K,\n        typename T2, size_t N1, size_t M1>\nvoid reshape(T1 (&in1)[N][M][L][K], T2 (&result)[N1][M1])\n{\n#ifdef _DEBUG\n    cout << \"reshape()-4D -> 2D)\" << endl;\n#endif\n    //\n//    clock_t start, end;\n//    start = clock();\n\n//    cout << \"^^^^^^^^^^\" << endl;\n//\n//\tfor(int j = 0; j < M; j++){\n//\t\tif(j%10 == 0) cout <<endl;\n//\t\tcout << in1[0][j][0][0] << \"\\t\";\n//\t}\n\n    int total = 0;\n    for(size_t i1 = 0; i1 < N; i1++) {\n        for(size_t i2 = 0; i2 < M; i2++) {\n            for(size_t i3 = 0; i3 < L; i3++) {\n                for(size_t i4 = 0; i4 < K; i4++) {\n\n                    total = i1*M*L*K + i2*L*K + i3*K + i4;\n                    int idx1 = total/M1, idx2 = total%M1;\n\n                    result[idx1][idx2] = in1[i1][i2][i3][i4];\n\n                }\n            }\n        }\n    }\n//\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n}\n\n\n\n/*\n *\n *\n * Reshape 6D => 4D\n *\n *\n */\ntemplate <typename T1, size_t N1, size_t N2, size_t N3, size_t N4, size_t N5, size_t N6,\n        typename T2, size_t M1, size_t M2, size_t M3, size_t M4>\nvoid reshape(T1 (&in1)[N1][N2][N3][N4][N5][N6], T2 (&result)[M1][M2][M3][M4])\n{\n#ifdef _DEBUG\n    cout << \"reshape()-6D -> 4D\" << endl;\n#endif\n//    clock_t start, end;\n//    start = clock();\n\n    int total = 0;\n    for(int i1 = 0; i1 < N1; i1++) {\n        for(int i2 = 0; i2 < N2; i2++) {\n            for(int i3 = 0; i3 <N3; i3++) {\n                for(int i4 = 0; i4 < N4; i4++) {\n                    for(int i5 = 0; i5 < N5; i5++) {\n                        for(int i6 = 0; i6 < N6; i6++) {\n                            total = i1*N2*N3*N4*N5 + i2*N3*N4*N5 + i3*N4*N5 + i4*N5 + i6;\n\n                            int m1 = M2*M3*M4;\n                            int m2 = M3*M4;\n\n                            int idx1 = total/m1;\n                            int idx2 = (total%m1)/m2;\n                            int idx3 = (total%m1)%m2/M4;\n                            int idx4 = (total%m1)%m2%M4;\n                            result[idx1][idx2][idx3][idx4] = in1[i1][i2][i3][i4][i5][i6];\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n}\n\n\n\n/*\n *\n *\n * Reshape 4D => 6D\n *\n *\n */\ntemplate <typename T1, size_t N1, size_t N2, size_t N3, size_t N4,\n        typename T2, size_t M1, size_t M2, size_t M3, size_t M4, size_t M5, size_t M6>\nvoid reshape(T1 (&in1)[N1][N2][N3][N4], T2 (&result)[M1][M2][M3][M4][M5][M6])\n{\n#ifdef _DEBUG\n    cout << \"reshape()4D -> 6D\" << endl;\n#endif\n    //\n//    clock_t start, end;\n//    start = clock();\n\n    int total = 0;\n    for(int i1 = 0; i1 < N1; i1++) {\n        for(int i2 = 0; i2 < N2; i2++) {\n            for(int i3 = 0; i3 <N3; i3++) {\n                for(int i4 = 0; i4 < N4; i4++) {\n                    total = i1*N2*N3*N4 + i2*N3*N4 + i3*N4 + i4;\n\n                    int m1 = M2*M3*M4*M5*M6;\n                    int m2 = M3*M4*M5*M6;\n                    int m3 = M4*M5*M6;\n                    int m4 = M5*M6;\n\n                    int idx1 = total/m1;\n                    int idx2 = (total%m1)/m2;\n                    int idx3 = ((total%m1)%m2)/m3;\n                    int idx4 = ((total%m1)%m2%m3)/m4;\n                    int idx5 = (((total%m1)%m2%m3)%m4)/M6;\n                    int idx6 = (((total%m1)%m2%m3)%m4)%M6;\n                    result[idx1][idx2][idx3][idx4][idx5][idx6] = in1[i1][i2][i3][i4];\n                }\n            }\n        }\n    }\n//\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n}\n\n\ntemplate<typename T1>\nvoid leakyRelu(T1 in, vector<size_t> idim, T1 result, int type)\n{\n    cout << \"leakyRelu():TBD\" << endl;\n}\n\n\ntemplate<typename T1, typename T2>\nvoid LRN(T1 in, vector<size_t> dim, float size, float beta, float bias, float windowSize, T2 result, int type)\n{\n    cout << \"LRN(): TBD\" << endl;\n}\n\ntemplate<typename T1, size_t N, size_t M, typename T2>\nvoid dropout(T1 (&in)[N][M], vector<size_t> dim, T1 (&result)[N][M], T2 (&mask)[N][M], int type)\n{\n    cout << \"dropout(): TBD\" << endl;\n}\n\n\ntemplate<typename T1, typename T2>\nvoid mul(T1 in1, vector<size_t> dim, T2 in2, T1 result, int type)\n{\n    cout << \"mul(): TBD\" << endl;\n}\n\ntemplate<typename T1, typename T2, size_t N, size_t M>\nvoid splat(T1 value, T2 (&result)[N][M])\n{\n    for(int i = 0; i < N; i++) {\n        for(int j = 0; j < M; j++) {\n            result[i][j] = (T2)value;\n        }\n    }\n}\n\ntemplate <typename T1, size_t N, size_t M, size_t K, size_t L>\nvoid channel_shuffle(T1 (&in1)[N][M][K][L], const int group, int kernel, T1 (&result)[N][M][K][L])\n{\n#ifdef _DEBUG\n    cout << \"shuffle()-4D\" << endl;\n    cout << \"group: \" << group << endl;\n    cout << \"kernel: \" << kernel << endl;\n#endif\n\n    const int gdim = L/group;\n    T1 rt[N][M][K][group][gdim];\n\n    //reshape 4d -> 5d\n    int total = 0;\n    for(int i1 = 0; i1 < N; i1++) {\n        for(int i2 = 0; i2 < M; i2++) {\n            for(int i3 = 0; i3 <K; i3++) {\n                for(int i4 = 0; i4 < L; i4++) {\n                    total = i1*M*K*L + i2*K*L + i3*L + i4;\n\n                    int m1 = M*K*group*gdim;\n                    int m2 = K*group*gdim;\n                    int m3 = group*gdim;\n                    int m4 = gdim;\n\n                    int idx1 = total/m1;\n                    int idx2 = (total%m1)/m2;\n                    int idx3 = ((total%m1)%m2)/m3;\n                    int idx4 = ((total%m1)%m2%m3)/m4;\n                    int idx5 = ((total%m1)%m2%m3)%m4;\n                    rt[idx1][idx2][idx3][idx4][idx5] = in1[i1][i2][i3][i4];\n                }\n            }\n        }\n    }\n\n    T1 transrt[N][M][K][gdim][group];\n//    //transpose\n    for (size_t i1 = 0; i1 < N; i1++){\n        for (size_t i2 = 0; i2< M; i2++){\n            for (size_t i3 = 0; i3 < K; i3++){\n                for (size_t i4 = 0; i4 < group; i4++){\n                    for (size_t i5 = 0; i5 < gdim; i5++) {\n                        transrt[i1][i2][i3][i5][i4] = rt[i1][i2][i3][i4][i5];\n                    }\n                }\n            }\n        }\n    }\n\n    //reshape 5d -> 4d\n    total = 0;\n    for(int i1 = 0; i1 < N; i1++) {\n        for(int i2 = 0; i2 < M; i2++) {\n            for(int i3 = 0; i3 <K; i3++) {\n                for(int i4 = 0; i4 < gdim; i4++) {\n                    for(int i5 = 0; i5 < group; i5++) {\n                            total = i1*M*K*gdim*group + i2*K*gdim*group + i3*gdim*group + i4*group + i5;\n\n                            int m1 = M*K*L;\n                            int m2 = K*L;\n\n                            int idx1 = total/m1;\n                            int idx2 = (total%m1)/m2;\n                            int idx3 = (total%m1)%m2/L;\n                            int idx4 = (total%m1)%m2%L;\n                            result[idx1][idx2][idx3][idx4] = transrt[i1][i2][i3][i4][i5];\n                        }\n                }\n            }\n        }\n    }\n\n//\tend = clock();\n//    cout << \"==> [time] : \" << (((double)(end - start)) / CLOCKS_PER_SEC) << \" seconds\" << endl;\n\n}\n\n\n#endif /* LIBRARY_H_ */", "meta": {"hexsha": "39cdf54b444f40018385fe1ff6131992ff87f5f7", "size": 69956, "ext": "h", "lang": "C", "max_stars_repo_path": "tests/CCodeGenTest/src/library.h", "max_stars_repo_name": "etri/nest-compiler", "max_stars_repo_head_hexsha": "c6ac790ed12807f2e0855e3aa0170cb149dc237d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2020-12-16T07:05:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T08:12:03.000Z", "max_issues_repo_path": "tests/CCodeGenTest/src/library.h", "max_issues_repo_name": "etri/nest-compiler", "max_issues_repo_head_hexsha": "c6ac790ed12807f2e0855e3aa0170cb149dc237d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-25T03:36:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T05:01:43.000Z", "max_forks_repo_path": "tests/CCodeGenTest/src/library.h", "max_forks_repo_name": "etri/nest-compiler", "max_forks_repo_head_hexsha": "c6ac790ed12807f2e0855e3aa0170cb149dc237d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2021-01-08T01:36:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T02:03:08.000Z", "avg_line_length": 28.6822468225, "max_line_length": 188, "alphanum_fraction": 0.4898793527, "num_tokens": 23234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.35521366030339907}}
{"text": "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include <Python.h>\n#include <numpy/arrayobject.h>\n#include <lapacke.h>\n\n/* DGESVD prototype */\nextern void LAPACK_dgesvd( char* jobu, char* jobvt, int* m, int* n, double* a,\n                    int* lda, double* s, double* u, int* ldu, double* vt, int* ldvt,\n                    double* work, int* lwork, int* info );\n\ndouble** An(double *pi, double *x, int labs, int dims);\ndouble** A(double **PI, double **X, int labs, int dims, int n_pool);\ndouble** Fisher(double *pi, double *x, double sigma, int labs, int dims);\n\nstatic char estVar_docstring[] =\n    \"Calculate the A and Fisher matrix.\";\n\nstatic PyObject *varRedu_estVar(PyObject *self, PyObject *args);\n\nstatic PyMethodDef module_methods[] = {\n    {\"estVar\", varRedu_estVar, METH_VARARGS, estVar_docstring},\n    {NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef moduledef = {\n    PyModuleDef_HEAD_INIT,\n    \"_variance_reduction\",  /* m_name */\n    \"This module provides calculate A and Fisher matrix using C.\",  /* m_doc */\n    -1,                  /* m_size */\n    module_methods,      /* m_methods */\n    NULL,                /* m_reload */\n    NULL,                /* m_traverse */\n    NULL,                /* m_clear */\n    NULL,                /* m_free */\n};\n\nPyMODINIT_FUNC PyInit__variance_reduction(void){\n    PyObject *m = PyModule_Create(&moduledef);\n    if(m==NULL){\n        return NULL;\n    }\n\n    /* Load 'numpy' */\n    import_array();\n\n    return m;\n}\n\ndouble* matrix_mul(double* a, double* b, int m1, int n1, int m2, int n2){\n    double *ret = (double*) malloc(m1 * n2 * sizeof(double));\n    if(n1 != m2){\n        return NULL;\n    }\n    for(int i=0; i<m1; i++)\n        for(int j=0; j<n2; j++){\n            double temp = 0.0;\n            for(int p=0; p<n1; p++)\n                temp += a[i*n1 + p] * b[p*n2 + j];\n            ret[i*n2 + j] = temp;\n        }\n    return ret;\n}\n\n\nvoid pinv(double** X, int labs, int dims){\n    int m = labs*dims, n = labs*dims, lda = labs*dims, ldu = labs*dims, \n        ldvt = labs*dims, lwork, info;\n    double wkopt;\n    double *work;\n    double *s  = (double*) malloc(labs*dims * sizeof(double));\n    double *u  = (double*) malloc(labs*dims * labs*dims * sizeof(double));\n    double *vt = (double*) malloc(labs*dims * labs*dims * sizeof(double));\n    double *a  = (double*) malloc(labs*dims * labs*dims * sizeof(double));\n\n    for(int i=0; i<m; i++)\n        for(int j=0; j<n; j++)\n            a[i*labs*dims + j] = X[i][j];\n\n     /* Query and allocate the optimal workspace */\n    lwork = -1;\n    LAPACK_dgesvd(\"All\", \"All\", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, &wkopt, &lwork,\n        &info);\n    lwork = (int)wkopt;\n    work = (double*)malloc( lwork*sizeof(double) );\n    /* Compute SVD */\n    LAPACK_dgesvd(\"All\", \"All\", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork,\n        &info);\n    /* Check for convergence  */\n    if(info > 0) {\n        printf(\"The algorithm computing SVD failed to converge. %d\\n\", info);\n    }\n    if(info < 0) {\n        printf(\"Has illegal value. %d\\n\", info);\n    }\n\n    int numSigular = 0;\n    double *si  = (double*) malloc(labs*dims * labs*dims * sizeof(double));\n    memset(si, 0, labs*dims * labs*dims * sizeof(double));\n\n    for(int i=0; i<ldu; i++){\n        if(s[i] > 1e-30){\n            si[i*ldu + i] = 1.0 / s[i];\n            numSigular += 1;\n        }else{\n            si[i+ldu + i] = 0.0;\n        }\n    }\n\n    /* calculating transpose */\n    double *ret = matrix_mul(vt, si, labs*dims, numSigular, numSigular, numSigular);\n    double *ret_pinv = matrix_mul(ret, u, labs*dims, numSigular, numSigular, labs*dims);\n\n    for(int i=0; i<m; i++)\n        for(int j=0; j<n; j++)\n            X[i][j] = ret_pinv[i*n + j];\n\n    free(ret);\n    free(ret_pinv);\n    free(work);\n    free(a);\n    free(s);\n    free(vt);\n    free(u);\n    free(si);\n\n    return;\n}\n\nstatic PyObject *varRedu_estVar(PyObject *self, PyObject *args)\n{\n    int dims, n_pool, labs, sigma;\n    PyObject *PI_obj, *X_obj, *ePI_obj, *eX_obj;\n\n    if (!PyArg_ParseTuple(args, \"dOOOO\", &sigma, &PI_obj, &X_obj, &ePI_obj, &eX_obj))\n        return NULL;\n\n    PyArrayObject *PI_array  =  (PyArrayObject*)PyArray_FROM_OTF(PI_obj,  NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);\n    PyArrayObject *X_array   =  (PyArrayObject*)PyArray_FROM_OTF(X_obj,   NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);\n    PyArrayObject *ePI_array =  (PyArrayObject*)PyArray_FROM_OTF(ePI_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);\n    PyArrayObject *eX_array  =  (PyArrayObject*)PyArray_FROM_OTF(eX_obj,  NPY_DOUBLE, NPY_ARRAY_IN_ARRAY);\n\n    if (PI_array == NULL || X_array == NULL || ePI_array == NULL || eX_array == NULL) {\n        Py_XDECREF(PI_array);\n        Py_XDECREF(X_array);\n        Py_XDECREF(ePI_array);\n        Py_XDECREF(eX_array);\n        return NULL;\n    }\n\n    labs   = (int)PyArray_DIM(PI_array, 1);\n    n_pool = (int)PyArray_DIM(X_array, 0);\n    dims   = (int)PyArray_DIM(X_array, 1);\n\n    double **PI  =  (double**) malloc(n_pool * sizeof(double*));\n    double **X   =  (double**) malloc(n_pool * sizeof(double*));\n    for(int i=0; i<n_pool; i++){\n        PI[i] = (double*) malloc(labs * sizeof(double));\n        X[i]  = (double*) malloc(dims * sizeof(double));\n    }\n    for(int i=0; i<n_pool; i++){\n        for(int j=0; j<labs; j++){\n            PI[i][j] = *(double*)PyArray_GETPTR2(PI_array, i, j);\n        }\n        for(int j=0; j<dims; j++){\n            X[i][j] = *(double*)PyArray_GETPTR2(X_array, i, j);\n        }\n    }\n    double *ePI =  (double*) PyArray_DATA(ePI_array);\n    double *eX  =  (double*) PyArray_DATA(eX_array);\n\n    double **retF = Fisher(ePI, eX, sigma, labs, dims);\n    double **retA = A(PI, X, labs, dims, n_pool);\n\n    pinv(retF, labs, dims);\n\n    /* calculates the trace of the multiply of pinv(F) and A  */\n    double score = 0.0;\n    for(int i=0; i<dims*labs; i++){\n        for(int k=0; k<dims*labs; k++){\n            score += retA[i][k] * retF[k][i];\n        }\n    }\n\n    Py_DECREF(PI_array);\n    Py_DECREF(X_array);\n    Py_DECREF(ePI_array);\n    Py_DECREF(eX_array);\n\n    PyObject* ret = Py_BuildValue(\"d\", score);\n\n    for(int i=0; i<n_pool; i++){\n        free(PI[i]);\n        free(X[i]);\n    }\n    free(PI);\n    free(X);\n\n    for(int i=0; i<labs*dims; i++){\n        free(retF[i]);\n        free(retA[i]);\n    }\n    free(retF);\n    free(retA);\n\n    return ret;\n}\n\ndouble** An(double *pi, double *x, int labs, int dims){\n    double **g = (double**) malloc(labs*dims * sizeof(double*));\n    for(int i=0; i<labs*dims; i++){\n        g[i] = (double*) malloc(labs * sizeof(double));\n        memset(g[i], 0, labs * sizeof(double));\n    }\n    \n    for(int p=0; p<labs; p++)\n        for(int i=0; i<dims; i++){\n            for(int c=0; c<labs; c++)\n                if(p == c) g[p*dims + i][c] = pi[p] * (1.0-pi[p]) * x[i];\n                else g[p*dims + i][c] = -1.0 * pi[p] * pi[c] * x[i];\n        }\n\n    double **an = (double**) malloc(labs*dims * sizeof(double*));\n    for(int i=0; i<labs*dims; i++){\n        an[i] = (double*) malloc(labs*dims * sizeof(double));\n        memset(an[i], 0, labs*dims * sizeof(double));\n    }\n    \n    for(int p=0; p<labs; p++)\n        for(int i=0; i<dims; i++)\n            for(int q=0; q<labs; q++)\n                for(int j=0; j<dims; j++){\n                    /* inner product */\n                    double tmp = 0.0;\n                    for(int k=0; k<labs; k++){\n                        tmp += g[p*dims + i][k] * g[q*dims + j][k];\n                    }\n                    an[p*dims + i][q*dims + j] = tmp;\n                }\n\n    for(int i=0; i<labs*dims; i++)\n        free(g[i]);\n    free(g);\n\n    return an;\n}\n\ndouble** A(double **PI, double **X, int labs, int dims, int n_pool){\n    double **ret = (double**) malloc(labs*dims * sizeof(double*));\n    for(int i=0; i<labs*dims; i++){\n        ret[i] = (double*) malloc(labs*dims * sizeof(double));\n        memset(ret[i], 0, labs*dims * sizeof(double));\n    }\n\n    for(int n=0; n<n_pool; n++){\n        double **an = An(PI[n], X[n], labs, dims);\n\n        for(int p=0; p<labs; p++)\n            for(int i=0; i<dims; i++)\n                for(int q=0; q<labs; q++)\n                    for(int j=0; j<dims; j++)\n                        ret[p*dims + i][q*dims + j] += an[p*dims + i][q*dims + j];\n        for(int i=0; i<labs*dims; i++)\n            free(an[i]);\n        free(an);\n    }\n    return ret;\n}\n\ndouble** Fisher(double *pi, double *x, double sigma, int labs, int dims){\n    double **ret = (double**) malloc(labs*dims * sizeof(double*));\n    for(int i=0; i<labs*dims; i++){\n        ret[i] = (double*) malloc(labs*dims * sizeof(double*));\n        memset(ret[i], 0, labs*dims * sizeof(double));\n    }\n\n    for(int p=0; p<labs; p++)\n        for(int i=0; i<dims; i++)\n            for(int q=0; q<labs; q++)\n                for(int j=0; j<dims; j++){\n                    if(p == q && i == j)\n                        ret[p*dims + i][q*dims + j] = x[i]*x[i]*pi[p]*(1.0-pi[p]) + 1.0/sigma*sigma;\n                    else if(p == q && i != j)\n                        ret[p*dims + i][q*dims + j] = x[i]*x[j]*pi[p]*(1.0-pi[p]);\n                    else\n                        ret[p*dims + i][q*dims + j] = x[i]*x[j]*pi[p]*pi[q];\n                }\n    return ret;\n}\n", "meta": {"hexsha": "85a3e9f6f0921ad68f037dfa3f004477526f0cf8", "size": 9191, "ext": "c", "lang": "C", "max_stars_repo_path": "libact/query_strategies/src/variance_reduction/variance_reduction.c", "max_stars_repo_name": "crowdEEG/libact", "max_stars_repo_head_hexsha": "706ca2adfa3ee081d1f7a2f01aacb6c7c0efd5de", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-11-23T05:56:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-18T11:16:02.000Z", "max_issues_repo_path": "libact/query_strategies/src/variance_reduction/variance_reduction.c", "max_issues_repo_name": "crowdEEG/libact", "max_issues_repo_head_hexsha": "706ca2adfa3ee081d1f7a2f01aacb6c7c0efd5de", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libact/query_strategies/src/variance_reduction/variance_reduction.c", "max_forks_repo_name": "crowdEEG/libact", "max_forks_repo_head_hexsha": "706ca2adfa3ee081d1f7a2f01aacb6c7c0efd5de", "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.6931034483, "max_line_length": 106, "alphanum_fraction": 0.5190947666, "num_tokens": 2871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3550896847980452}}
{"text": "#ifndef H_EASY_GSL\n#define H_EASY_GSL\n\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nstruct egsl_val {\n\tgsl_matrix * gslm;\n\tint cid : 16;\n\tint index : 16;\n};\n\ntypedef struct egsl_val val;\n\n/* Core functions */\n\n/* Push a new context. */\nvoid egsl_push();\nvoid egsl_push_named(const char*name);\n/* Pops a context */\nvoid egsl_pop();\nvoid egsl_pop_named(const char*name);\nvoid egsl_free(void);\n\ndouble* egsl_atmp(val v, size_t i, size_t j);\nval egsl_alloc(size_t rows, size_t columns);\nval egsl_alloc_in_context(int cid, size_t rows, size_t cols);\ngsl_matrix * egsl_gslm(val v);\n/** Creates a copy of v in the previous context.*/\nval egsl_promote(val v);\n\n/** Operations among values */\nval egsl_scale(double, val);\nval egsl_sum(val, val);\nval egsl_sum3(val, val, val);\nval egsl_mult(val, val);\nval egsl_transpose(val);\nval egsl_inverse(val);\nval egsl_sub(val,val);\nval egsl_sum(val v1,val v2);\nval egsl_compose_col(val v1, val v2);\nval egsl_compose_row(val v1, val v2);\nvoid egsl_add_to(val v1, val v2);\nvoid egsl_add_to_col(val v1, size_t j, val v2);\n\ndouble egsl_norm(val);\n\nvoid egsl_symm_eig(val v, double* eigenvalues, val* eigenvectors);\n\ndouble egsl_atv(val, size_t i);\ndouble egsl_atm(val, size_t i, size_t j);\n\n/* File: egsl_conversions.c\n  Conversions */\n\nval egsl_vFa(size_t rows, const double*);\nval egsl_vFda(size_t rows, size_t columns, const double*);\n\n/** Copies a VECTOR value into array */\nvoid egsl_v2a(val, double*);\n/** Copies a MATRIX value into array (row1 .. rown) */\nvoid egsl_v2da(val, double*);\n/** Copies a vector value into a gsl_vector */\nvoid egsl_v2vec(val, gsl_vector*);\n\nval egsl_vFgslv(const gsl_vector*);\nval egsl_vFgslm(const gsl_matrix*);\n\ngsl_matrix* egsl_v2gslm(val);\n\n/*/ File: egsl_misc.c\n    Miscellaneous useful matrixes. */\nval egsl_zeros(size_t rows, size_t columns);\nval egsl_ones(size_t rows, size_t columns);\nval egsl_vers(double theta);\nval egsl_rot(double theta);\n\n\n/* Misc */\nvoid egsl_print(const char*str, val);\t\n/** Prints eigenvalues and eigenvectors of a symmetric matrix */\nvoid egsl_print_spectrum(const char*s, val v);\nvoid egsl_print_stats(void);\n\n\n\t\n/** Private implementations things */\nvoid egsl_expect_size(val v, size_t rows, size_t cols);\nvoid egsl_error(void);\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n", "meta": {"hexsha": "0b8c17cd77f2c66fcd93fcd00d6d0906e82e7782", "size": 2318, "ext": "h", "lang": "C", "max_stars_repo_path": "src/csm/sm/lib/egsl/egsl.h", "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-21T00:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T02:53:37.000Z", "max_issues_repo_path": "src/csm/sm/lib/egsl/egsl.h", "max_issues_repo_name": "alecone/ROS_project", "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/csm/sm/lib/egsl/egsl.h", "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-24T20:11:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T12:39:31.000Z", "avg_line_length": 22.7254901961, "max_line_length": 66, "alphanum_fraction": 0.7364106989, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3549809737929451}}
{"text": "#include <stdio.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_permutation.h>\n\nint\nmain (void) \n{\n  const size_t N = 10;\n  const gsl_rng_type * T;\n  gsl_rng * r;\n\n  gsl_permutation * p = gsl_permutation_alloc (N);\n  gsl_permutation * q = gsl_permutation_alloc (N);\n\n  gsl_rng_env_setup();\n  T = gsl_rng_default;\n  r = gsl_rng_alloc (T);\n\n  printf (\"initial permutation:\");  \n  gsl_permutation_init (p);\n  gsl_permutation_fprintf (stdout, p, \" %u\");\n  printf (\"\\n\");\n\n  printf (\" random permutation:\");  \n  gsl_ran_shuffle (r, p->data, N, sizeof(size_t));\n  gsl_permutation_fprintf (stdout, p, \" %u\");\n  printf (\"\\n\");\n\n  printf (\"inverse permutation:\");  \n  gsl_permutation_inverse (q, p);\n  gsl_permutation_fprintf (stdout, q, \" %u\");\n  printf (\"\\n\");\n\n  gsl_permutation_free (p);\n  gsl_permutation_free (q);\n  gsl_rng_free (r);\n\n  return 0;\n}\n", "meta": {"hexsha": "72478641d42975cc83d252fc68cf693c87c37400", "size": 873, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/permshuffle.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/permshuffle.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/permshuffle.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 21.2926829268, "max_line_length": 50, "alphanum_fraction": 0.6655211913, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.35487599114879576}}
{"text": "/* bclsqr.c\n   $Revision: 273 $ $Date: 2006-09-04 15:59:04 -0700 (Mon, 04 Sep 2006) $\n\n   ----------------------------------------------------------------------\n   This file is part of BCLS (Bound-Constrained Least Squares).\n\n   Copyright (C) 2006 Michael P. Friedlander, Department of Computer\n   Science, University of British Columbia, Canada. All rights\n   reserved. E-mail: <mpf@cs.ubc.ca>.\n   \n   BCLS is free software; you can redistribute it and/or modify it\n   under the terms of the GNU Lesser General Public License as\n   published by the Free Software Foundation; either version 2.1 of the\n   License, or (at your option) any later version.\n   \n   BCLS is distributed in the hope that it will be useful, but WITHOUT\n   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General\n   Public License for more details.\n   \n   You should have received a copy of the GNU Lesser General Public\n   License along with BCLS; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n   USA\n   ----------------------------------------------------------------------\n*/\n/*!\n   \\file\n   Interface to LSQR routine.  Used to compute a Newton step.\n*/\n\n#include <cblas.h>\n#include <string.h>\n#include <stdio.h>\n\n#include \"bcls.h\"\n#include \"bclib.h\"\n#include \"bclsqr.h\"\n#include \"lsqr.h\"\n\n/*!\n\n  \\brief Mat-vec routine called by LSQR.\n\n  LSQR calls this routine, which in turn calls bcls_aprod: This\n  routine is declared \"static\" so that it won't be confused with the\n  user's own Aprod routine.\n  \n  - If mode = 1,\n    - y(1:m)  <-  y(1:m)  +  A(:,ix) * dxFree.\n    - y(m+1:) <-  y(m+1:) +     damp * dxFree\n\n  - If mode = 2,\n    - dxFree <- dxFree + A'* y(1:m) + damp y(m+1:).\n\n  Note that mSubProb is the number of rows in the subproblem.  This\n  may or may not be equal to m, which is the number of rows in the\n  original problem.  If the subproblem is damped (because the user has\n  either provided a linear term or an explicit damping parameter),\n  then mSubProb = m + nFree.  Otherwise, mSubProb = m.\n\n  \\param[in]      mode      Determines which producte with A is required.\n\n  \\param[in]      mSubProb  Number of rows in the matrix seen by LSQR.  Also:\n                            - length of y.\n  \\param[in]      nFree     Number of columns in A(:,ix).  Also:\n                            - length of ix\n                            - length of dxFree.\n  \\param[in,out]  dxFree    Primal variables\n  \\param[in,out]  y         Dual variables.\n  \\param[in,out]  UsrWrk    Transit pointer to the BCLS problem context.\n\n*/\nstatic void\naprod_free_lsqr( const int mode, const int mSubProb, const int nFree,\n                 double dxFree[], double y[], void *UsrWrk)\n{\n    int j;\n    BCLS *ls = (BCLS *)UsrWrk;  // Reclaim access to the BCLS workspace.\n    const int    m      = ls->m;\n    const int    preconditioned = ls->Usolve != NULL;\n    const int    damped = ls->damp_actual > 0.0;\n    const double damp   = ls->damp_actual;\n    int          *ix    = ls->ix;\n    double       *dx    = ls->dx;    // Used as workspace.\n    double       *dy    = ls->wrk_u; // ...\n\n    if (mode == 1) {\n        \n        // Solve U dy = dxFree.  U is nFree-by-nFree, and so the\n        // relevant part of dy has length nFree.\n        if (preconditioned)\n            bcls_usolve( ls, BCLS_PRECON_U, nFree, ix, dy, dxFree );\n        else\n            cblas_dcopy( nFree, dxFree, 1, dy, 1 );\n\n        // y2 <- y2 + damp * dy(1:nFree).\n        if (damped)\n            cblas_daxpy( nFree, damp, dy, 1, &y[m], 1 );\n        \n        // Scatter dy into dx: dx(ix) <- dy(1:nFree).\n        for (j = 0; j < nFree; j++)  dx[ ix[j] ] = dy[j];\n        \n        // dy <- A(:,ix) * dx(ix).\n        bcls_aprod( ls, BCLS_PROD_A, nFree, ix, dx, dy );\n        \n        // y1 <- y1 + dy.\n        cblas_daxpy( m, 1.0, dy, 1, y, 1 );\n        \n    }\n    else { // mode == 2\n        \n        // dx <- A' * y1.\n        bcls_aprod( ls, BCLS_PROD_At, nFree, ix, dx, y );\n        \n        // Gather dx(ix) into dy: dy(1:nFree) <- dx(ix).\n        for (j = 0; j < nFree; j++) dy[j] = dx[ ix[j] ];\n        \n        // dy <- dy + damp * y2.\n        if (damped)\n            cblas_daxpy( nFree, damp, &y[m], 1, dy, 1 );\n        \n        // Solve U' dx = dy.\n        if (preconditioned)\n            bcls_usolve( ls, BCLS_PRECON_Ut, nFree, ix, dy, dx );\n        else\n            cblas_dcopy( nFree, dy, 1, dx, 1 );\n\n        // dxFree <- dxFree + dx.\n        cblas_daxpy( nFree, 1.0, dx, 1, dxFree, 1 );\n        \n    }\n    return;\n}\n\n/*!\n\n  \\brief Compute a Newton step using LSQR.\n\n  \\see  bcls_newton_step_cgls.\n\n  \\param[in,out] ls      BCLS problem context.\n  \\param[in]     m       Number of rows in A.\n  \\param[in]     nFree   Number of columns in A(:,ix).  Also:\n                         - length of ix and dxFree\n  \\param[in]     ix      Index of free variables.\n  \\param[in]     damp    Regularization parameter.\n  \\param[in]     itnLim  Iteration limit on current LSQR call.\n  \\param[in]     tol     LSQR's atol and btol.\n  \\param[in,out] dxFree  Search direction on free variables.\n  \\param[in,out] x       Current point.\n  \\param[in]     c       Linear term.\n  \\param[in,out] r       Residual. Used as RHS for LSQR.\n  \\param[out]    itns    Number of LSQR iterations on current subproblem.\n  \\param[out]    opt     Optimality achieved by LSQR on current subproblem.\n\n  \\return\n  - 0: Required accurace was achieved.\n  - 1: The iteration limit (itnLim) was reached.\n  - 2: A(:,ix) is excessively ill-conditioned.\n\n*/\nint\nbcls_newton_step_lsqr( BCLS *ls, int m, int nFree, int ix[], double damp,\n\t\t       int itnLim, double tol, double dxFree[], double x[],\n\t\t       double c[], double r[], int *itns, double *opt )\n{\n    int j, k;                             // Misc. counters.\n    int mpn;                              // No. of rows in [ N; damp I ].\n    int          unscale_dxFree   = 0;\n    const int    rescaling_method = 1;\n    const int    linear   = c != NULL;\n    const int    damped   = damp  > 0.0;\n    const double damp_min = ls->damp_min;\n    const double damp2    = damp * damp;\n    const double zero     = 0.0;\n    double damp_actual;\n    double beta1, beta2;\n\n    // LSQR outputs\n    int    istop;      // Termination flag.\n    double anorm;      // Estimate of Frobenious norm of Abar.\n    double acond;      // Estimate of condition no. of Abar.\n    double rnorm;      // Estimate of the final value of norm(rbar).\n    double xnorm;      // Estimate of the norm of the final solution dx.\n\n    // Set r(m+1:) <- - 1/beta c + damp^2/beta x, where\n    //     beta = max(min_damp, damp).\n    // Note that r is declared length (m+n), so there is always enough\n    // space.  The chosen damping parameter is stored in\n    // ls->damp_actual so that it can be used in bcls_aprod_free.\n    if (!damped  &&  !linear) {\n\tmpn = m;\n\tls->damp_actual = 0.0;\n    }\n    else {\n\n\tmpn = m + nFree;\n\n\t//--------------------------------------------------------------\n\t// Rescale the RHS.  Will need to unscale LSQR's solution later.\n\t//--------------------------------------------------------------\n\tif (rescaling_method) {\n\n\t    if (linear) {\n\n\t\tunscale_dxFree  = 1;\n\t\tdamp_actual     = fmax( damp, damp_min );\n\t\tls->damp_actual = damp_actual;\n\t\t\n\t\t// r(1:m) = damp_actual * r(1:m)\n\t\tcblas_dscal( m, damp_actual, r, 1 );\n\n\t\t// r(m+1:) = - c\n\t\tfor (j = 0; j < nFree; j++ )\n\t\t    r[m+j] = - c[ ix[j] ];\n\t\t\n\t\t// r(m+1:) = - c - damp^2 * x\n\t\tif (damped)\n\t\t    for (j = 0; j < nFree; j++)\n\t\t\tr[m+j] -= damp2 * x[ ix[j] ];\n\t    }\n\t    else {\n\t\t\n\t        ls->damp_actual = damp;\n\t\tfor (j = 0; j < nFree; j++)\n\t\t    r[m+j] = - damp * x[ ix[j] ];\n\t    }\n\t}\n\t//--------------------------------------------------------------\n\t// No rescaling.\n\t//--------------------------------------------------------------\n\telse {\n\t    if (damped  &&  linear) {\n\t\t\n\t\tdamp_actual     =  fmax( damp, damp_min );\n\t\tbeta1           =  -1.0 / damp_actual;\n\t\tbeta2           =  -damp * damp / damp_actual;\n\t\tls->damp_actual =  damp_actual;\n\t\t\n\t\tfor (j = 0; j < nFree; j++) {\n\t\t    k = ix[j];\n\t\t    r[m+j] = beta1 * c[k] + beta2 * x[k];\n\t\t}\n\t    }\n\t    else if ( damped  &&  !linear ) {\n\t\t\n\t\tbeta2 = - damp;\n\t\tls->damp_actual = damp;\n\t\tfor (j = 0; j < nFree; j++)\n\t\t    r[m+j] = beta2 * x[ ix[j] ];\n\t    }\n\t    else if (!damped  &&   linear ) {\n\t\t\n\t\tbeta1 = - 1.0 / damp_min;\n\t\tls->damp_actual = damp_min;\n\t\tfor (j = 0; j < nFree; j++)\n\t\t    r[m+j] = beta1 * c[ ix[j] ];\n\t    }\n\t}\n    }\n    \n    // -----------------------------------------------------------------\n    // Solve the subproblem with LSQR.\n    // -----------------------------------------------------------------\n    bcls_timer( &(ls->stopwatch[BCLS_TIMER_LSQR]), BCLS_TIMER_START );\n\n    lsqr( mpn, nFree, aprod_free_lsqr, zero, (void *)ls,\n          r, ls->wrk_v, ls->wrk_w, dxFree, NULL,\n          tol, tol, ls->conlim, itnLim, ls->minor_file,\n          &istop, itns, &anorm, &acond,\n          &rnorm, opt, &xnorm );\n\n    bcls_timer( &(ls->stopwatch[BCLS_TIMER_LSQR]), BCLS_TIMER_STOP );\n\n    // -----------------------------------------------------------------\n    // Cleanup and exit.  First unscale dxFree if needed.\n    // -----------------------------------------------------------------\n    if (rescaling_method  &&  unscale_dxFree)\n\tcblas_dscal( nFree, 1.0/damp_actual, dxFree, 1 );\n\n    if (istop <= 3)\n\treturn 0;\n    else if (istop == 5)\n\treturn 1;\n    else\n\treturn 2;\n}\n", "meta": {"hexsha": "9dd3448e124a12271c5d4a3e4870989d3c035a02", "size": 9496, "ext": "c", "lang": "C", "max_stars_repo_path": "bcls-0.1/src/bclsqr.c", "max_stars_repo_name": "echristakopoulou/glslim", "max_stars_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-16T01:56:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:45:41.000Z", "max_issues_repo_path": "bcls-0.1/src/bclsqr.c", "max_issues_repo_name": "echristakopoulou/glslim", "max_issues_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bcls-0.1/src/bclsqr.c", "max_forks_repo_name": "echristakopoulou/glslim", "max_forks_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T07:46:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T13:00:19.000Z", "avg_line_length": 32.8581314879, "max_line_length": 77, "alphanum_fraction": 0.5216933446, "num_tokens": 2834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3546116088316674}}
{"text": "// --------------------------------------------------------------------------\n//                   OpenMS -- Open-Source Mass Spectrometry\n// --------------------------------------------------------------------------\n// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,\n// ETH Zurich, and Freie Universitaet Berlin 2002-2013.\n//\n// This software is released under a three-clause BSD license:\n//  * Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//  * Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n//  * Neither the name of any author or any participating institution\n//    may be used to endorse or promote products derived from this software\n//    without specific prior written permission.\n// For a full list of authors, refer to the file AUTHORS.\n// --------------------------------------------------------------------------\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING\n// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// --------------------------------------------------------------------------\n// $Maintainer: Erhan Kenar $\n// $Authors: Vipul Patel $\n// --------------------------------------------------------------------------\n#ifndef OPENMS_COMPARISON_SPECTRA_COMPAREFOURIERTRANSFORM_H\n#define OPENMS_COMPARISON_SPECTRA_COMPAREFOURIERTRANSFORM_H\n\n#include <OpenMS/COMPARISON/SPECTRA/PeakSpectrumCompareFunctor.h>\n#include <OpenMS/KERNEL/StandardTypes.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_fft_real.h>\n\nnamespace OpenMS\n{\n  /**\n      @brief Compare Discrete Cosines value from a Fourier transformation, also known as Discrete Cosines Transformation\n\n      The Direct Cosines Transformation based on the theory of the Fourier transformation.\n      In this class the Fast Fourier Transformation(FFT) algorithm of the gsl library is used. FFT has a run-time complexity of\n      n (log n). To get the Direct Cosines Transformation from a FFT there is preparation necessary. First the\n      input data has to be mirrored. This is necessary, because FFT needs data which has a periodic nature.\n      After the computation of FFT only the cosine values are important and stored in the Meta Data Array. So an inverse transformation of these values\n      to get the original spectrum is not available.\n      The comparison is done between two Meta Data Arrays, which contain the stored cosine values of their individual spectrum.\n      The advantage of this method is how the comparison works. There is only one sum which has to be count, no multiplication is needed.\n\n      Attention: only use the compare function, if the Spectrum was transformed earlier, else an error is going to appear.\n      Only use this method of transformation, if you are sure there exists enough free memory. This is a fast estimation, but it only gives one or\n      zero back.\n\n      @htmlinclude OpenMS_CompareFouriertransform.parameters\n\n      @ingroup SpectraComparison\n\n  */\n\n  class OPENMS_DLLAPI CompareFouriertransform :\n    public PeakSpectrumCompareFunctor\n  {\npublic:\n\n    // @name Constructors and Destructors\n    // @{\n    /// default constructor\n    CompareFouriertransform();\n\n    /// copy constructor\n    CompareFouriertransform(const CompareFouriertransform & source);\n\n    /// destructor\n    virtual ~CompareFouriertransform();\n    // @}\n\n    // @name Operators\n    // @{\n    /// assignment operator\n    CompareFouriertransform & operator=(const CompareFouriertransform & source);\n\n    /**\n      @brief Dummy function\n\n      This function only returns 0 for any given PeakSpectrum, please use the other compare operator function\n    */\n    double operator()(const PeakSpectrum &) const;\n    /**\n        @brief compare two PeakSpectrum by their Discrete Cosines Transformation.\n\n        This function compares two given PeakSpectrum about their  Discrete Cosines Transformation.\n        First, a transformation has to be calculated. Please use the function transform() in this class, before calling this\n            function. The comparison works by summing the subtractions of each coefficient for all elements of both transformations. sum(_i=1)\n            ^n x_i-y_i. If the sum is zero, both Spectra are identical in the real part and one is emitted, otherwise a zero.\n        */\n    double operator()(const PeakSpectrum & spec1, const PeakSpectrum & spec2) const;\n\n    ///\n    static PeakSpectrumCompareFunctor * create() { return new CompareFouriertransform(); }\n\n    ///Returns the name used in the factory\n    static const String getProductName()\n    {\n      return \"CompareFouriertransform\";\n    }\n\n    /**\n    @brief calculate the Discrete Cosines Fourier Transformation.\n\n    This function transforms a given PeakSpectrum to a Discrete Cosines Fourier\n    Transformation. It stores only the part of the cosines of the FFT in the\n    FloatDataArray which is a container from the PeakSpectrum.  Only call this\n    function, if you are sure there is no other transformation done earlier\n    over the same PeakSpectrum, because it isn't\n    checked if there already exists a transformation.\n    */\n    void transform(PeakSpectrum & spec);\nprotected:\n    /**\n        @brief Search in the PeakSpectrum, if a Discrete Fourier transformation\n        occurs, if not an error is going to be thrown, else the index\n        of the occurrence is returned.\n\n        This function gives back the position, where the transformation was\n        saved in a FloatDataArray. If there is no entry, an error is thrown to\n        indicate that a transformation has to be calculated before calling this\n        comparison operator.\n    */\n    UInt searchTransformation_(const PeakSpectrum & spec) const;\n\n\n  };\n\n}\n#endif /*OPENMS_COMPARISON_SPECTRA_COMPAREFOURIERTRANSFORM_H*/\n", "meta": {"hexsha": "b992f2827f6fb8498f54b1b36f9ab3ff39126605", "size": 6650, "ext": "h", "lang": "C", "max_stars_repo_path": "include/OpenMS/COMPARISON/SPECTRA/CompareFouriertransform.h", "max_stars_repo_name": "open-ms/all-svn-branches", "max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z", "max_issues_repo_path": "src/openms/include/OpenMS/COMPARISON/SPECTRA/CompareFouriertransform.h", "max_issues_repo_name": "kreinert/OpenMS", "max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_issues_repo_licenses": ["Zlib", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/include/OpenMS/COMPARISON/SPECTRA/CompareFouriertransform.h", "max_forks_repo_name": "kreinert/OpenMS", "max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_forks_repo_licenses": ["Zlib", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.8309859155, "max_line_length": 151, "alphanum_fraction": 0.6993984962, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3545095668925466}}
{"text": "/* min/gsl_min.h\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#ifndef __GSL_MIN_H__\n#define __GSL_MIN_H__\n\n#include <stdlib.h>\n#include <gsl/gsl_types.h>\n#include <gsl/gsl_math.h>\n\n#undef __BEGIN_DECLS\n#undef __END_DECLS\n#ifdef __cplusplus\n# define __BEGIN_DECLS extern \"C\" {\n# define __END_DECLS }\n#else\n# define __BEGIN_DECLS /* empty */\n# define __END_DECLS /* empty */\n#endif\n\n__BEGIN_DECLS\n\ntypedef struct\n  {\n    const char *name;\n    size_t size;\n    int (*set) (void *state, gsl_function * f, double x_minimum, double f_minimum, double x_lower, double f_lower, double x_upper, double f_upper);\n    int (*iterate) (void *state, gsl_function * f, double * x_minimum, double * f_minimum, double * x_lower, double * f_lower, double * x_upper, double * f_upper);\n  }\ngsl_min_fminimizer_type;\n\ntypedef struct\n  {\n    const gsl_min_fminimizer_type * type;\n    gsl_function * function ;\n    double x_minimum ;\n    double x_lower ;\n    double x_upper ;\n    double f_minimum, f_lower, f_upper;\n    void *state;\n  }\ngsl_min_fminimizer;\n\ngsl_min_fminimizer *\ngsl_min_fminimizer_alloc (const gsl_min_fminimizer_type * T) ;\n                                      \nvoid gsl_min_fminimizer_free (gsl_min_fminimizer * s);\n\nint gsl_min_fminimizer_set (gsl_min_fminimizer * s, \n                            gsl_function * f, double x_minimum, \n                            double x_lower, double x_upper);\n\nint gsl_min_fminimizer_set_with_values (gsl_min_fminimizer * s, \n                                        gsl_function * f, \n                                        double x_minimum, double f_minimum,\n                                        double x_lower, double f_lower,\n                                        double x_upper, double f_upper);\n\nint gsl_min_fminimizer_iterate (gsl_min_fminimizer * s);\n\nconst char * gsl_min_fminimizer_name (const gsl_min_fminimizer * s);\n\ndouble gsl_min_fminimizer_x_minimum (const gsl_min_fminimizer * s);\ndouble gsl_min_fminimizer_x_lower (const gsl_min_fminimizer * s);\ndouble gsl_min_fminimizer_x_upper (const gsl_min_fminimizer * s);\ndouble gsl_min_fminimizer_f_minimum (const gsl_min_fminimizer * s);\ndouble gsl_min_fminimizer_f_lower (const gsl_min_fminimizer * s);\ndouble gsl_min_fminimizer_f_upper (const gsl_min_fminimizer * s);\n\n/* Deprecated, use x_minimum instead */\ndouble gsl_min_fminimizer_minimum (const gsl_min_fminimizer * s);\n\nint\ngsl_min_test_interval (double x_lower, double x_upper, double epsabs, double epsrel);\n\nGSL_VAR const gsl_min_fminimizer_type  * gsl_min_fminimizer_goldensection;\nGSL_VAR const gsl_min_fminimizer_type  * gsl_min_fminimizer_brent;\nGSL_VAR const gsl_min_fminimizer_type  * gsl_min_fminimizer_quad_golden;\n\ntypedef\nint (*gsl_min_bracketing_function)(gsl_function *f,\n                                   double *x_minimum,double * f_minimum,\n                                   double *x_lower, double * f_lower,\n                                   double *x_upper, double * f_upper,\n                                   size_t eval_max);\n\nint \ngsl_min_find_bracket(gsl_function *f,double *x_minimum,double * f_minimum,\n                     double *x_lower, double * f_lower,\n                     double *x_upper, double * f_upper,\n                     size_t eval_max);\n\n__END_DECLS\n\n#endif /* __GSL_MIN_H__ */\n", "meta": {"hexsha": "2cfa8023be99f1448cd22b68b3316223081c8720", "size": 4039, "ext": "h", "lang": "C", "max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_min.h", "max_stars_repo_name": "snipekill/FPGen", "max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z", "max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_min.h", "max_issues_repo_name": "snipekill/FPGen", "max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_min.h", "max_forks_repo_name": "snipekill/FPGen", "max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "avg_line_length": 36.0625, "max_line_length": 163, "alphanum_fraction": 0.684822976, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3543978975432917}}
{"text": "#include <math.h>\n#include <stdlib.h>\n#if !defined(__APPLE__)\n#include <malloc.h>\n#endif\n#include <stdio.h>\n#include <assert.h>\n#include <time.h>\n#include <string.h>\n\n#include <fftw3.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_sf_erf.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_sf_gamma.h>\n#include <gsl/gsl_sf_legendre.h>\n#include <gsl/gsl_sf_bessel.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_sf_expint.h>\n#include <gsl/gsl_deriv.h>\n#include <gsl/gsl_interp2d.h>\n#include <gsl/gsl_spline2d.h>\n\n\n#include \"../cosmolike_core/theory/basics.c\"\n#include \"../cosmolike_core/theory/structs.c\"\n#include \"../cosmolike_core/theory/parameters.c\"\n#include \"../cosmolike_core/emu17/P_cb/emu.c\"\n#include \"../cosmolike_core/theory/recompute.c\"\n#include \"../cosmolike_core/theory/cosmo3D.c\"\n#include \"../cosmolike_core/theory/redshift_spline.c\"\n#include \"../cosmolike_core/theory/halo.c\"\n#include \"../cosmolike_core/theory/HOD.c\"\n#include \"../cosmolike_core/theory/pt.c\"\n#include \"../cosmolike_core/theory/cosmo2D_fourier.c\"\n#include \"../cosmolike_core/theory/IA.c\"\n#include \"../cosmolike_core/theory/cluster.c\"\n#include \"../cosmolike_core/theory/BAO.c\"\n#include \"../cosmolike_core/theory/external_prior.c\"\n#include \"../cosmolike_core/theory/init_baryon.c\"\n#include \"init_emu.c\"\n\ndouble C_shear_tomo_sys(double ell,int z1,int z2);\ndouble C_cgl_tomo_sys(double ell_Cluster,int zl,int nN, int zs);\ndouble C_gl_tomo_sys(double ell,int zl,int zs);\nvoid set_data_shear(int Ncl, double *ell, double *data, int start);\nvoid set_data_ggl(int Ncl, double *ell, double *data, int start);\nvoid set_data_clustering(int Ncl, double *ell, double *data, int start);\nvoid set_data_cluster_N(double *data, int start);\nvoid set_data_cgl(double *ell_Cluster, double *data, int start);\nvoid compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3);\ndouble log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3);\nvoid write_vector_wrapper(char *details, input_cosmo_params ic, input_nuisance_params in);\ndouble log_like_wrapper(input_cosmo_params ic, input_nuisance_params in);\nint get_N_tomo_shear(void);\nint get_N_tomo_clustering(void);\nint get_N_ggl(void);\nint get_N_ell(void);\n\nint get_N_tomo_shear(void){\n  return tomo.shear_Nbin;\n}\nint get_N_tomo_clustering(void){\n  return tomo.clustering_Nbin;\n}\nint get_N_ggl(void){\n  return tomo.ggl_Npowerspectra;\n}\nint get_N_ell(void){\n  return like.Ncl;\n}\n\n\ndouble C_shear_tomo_sys(double ell, int z1, int z2)\n{\n  double C;\n  // C= C_shear_tomo_nointerp(ell,z1,z2);\n  // if(like.IA==1) C+=C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2);\n  \n  if(like.IA!=1) C= C_shear_tomo_nointerp(ell,z1,z2);\n  //if(like.IA==1) C= C_shear_shear_IA(ell,z1,z2);\n  if(like.IA==1) C = C_shear_tomo_nointerp(ell,z1,z2)+C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2);\n  if(like.IA==2) C += C_II_lin_nointerp(ell,z1,z2)+C_GI_lin_nointerp(ell,z1,z2);  \n  if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[z1])*(1.0+nuisance.shear_calibration_m[z2]);\n  //printf(\"%le %d %d %le\\n\",ell,z1,z2,C_shear_tomo_nointerp(ell,z1,z2)+C_II_JB_nointerp(ell,z1,z2)+C_GI_JB_nointerp(ell,z1,z2));\nreturn C;\n}\n\ndouble C_gl_tomo_sys(double ell,int zl,int zs)\n{\n  double C;\n  // C=C_gl_tomo_nointerp(ell,zl,zs); \n  // if(like.IA==1) C += C_gI_nointerp(ell,zl,zs);\n  \n  if(like.IA!=1) C=C_gl_tomo_nointerp(ell,zl,zs);\n  if(like.IA==1) C = C_ggl_IA(ell,zl,zs);\n  if(like.IA==2) C += C_gI_lin_nointerp(ell,zl,zs);\n  if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);\nreturn C;\n}\n\ndouble C_cgl_tomo_sys(double ell_Cluster, int zl,int nN, int zs)\n{\n  double C;\n  C=C_cgl_tomo_nointerp(ell_Cluster,zl,nN,zs);\n  //if(like.IA!=0) C += \n  if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);\nreturn C;\n}      \n\nvoid set_data_shear(int Ncl, double *ell, double *data, int start)\n{\n  int i,z1,z2,nz;\n  double a;\n  for (nz = 0; nz < tomo.shear_Npowerspectra; nz++){\n    z1 = Z1(nz); z2 = Z2(nz);\n    for (i = 0; i < Ncl; i++){\n      if (ell[i] < like.lmax_shear){ data[Ncl*nz+i] = C_shear_tomo_sys(ell[i],z1,z2);}\n      else {data[Ncl*nz+i] = 0.;}\n    }\n  }\n}\n\nvoid set_data_ggl(int Ncl, double *ell, double *data, int start)\n{\n  int i, zl,zs,nz;  \n  for (nz = 0; nz < tomo.ggl_Npowerspectra; nz++){\n    zl = ZL(nz); zs = ZS(nz);\n    for (i = 0; i < Ncl; i++){\n      if (test_kmax(ell[i],zl)){\n        data[start+(Ncl*nz)+i] = C_gl_tomo_sys(ell[i],zl,zs);\n      }\n      else{\n        data[start+(Ncl*nz)+i] = 0.;\n      }\n    } \n  }\n}\n\nvoid set_data_clustering(int Ncl, double *ell, double *data, int start){\n  int i, nz;\n  for (nz = 0; nz < tomo.clustering_Npowerspectra; nz++){\n    //printf(\"%d %e %e\\n\",nz, gbias.b[nz][1],pf_photoz(gbias.b[nz][1],nz));\n    for (i = 0; i < Ncl; i++){\n      if (test_kmax(ell[i],nz)){data[start+(Ncl*nz)+i] = C_cl_tomo_nointerp(ell[i],nz,nz);}\n      else{data[start+(Ncl*nz)+i] = 0.;}\n      //printf(\"%d %d %le %le\\n\",nz,nz,ell[i],data[Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra + nz)+i]);\n    }\n  }\n}\n\nvoid set_data_cluster_N(double *data, int start){\n  int nN, nz;\n  for (nz = 0; nz < tomo.cluster_Nbin; nz++){\n    for (nN = 0; nN < Cluster.N200_Nbin; nN++){\n      data[start+Cluster.N200_Nbin*nz+nN] = N_N200(nz, nN);\n    }\n  }\n}\n\n\nvoid set_data_cgl(double *ell_Cluster, double *data, int start)\n{\n  int zl,zs,nN,nz,i,j;\n  for(nN = 0; nN < Cluster.N200_Nbin; nN++){\n    for (nz = 0; nz < tomo.cgl_Npowerspectra; nz++){\n      zl = ZC(nz); zs = ZSC(nz);\n      for (i = 0; i < Cluster.lbin; i++){\n        j = start;\n        j += (nz*Cluster.N200_Nbin+nN)*Cluster.lbin +i;\n        data[j] = C_cgl_tomo_sys(ell_Cluster[i],zl,nN,zs);\n      }\n    }\n  }\n}\n\n\nint set_cosmology_params(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu)\n{\n  cosmology.Omega_m=OMM;\n  cosmology.Omega_v= 1.0-cosmology.Omega_m;\n  cosmology.sigma_8=S8;\n  cosmology.n_spec= NS;\n  cosmology.w0=W0;\n  cosmology.wa=WA;\n  cosmology.omb=OMB;\n  cosmology.h0=H0;\n  cosmology.MGSigma=MGSigma;\n  cosmology.MGmu=MGmu;\n\n  if (cosmology.Omega_m < 0.04 || cosmology.Omega_m > 0.7) return 0;\n  if (cosmology.omb < 0.04 || cosmology.omb > 0.055) return 0;\n  if (cosmology.sigma_8 < 0.4 || cosmology.sigma_8 > 1.2) return 0;\n  if (cosmology.n_spec < 0.84 || cosmology.n_spec > 1.06) return 0;\n  if (cosmology.w0 < -2.1 || cosmology.w0 > -0.0) return 0;\n  if (cosmology.wa < -2.6 || cosmology.wa > 2.6) return 0;\n  if (cosmology.h0 < 0.4 || cosmology.h0 > 0.9) return 0;\n  \n  return 1;\n}\n\nvoid set_nuisance_shear_calib(double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10)\n{\n  nuisance.shear_calibration_m[0] = M1;\n  nuisance.shear_calibration_m[1] = M2;\n  nuisance.shear_calibration_m[2] = M3;\n  nuisance.shear_calibration_m[3] = M4;\n  nuisance.shear_calibration_m[4] = M5;\n  nuisance.shear_calibration_m[5] = M6;\n  nuisance.shear_calibration_m[6] = M7;\n  nuisance.shear_calibration_m[7] = M8;\n  nuisance.shear_calibration_m[8] = M9;\n  nuisance.shear_calibration_m[9] = M10;\n}\n\nint set_nuisance_shear_photoz(double SP1,double SP2,double SP3,double SP4,double SP5,double SP6,double SP7,double SP8,double SP9,double SP10,double SPS1)\n{\n  int i;\n  nuisance.bias_zphot_shear[0]=SP1;\n  nuisance.bias_zphot_shear[1]=SP2;\n  nuisance.bias_zphot_shear[2]=SP3;\n  nuisance.bias_zphot_shear[3]=SP4;\n  nuisance.bias_zphot_shear[4]=SP5;\n  nuisance.bias_zphot_shear[5]=SP6;\n  nuisance.bias_zphot_shear[6]=SP7;\n  nuisance.bias_zphot_shear[7]=SP8;\n  nuisance.bias_zphot_shear[8]=SP9;\n  nuisance.bias_zphot_shear[9]=SP10;\n  \n  for (i=0;i<tomo.shear_Nbin; i++){ \n    nuisance.sigma_zphot_shear[i]=SPS1;\n    if (nuisance.sigma_zphot_shear[i]<0.000001) return 0;\n  }\n  return 1;\n}\n\nint set_nuisance_clustering_photoz(double CP1,double CP2,double CP3,double CP4,double CP5,double CP6,double CP7,double CP8,double CP9,double CP10,double CPS1)\n{\n  int i;\n  nuisance.bias_zphot_clustering[0]=CP1;\n  nuisance.bias_zphot_clustering[1]=CP2;\n  nuisance.bias_zphot_clustering[2]=CP3;\n  nuisance.bias_zphot_clustering[3]=CP4;\n  nuisance.bias_zphot_clustering[4]=CP5;\n  nuisance.bias_zphot_clustering[5]=CP6;\n  nuisance.bias_zphot_clustering[6]=CP7;\n  nuisance.bias_zphot_clustering[7]=CP8;\n  nuisance.bias_zphot_clustering[8]=CP9;\n  nuisance.bias_zphot_clustering[9]=CP10;\n  \n  for (i=0;i<tomo.clustering_Nbin; i++){ \n    nuisance.sigma_zphot_clustering[i]=CPS1;\n    if (nuisance.sigma_zphot_clustering[i]<0.0001) return 0;\n  }\n  return 1;\n}\n\nint set_nuisance_ia(double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q)\n{\n  nuisance.A_ia=A_ia;  \n  nuisance.beta_ia=beta_ia;\n  nuisance.eta_ia=eta_ia;\n  nuisance.eta_ia_highz=eta_ia_highz;\n  nuisance.LF_alpha=LF_alpha;\n  nuisance.LF_P=LF_P;\n  nuisance.LF_Q=LF_Q;\n  nuisance.LF_red_alpha=LF_red_alpha;\n  nuisance.LF_red_P=LF_red_P;\n  nuisance.LF_red_Q=LF_red_Q;\n  if (nuisance.A_ia < 0.0 || nuisance.A_ia > 10.0) return 0;\n  if (nuisance.beta_ia < -1.0 || nuisance.beta_ia > 3.0) return 0;\n  if (nuisance.eta_ia < -3.0 || nuisance.eta_ia> 3.0) return 0;\n  if (nuisance.eta_ia_highz < -1.0 || nuisance.eta_ia_highz> 1.0) return 0;\n  // if(like.IA!=0){\n  //  if (check_LF()) return 0;\n  // }\nreturn 1;\n}\n\nint set_nuisance_cluster_Mobs(double cluster_Mobs_lgN0,  double cluster_Mobs_alpha, double cluster_Mobs_beta, double cluster_Mobs_sigma0, double cluster_Mobs_sigma_qm, double cluster_Mobs_sigma_qz)\n{\n  //  nuisance.cluster_Mobs_lgM0 = mass_obs_norm;  //fiducial : 1.72+log(1.e+14*0.7); could use e.g. sigma = 0.2 Gaussian prior\n  //  nuisance.cluster_Mobs_alpha = mass_obs_slope; //fiducial: 1.08; e.g. sigma = 0.1 Gaussian prior\n  //  nuisance.cluster_Mobs_beta = mass_z_slope; //fiducial: 0.0; e.g. sigma = 0.1 Gaussian prior\n  //  nuisance.cluster_Mobs_sigma = mass_obs_scatter; //fiducial 0.25; e.g. sigma = 0.05 Gaussian prior\n\n  // fiducial values and priors from Murata et al. (2018) except for redshift-related parameters\n  nuisance.cluster_Mobs_lgN0 = cluster_Mobs_lgN0; //fiducial: 3.207, flat prior [0.5, 5.0]\n  nuisance.cluster_Mobs_alpha = cluster_Mobs_alpha; //fiducial: 0.993, flat prior [0.0, 2.0]\n  nuisance.cluster_Mobs_beta = cluster_Mobs_beta; //fiducial: 0.0, flat prior [-1.5, 1.5]\n  nuisance.cluster_Mobs_sigma0 = cluster_Mobs_sigma0; //fiducial: 0.456, flat prior [0.0, 1.5]\n  nuisance.cluster_Mobs_sigma_qm = cluster_Mobs_sigma_qm; //fiducial: -0.169, flat prior [-1.5, 1.5]\n  nuisance.cluster_Mobs_sigma_qz = cluster_Mobs_sigma_qz; //fiducial: 0.0, flat prior [-1.5, 1.5]\n\n  if (nuisance.cluster_Mobs_lgN0 < 0.5 || nuisance.cluster_Mobs_lgN0 > 5.0) return 0;\n  if (nuisance.cluster_Mobs_alpha < 0.0 || nuisance.cluster_Mobs_alpha > 2.0) return 0;\n  if (nuisance.cluster_Mobs_beta < -1.5 || nuisance.cluster_Mobs_beta > 1.5) return 0;\n  if (nuisance.cluster_Mobs_sigma0 < 0.0|| nuisance.cluster_Mobs_sigma0 > 1.5) return 0;\n  if (nuisance.cluster_Mobs_sigma_qm < -1.5 && nuisance.cluster_Mobs_sigma_qm > 1.5) return 0;\n  if (nuisance.cluster_Mobs_sigma_qz < -1.5 && nuisance.cluster_Mobs_sigma_qz > 1.5)return 0;\n\nreturn 1;\n}\n\n\nint set_nuisance_gbias(double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8,double B9, double B10)\n{\n  int i;\n  gbias.b[0] = B1;\n  gbias.b[1] = B2;\n  gbias.b[2] = B3;\n  gbias.b[3] = B4;\n  gbias.b[4] = B5;\n  gbias.b[5] = B6;\n  gbias.b[6] = B7;\n  gbias.b[7] = B8;\n  gbias.b[8] = B9;\n  gbias.b[9] = B10;\n  if(like.bias==1){\n    for (i = 0; i < 10; i++){\n      if (gbias.b[i] < 0.8 || gbias.b[i] > 3.0) return 0;\n    }\n  }\n  return 1;\n} \n\ndouble log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3)\n{\n  int i,j,k,m=0,l;\n  static double *pred;\n  static double *ell;\n  static double *ell_Cluster;\n  static double darg;\n  double chisqr,a,log_L_prior=0.0, log_L=0.0;\n  \n  if(ell==0){\n    pred= create_double_vector(0, like.Ndata-1);\n    ell= create_double_vector(0, like.Ncl-1);\n    darg=(log(like.lmax)-log(like.lmin))/like.Ncl;\n    for (l=0;l<like.Ncl;l++){\n      ell[l]=exp(log(like.lmin)+(l+0.5)*darg);\n    }\n    ell_Cluster= create_double_vector(0, Cluster.lbin-1);\n    darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin;\n    for (l=0;l<Cluster.lbin;l++){\n      ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg);\n    }\n  }\n  if (set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu)==0){\n    printf(\"Cosmology out of bounds\\n\");\n    return -1.0e15;\n  }\n  set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10);\n  if (set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10,SPS1)==0){\n    printf(\"Shear photo-z sigma too small\\n\");\n    return -1.0e15;\n  }\n  if (set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10,CPS1)==0){\n    printf(\"Clustering photo-z sigma too small\\n\");\n    return -1.0e15;\n  }\n  if (set_nuisance_ia(A_ia,beta_ia,eta_ia,eta_ia_highz,LF_alpha,LF_P,LF_Q,LF_red_alpha,LF_red_P,LF_red_Q)==0){\n    printf(\"IA parameters out of bounds\\n\");\n    return -1.0e15; \n  }\n  if (set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10)==0){\n    printf(\"Bias out of bounds\\n\");\n    return -1.0e15;\n  }\n       \n  //printf(\"like %le %le %le %le %le %le %le %le\\n\",cosmology.Omega_m, cosmology.Omega_v,cosmology.sigma_8,cosmology.n_spec,cosmology.w0,cosmology.wa,cosmology.omb,cosmology.h0); \n  // printf(\"like %le %le %le %le\\n\",gbias.b[0][0], gbias.b[1][0], gbias.b[2][0], gbias.b[3][0]);    \n  // for (i=0; i<10; i++){\n  //   printf(\"nuisance %le %le %le\\n\",nuisance.shear_calibration_m[i],nuisance.bias_zphot_shear[i],nuisance.sigma_zphot_shear[i]);\n  // }\n\n  log_L_prior=0.0;\n  // if(like.Aubourg_Planck_BAO_SN==1) log_L_prior+=log_L_Planck_BAO_SN();\n  // if(like.SN==1) log_L_prior+=log_L_SN();\n  //if(like.BAO==1) log_L_prior+=log_L_BAO();\n  // if(like.Planck==1) log_L_prior+=log_L_Planck();\n  // if(like.Planck15_BAO_w0wa==1) log_L_prior+=log_L_Planck15_BAO_w0wa();//CH\n  //if(like.Planck15_BAO_H070p6_JLA_w0wa==1) log_L_prior+=log_L_Planck15_BAO_H070p6_JLA_w0wa();//CH\n  // if(like.IA!=0) log_L_prior+=log_L_ia();\n  // if(like.IA!=0) log_L_prior+=log_like_f_red();\n  if(like.wlphotoz!=0) log_L_prior+=log_L_wlphotoz();\n  if(like.clphotoz!=0) log_L_prior+=log_L_clphotoz();\n  if(like.shearcalib==1) log_L_prior+=log_L_shear_calib();\n  if(like.IA!=0) {\n    log_L = 0.0;\n    log_L -= pow((nuisance.A_ia - prior.A_ia[0])/prior.A_ia[1],2.0);\n    log_L -= pow((nuisance.beta_ia - prior.beta_ia[0])/prior.beta_ia[1],2.0);\n    log_L -= pow((nuisance.eta_ia - prior.eta_ia[0])/prior.eta_ia[1],2.0);\n    log_L -= pow((nuisance.eta_ia_highz - prior.eta_ia_highz[0])/prior.eta_ia_highz[1],2.0);\n    log_L_prior+=0.5*log_L;\n  }\n  if(like.baryons==1){\n    log_L = 0.0;\n    log_L -= pow((Q1 - prior.bary_Q1[0])/prior.bary_Q1[1],2.0);\n    log_L -= pow((Q2 - prior.bary_Q2[0])/prior.bary_Q2[1],2.0);\n    log_L -= pow((Q3 - prior.bary_Q3[0])/prior.bary_Q3[1],2.0);\n    log_L_prior+=0.5*log_L;\n  }\n \n  // if(like.clusterMobs==1) log_L_prior+=log_L_clusterMobs();\n \n  // printf(\"%d %d %d %d\\n\",like.BAO,like.wlphotoz,like.clphotoz,like.shearcalib);\n  // printf(\"logl %le %le %le %le\\n\",log_L_shear_calib(),log_L_wlphotoz(),log_L_clphotoz(),log_L_clusterMobs());\n  int start=0;  \n  \n  if(like.shear_shear==1) {\n    set_data_shear(like.Ncl, ell, pred, start);\n    start=start+like.Ncl*tomo.shear_Npowerspectra;\n  }\n  if(like.shear_pos==1){\n    set_data_ggl(like.Ncl, ell, pred, start);\n    start=start+like.Ncl*tomo.ggl_Npowerspectra;\n  } \n  if(like.pos_pos==1){\n    set_data_clustering(like.Ncl,ell,pred, start);\n    start=start+like.Ncl*tomo.clustering_Npowerspectra;\n  }\n\n  chisqr=0.0;\n  for (i=0; i<like.Ndata; i++){\n    for (j=0; j<like.Ndata; j++){\n      a=(pred[i]-data_read(1,i)+Q1*bary_read(1,0,i)+Q2*bary_read(1,1,i)+Q3*bary_read(1,2,i))*invcov_read(1,i,j)*(pred[j]-data_read(1,j)+Q1*bary_read(1,0,j)+Q2*bary_read(1,1,j)+Q3*bary_read(1,2,j));\n      //a=(pred[i]-data_read(1,i))*invcov_read(1,i,j)*(pred[j]-data_read(1,j));\n      chisqr=chisqr+a;\n    }\n    // if (fabs(data_read(1,i)) < 1.e-25){\n    //    printf(\"%d %le %le %le\\n\",i,data_read(1,i),pred[i],invcov_read(1,i,i));\n    // }\n  }\n  if (chisqr<0.0){\n    printf(\"error: chisqr = %le\\n\",chisqr);\n    //exit(EXIT_FAILURE);\n  }\n//  printf(\"%le\\n\",chisqr);\n  return -0.5*chisqr+log_L_prior;\n}\n\nvoid compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5,double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3)\n{\n\n  int i,j,k,m=0,l;\n  static double *pred;\n  static double *ell;\n  static double *ell_Cluster;\n  static double darg;\n  double chisqr,a,log_L_prior=0.0;\n  \n  if(ell==0){\n    pred= create_double_vector(0, like.Ndata-1);\n    ell= create_double_vector(0, like.Ncl-1);\n    darg=(log(like.lmax)-log(like.lmin))/like.Ncl;\n    for (l=0;l<like.Ncl;l++){\n      ell[l]=exp(log(like.lmin)+(l+0.5)*darg);\n    }\n    ell_Cluster= create_double_vector(0, Cluster.lbin-1);\n    darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin;\n    for (l=0;l<Cluster.lbin;l++){\n      ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg);    \n    }\n  }\n// for (l=0;l<like.Ncl;l++){\n//   printf(\"%d %le\\n\",i,ell[l]);\n// }\n\n  set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu);\n  set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10);\n  set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10,SPS1);\n  set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10,CPS1);\n  set_nuisance_ia(A_ia,beta_ia,eta_ia,eta_ia_highz,LF_alpha,LF_P,LF_Q,LF_red_alpha,LF_red_P,LF_red_Q);\n  set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10);\n  \n  int start=0;  \n  if(like.shear_shear==1) {\n    set_data_shear(like.Ncl, ell, pred, start);\n    start=start+like.Ncl*tomo.shear_Npowerspectra;\n  }\n  if(like.shear_pos==1){\n    //printf(\"ggl\\n\");\n    set_data_ggl(like.Ncl, ell, pred, start);\n    start=start+like.Ncl*tomo.ggl_Npowerspectra;\n  } \n  if(like.pos_pos==1){\n    //printf(\"clustering\\n\");\n    set_data_clustering(like.Ncl,ell,pred, start);\n    start=start+like.Ncl*tomo.clustering_Npowerspectra;\n  }\n\n  FILE *F;\n  char filename[300];\n  if (strstr(details,\"FM\") != NULL){\n    sprintf(filename,\"%s\",details);\n  }\n  else {sprintf(filename,\"datav/%s_%s\",like.probes,details);}\n  F=fopen(filename,\"w\");\n  for (i=0;i<like.Ndata; i++){  \n    fprintf(F,\"%d %le\\n\",i,pred[i]);\n    //printf(\"%d %le\\n\",i,pred[i]);\n  }\n  fclose(F);\n  // printf(\"&gbias.b1_function %p\\n\",&gbias.b1_function);\n  // printf(\"gbias.b1_function  %p\\n\",gbias.b1_function);\n  // printf(\"bgal_z   %p\\n\",bgal_z);\n  // printf(\"&bgal_z  %p\\n\",&bgal_z);\n  // printf(\"b1_per_bin   %p\\n\",b1_per_bin);\n  // printf(\"&b1_per_bin  %p\\n\",&b1_per_bin);\n\n}\n\n\n\nvoid write_datavector_wrapper(char *details, input_cosmo_params ic, input_nuisance_params in)\n{\n  compute_data_vector(details, ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu,\n    in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9], \n    in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4], \n    in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9], \n    in.source_z_s, \n    in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4], \n    in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9], \n    in.lens_z_s, \n    in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4], \n    in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9], \n    in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz,\n    in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5],\n    in.m_lambda[0], in.m_lambda[1], in.m_lambda[2], in.m_lambda[3],\n    in.m_lambda[4], in.m_lambda[5],in.bary[0], in.bary[1], in.bary[2]);\n}\n\ndouble log_like_wrapper(input_cosmo_params ic, input_nuisance_params in)\n{\n  double like = log_multi_like(ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu,\n    in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9], \n    in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4], \n    in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9], \n    in.source_z_s, \n    in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4], \n    in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9], \n    in.lens_z_s, \n    in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4], \n    in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9], \n    in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz,\n    in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5], \n    in.m_lambda[0], in.m_lambda[1], in.m_lambda[2], in.m_lambda[3],\n    in.m_lambda[4], in.m_lambda[5],in.bary[0], in.bary[1], in.bary[2]);\n  \n  return like;\n}\n\n\n\nvoid save_zdistr_sources(int zs){\n  double z,dz =(redshift.shear_zdistrpar_zmax-redshift.shear_zdistrpar_zmin)/300.0;\n  printf(\"Printing redshift distribution n(z) for source redshift bin %d\\n\",zs);\n  \n   FILE *F1;\n   char filename[300];\n   sprintf(filename,\"zdistris/zdist_sources_bin%d.txt\",zs);\n   F1 = fopen(filename,\"w\");\n   for (z =redshift.shear_zdistrpar_zmin; z< redshift.shear_zdistrpar_zmax; z+= dz){\n      fprintf(F1,\"%e %e\\n\", z, zdistr_photoz(z,zs));\n   }\n}\n\n\nvoid save_zdistr_lenses(int zl){\n   double z,dz =(redshift.clustering_zdistrpar_zmax-redshift.clustering_zdistrpar_zmin)/300.0;\n  printf(\"Printing redshift distribution n(z) and bias b(z) for lens redshift bin %d\\n\",zl);\n   \n   FILE *F1;\n   char filename[300];\n   sprintf(filename,\"zdistris/zdist_lenses_bin%d.txt\", zl);\n   F1 = fopen(filename,\"w\");\n   for (z =redshift.clustering_zdistrpar_zmin; z< redshift.clustering_zdistrpar_zmax; z+= dz){\n      fprintf(F1,\"%e %e\\n\", z, pf_photoz(z,zl));\n   }\n}\n\n\n int main(int argc, char** argv)\n{\n  clock_t begin, end;\n  double time_spent;\n  int i;\n  char arg1[400],arg2[400],arg3[400];\n/* here, do your time-consuming job */\n  int sce=atoi(argv[1]);\n\n  int N_scenarios=36;\n  \n  double area_table[36]={7623.22,14786.3,9931.47,8585.43,17681.8,15126.9,9747.99,8335.08,9533.42,18331.3,12867.8,17418.9,19783.1,12538.8,15260.0,16540.7,19636.8,11112.7,10385.5,16140.2,18920.1,17976.2,11352.0,9214.77,16910.7,11995.6,16199.8,14395.1,8133.86,13510.5,19122.3,15684.5,12014.8,14059.7,10919.3,13212.7};\n\n  double nsource_table[36]={13.991,33.3975,17.069,28.4875,35.3643,10.3802,11.1105,29.5904,31.4608,15.7463,13.3066,9.07218,9.58719,16.3234,25.8327,10.7415,38.0412,32.8821,19.8893,27.0369,15.1711,14.2418,19.1851,26.926,22.0012,12.6553,18.6304,11.9787,36.8728,22.5265,17.4381,12.3424,10.0095,23.5979,20.8771,24.8956};\n  \n  double nlens_table[36]={22.9726 ,61.5948 ,28.7809 ,51.4354 ,65.7226 ,16.3777 ,17.6899 ,53.6984 ,57.562 ,26.266 ,21.703 ,14.0587 ,14.9667 ,27.36 ,46.0364 ,17.0253 ,71.39 ,60.5184 ,34.2283 ,48.4767 ,25.1812 ,23.44 ,32.8578 ,48.2513 ,38.3766 ,20.5029 ,31.783 ,19.2647 ,68.9094 ,39.4168 ,29.4874 ,19.9292 ,15.7162 ,41.5487 ,36.1616 ,44.148};\n\n  char survey_designation[1][200]={\"LSST\"};\n  char tomo_binning_source[1][200]={\"source_std\"};\n  char tomo_binning_lens[1][200]={\"LSST_gold\"};\n\n  char source_zfile[36][400]={\"wl_redshift_model0_WLz01.880307e-01_WLalpha8.485694e-01.txt\", \"wl_redshift_model1_WLz01.731166e-01_WLalpha7.662434e-01.txt\", \"wl_redshift_model2_WLz01.846221e-01_WLalpha8.297540e-01.txt\", \"wl_redshift_model3_WLz01.758423e-01_WLalpha7.812893e-01.txt\", \"wl_redshift_model4_WLz01.721357e-01_WLalpha7.608290e-01.txt\", \"wl_redshift_model5_WLz01.931476e-01_WLalpha8.768147e-01.txt\", \"wl_redshift_model6_WLz01.919821e-01_WLalpha8.703814e-01.txt\", \"wl_redshift_model7_WLz01.751912e-01_WLalpha7.776952e-01.txt\", \"wl_redshift_model8_WLz01.741405e-01_WLalpha7.718958e-01.txt\", \"wl_redshift_model9_WLz01.860048e-01_WLalpha8.373865e-01.txt\", \"wl_redshift_model10_WLz01.888904e-01_WLalpha8.533151e-01.txt\", \"wl_redshift_model11_WLz01.954564e-01_WLalpha8.895592e-01.txt\", \"wl_redshift_model12_WLz01.945099e-01_WLalpha8.843347e-01.txt\", \"wl_redshift_model13_WLz01.853877e-01_WLalpha8.339802e-01.txt\", \"wl_redshift_model14_WLz01.775192e-01_WLalpha7.905458e-01.txt\", \"wl_redshift_model15_WLz01.925611e-01_WLalpha8.735775e-01.txt\", \"wl_redshift_model16_WLz01.708849e-01_WLalpha7.539247e-01.txt\", \"wl_redshift_model17_WLz01.733832e-01_WLalpha7.677150e-01.txt\", \"wl_redshift_model18_WLz01.820009e-01_WLalpha8.152851e-01.txt\", \"wl_redshift_model19_WLz01.767381e-01_WLalpha7.862345e-01.txt\", \"wl_redshift_model20_WLz01.866426e-01_WLalpha8.409073e-01.txt\", \"wl_redshift_model21_WLz01.877261e-01_WLalpha8.468882e-01.txt\", \"wl_redshift_model22_WLz01.826188e-01_WLalpha8.186960e-01.txt\", \"wl_redshift_model23_WLz01.768086e-01_WLalpha7.866234e-01.txt\", \"wl_redshift_model24_WLz01.802711e-01_WLalpha8.057362e-01.txt\", \"wl_redshift_model25_WLz01.897506e-01_WLalpha8.580632e-01.txt\", \"wl_redshift_model26_WLz01.831217e-01_WLalpha8.214720e-01.txt\", \"wl_redshift_model27_WLz01.906926e-01_WLalpha8.632630e-01.txt\", \"wl_redshift_model28_WLz01.714197e-01_WLalpha7.568766e-01.txt\", \"wl_redshift_model29_WLz01.798667e-01_WLalpha8.035040e-01.txt\", \"wl_redshift_model30_WLz01.842554e-01_WLalpha8.277299e-01.txt\", \"wl_redshift_model31_WLz01.901797e-01_WLalpha8.604322e-01.txt\", \"wl_redshift_model32_WLz01.937710e-01_WLalpha8.802561e-01.txt\", \"wl_redshift_model33_WLz01.790701e-01_WLalpha7.991072e-01.txt\", \"wl_redshift_model34_WLz01.811701e-01_WLalpha8.106987e-01.txt\", \"wl_redshift_model35_WLz01.781525e-01_WLalpha7.940419e-01.txt\"};\n\n  char lens_zfile[36][400]={\"LSS_redshift_model0_LSSz02.629496e-01_LSSalpha9.285983e-01.txt\",\"LSS_redshift_model1_LSSz02.852923e-01_LSSalpha8.985943e-01.txt\",\"LSS_redshift_model2_LSSz02.664822e-01_LSSalpha9.186036e-01.txt\",\"LSS_redshift_model3_LSSz02.798758e-01_LSSalpha9.014201e-01.txt\",\"LSS_redshift_model4_LSSz02.873873e-01_LSSalpha8.978683e-01.txt\",\"LSS_redshift_model5_LSSz02.593970e-01_LSSalpha9.470921e-01.txt\",\"LSS_redshift_model6_LSSz02.600213e-01_LSSalpha9.425114e-01.txt\",\"LSS_redshift_model7_LSSz02.811155e-01_LSSalpha9.006370e-01.txt\",\"LSS_redshift_model8_LSSz02.831875e-01_LSSalpha8.995165e-01.txt\",\"LSS_redshift_model9_LSSz02.649368e-01_LSSalpha9.224338e-01.txt\",\"LSS_redshift_model10_LSSz02.622058e-01_LSSalpha9.314128e-01.txt\",\"LSS_redshift_model11_LSSz02.584820e-01_LSSalpha9.568082e-01.txt\",\"LSS_redshift_model12_LSSz02.588053e-01_LSSalpha9.527220e-01.txt\",\"LSS_redshift_model13_LSSz02.656075e-01_LSSalpha9.206866e-01.txt\",\"LSS_redshift_model14_LSSz02.768397e-01_LSSalpha9.037492e-01.txt\",\"LSS_redshift_model15_LSSz02.596975e-01_LSSalpha9.447600e-01.txt\",\"LSS_redshift_model16_LSSz02.901709e-01_LSSalpha8.971658e-01.txt\",\"LSS_redshift_model17_LSSz02.847362e-01_LSSalpha8.988183e-01.txt\",\"LSS_redshift_model18_LSSz02.698330e-01_LSSalpha9.121821e-01.txt\",\"LSS_redshift_model19_LSSz02.782257e-01_LSSalpha9.026084e-01.txt\",\"LSS_redshift_model20_LSSz02.642756e-01_LSSalpha9.243038e-01.txt\",\"LSS_redshift_model21_LSSz02.632273e-01_LSSalpha9.276296e-01.txt\",\"LSS_redshift_model22_LSSz02.689934e-01_LSSalpha9.135968e-01.txt\",\"LSS_redshift_model23_LSSz02.780987e-01_LSSalpha9.027073e-01.txt\",\"LSS_redshift_model24_LSSz02.723464e-01_LSSalpha9.085463e-01.txt\",\"LSS_redshift_model25_LSSz02.615210e-01_LSSalpha9.343470e-01.txt\",\"LSS_redshift_model26_LSSz02.683327e-01_LSSalpha9.147934e-01.txt\",\"LSS_redshift_model27_LSSz02.608392e-01_LSSalpha9.376962e-01.txt\",\"LSS_redshift_model28_LSSz02.889655e-01_LSSalpha8.974355e-01.txt\",\"LSS_redshift_model29_LSSz02.729686e-01_LSSalpha9.077654e-01.txt\",\"LSS_redshift_model30_LSSz02.669178e-01_LSSalpha9.176391e-01.txt\",\"LSS_redshift_model31_LSSz02.612016e-01_LSSalpha9.358553e-01.txt\",\"LSS_redshift_model32_LSSz02.591077e-01_LSSalpha9.496317e-01.txt\",\"LSS_redshift_model33_LSSz02.742326e-01_LSSalpha9.063038e-01.txt\",\"LSS_redshift_model34_LSSz02.710103e-01_LSSalpha9.103760e-01.txt\",\"LSS_redshift_model35_LSSz02.757517e-01_LSSalpha9.047459e-01.txt\"};\n\ndouble shear_prior[36]={0.00891915,0.0104498 ,0.0145972 ,0.0191916 ,0.00450246 ,0.00567828 ,0.00294841 ,0.00530922 ,0.0118632 ,0.0151849 ,0.00410151 ,0.0170622 ,0.0197331 ,0.0106615 ,0.0124445 ,0.00994507 ,0.0136251 ,0.0143491 ,0.0164314 ,0.016962 ,0.0186608 ,0.00945903 ,0.0113246 ,0.0155225 ,0.00800846 ,0.00732104 ,0.00649453 ,0.00243976 ,0.0125932 ,0.0182587 ,0.00335859 ,0.00682287 ,0.0177269 ,0.0035219 ,0.00773304 ,0.0134886};\n\ndouble delta_z_prior[36]={0.0032537,0.00135316,0.00168787,0.00215043,0.00406031,0.00222358,0.00334993,0.00255186,0.00266499,0.00159226,0.00183664,0.00384965,0.00427765,0.00314377,0.00456113,0.00347868,0.00487938,0.00418152,0.00469911,0.00367598,0.0028009,0.00234161,0.00194964,0.00200982,0.00122739,0.00310886,0.00275168,0.00492736,0.00437241,0.00113931,0.00104864,0.00292328,0.00452082,0.00394114,0.00150756,0.003613};\n\ndouble sigma_z[36]={0.0849973 ,0.0986032 ,0.0875521 ,0.0968222 ,0.0225239 ,0.0718278 ,0.0733675 ,0.0385274 ,0.0425549 ,0.0605867 ,0.0178555 ,0.0853407 ,0.0124119 ,0.0531027 ,0.0304032 ,0.0503145 ,0.0132213 ,0.0941765 ,0.0416444 ,0.0668198 ,0.063227 ,0.0291332 ,0.0481633 ,0.0595606 ,0.0818742 ,0.0472518 ,0.0270185 ,0.0767401 ,0.0219945 ,0.0902663 ,0.0779705 ,0.0337666 ,0.0362358 ,0.0692429 ,0.0558841 ,0.0150457};\n\ndouble sigma_z_prior[36]={0.00331909,0.00529541,0.00478151,0.00437497,0.00443062,0.00486333,0.00467423,0.0036723,0.00426963,0.00515357,0.0054553,0.00310132,0.00305971,0.00406327,0.00594293,0.00348709,0.00562526,0.00396025,0.00540537,0.00500447,0.00318595,0.00460592,0.00412137,0.00336418,0.00524988,0.00390092,0.00498349,0.0056667,0.0036384,0.00455861,0.00554822,0.00381061,0.0057615,0.00357705,0.00590572,0.00422393};\n\n\n  init_cosmo_runmode(\"halofit\");\n  init_bary(\"dmo\");\n  init_binning_fourier(15,20.0,3000.0,3000.0,21.0,10,10);\n  init_priors(shear_prior[sce],sigma_z[sce],delta_z_prior[sce],sigma_z_prior[sce],sigma_z[sce]*0.6,delta_z_prior[sce],sigma_z_prior[sce],3.0,1.2,3.8,2.0,16.0,5.0,0.8);\n  init_survey(survey_designation[0],nsource_table[sce],nlens_table[sce],area_table[sce]);\n  sprintf(arg1,\"zdistris/%s\",source_zfile[sce]);\n  sprintf(arg2,\"zdistris/%s\",lens_zfile[sce]); \n  init_galaxies(arg1,arg2,\"gaussian\",\"gaussian\",tomo_binning_source[0],tomo_binning_lens[0]);\n  init_IA(\"NLA_HF\",\"GAMA\"); \n  init_probes(\"3x2pt\");\n\n\n\n  //init_Pdelta(\"emu\",0.8,0.35);\n  // init_Pdelta(\"linear\",0.8,0.35);\n\n  // for (i =0; i< 10; i++){\n  //   save_zdistr_sources(i);\n  // }\n  // for (i =0; i< 10; i++){\n  //   save_zdistr_lenses(i);\n  // }\n//   double Omega;\n//   char filename[300];\n// for (i=0;i<200; i++){\n//   Omega=0.05+i*0.002; \n//   sprintf(filename,\"test_fid_%d\", i);\n//compute_data_vector(filename,Omega,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0);\n// }\n\nsprintf(arg3,\"Y10_area%le\",area_table[sce]);\ncompute_data_vector(arg3,0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,gbias.b[0],gbias.b[1],gbias.b[2],gbias.b[3],gbias.b[4],gbias.b[5],gbias.b[6],gbias.b[7],gbias.b[8],gbias.b[9],0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,sigma_z[sce],0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,sigma_z[sce]*0.6,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0,0.0,0.0,0.0);\n\n// compute_data_vector(\"mu1_Sigma0\",0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,1.,1.35,1.5,1.65,1.8,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.72+log(1.e+14*0.7),1.08,0.0,0.25,0.9,0.9,0.9,0.9);\n  // compute_data_vector(\"mu1_Sigma1\",0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,1.,1.,1.35,1.5,1.65,1.8,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.72+log(1.e+14*0.7),1.08,0.0,0.25,0.9,0.9,0.9,0.9);\n\n  // init_data_inv(\"cov/WFIRST_3x2pt_clusterN_clusterWL_inv\",\"datav/WFIRST_all_2pt_clusterN_clusterWL_fid\");\n  \n\n  // begin = clock();\n  // log_multi_like(0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0);\n  // // printf(\"knonlin %le\\n\",nonlinear_scale_computation(1.0));\n  // // printf(\"knonlin %le\\n\",nonlinear_scale_computation(0.5));\n  // end = clock();\n  // time_spent = (double)(end - begin) / CLOCKS_PER_SEC;      \n  // printf(\"timespent %le\\n\",time_spent);\n  \n \n  return 0;\n}\n\n\n", "meta": {"hexsha": "81da2cc12a65409f8c7f6d64676c639599d158f7", "size": 36589, "ext": "c", "lang": "C", "max_stars_repo_path": "like_fourier.c", "max_stars_repo_name": "CosmoLike/LSST_emu", "max_stars_repo_head_hexsha": "ed4d26b52ed26172eb35b3a030403c123e29eb2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "like_fourier.c", "max_issues_repo_name": "CosmoLike/LSST_emu", "max_issues_repo_head_hexsha": "ed4d26b52ed26172eb35b3a030403c123e29eb2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "like_fourier.c", "max_forks_repo_name": "CosmoLike/LSST_emu", "max_forks_repo_head_hexsha": "ed4d26b52ed26172eb35b3a030403c123e29eb2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.2863501484, "max_line_length": 2395, "alphanum_fraction": 0.7147230042, "num_tokens": 14989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.35439761859568164}}
{"text": "#ifndef PDCD_SMSVM_H\r\n#define PDCD_SMSVM_H\r\n\r\n#include <string>\r\n#include <gsl/gsl_rng.h>\r\n#include <gsl/gsl_randist.h>\r\n#include <stdio.h>      /* printf */\r\n#include <time.h>\r\n#include <fstream>\r\n#include <algorithm>\r\n#include <iomanip>\r\n#include <ctime>\r\n#include <math.h>\r\n\r\n\r\n//This class implements the method SMART_CD.\r\n\r\n\r\n/*\r\nThe optimization problem to solve is of the form f(x)+g(x)+h(Mx) ;\r\n where f(x)=sum_{j=1}^m lambda_f[j] phi_j(<A_j,x>) and g(x)=sum_{i=1}^n g_i(x_i), h(x)= |x|_1. We all assume that each phi_j is 1-smooth.\r\n*/\r\n\r\n\r\n\r\n\r\ntemplate<typename L, typename D>\r\nclass PDCD_SMSVM\r\n{\r\nprivate:\r\n\r\n  std::vector<D> Au;\r\n  std::vector<D> Az;\r\n\r\n  std::vector<D> Mu;\r\n  std::vector<D> Mz;\r\n\r\n\r\n  std::vector<D> Mx;\r\n  std::vector<D> Ax;\r\n  std::vector<D> lambda_f;\r\n\r\n\r\n\r\nprotected:\r\n\r\n  // parameters\r\n\r\n  D mu_f;\r\n\r\n  D mu_psi;\r\n\r\n  D mu_g;\r\n\r\n  L n;   // x\\in \\R^n\r\n\r\n  L tau;  //number of threads on each node/computer\r\n\r\n  D sumofLi;\r\n\r\n  // variables\r\n  std::vector<D> u;\r\n\r\n  std::vector<D> z;\r\n\r\n  std::vector<D> x;\r\n\r\n  std::vector<D> v;\r\n\r\n  std::vector<D> L_M;\r\n\r\n  std::vector<D> L_f;\r\n\r\n  std::vector<D> t;\r\n\r\n  D gamma;\r\n\r\n  D theta;\r\n\r\n  D theta0;\r\n\r\n  L m_1;\r\n\r\n  L m_2;\r\n\r\n  // sampling variables\r\n\r\n  std::vector<D> proba_vector;\r\n\r\n  std::vector<D> S;\r\n\r\n  std::vector<D> all_n;\r\n\r\n  std::vector<D> sampled;\r\n\r\n  D max_p;\r\n\r\n  D min_p;\r\n\r\n  // auxiliary variables\r\n\r\n  L max_nb_loops;\r\n\r\n  L evaluation;\r\n\r\n  ofstream samp;\r\n\r\n  L nb_iters;\r\n\r\n  L nb_of_iters_per_loop;\r\n\r\n  L print_every_N;\r\n\r\n  D running_time;\r\n\r\n  Matrix<L,D> data_A;\r\n\r\n  Matrix<L, D> data_M;\r\n\r\n  std::vector<D> lambda;\r\n\r\n  std::vector<D> M_tlambda;\r\n\r\n  D beta_s;\r\n\r\n  D function_value;\r\n\r\n  D residual1;\r\n\r\n  D residual2;\r\n\r\n\r\n\r\n\r\npublic:\r\n\r\n\r\n  gsl_rng * rng;\r\n\r\n  virtual inline D gradient_of_phi_j(D, L){return D(NULL);}\r\n\r\n  virtual inline D value_of_g_i(D, L){return D(NULL);}\r\n  virtual inline D value_of_phi_j(D, L){return D(NULL);}\r\n\r\n  virtual inline D prox_of_g_i(D,D,D, L){return D(NULL);}\r\n  virtual inline D value_of_phistar_i(D,L) {return D(NULL);}\r\n\r\n  virtual inline void set_matrix_M(){}\r\n\r\n  virtual inline void set_matrix_A(){}\r\n  PDCD_SMSVM()\r\n  {\r\n\r\n  }\r\n\r\n\r\n\r\n  void set_rng()\r\n  {\r\n    gsl_rng_env_setup();\r\n    const gsl_rng_type * T;\r\n    T = gsl_rng_default;\r\n    rng = gsl_rng_alloc(T);\r\n    gsl_rng_set(rng,time(NULL));\r\n    //gsl_rng_set(rng, 27432042);\r\n\r\n  }\r\n\r\n\r\n\r\n// sample i with probability pi=proba_vector[i]\r\n  L sampling()\r\n  {\r\n    //L i=(floor)(gsl_rng_uniform(rng)*n);\r\n    L i=gsl_rng_uniform_int(rng, n);\r\n    if(tau==1)\r\n    {\r\n      D y=gsl_rng_uniform(rng);\r\n      while(y*max_p>proba_vector[i])\r\n      {\r\n        i=(floor)(gsl_rng_uniform(rng)*n);\r\n        y=gsl_rng_uniform(rng);\r\n      }\r\n    }\r\n    return i;\r\n  }\r\n\r\n\r\n// sample S\r\n  void batch_sampling()\r\n  {\r\n    if(tau<n)\r\n    {\r\n      L i=sampling();\r\n      for(L k=0;k<tau;k++)\r\n      {\r\n        while(sampled[i]==1)\r\n        {\r\n          i=sampling();\r\n        }\r\n        sampled[i]=1;\r\n        S[k]=i;\r\n      }\r\n      for(L k=0;k<tau;k++)\r\n      {\r\n        sampled[S[k]]=0;\r\n      }\r\n    }\r\n    else {\r\n      S=all_n;\r\n      //cout<<\"s=all_n\"<<endl;\r\n    }\r\n  }\r\n\r\n\r\n  void compute_x()\r\n  {\r\n    for(L i=0;i<n;i++){\r\n    x[i]=gamma*u[i]+z[i];\r\n\t}\r\n\tfor(L j=0;j<m_2;j++){\r\n        Mx[j]=gamma*Mu[j]+Mz[j];\r\n    }\r\n    for(L j=0;j<m_1;j++){\r\n        Ax[j]=gamma*Au[j]+Az[j];\r\n    }\r\n  }\r\n\r\n  inline void compute_function_value() {\r\n     D res=0;\r\n     D res2= 0;\r\n     D tmp1= 0;\r\n     for(L i=0;i<this->n;i++){\r\n       res+=value_of_g_i(x[i],i);\r\n     }\r\n     for(L j=0;j<m_1;j++){\r\n       res+=lambda_f[j]*value_of_phi_j(Ax[j],j);\r\n     }\r\n     for(L j=0;j<m_2;j++){\r\n     \tif (1- Mx[j]> tmp1){\r\n     \t\ttmp1= 1- Mx[j];\r\n\t\t }\r\n        res2+=max(0.0,1- Mx[j]);\r\n     }\r\n     residual1= tmp1;\r\n     residual2= res2/m_2;\r\n     function_value=res+ m_2*residual2;;\r\n   }\r\n\r\n  void initialize(D beta_0, vector<D> & x0, vector<D> & y0, L val_tau, D p_N, D val_lambda_f)\r\n  {\r\n  \tset_matrix_M();\r\n    set_matrix_A();\r\n\r\n    this->tau=val_tau;\r\n    m_1=data_A.get_n();\r\n    m_2=data_M.get_n();\r\n    cout<<\"m_1=\"<<m_1<<endl;\r\n    cout<<\"m_2=\"<<m_2<<endl;\r\n    lambda_f.resize(m_1,val_lambda_f);\r\n    n=data_A.nfeatures;\r\n    tau=val_tau;\r\n    all_n.resize(n,0);\r\n    for(L i=0;i<n;i++)\r\n    all_n[i]=i;\r\n    print_every_N= p_N;\r\n    nb_of_iters_per_loop=floor(max(1.,n/(tau+0.0)));\r\n    lambda.resize(m_2,0);\r\n    for(L j=0;j<m_2;j++)\r\n           lambda[j]=y0[j];\r\n\r\n    u.clear();\r\n    u.resize(n,0);\r\n    z.clear();\r\n    z.resize(n,0);\r\n    x.clear();\r\n    x.resize(n,0);\r\n    for(L i=0;i<n;i++)\r\n    {\r\n      z[i]=x0[i];\r\n      x[i]=x0[i];\r\n    }\r\n    sampled.clear();\r\n    sampled.resize(n,0);\r\n    S.clear();\r\n    S.resize(tau,0);\r\n    t.clear();\r\n    t.resize(n,0);\r\n    M_tlambda.resize(n,0);\r\n    compute_Mty();\r\n\r\n    Au.clear();\r\n    Au.resize(m_1,0);\r\n    Az.clear();\r\n    Az.resize(m_1,0);\r\n    Ax.clear();\r\n    Ax.resize(m_1,0);\r\n    Mu.clear();\r\n    Mu.resize(m_2,0);\r\n    Mz.clear();\r\n    Mz.resize(m_2,0);\r\n    Mx.clear();\r\n    Mx.resize(m_2,0);\r\n    compute_Az(x0);\r\n    compute_Mz(x0);\r\n    compute_Ax(x0);\r\n    compute_Mx(x0);\r\n    beta_s= beta_0;\r\n    set_v();\r\n    set_p();\r\n    set_rng();\r\n\r\n    theta0= min_p;\r\n    theta= theta0;\r\n    cout<< \"theta0= \"<< theta0<< endl;\r\n    gamma= 1- theta0;\r\n\r\n    cout<<\"finished SMART_CD initializing\"<<endl;\r\n  }\r\n\r\n  inline void compute_and_record_res(){\r\n  \t    if (nb_iters%print_every_N== 0){\r\n  \t    cout<< \"gamma= \"<< gamma<< \" theta= \"<< theta<< \" beta_s= \"<< beta_s<< endl;\r\n        //compute_KKT_residual();\r\n        compute_function_value();\r\n        cout<<setprecision(9)<<\"Iteration: \"<<nb_iters<<\"; time=\"<<running_time<<\"; infeasibility= \"<< residual1<<\" \"<< residual2<<\"; function value=\"<<function_value<< endl;\r\n        samp<<setprecision(9)<< nb_iters<<\" \"<<running_time<<\" \"<<residual1<< \" \"<< residual2<< \" \"<< function_value<<\" \"<<endl;\r\n        }\r\n   }\r\n\r\n\r\n  inline D partial_i_of_f(L i)\r\n  {\r\n  \tD res=0;\r\n      for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n      {\r\n        L j=data_A.col_idx[k];\r\n        D tmp=lambda_f[j]*gradient_of_phi_j(gamma*Au[j]+Az[j], j);\r\n        res+=data_A.A_t[k]*tmp;\r\n      }\r\n      for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n      {\r\n        L j=data_M.col_idx[k];\r\n        D tmp=(gamma*Mu[j]+Mz[j]- 1)/beta_s+lambda[j];\r\n        if (tmp> 0){\r\n        \ttmp= 0;\r\n\t\t}\r\n\t\telse if( tmp< -1){\r\n\t\t\ttmp= -1;\r\n\t\t}\r\n        res+=data_M.A_t[k]*tmp;\r\n      }\r\n      return res;\r\n  }\r\n\r\n\r\n  inline void set_v()\r\n   {\r\n     v.resize(n,0);\r\n     L_f.resize(n,0);\r\n     L_M.resize(n,0);\r\n     D maxv=0;\r\n     D minv=std::numeric_limits<double>::max();\r\n     D sumv=0;\r\n     D sumvi1=0;\r\n     L sumw=0;\r\n     L maxw=0;\r\n     L minw=n;\r\n     sumofLi=0;\r\n     for(L j=0;j<m_1;j++)\r\n     {\r\n       sumw+=data_A.w_t[j];\r\n       maxw=max(maxw,data_A.w_t[j]);\r\n       minw=min(minw,data_A.w_t[j]);\r\n     }\r\n     cout<<\"sumw=\"<<sumw<<\";  maxw=\"<<maxw<<\"; minw=\"<<minw<<endl;\r\n     for(L i=0;i<n;i++)\r\n     {\r\n       D lfi=0;\r\n       D lmi=0;\r\n       D lfi1= 0;\r\n       D lmi1= 0;\r\n       for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n       {\r\n         L j=data_A.col_idx[k];\r\n         lfi+=(1.+(data_A.w_t[j]-1.)*(tau-1.)/max(n-1.,1.))*data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];\r\n         lfi1+=data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];\r\n       }\r\n       for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n       {\r\n         L j=data_M.col_idx[k];\r\n         lmi+=(1.+(data_M.w_t[j]-1.)*(tau-1.)/max(n-1.,1.))*data_M.A_t[k]*data_M.A_t[k];\r\n         lmi1+=data_M.A_t[k]*data_M.A_t[k];\r\n       }\r\n       L_f[i]=lfi;\r\n       L_M[i]= lmi;\r\n       sumv+=lfi;\r\n       sumvi1+=lfi1;\r\n       if(maxv<lfi) maxv=lfi;\r\n       if(minv>lfi) minv=lfi;\r\n     }\r\n     if(tau==n){\r\n          for(L i=0;i<n;i++)\r\n              L_f[i]=sumvi1;\r\n     }\r\n     sumofLi=sumvi1;\r\n     cout<<\"  max of v: \"<<maxv<<\" ;  min of v: \"<<minv<<\" ;  sumofv: \"<<sumv<<\" sumofLi=\"<<sumofLi<<endl;\r\n   }\r\n\r\n   inline void set_p(){\r\n     proba_vector.resize(n,0.0);\r\n     D res= 0;\r\n     D tmp= 1;\r\n     D tmp2= 0;\r\n     for (L i=0; i< n; i++){\r\n     \tres+= sqrt(L_f[i]+ L_M[i]/beta_s);\r\n\t }\r\n\t for (L i= 0; i< n; i++){\r\n\t \tproba_vector[i]= sqrt(L_f[i]+ L_M[i]/beta_s)/res;\r\n\t \tif (proba_vector[i]< tmp){\r\n\t \t\ttmp= proba_vector[i];\r\n\t\t }\r\n\t\tif (proba_vector[i]> tmp2){\r\n\t \t\ttmp2= proba_vector[i];\r\n\t\t }\r\n\t }\r\n\t if (tmp== 0){\r\n\t \tfor (L i= 0; i< n; i++){\r\n\t \tproba_vector[i]= 1.0/n;\r\n\t    }\r\n\t    min_p= 1.0/n;\r\n\t    max_p= 1.0/n;\r\n\t }\r\n\t else{\r\n\t    min_p= tmp;\r\n\t    max_p= tmp2;\r\n     }\r\n\t cout<< \"max_p= \"<< max_p<< \"; min_p= \"<< min_p<< endl;\r\n   }\r\n\r\n\r\n  inline void update_z_coordinate( L i, D dz){\r\n     z[i]+=dz;\r\n     for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n     {\r\n       L j=data_A.col_idx[k];\r\n       Az[j]+=dz*data_A.A_t[k];\r\n     }\r\n     for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n     {\r\n       L j=data_M.col_idx[k];\r\n       Mz[j]+=dz*data_M.A_t[k];\r\n       //if(j==2869) cout<<\"gamma=\"<<gamma<<\"; \"<<dz<<\"; \"<<Mz[j]<<endl;\r\n     }\r\n   }\r\n\r\n    inline void update_x_coordinate( L i, D dx){\r\n     x[i]+=dx;\r\n     x[i]=x[i];\r\n     L j;\r\n     for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n     {\r\n       j=data_M.col_idx[k];\r\n       Mx[j]+=dx*data_M.A_t[k];\r\n     }\r\n      for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n     {\r\n       j=data_A.col_idx[k];\r\n       Ax[j]+=dx*data_A.A_t[k];\r\n     }\r\n   }\r\n\r\n   inline void update_u_coordinate( L i, D du){\r\n     u[i]+=du;\r\n     for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)\r\n     {\r\n       L j=data_A.col_idx[k];\r\n       Au[j]+=du*data_A.A_t[k];\r\n     }\r\n     for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)\r\n     {\r\n       L j=data_M.col_idx[k];\r\n       Mu[j]+=du*data_M.A_t[k];\r\n     }\r\n   }\r\n\r\n   void compute_Au(){\r\n     for(L j=0;j<m_1;j++)\r\n       for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){\r\n         L kj=data_A.row_idx[k];\r\n         Au[j]+=u[kj]*data_A.A[k];\r\n       }\r\n   }\r\n\r\n   void compute_Mu(){\r\n     for(L j=0;j<m_2;j++)\r\n       for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){\r\n         L kj=data_M.row_idx[k];\r\n         Mu[j]+=u[kj]*data_M.A[k];\r\n       }\r\n   }\r\n\r\n   void compute_Az(){\r\n     for(L j=0;j<m_1;j++)\r\n       for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){\r\n         L kj=data_A.row_idx[k];\r\n         Az[j]+=z[kj]*data_A.A[k];\r\n       }\r\n   }\r\n   void compute_Mz(){\r\n     for(L j=0;j<m_2;j++)\r\n       for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){\r\n         L kj=data_M.row_idx[k];\r\n         Mz[j]+=z[kj]*data_M.A[k];\r\n       }\r\n   }\r\n\r\n   void compute_Au(vector<D> & x0){\r\n     for(L j=0;j<m_1;j++)\r\n       for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){\r\n         L kj=data_A.row_idx[k];\r\n         Au[j]+=x0[kj]*data_A.A[k];\r\n       }\r\n\r\n   }\r\n\r\n   void compute_Az(vector<D> & x0){\r\n     for(L j=0;j<m_1;j++)\r\n       for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){\r\n         L kj=data_A.row_idx[k];\r\n         Az[j]+=x0[kj]*data_A.A[k];\r\n       }\r\n   }\r\n   void compute_Mu(vector<D> & x0){\r\n     for(L j=0;j<m_2;j++)\r\n       for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){\r\n         L kj=data_M.row_idx[k];\r\n         Mu[j]+=x0[kj]*data_M.A[k];\r\n       }\r\n\r\n   }\r\n\r\n\r\n   void compute_Mz(vector<D> & x0){\r\n     for(L j=0;j<m_2;j++)\r\n       for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){\r\n         L kj=data_M.row_idx[k];\r\n         Mz[j]+=x0[kj]*data_M.A[k];\r\n       }\r\n   }\r\n\r\n     void compute_Mx(vector<D> & x0){\r\n     for(L j=0;j<m_2;j++)\r\n       for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){\r\n         L kj=data_M.row_idx[k];\r\n         Mx[j]+=x0[kj]*data_M.A[k];\r\n       }\r\n   }\r\n\r\n   void compute_Ax(vector<D> & x0){\r\n     for(L j=0;j<m_1;j++)\r\n       for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){\r\n         L kj=data_A.row_idx[k];\r\n         Ax[j]+=x0[kj]*data_A.A[k];\r\n       }\r\n   }\r\n\r\n  void compute_Mty(){\r\n        M_tlambda.clear();\r\n        M_tlambda.resize(this->n,0);\r\n        for(L i=0;i<this->n;i++)\r\n        {\r\n          for(L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++){\r\n            L j=data_M.col_idx[k];\r\n            M_tlambda[i]+=lambda[j]*data_M.A_t[k];\r\n           }\r\n        }\r\n\r\n    }\r\n\r\n    void update_theta()\r\n  {\r\n\r\n\t theta= (sqrt(theta*theta*theta*theta+ 4*theta*theta)- theta*theta)/2;\r\n\t \r\n  }\r\n\r\n  void reset(){\r\n  \tbeta_s= beta_s/(1+ theta);\r\n  }\r\n\r\n  void PDCD_SMSVM_solver(D beta_0, vector<D> & x0,vector<D> & y0, L val_tau, L max_nb_epoch, L p_N, D val_lambda_f,string filename1, D time2)\r\n  {\r\n    initialize(beta_0, x0, y0, val_tau,  p_N, val_lambda_f);\r\n    cout<<\"running SMART_CD\"<<\" ; \"<<filename1<<\" max_nb_epoch \"<<max_nb_epoch<<endl;\r\n    nb_iters=0;\r\n    filename1=\"results/PDCD_SMSVM_\"+filename1;\r\n    samp.open(filename1.c_str());\r\n    //srand48(27432042);\r\n    srand(time(NULL));\r\n    running_time= 0;\r\n    print_every_N=p_N;\r\n    compute_and_record_res();\r\n    D start;\r\n    start = std::clock();\r\n    while(nb_iters<max_nb_epoch)\r\n    {\r\n      start = std::clock();\r\n      D ti=0;\r\n      //D si=0;\r\n      D gi=0;\r\n      D Li=0;\r\n      L i=0;\r\n      for(L it=0;it<nb_of_iters_per_loop;it++)\r\n      {\r\n        gamma*=(1-theta);\r\n        if(theta==1) gamma=1;\r\n        batch_sampling();\r\n        for(L it_S=0;it_S<tau;it_S++)\r\n        {\r\n          i=S[it_S];\r\n          gi=partial_i_of_f(i);\r\n          Li=(L_f[i]+ L_M[i]/beta_s)*theta/theta0;\r\n          t[i]=prox_of_g_i(gi, Li, z[i],i);\r\n        }\r\n        for(L it_S=0;it_S<tau;it_S++)\r\n        {\r\n          i=S[it_S];\r\n          ti=t[i];\r\n          update_z_coordinate(i, ti);\r\n          update_u_coordinate(i, -(1- theta/theta0)/gamma*ti);\r\n        }\r\n        update_theta();\r\n        reset();\r\n      }\r\n      running_time+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;\r\n      nb_iters++;\r\n      compute_x();\r\n      compute_and_record_res();\r\n      if (running_time> time2){\r\n      \tbreak;\r\n\t  }\r\n    }\r\n\r\n\r\n  }\r\n\r\n\r\n\r\n\r\n\r\n};\r\n\r\n#endif\r\n", "meta": {"hexsha": "65e2edf03ba1a78009523641bc882f907b26cc6d", "size": 13991, "ext": "h", "lang": "C", "max_stars_repo_path": "IPALM_OPENMP/PDCD_SMSVM.h", "max_stars_repo_name": "lifei16/supplementary_code", "max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_stars_repo_licenses": ["BSD-Source-Code"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IPALM_OPENMP/PDCD_SMSVM.h", "max_issues_repo_name": "lifei16/supplementary_code", "max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_issues_repo_licenses": ["BSD-Source-Code"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IPALM_OPENMP/PDCD_SMSVM.h", "max_forks_repo_name": "lifei16/supplementary_code", "max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff", "max_forks_repo_licenses": ["BSD-Source-Code"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z", "avg_line_length": 21.3603053435, "max_line_length": 175, "alphanum_fraction": 0.4874562219, "num_tokens": 4548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3541938836019902}}
{"text": "#include <stdio.h>\n#include <time.h>\n#include <linux/limits.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <math.h>\n#include \"Globals.h\"\n#include \"constitutive_equations.h\"\n#include \"Watershed.h\"\n#include \"manufactured_solution.h\"\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_blas.h>\n\nextern void GetLGLWeights(int N, double* w);\n\nvoid *xcalloc(int items, int size)\n{\n\tvoid *ptr = calloc(items, size);\n\tif (ptr == NULL)\n\t{\n\t\tprintf(\"Unable to allocate memory\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\treturn ptr;\n}\n\nstatic int firstOutput = 1;\nstatic char folderName[500];\nstatic char ChannelHeightFileName[PATH_MAX + 1];\nstatic char ChannelQFileName[PATH_MAX + 1];\nstatic char KinFileName[PATH_MAX + 1];\nstatic char JuncHeightFileName[PATH_MAX + 1];\nstatic char JuncQFileName[PATH_MAX + 1];\nstatic char FpHeightFileName[PATH_MAX + 1];\nstatic char FpQFileName[PATH_MAX + 1];\n\nvoid outputFloodplainDataToFile(double currtime, double finalTime, double recordTimeIntervals)\n{\n\tchar openFileFormat[1];\n\tint writeHeader = 0;\n\tif (firstOutput)\n\t{\n\t\ttime_t rawtime;\n\t\ttime(&rawtime);\n\t\tstruct tm *timeinfo = localtime(&rawtime);\n\t\tsprintf(folderName, \"DataOutput_%d_%02d_%02d_%02d_%02d_%02d\",timeinfo->tm_year+1900, timeinfo->tm_mon+1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\n\t\tif (mkdir(folderName, 0777) == -1)\n\t\t\tperror(\"The following error occured while making the data output directory\");\n\t\t\n\t\tsprintf(FpHeightFileName, \"%s/Floodplains.63\", folderName);\n\t\tsprintf(FpQFileName, \"%s/Floodplains.64\", folderName);\n\n\t\topenFileFormat[0] = 'w';\n\t\twriteHeader = 1;\n\t\tfirstOutput = 0;\n\t}\n\telse\n\t{\n\t\topenFileFormat[0] = 'a';\n\t}\n\n\t// Output Floodplain data\n\tFILE *file1 = fopen(FpHeightFileName, openFileFormat);\n\tFILE *file2 = fopen(FpQFileName, openFileFormat);\n\tif (!file1)\n\t\tprintf(\"Error while opening file1\\n\");\n\tif (!file2)\n\t\tprintf(\"Error while opening file2\\n\");\n\tif (writeHeader)\n\t{\n\t\tint numRecords;\n\t\tif (fmod(finalTime, recordTimeIntervals) == 0)\n\t\t\tnumRecords = finalTime/recordTimeIntervals + 1;\n\t\telse\n\t\t\tnumRecords = finalTime/recordTimeIntervals + 2;\n\n\t\tfprintf(file1, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t\tfprintf(file1, \"Number of Floodplains = %d\\n\", NumFloodplains);\n\t\tfprintf(file2, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t\tfprintf(file2, \"Number of Floodplains = %d\\n\", NumFloodplains);\n\t\tfor (int j = 0; j < NumFloodplains; j++)\n\t\t{\n\t\t\tfprintf(file1, \"Number of data points for junction %d = %d\\n\", j, FloodplainList[j]->NumEl);\n\t\t\tfprintf(file2, \"Number of data points for junction %d = %d\\n\", j, FloodplainList[j]->NumEl);\n\t\t}\n\t}\n\tfor (int i=0; i < NumFloodplains; i++)\n\t{\n\t\tfprintf(file1, \"# Average H and Zeta at time %.3f for Junction %d\\n\", currtime, i); \n\t\tfprintf(file2, \"# Average Qx and Qy at time %.3f for Junction %d\\n\", currtime, i);\n\n\t\tfor (int j=0; j < FloodplainList[i]->NumEl; ++j)\n\t\t{\n\t\t\tdouble avgZeta = 0, avgHeight = 0, avgQx = 0, avgQy =0, avgz =0, zarr[3];\n\t\t\tfor(int k=0; k<3; ++k)\t\n\t\t\t{\n\t\t\t\tdouble zeta = FloodplainList[i]->zeta[j][k];\n\t\t\t\tdouble Qx = FloodplainList[i]->Qx[j][k];\n\t\t\t\tdouble Qy = FloodplainList[i]->Qy[j][k];\n\t\t\t\tzarr[k]= FloodplainList[i]->NodalZ[j][k];\n\t\t\t\tdouble height = zeta + zarr[k];\n\t\t\t\t\n\t\t\t\tavgZeta += zeta;\n\t\t\t\tavgHeight += height;\n\t\t\t\tavgQx += Qx;\n\t\t\t\tavgQy += Qy;\n\t\t\t\tavgz += zarr[k];\n\t\t\t}\n\t\t\tfprintf(file1, \"%d \\t %.13f \\t %.13f \\n\", j, avgHeight/3, avgZeta/3);\n\t\t\tfprintf(file2, \"%d \\t %.13f \\t %.13f\\n\", j, avgQx/3, avgQy/3 );\n\t\t}\t\t\n\t}\n\tfclose(file1);\n\tfclose(file2);\n\n}\n\nvoid output2DNodalError(double time)\n{\n\tchar *fileName1 = \"NodalErrorsH.out\";\n\tchar *fileName2 = \"NodalErrorsQ.out\";\n\tFILE* ef1 = fopen(fileName1, \"w\");\n\tFILE* ef2 = fopen(fileName2, \"w\");\n\n\tint i = 0;\n\tfor (int j=0; j < FloodplainList[i]->NumVerts; ++j)\n\t{\n\t\tdouble xval = FloodplainList[i]->Vx[j];\n\t\tdouble yval = FloodplainList[i]->Vy[j];\n\t\tint num_conn_els = FloodplainList[i]->ElCount[i];\n\t\tdouble nodalZeta = 0;\n\t\tdouble nodalQx = 0;\n\t\tdouble nodalQy = 0;\n\t\tfor (int k = 0; k < num_conn_els; k++)\n\t\t{\n\t\t\tint curr_el = FloodplainList[i]->VtoEl[j][k];\n\t\t\tint loc_v;\n\t\t\t// find the local vertex number for curr_el\n\t\t\tfor (int v = 0; v < 3; v++)\n\t\t\t{\n\t\t\t\tif (j == FloodplainList[i]->EltoVert[curr_el*3+v])\n\t\t\t\t{\n\t\t\t\t\tloc_v = v;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint loc_node = FloodplainList[i]->VtoNode[curr_el][loc_v];\n\t\t\tnodalZeta += FloodplainList[i]->zeta[curr_el][loc_node];\n\t\t\tnodalQx += FloodplainList[i]->Qx[curr_el][loc_node];\n\t\t\tnodalQy += FloodplainList[i]->Qy[curr_el][loc_node];\n\n\t\t}\n\t\tnodalZeta /= num_conn_els;\n\t\tnodalQx /= num_conn_els;\n\t\tnodalQy /= num_conn_els;\n\n\t\tdouble manzeta = getmanH(xval, yval, time);\n\t\tdouble manQx = getQx(xval, yval, time);\n\t\tdouble manQy = getQy(xval, yval, time);\n\n\t\tdouble er1 = -nodalZeta + manzeta;\n\t\tdouble er2 = -nodalQx + manQx;\n\t\tdouble er3 = -nodalQy + manQy;\n\n\t\tfprintf(ef1, \"%d \\t %.13f\\n\", j, er1);\n\t\tfprintf(ef2, \"%d \\t %.13f \\t %.13f\\n\", j, er2, er3);\n\t}\n\n\tfclose(ef1);\n\tfclose(ef2);\n\n}\n\nvoid outputFloodplainNodalDataToFile(double currtime, double finalTime, double recordTimeIntervals)\n{\n\tchar openFileFormat[1];\n\tint writeHeader = 0;\n\tif (firstOutput)\n\t{\n\t\ttime_t rawtime;\n\t\ttime(&rawtime);\n\t\tstruct tm *timeinfo = localtime(&rawtime);\n\t\tsprintf(folderName, \"DataOutput_%d_%02d_%02d_%02d_%02d_%02d\",timeinfo->tm_year+1900, timeinfo->tm_mon+1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\n\t\tif (mkdir(folderName, 0777) == -1)\n\t\t\tperror(\"The following error occured while making the data output directory\");\n\t\t\n\t\tsprintf(FpHeightFileName, \"%s/Floodplains.63\", folderName);\n\t\tsprintf(FpQFileName, \"%s/Floodplains.64\", folderName);\n\n\t\topenFileFormat[0] = 'w';\n\t\twriteHeader = 1;\n\t\tfirstOutput = 0;\n\t}\n\telse\n\t{\n\t\topenFileFormat[0] = 'a';\n\t}\n\n\t// Output Floodplain data\n\tFILE *file1 = fopen(FpHeightFileName, openFileFormat);\n\tFILE *file2 = fopen(FpQFileName, openFileFormat);\n\tif (!file1)\n\t\tprintf(\"Error while opening file1\\n\");\n\tif (!file2)\n\t\tprintf(\"Error while opening file2\\n\");\n\tif (writeHeader)\n\t{\n\t\tint numRecords;\n\t\tif (fmod(finalTime, recordTimeIntervals) == 0)\n\t\t\tnumRecords = finalTime/recordTimeIntervals + 1;\n\t\telse\n\t\t\tnumRecords = finalTime/recordTimeIntervals + 2;\n\n\t\tfprintf(file1, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t\tfprintf(file1, \"Number of Floodplains = %d\\n\", NumFloodplains);\n\t\tfprintf(file2, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t\tfprintf(file2, \"Number of Floodplains = %d\\n\", NumFloodplains);\n\t\tfor (int j = 0; j < NumFloodplains; j++)\n\t\t{\n\t\t\tfprintf(file1, \"Number of data points for junction %d = %d\\n\", j, FloodplainList[j]->NumVerts);\n\t\t\tfprintf(file2, \"Number of data points for junction %d = %d\\n\", j, FloodplainList[j]->NumVerts);\n\t\t}\n\t}\n\tfor (int i=0; i < NumFloodplains; i++)\n\t{\n\t\tfprintf(file1, \"# Nodal H at time %.3f for Junction %d\\n\", currtime, i); \n\t\tfprintf(file2, \"# Nodal Qx and Qy at time %.3f for Junction %d\\n\", currtime, i);\n\n\t\tfor (int j=0; j < FloodplainList[i]->NumVerts; ++j)\n\t\t{\n\t\t\tint num_conn_els = FloodplainList[i]->ElCount[i];\n\t\t\tdouble nodalZeta = 0;\n\t\t\tdouble nodalQx = 0;\n\t\t\tdouble nodalQy = 0;\n\t\t\tfor (int k = 0; k < num_conn_els; k++)\n\t\t\t{\n\t\t\t\tint curr_el = FloodplainList[i]->VtoEl[j][k];\n\t\t\t\tint loc_v;\n\t\t\t\t// find the local vertex number for curr_el\n\t\t\t\tfor (int v = 0; v < 3; v++)\n\t\t\t\t{\n\t\t\t\t\tif (j == FloodplainList[i]->EltoVert[curr_el*3+v])\n\t\t\t\t\t{\n\t\t\t\t\t\tloc_v = v;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tint loc_node = FloodplainList[i]->VtoNode[curr_el][loc_v];\n\t\t\t\tnodalZeta += FloodplainList[i]->zeta[curr_el][loc_node];\n\t\t\t\tnodalQx += FloodplainList[i]->Qx[curr_el][loc_node];\n\t\t\t\tnodalQy += FloodplainList[i]->Qy[curr_el][loc_node];\n\n\t\t\t}\n\t\t\tnodalZeta /= num_conn_els;\n\t\t\tnodalQx /= num_conn_els;\n\t\t\tnodalQy /= num_conn_els;\n\t\t\t\n\t\t\tfprintf(file1, \"%d \\t %.13f\\n\", j, nodalZeta);\n\t\t\tfprintf(file2, \"%d \\t %.13f \\t %.13f\\n\", j, nodalQx, nodalQy );\n\t\t}\t\t\n\t}\n\tfclose(file1);\n\tfclose(file2);\n\n}\nvoid outputDataToFile(double currtime, double finalTime, double recordTimeIntervals)\n{\n\tchar openFileFormat[1];\n\tint writeHeader = 0;\n\tif (firstOutput)\n\t{\n\t\ttime_t rawtime;\n\t\ttime(&rawtime);\n\t\tstruct tm *timeinfo = localtime(&rawtime);\n\t\tsprintf(folderName, \"DataOutput_%d_%02d_%02d_%02d_%02d_%02d\",timeinfo->tm_year+1900, timeinfo->tm_mon+1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);\n\t\tif (mkdir(folderName, 0777) == -1)\n\t\t\tperror(\"The following error occured while making the data output directory\");\n\t\t\n\t\tsprintf(ChannelHeightFileName, \"%s/Channels.63\", folderName);\n\t\tsprintf(ChannelQFileName, \"%s/Channels.64\", folderName);\n\t\tsprintf(KinFileName, \"%s/KinField.63\", folderName);\n\t\tsprintf(JuncHeightFileName, \"%s/Junctions.63\", folderName);\n\t\tsprintf(JuncQFileName, \"%s/Junctions.64\", folderName);\n\t\t//sprintf(FpHeightFileName, \"%s/Floodplains.63\", folderName);\n\t\t//sprintf(FpQFileName, \"%s/Floodplains.64\", folderName);\n\n\t\t// Move junction grid data file to this newly created folder\n\t\t/*char NewJunctionGridFileName[PATH_MAX + 1];\n\t\tsprintf(NewJunctionGridFileName, \"%s/JunctionMesh.14\", folderName);\n\t\tint ret = rename(\"./Output/JunctionMesh.14\", NewJunctionGridFileName);\n\t\tif (ret != 0)\n\t\t\tprintf(\"Error: unable to move the junction grid file\\n\");\n*/\n\t\t// Move flowpaths file to this newly created folder\n\t\tint ret;\n\t\tchar NewFlowPathsFileName[PATH_MAX + 1];\n\t\tsprintf(NewFlowPathsFileName, \"%s/FlowPaths.out\", folderName);\n\t\tret = rename(\"./Output/FlowPaths.out\", NewFlowPathsFileName);\n\t\tif (ret != 0)\n\t\t\tprintf(\"Error: unable to move the flow paths file\\n\");\n\n\t\t// Move ChannelNodes.14 to this newly created folder\n/*\t\tchar NewChannelsGridFileName[PATH_MAX + 1];\n\t\tsprintf(NewChannelsGridFileName, \"%s/Channels.14\", folderName);\n\t\tret = rename(\"./Output/Channels.14\", NewChannelsGridFileName);\n\t\tif (ret != 0)\n\t\t\tprintf(\"Error: unable to move channels grid file\\n\");\n*/\n\t\topenFileFormat[0] = 'w';\n\t\twriteHeader = 1;\n\t\tfirstOutput = 0;\n\t}\n\telse\n\t{\n\t\topenFileFormat[0] = 'a';\n\t}\n\n\t\t//char cwd[PATH_MAX+1];\n\t//if (getcwd(cwd, sizeof(cwd))==NULL)\n\t//\tperror(\"Error while getting current working directory\");\n\t\n\t\n\t//Output Channels data \n\tFILE* file1;\n\tFILE* file2;\n\tfile1 = fopen(ChannelHeightFileName, openFileFormat);\n\tfile2 = fopen(ChannelQFileName, openFileFormat);\n\t//if (!file1 || !file2)\n\t//{\n\t//\tprintf(\"Could not open file for writing. Exiting now\\n\");\n\t//\texit(1);\n\t//}\n\tif (writeHeader)\n\t{\n\t\tint numRecords;\n\t\tif (fmod(finalTime, recordTimeIntervals) == 0)\n\t\t\tnumRecords = finalTime/recordTimeIntervals+1;\n\t\telse\n\t\t\tnumRecords = finalTime/recordTimeIntervals + 2;\n\t\tfprintf(file1, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t\tfprintf(file1, \"Number of Channels = %d\\n\", NumChannels);\n\t\tfprintf(file2, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t\tfprintf(file2, \"NumChannels = %d\\n\", NumChannels);\n\t\tfor (int c = 0; c < NumChannels; c++)\n\t\t{\n\t\t\tfprintf(file1, \"Number of data points for channel %d = %d\\n\", c, ChannelList[c]->NumNodes);\n\t\t\tfprintf(file2, \"Number of data points for channel %d = %d\\n\", c, ChannelList[c]->NumNodes);\n\t\t}\n\t}\n\tfor (int i=0; i<NumChannels; i++)\n\t{\n\t\tfprintf(file1, \"# H and Zeta at time %.3f for Channel %d\\n\", currtime, i); \n\t\tfprintf(file2, \"#Q at time %.3f for Channel %d\\n\", currtime, i);\n\n\t\tint NumNodes = ChannelList[i]->NumNodes;\t\n\n\t\tfor (int j = 0; j<NumNodes; j++)\n\t\t{\t\n\t\t\tdouble bval = ChannelList[i]->NodalB[j];\n\t\t\tdouble zval = ChannelList[i]->NodalZ[j];\n\t\t\tdouble x_val = ChannelList[i]->NodalX[j];\n\t\t\tdouble y_val = ChannelList[i]->NodalY[j];\n\t\t\tdouble A = ChannelList[i]->A[j+1]; \n\t\t\tdouble Q = ChannelList[i]->Q[j+1];\n\t\t\tdouble m1val = ChannelList[i]->Nodalm1[j];\n\t\t\tdouble m2val = ChannelList[i]->Nodalm2[j];\n\t\t\tdouble H = getH(A, bval, m1val, m2val); \n\t\t\tdouble zeta = H - zval;\n\t\t\tfprintf(file1, \"%.13f \\t %.13f\\n\", H, zeta);\n\t\t\tfprintf(file2, \"%.13f\\n\", Q);\n\n\t\t}\n\n\t}\n\n\tfclose(file1);\n\tfclose(file2);\n\n\t// Output Junction data\n\tfile1 = fopen(JuncHeightFileName, openFileFormat);\n\tfile2 = fopen(JuncQFileName, openFileFormat);\n\tif (!file1)\n\t\tprintf(\"Error while opening file1\\n\");\n\tif (!file2)\n\t\tprintf(\"Error while opening file2\\n\");\n\tif (writeHeader)\n\t{\n\t\tint numRecords;\n\t\tif (fmod(finalTime, recordTimeIntervals) == 0)\n\t\t\tnumRecords = finalTime/recordTimeIntervals + 1;\n\t\telse\n\t\t\tnumRecords = finalTime/recordTimeIntervals + 2;\n\n\t\tfprintf(file1, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t\tfprintf(file1, \"Number of Junctions = %d\\n\", NumJunctions);\n\t\tfprintf(file2, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t\tfprintf(file2, \"NumJunctions = %d\\n\", NumJunctions);\n\t\tfor (int j = 0; j < NumJunctions; j++)\n\t\t{\n\t\t\tfprintf(file1, \"Number of data points for junction %d = %d\\n\", j, JunctionList[j]->NumEl);\n\t\t\tfprintf(file2, \"Number of data points for junction %d = %d\\n\", j, JunctionList[j]->NumEl);\n\t\t}\n\t}\n\tfor (int i=0; i<NumJunctions; i++)\n\t{\n\t\t\n\t\tfprintf(file1, \"# Average H and Zeta at time %.3f for Junction %d\\n\", currtime, i); \n\t\tfprintf(file2, \"# Average Qx and Qy at time %.3f for Junction %d\\n\", currtime, i);\n\t\t\n\t\tfor (int j=0; j<JunctionList[i]->NumEl; ++j)\n\t\t{\n\t\t\tdouble avgZeta = 0, avgHeight = 0, avgQx = 0, avgQy =0, avgz =0, zarr[3];\n\t\t\tfor(int k=0; k<3; ++k)\t\n\t\t\t{\n\t\t\t\tdouble zeta = JunctionList[i]->zeta[j][k];\n\t\t\t\tdouble Qx = JunctionList[i]->Qx[j][k];\n\t\t\t\tdouble Qy = JunctionList[i]->Qy[j][k];\n\t\t\t\tzarr[k]= JunctionList[i]->NodalZ[j][k];\n\t\t\t\tdouble height = zeta + zarr[k];\n\t\t\t\t\n\t\t\t\tavgZeta += zeta;\n\t\t\t\tavgHeight += height;\n\t\t\t\tavgQx += Qx;\n\t\t\t\tavgQy += Qy;\n\t\t\t\tavgz += zarr[k];\n\n\t\t\t}\n\t\t\tfprintf(file1, \"%d \\t %.13f \\t %.13f \\n\", j, avgHeight/3, avgZeta/3);\n\t\t\tfprintf(file2, \"%d \\t %.13f \\t %.13f\\n\", j, avgQx/3, avgQy/3 );\n\t\t}\t\t\n\t}\n\tfclose(file1);\n\tfclose(file2);\n\n\t// Output Kinematic Field Data\n\t// Here we assume that we are working with first order polynomials only\n\tif (FloodplainList[0]->floodedStatus == 0)\n\t{\n\t\tfile1 = fopen(KinFileName, openFileFormat);\n\t\tif (writeHeader)\n\t\t{\n\t\t\tint numRecords;\n\t\t\tif (fmod(finalTime, recordTimeIntervals) == 0)\n\t\t\t\tnumRecords = finalTime/recordTimeIntervals + 1;\n\t\t\telse\n\t\t\t\tnumRecords = finalTime/recordTimeIntervals + 2;\n\n\t\t\tfprintf(file1, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t\t}\n\t\tfprintf(file1,\"# Average height at time %3.3f in Kinematic Field\\n\", currtime);\n\n\t\tint NumEl = FloodplainList[0]->NumEl;\n\t\tfor (int i = 0; i < NumEl; i++)\n\t\t{\n\t\t\tif (KinematicElList[i]->isActive == 1)\n\t\t\t{\n\t\t\t\tdouble weq = KinematicElList[i]->weq;\n\t\t\t\tdouble height = KinematicElList[i]->A[0]/weq;\n\t\t\t\tif (KinematicElList[i]->numUpstreamEls > 0)\n\t\t\t\t{\n\t\t\t\t\tint numUpstreamEls = KinematicElList[i]->numUpstreamEls;\n\t\t\t\t\theight = KinematicElList[i]->A[0]/weq;\n\t\t\t\t\tfor (int j = 0; j < numUpstreamEls; j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint el = KinematicElList[i]->upstreamEls[j];\n\t\t\t\t\t\theight += KinematicElList[el]->A[1]/weq;\n\t\t\t\t\t}\n\t\t\t\t\theight = height/(numUpstreamEls+1);\n\t\t\t\t}\n\t\t\t\t//printf(\"%d %.13f\\n\", i, height);\n\t\t\t\tfprintf(file1, \"%d %.13f\\n\", i, height);\n\t\t\t}\n\t\t\telse\n\t\t\t\tfprintf(file1, \"%d %1.13f\\n\", i, 1e-7);\n\t\t}\n\t\tfclose(file1);\n\t}\n\n\t//static int previouslyFlooded = 0;\n\t//static char fpOpenFileFormat[1];\n\t//int writefpHeader = 0;\n\n\t//// Output Floodplain data if the channels have flooded\n\t//if (FloodplainList[0]->floodedStatus == 1)\n\t//{\n\t//\tif (previouslyFlooded)\n\t//\t{\n\t//\t\tfpOpenFileFormat[0] = 'a';\n\t//\t}\n\t//\telse\n\t//\t{\n\t//\t\tfpOpenFileFormat[0] = 'w';\n\t//\t\twritefpHeader = 1;\t\n\t//\t}\n\n\t//\tfile1 = fopen(FpHeightFileName, fpOpenFileFormat);\n\t//\tfile2 = fopen(FpQFileName, fpOpenFileFormat);\n\n\t//\t\n\t//\tif (!file1)\n\t//\t\tprintf(\"Error while opening file1\\n\");\n\t//\tif (!file2)\n\t//\t\tprintf(\"Error while opening file2\\n\");\n\t//\tif (writefpHeader)\n\t//\t{\n\t//\t\tint numRecords;\n\t//\t\tif (fmod(finalTime, recordTimeIntervals) == 0)\n\t//\t\t\tnumRecords = finalTime/recordTimeIntervals + 1;\n\t//\t\telse\n\t//\t\t\tnumRecords = finalTime/recordTimeIntervals + 2;\n\n\t//\t\tfprintf(file1, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t//\t\tfprintf(file2, \"End of Simulation Time = %lf.\\nTotal Number of Records = %d\\n\", finalTime, numRecords);\n\t//\t\tfprintf(file1, \"Number of data points for floodplain = %d\\n\", FloodplainList[0]->NumEl);\n\t//\t\tfprintf(file2, \"Number of data points for floodplain = %d\\n\", FloodplainList[0]->NumEl);\n\t//\t}\n\t//\t\t\n\t//\tfprintf(file1, \"# Average H and Zeta at time %.3f\\n\", currtime); \n\t//\tfprintf(file2, \"# Average Qx and Qy at time %.3f\\n\", currtime);\n\t//\n\t//\tfor (int j=0; j<FloodplainList[0]->NumEl; ++j)\n\t//\t{\n\t//\t\tdouble avgZeta = 0, avgHeight = 0, avgQx = 0, avgQy =0, avgz =0, zarr[3];\n\t//\t\tfor(int k=0; k<3; ++k)\t\n\t//\t\t{\n\t//\t\t\tdouble zeta = FloodplainList[0]->zeta[j][k];\n\t//\t\t\tdouble Qx = FloodplainList[0]->Qx[j][k];\n\t//\t\t\tdouble Qy = FloodplainList[0]->Qy[j][k];\n\t//\t\t\tzarr[k]= FloodplainList[0]->NodalZ[j][k];\n\t//\t\t\tdouble height = zeta + zarr[k];\n\t//\t\t\t\n\t//\t\t\tavgZeta += zeta;\n\t//\t\t\tavgHeight += height;\n\t//\t\t\tavgQx += Qx;\n\t//\t\t\tavgQy += Qy;\n\t//\t\t\tavgz += zarr[k];\n\n\t//\t\t}\n\t//\t\tfprintf(file1, \"%d \\t %.13f \\t %.13f \\n\", j, avgHeight/3, avgZeta/3);\n\t//\t\tfprintf(file2, \"%d \\t %.13f \\t %.13f\\n\", j, avgQx/3, avgQy/3 );\n\t//\t}\t\t\n\t//\tfclose(file1);\n\t//\tfclose(file2);\n\n\t//\tpreviouslyFlooded = 1;\n\n\t//}\n\n}\n\nvoid calculate_l2_error_2d(double time)\n{\n\tint NumEl = FloodplainList[0]->NumEl;\n\tint Np = FloodplainList[0]->Np;\n\tdouble errsqH = 0, errsqQx = 0, errsqQy = 0;\n\n\tgsl_vector *diffH = gsl_vector_alloc(Np);\n\tgsl_vector *diffQx = gsl_vector_alloc(Np);\n\tgsl_vector *diffQy = gsl_vector_alloc(Np);\n\n\t//double max = 0;\n\tfor (int i = 0; i < NumEl; i++)\n\t{\n\t\tfor (int j = 0; j < Np; j++)\n\t\t{\n\t\t\tdouble xval = FloodplainList[0]->NodalX[i][j];\n\t\t\tdouble yval = FloodplainList[0]->NodalY[i][j];\n\t\t\tdouble exactH = getmanH(xval, yval, time);\n\t\t\tdouble exactQx = getQx(xval, yval, time);\n\t\t\tdouble exactQy = getQy(xval, yval, time);\n\t\t\tdouble compH = FloodplainList[0]->zeta[i][j];\n\t\t\tdouble compQx =  FloodplainList[0]->Qx[i][j];\n\t\t\tdouble compQy = FloodplainList[0]->Qy[i][j];\n\t\t\tgsl_vector_set(diffH, j, fabs(exactH-compH));\n\t\t\tgsl_vector_set(diffQx, j, fabs(exactQx-compQx));\n\t\t\tgsl_vector_set(diffQy, j, fabs(exactQy-compQy));\n\t\t\t//gsl_vector_set(diffH, j, RHSZeta[i*Np+j]);\n\t\t\t//gsl_vector_set(diffQx, j,  RHSQx[i*Np+j]);\n\t\t\t//gsl_vector_set(diffQy,j, RHSQy[i*Np+j]);\n\t\t\t//max = fmax(fabs(exactQx - compQx), max);\n\t\t\t\t\t\n\t\t}\n\n\t\tgsl_vector *tmpH = gsl_vector_alloc(Np);\n\t\tgsl_vector *tmpQx = gsl_vector_alloc(Np);\n\t\tgsl_vector *tmpQy = gsl_vector_alloc(Np);\n\t\tdouble jac = FloodplainList[0]->jac[i];\n\t\tgsl_blas_dgemv(CblasNoTrans, jac, MassMatrix2D, diffH, 0.0, tmpH);\n\t\tgsl_blas_dgemv(CblasNoTrans, jac, MassMatrix2D, diffQx, 0.0, tmpQx);\n\t\tgsl_blas_dgemv(CblasNoTrans, jac, MassMatrix2D, diffQy, 0.0, tmpQy);\n\n\t\tdouble elerrHsq, elerrQxsq, elerrQysq;\n\t\tgsl_blas_ddot(diffH, tmpH, &elerrHsq);\n\t\tgsl_blas_ddot(diffQx, tmpQx, &elerrQxsq);\n\t\tgsl_blas_ddot(diffQy, tmpQy, &elerrQysq);\n\n\t\terrsqH += elerrHsq;\n\t\terrsqQx += elerrQxsq;\n\t\terrsqQy += elerrQysq;\n\n\t\tgsl_vector_free(tmpH);\n\t\tgsl_vector_free(tmpQx);\n\t\tgsl_vector_free(tmpQy);\n\t}\n\n\tgsl_vector_free(diffH);\n\tgsl_vector_free(diffQx);\n\tgsl_vector_free(diffQy);\n\n\tprintf(\"time at error computation = %lf\\n\", time);\n\tprintf(\"l2 error in H = %lf \\n\", sqrt(errsqH));\n\tprintf(\"l2 error in Qx = %lf \\n\", sqrt(errsqQx));\n\tprintf(\"l2 error in Qy = %lf \\n\", sqrt(errsqQy));\n\t//printf(\"maximum difference in Qx = %lf\\n\", max);\n\t\n}\n\nvoid append_to_file(char *fileName, double time, double data)\n{\n\tFILE* file = fopen(fileName, \"a\");\n\tfprintf(file, \"%lf %lf\\n\", time,data);\n\tfclose(file);\n}\n\n\ndouble calculateTotalWater(struct channel *Chan)\n{\n\tint NumEl = Chan->NumEl;\n\tint Np = Chan->Np;\n\tint P = Chan->P;\n\n\tdouble totalWater = 0;\n\tdouble LGLWeight[Np];\n\tGetLGLWeights(P, LGLWeight);\n\tfor (int k = 0; k < NumEl; k++)\n\t{\n\t\tdouble water = 0;\n\t\tdouble dh = Chan->dh[k];\n\t\tfor (int i = 0; i < Np; i++)\n\t\t{\n\t\t\tdouble m1val = Chan->Nodalm1[k*Np+i];\n\t\t\tdouble m2val = Chan->Nodalm2[k*Np+i];\n\t\t\tdouble bval = Chan->NodalB[k*Np+i];\n\t\t\tdouble A = Chan->A[k*Np+i+1];\n\t\t\tdouble h = getH(A, bval, m1val, m2val);\n\t\t\twater += LGLWeight[i]*(h-0.0000001);\n\t\t}\n\t\ttotalWater += 0.5*dh*water;\n\t}\n\n\treturn totalWater;\n\n}\n\n\ndouble ftTom(double ft)\n{\n\tdouble meter = ft*0.3048;\n\treturn meter;\n}\n\ndouble mToft (double m)\n{\n\tdouble ft = m*3.28084;\n\treturn ft;\n\n}\n\n", "meta": {"hexsha": "f1f0329089e1912cd8ffba4361a4bf979edfd235", "size": 20471, "ext": "c", "lang": "C", "max_stars_repo_path": "DGSHED/helper_routines.c", "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_issues_repo_path": "DGSHED/helper_routines.c", "max_issues_repo_name": "evalseth/DG-RAIN", "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DGSHED/helper_routines.c", "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "avg_line_length": 30.462797619, "max_line_length": 181, "alphanum_fraction": 0.6559034732, "num_tokens": 7024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.35417599310689496}}
{"text": "#include <stdio.h>\n#include <unistd.h>\n#include <assert.h>\n#include <math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_rng.h>\n#include \"dlib.h\"\n#include \"svec.h\"\n#include \"rng.h\"\n\nconst char *usage = \"Usage: scode [OPTIONS] < file\\n\"\n  \"file should have columns of arbitrary tokens\\n\"\n  \"-r RESTART: number of restarts (default 1)\\n\"\n  \"-i NITER: number of iterations over data (default UINT32_MAX)\\n\"\n  \"-t THRESHOLD: quit if logL increase for iter <= this (default .001)\\n\"\n  \"-d NDIM: number of dimensions (default 25)\\n\"\n  \"-z Z: partition function approximation (default 0.166)\\n\"\n  \"-p PHI0: learning rate parameter (default 50.0)\\n\"\n  \"-u ETA0: learning rate parameter (default 0.2)\\n\"\n  \"-s SEED: random seed (default 0)\\n\"\n  \"-c calculate real Z (default false)\\n\"\n  \"-w The first line of the input is weights (default false)\\n\"\n  \"-v verbose messages (default false)\\n\";\n\n//typedef uint32_t u32;\n//typedef uint64_t u64;\nu32 RESTART = 1;\nu32 NITER = UINT32_MAX;\ndouble THRESHOLD = 0.001;\nu32 NDIM = 25;\ndouble Z = 0.166;\ndouble PHI0 = 50.0;\ndouble ETA0 = 0.2;\nunsigned long int SEED = 0;\nbool CALCZ = false;\nbool WEIGHT = false;\nbool VERBOSE = false;\n\nu32 NTOK = 0;\nu64 NTUPLE = 0;\n\nconst gsl_rng_type *rng_T;\ngsl_rng *rng_R = NULL;\ndarr_t data;\nu64 **update_cnt;\ndouble * weight = NULL;\ndouble * uweight = NULL; /*Updated weights*/\nu64 **cnt;\n#define frq(i,j) ((double)cnt[i][j]*NTOK/len(data))\nsvec **vec;\nsvec **best_vec;\nsvec dummy_vec;\nsym_t qmax;\nsym_t NULLFEATID;\n#define NULLFEATMARKER \"/XX/\"\n\nint main(int argc, char **argv);\nvoid init_rng();\nvoid free_rng();\nu64 init_data();\nu32 init_weight();\nvoid free_weight();\nvoid randomize_vectors();\nvoid copy_best_vec();\nvoid free_data();\nvoid update_tuple(sym_t *t);\ndouble logL();\ndouble calcZ();\n\n#define vmsg(...) if(VERBOSE)msg(__VA_ARGS__)\n\nint main(int argc, char **argv) {\n  int opt;\n  while((opt = getopt(argc, argv, \"r:i:t:d:z:p:u:s:cwv\")) != -1) {\n    switch(opt) {\n    case 'r': RESTART = atoi(optarg); break;\n    case 'i': NITER = atoi(optarg); break;\n    case 't': THRESHOLD = atof(optarg); break;\n    case 'd': NDIM = atoi(optarg); break;\n    case 'z': Z = atof(optarg); break;\n    case 'p': PHI0 = atof(optarg); break;\n    case 'u': ETA0 = atof(optarg); break;\n    case 's': SEED = atoi(optarg); break;\n    case 'c': CALCZ = true; break;\n    case 'w': WEIGHT = true; break;\n    case 'v': VERBOSE = true; break;\n    default: die(\"%s\",usage);\n    }\n  }\n\n  vmsg(\"scode -r %u -i %u -t %g -d %u -z %g -p %g -u %g -s %lu %s%s%s\",\n       RESTART, NITER, THRESHOLD, NDIM, Z, PHI0, ETA0, SEED,\n       (CALCZ ? \"-c \" : \"\"), (WEIGHT ? \"-w \" : \"\"), (VERBOSE ? \"-v \" : \"\"));\n\n  init_rng();\n  if (SEED) gsl_rng_set(rng_R, SEED);\n  if (WEIGHT) NTOK = init_weight();\n  NTUPLE = init_data();\n  vmsg(\"Read %zu tuples %u uniq tokens\", NTUPLE, qmax);\n\n  double best_logL = 0;\n  for (u32 start = 0; start < RESTART; start++) {\n    randomize_vectors();\n    double ll = logL();\n    vmsg(\"Restart %u/%u logL0=%g best=%g\", 1+start, RESTART, ll, best_logL);\n    if (CALCZ) vmsg(\"Z=%g (approx %g)\", calcZ(), Z);\n    for (u32 iter = 0; iter < NITER; iter++) {\n      for (u64 di = 0; di < NTUPLE; di++) {\n\tupdate_tuple(&val(data, di * NTOK, sym_t));\n      }\n      double ll0 = ll;\n      ll = logL();\n      vmsg(\"Iteration %u/%u logL=%g\", 1+iter, NITER, ll);\n      if (ll - ll0 <= THRESHOLD) break;\n    }\n    if (start == 0 || ll > best_logL) {\n      vmsg(\"Updating best_vec with logL=%g\", ll);\n      best_logL = ll;\n      copy_best_vec();\n    }\n    vmsg(\"Restart %u/%u logL1=%g best=%g\", 1+start, RESTART, ll, best_logL);\n    if (CALCZ) vmsg(\"Z=%g (approx %g)\", calcZ(), Z);\n  }\n  for (u32 t = 0; t < NTOK; t++) {\n    for (sym_t q = 1; q <= qmax; q++) {\n      if (best_vec[t][q] == NULL) continue;\n      printf(\"%u:%s\\t%zu\\t\", t, sym2str(q), cnt[t][q]);\n      svec_print(best_vec[t][q]);\n      putchar('\\n');\n    }\n  }\n  fflush(stdout);\n  free_data();\n  free_rng();\n  if (WEIGHT) free_weight();\n  symtable_free();\n  dfreeall();\n  fprintf(stderr, \"%f\\n\", best_logL);\n  vmsg(\"bye\");\n}\n\ndouble logL() {\n  double l = 0;\n  for (u64 i = 0; i < NTUPLE; i++) {\n    sym_t *t = &val(data, i * NTOK, sym_t);\n    sym_t x = t[0];\n    sym_t y = t[1];\n    float px = frq(0, x);\n    float py = frq(1, y);\n    svec vx = vec[0][x];\n    svec vy = vec[1][y];\n    float xy = svec_sqdist(vx, vy);\n    l += log(px * py) - xy;\n  }\n  return (l / NTUPLE - log(Z));\n}\n\ndouble calcZ() {\n  double z = 0;\n  for (sym_t x = 1; x <= qmax; x++) {\n    if (VERBOSE && (x % 1000 == 0)) fputc('.', stderr);\n    if (cnt[0][x] == 0) continue;\n    float px = frq(0, x);\n    svec vx = vec[0][x];\n    for (sym_t y = 1; y <= qmax; y++) {\n      if (cnt[1][y] == 0) continue;\n      float py = frq(1, y);\n      svec vy = vec[1][y];\n      float xy = svec_sqdist(vx, vy);\n      z += px * py * exp(-xy);\n    }\n  }\n  if (VERBOSE) fputc('\\n', stderr);\n  return z;\n}\n\nvoid update_tuple(sym_t *t) {\n  /*weighted update*/\n  static svec *u = NULL;\n  static svec *v = NULL;\n  static svec dx = NULL;\n  if (u == NULL) u = _d_malloc(NTOK * sizeof(svec));\n  if (v == NULL) v = _d_malloc(NTOK * sizeof(svec));\n  if (dx == NULL) dx = svec_alloc(NDIM);\n  for (u32 i = 0; i < NTOK; i++) u[i] = vec[i][t[i]];\n  for (u32 i = 0; i < NTOK; i++) {\n    /* Sampling values from the marginal distributions. */\n    /* Can this be done once, or do we have to resample for every x? */\n    if(i > 0 && t[i] == NULLFEATID) continue;\n    for (u32 j = 0; j < NTOK; j++) {\n      if (j==i) { v[j] = u[i]; continue;}\n      u64 r = gsl_rng_get(rng_R);\n      r = (r << 32) | gsl_rng_get(rng_R);\n      r = r % NTUPLE;\n      sym_t y = val(data, r * NTOK + j, sym_t);\n      v[j] = vec[j][y];\n      if(i > 0) break;\n    }          \n    /* Compute the move for u[i] */\n    svec_set_zero(dx);\n    double ww;\n    for (u32 j = 0; j < NTOK; j++) {\n      if (j == i) continue;\n      ww = weight == NULL ? 1 : (i > 0 ? weight[i] : weight[j]);\n      double push = 0, pull = 0;\n      if (v[j] == NULL) v[j] = dummy_vec;\n      else push = exp(-svec_sqdist(u[i], v[j])) / Z;\n      if(u[j] == NULL)  u[j] = dummy_vec;\n      else pull = 1;\n      if(push != 0 || pull != 0){\n\tfor (u32 d = 0; d < NDIM; d++) {                    \n\t  float dxd = svec_get(dx, d);\n\t  float x = svec_get(u[i], d);\n\t  float y = svec_get(u[j], d);\n\t  float z = svec_get(v[j], d);\n\t  svec_set(dx, d, dxd + ww * ( pull * (y - x) + push * (x - z)));\n\t}\n      }\n      /*restore the vectors to original forms*/\n      if(push == 0) v[j] = NULL;\n      if(pull == 0) u[j] = NULL;\n      if(i > 0) break;\n      }\n    /* Apply the move scaled by learning parameter */\n    u64 cx = update_cnt[i][t[i]]++;\n    float nx = ETA0 * (PHI0 / (PHI0 + cx));\n    svec_scale(dx, nx);\n    svec_add(u[i], dx);\n    svec_normalize(u[i]);\n  }\n}\n\nu32 init_weight(){\n  u32 size = 100, i = 0;\n  weight = _d_malloc(size * sizeof(double));\n  forline (buf, NULL) {\n    fortok (tok, buf) {\n      weight[i] = atof(tok);\n      assert(weight[i++] >= 0);\n      if(i >= 100) {\n\tsize *= 2; \n\tweight = _d_realloc(weight, size);\n      }\n    }\n    assert(i > 0);\n    break;\n  }\n  return i;\n}\n\nvoid free_weight() {\n  if (weight != NULL) _d_free(weight);\n}\n\nu64 init_data() {\n  qmax = 0;\n  data = darr(0, sym_t);\n  forline (buf, NULL) {\n    u32 ntok = 0;\n    fortok (tok, buf) {\n      sym_t q = str2sym(tok, true);\n      if (q > qmax) qmax = q;\n      size_t lendata = len(data);\n      val(data, lendata, sym_t) = q;\n      if(strcmp(tok, NULLFEATMARKER) == 0) NULLFEATID = q;\n      ntok++;\n    }\n    if(NTOK == 0) NTOK = ntok;\n    assert(ntok == NTOK); //Each line has equal number of tokens\n  }\n  assert(NTOK > 0);\n  update_cnt = _d_malloc(NTOK * sizeof(ptr_t));\n  cnt = _d_malloc(NTOK * sizeof(ptr_t));\n  vec = _d_malloc(NTOK * sizeof(ptr_t));\n  best_vec = _d_malloc(NTOK * sizeof(ptr_t));     \n  dummy_vec = svec_alloc(NDIM);\n  svec_zero(dummy_vec);\n  uweight = _d_calloc(NTOK, sizeof(double));\n  for (u32 i = 0; i < NTOK; i++) {\n    update_cnt[i] = _d_calloc(qmax+1, sizeof(u64));\n    cnt[i] = _d_calloc(qmax+1, sizeof(u64));\n    vec[i] = _d_calloc(qmax+1, sizeof(svec));\n    best_vec[i] = _d_calloc(qmax+1, sizeof(svec));\n  }\n  u64 N = len(data) / NTOK;\n  for (u64 i = 0; i < N; i++) {\n    sym_t *p = &val(data, i * NTOK, sym_t);\n    for (u32 j = 0; j < NTOK; j++) {\n      sym_t k = p[j];\n      assert(k <= qmax);\n      cnt[j][k]++;\n      if(k == NULLFEATID){\n\tvec[j][k] = best_vec[j][k] = NULL;\n      }\n      else if (vec[j][k] == NULL) {\n\tvec[j][k] = svec_alloc(NDIM);\n\tbest_vec[j][k] = svec_alloc(NDIM);\n      }\n    }\n  }\n  return N;\n}\n\nvoid free_data() {\n  for (u32 i = 0; i < NTOK; i++) {\n    for (sym_t j = 0; j <= qmax; j++) {\n      if (vec[i][j] != NULL) {\n\tsvec_free(vec[i][j]);\n\tsvec_free(best_vec[i][j]);\n      }\n    }\n    _d_free(best_vec[i]);\n    _d_free(vec[i]);\n    _d_free(cnt[i]);\n    _d_free(update_cnt[i]);\n  }\n  _d_free(uweight);\n  svec_free(dummy_vec);\n  _d_free(best_vec);\n  _d_free(vec);\n  _d_free(cnt);\n  _d_free(update_cnt);\n  darr_free(data);\n}\n\nvoid randomize_vectors() {\n  for (u32 j = 0; j < NTOK; j++) {\n    for (sym_t q = 1; q <= qmax; q++) {\n      if (vec[j][q] != NULL) {\n\tsvec_randomize(vec[j][q]);\n\tupdate_cnt[j][q] = 0;\n      }\n    }\n  }\n}\n\nvoid copy_best_vec() {\n  for (u32 j = 0; j < NTOK; j++) {\n    for (sym_t q = 1; q <= qmax; q++) {\n      if (vec[j][q] != NULL) {\n\tsvec_memcpy(best_vec[j][q], vec[j][q]);\n      }\n    }\n  }\n}\n\nvoid init_rng() {\n  gsl_rng_env_setup();\n  rng_T = gsl_rng_mt19937;\n  rng_R = gsl_rng_alloc(rng_T);\n}\n\nvoid free_rng() {\n  gsl_rng_free(rng_R);\n}\n\n", "meta": {"hexsha": "41d31075531fed357b24d59f99d7ef19f179fe5f", "size": 9499, "ext": "c", "lang": "C", "max_stars_repo_path": "scode.c", "max_stars_repo_name": "ai-ku/scode", "max_stars_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T16:46:05.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-21T18:29:03.000Z", "max_issues_repo_path": "scode.c", "max_issues_repo_name": "ai-ku/scode", "max_issues_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T18:20:04.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-03T17:43:04.000Z", "max_forks_repo_path": "scode.c", "max_forks_repo_name": "ai-ku/scode", "max_forks_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_forks_repo_licenses": ["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.6078431373, "max_line_length": 76, "alphanum_fraction": 0.5529003053, "num_tokens": 3362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.3540811481869805}}
{"text": "#ifndef GSL_WRAPPERS_H\n#define GSL_WRAPPERS_H\n\n// #include <gsl/gsl_check_range.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_permutation.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_multimin.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_blas.h>\n#include <math.h>\n#include <assert.h>\n#include <time.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n\n#define outlog(format, args...) \\\n    fprintf(stderr, format, args); \\\n    fprintf(stderr, \"\\n\");\n\ndouble safe_log(double);\ndouble log_sum(double, double);\n\nstatic inline double vget(const gsl_vector* v, int i)\n{ return(gsl_vector_get(v, i)); };\n\nstatic inline void vset(gsl_vector* v, int i, double x)\n{ gsl_vector_set(v, i, x); };\n\n// Increment a vector element by a double.\nvoid vinc(gsl_vector*, int, double);\n\nstatic inline double mget(const gsl_matrix* m, int i, int j)\n{ return(gsl_matrix_get(m, i, j)); };\n\nstatic inline void mset(gsl_matrix* m, int i, int j, double x)\n{ gsl_matrix_set(m, i, j, x); };\n\nvoid msetcol(gsl_matrix* m, int r, const gsl_vector* val);\n\n// Increment a matrix element by a double.\nvoid minc(gsl_matrix*, int, int, double);\nvoid msetrow(gsl_matrix*, int, const gsl_vector*);\n\nvoid col_sum(gsl_matrix*, gsl_vector*);\n\nvoid vct_printf(const gsl_vector* v);\nvoid mtx_printf(const gsl_matrix* m);\nvoid vct_fscanf(const char*, gsl_vector* v);\nvoid mtx_fscanf(const char*, gsl_matrix* m);\nvoid vct_fprintf(const char* filename, gsl_vector* v);\nvoid mtx_fprintf(const char* filename, const gsl_matrix* m);\n\ndouble log_det(gsl_matrix*);\n\nvoid matrix_inverse(gsl_matrix*, gsl_matrix*);\n\nvoid sym_eigen(gsl_matrix*, gsl_vector*, gsl_matrix*);\n\ndouble sum(const gsl_vector* v);\n\ndouble norm(gsl_vector * v);\n\nvoid vct_log(gsl_vector* v);\nvoid vct_exp(gsl_vector* x);\n\nvoid choose_k_from_n(int k, int n, int* result);\n\nvoid log_normalize(gsl_vector* x);\nvoid normalize(gsl_vector* x);\n\nvoid optimize(int dim,\n              gsl_vector* x,\n              void* params,\n              void (*fdf)(const gsl_vector*, void*, double*, gsl_vector*),\n              void (*df)(const gsl_vector*, void*, gsl_vector*),\n              double (*f)(const gsl_vector*, void*));\n\nvoid optimize_fdf(int dim,\n                  gsl_vector* x,\n                  void* params,\n                  void (*fdf)(const gsl_vector*, void*, double*, gsl_vector*),\n                  void (*df)(const gsl_vector*, void*, gsl_vector*),\n                  double (*f)(const gsl_vector*, void*),\n                  double* f_val,\n                  double* conv_val,\n                  int* niter);\n\nvoid log_write(FILE* f, char* string);\nint directory_exist(const char *dname);\nvoid make_directory(char* name);\n\ngsl_rng* new_random_number_generator();\n\n#endif\n", "meta": {"hexsha": "02956b0c5ea2da80c20b865be7b6e33c136ac6ba", "size": 2806, "ext": "h", "lang": "C", "max_stars_repo_path": "scripts/lib/DTM/dtm/gsl-wrappers.h", "max_stars_repo_name": "iwangjian/dtm-lab", "max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z", "max_issues_repo_path": "scripts/lib/DTM/dtm/gsl-wrappers.h", "max_issues_repo_name": "iwangjian/topic-extractor", "max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_issues_repo_licenses": ["MIT"], "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/lib/DTM/dtm/gsl-wrappers.h", "max_forks_repo_name": "iwangjian/topic-extractor", "max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z", "avg_line_length": 28.06, "max_line_length": 78, "alphanum_fraction": 0.6724875267, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.629774621301746, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.35404449295009416}}
{"text": "#include <assert.h>\n#include <cblas.h>\n#include <complex.h>\n#include <errno.h>\n#include <fftw3.h>\n#include <getopt.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_permutation.h>\n#include <math.h>\n#include <omp.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\n\n#define C 299792458\n#define PI 3.141592654\n#define ANSI_COLOR_RED     \"\\x1b[31m\"\n#define ANSI_COLOR_GREEN   \"\\x1b[32m\"\n#define ANSI_COLOR_YELLOW  \"\\x1b[33m\"\n#define ANSI_COLOR_BLUE    \"\\x1b[34m\"\n#define ANSI_COLOR_MAGENTA \"\\x1b[35m\"\n#define ANSI_COLOR_CYAN    \"\\x1b[36m\"\n#define ANSI_COLOR_RESET   \"\\x1b[0m\"\n#define _MODEL_DEBUG 0\n#define MAX_TX 1\n#define MAX_RX 1\n#define MAX_RIBBON_SIZE 20\n#define MAX_SURFACES 20\n// if max values exceeded, may cause memory bugs\n\nstruct simulation {\n        struct environment *env;\n        struct file_reader *fr;\n};\n\nstruct spatial_motion_model {\n        double velocity[3];\n        double position[3];\n};\n\nstruct transmission_model {\n        double power_in_dBm;\n};\n\nstruct propagation_model {\n        double distance;\n};\n\nstruct general_node {\n        struct spatial_motion_model *smm;\n        struct transmission_model *tm;\n        int id;\n};\n\nstruct transmitter {\n        struct general_node *gn;\n        double complex baseband_signal;\n};\n\nstruct receiver {\n        struct general_node *gn;\n        double recv_noise_power;\n        double complex rx_signal;\n        struct receiver_ray_ribbon_ll_node *rlln;\n};\n\nstruct perfect_reflector {\n        double unit_normal[3];\n        double unit_length_normal[3];\n        double unit_width_normal[3];\n        double center_point[3];\n        double length, width;\n};\n\nstruct environment {\n        struct receiver **receivers_array;\n        struct transmitter **transmitters_array;\n        struct perfect_reflector **prarray;\n        struct general_node **node_array;\n        struct ray_ribbon_array **env_paths;\n        struct ray_ribbon_array **tx_paths;\n\n        double recv_unit_normal[3];\n        double time;\n        double complex *unit_power_gaussian_noise;\n        double frequency;\n        double wavelength;\n        double delta_time;\n        double end_time;\n        double max_limit;\n        double min_limit;\n\tint refresh_time;\n\tint awgn_supplied;\n        int time_index;\n\n        int num_transmitters;\n        int num_receivers;\n        int num_reflectors;\n\n        int sz_array_tx;\n        int sz_array_rx;\n        int sz_array_gn;\n        int sz_array_pr;\n\n        // flags\n        bool read_in_nodes;\n        /* should be true by the time TX or RX is read in */\n        bool node_memory_allocated;\n        bool tx_paths_updated;\n        bool tx_paths_updated_rx_paths_updated;\n};\n\nstruct file_reader {\n        FILE *infile;\n        FILE *outfile;\n\n        // filenames longer than 999 will be truncated\n        char input_filename[1000];\n        char output_filename[1000];\n};\n\nint id();\nstruct simulation *init_simulation();\nstruct spatial_motion_model *init_spatial_motion_model();\nstruct transmission_model *init_transmission_model();\nstruct propagation_model *init_propagation_model();\nstruct general_node *init_general_node();\nstruct transmitter *init_transmitter();\nstruct receiver *init_receiver();\nstruct perfect_reflector *init_perfect_reflector(const double *normal,\n                                         const double *center_point,\n                                         const double *length_normal,\n                                         double length, double width);\nstruct perfect_reflector **init_perfect_reflectorarray(int number);\nstruct environment *init_environment();\nint malloc_environment(struct environment *env);\n\nvoid print_vector(const double *db);\nvoid print_spatial_motion_model(const struct spatial_motion_model *smm);\nvoid print_transmission_model(const struct transmission_model *tm);\nvoid print_propagation_model(const struct propagation_model *pm);\nvoid print_general_node(const struct general_node *gn);\nvoid print_transmitter(const struct transmitter *tx);\nvoid print_receiver(const struct receiver *rx);\nvoid print_perfect_reflectors(const struct perfect_reflector *pr);\nvoid print_environment(const struct environment *env);\nvoid print_env_paths(const struct environment *env);\nvoid print_tx_paths(const struct environment *env);\n\nvoid destroy_spatial_motion_model(struct spatial_motion_model *smm);\nvoid destroy_simulation(struct simulation *sim);\nvoid destroy_transmission_model(struct transmission_model *tm);\nvoid destroy_propagation_model(struct propagation_model *pm);\nvoid destroy_transmitter(struct transmitter *tx);\nvoid destroy_receiver(struct receiver *tx);\nvoid destroy_environment(struct environment *env);\nvoid destroy_file_reader(struct file_reader *fr);\nvoid destroy_perfect_reflector(struct perfect_reflector *pr);\nvoid destroy_perfect_reflectorarray(struct perfect_reflector **pr_begin);\nstruct file_reader *init_file_reader(int argc, char *argv[]);\nvoid cross_product(const double *v1, const double *v2, double *v3);\ndouble normalize_unit_vector(double *v1);\nvoid diff(const double *v1, const double *v2, double *v3);\nint find_len(void **ptr);\n\nvoid add_receiver_patch(struct environment *env, int length);\nvoid destroy_last_reflector(struct environment *env);\ndouble distance(const struct general_node *gn1,\n                const struct general_node *gn2);\n\nbool update_environment_from_file_sim(struct simulation *sim);\nbool handle_request(struct environment *env, FILE *fp, const char *req_type);\nbool custom_fscanf(FILE *fp, const char *str, void *ptr);\n\n// Deprecated\nbool update_environment_from_file(struct environment *env,\n                                FILE *fp);\n", "meta": {"hexsha": "0a5e673f86a133f5428014322250594cd299d79c", "size": 5683, "ext": "h", "lang": "C", "max_stars_repo_path": "include/models.h", "max_stars_repo_name": "mainakch/wireless_link", "max_stars_repo_head_hexsha": "ebf7d4fcf9c4ef94f34f843cbfd25bcae6879f45", "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/models.h", "max_issues_repo_name": "mainakch/wireless_link", "max_issues_repo_head_hexsha": "ebf7d4fcf9c4ef94f34f843cbfd25bcae6879f45", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/models.h", "max_forks_repo_name": "mainakch/wireless_link", "max_forks_repo_head_hexsha": "ebf7d4fcf9c4ef94f34f843cbfd25bcae6879f45", "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.2252747253, "max_line_length": 77, "alphanum_fraction": 0.7193383776, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.35394212540494946}}
{"text": "# ifndef CELL_CYCLE_H\n# define CELL_CYCLE_H\n\n#include <vector>\n#include <deque>\n#include <string>\n#include <memory>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <math.h>\n\n\nusing namespace std;\n\n#define CONSTANT_PHASE 0\n#define EXPONENTIAL_PHASE 1\n\n#endif\n\n//////////////////////////////////////////////////////////////////////\n/////////////////////////////////////////////////////////////////////\t\nclass cell_cycle{//Class containing behaviour related to cell_cycle.\n////////////\n//////////\n\n\t\tprivate:\n\t\n\t\tint cell_state; // current state of the cycle\n\t\tdouble time_state; // current time in the state of the cycle\n\t\tdouble time_cycle; // total time in this cell_cycle\n\t\tdouble currentPhaseDuration; // time for the next phase\n\t\tvector<double> state_durations; // array with the cell states durations\n\t\tvector<int> state_types; // array with the cell phases types (exponential, uniform, ... )\n\t\tint divisions; // number of divisions so far\n\t\tint num_states; // total number of cell phases included\n\t\tbool divide_material; // flag to see if the species in the cell are dividied after cell division\n\t\tgsl_rng * rng; // allocator for the rng generator\n\n\n\t\tpublic:\n\n\t\tcell_cycle(){ // default constructor is a constructor with empty info\n\t\t\ttime_state = 0;\n\t\t\ttime_cycle = 0;\n\t\t\tdivisions = 0;\n\t\t\tcell_state = 0;\n\t\t\tnum_states = 0;\n\t\t\trng= gsl_rng_alloc (gsl_rng_mt19937);\n\t\t\tgsl_rng_set (rng,::time(NULL)*getpid());\n\t\t}\t\n\n\t\tvoid addCellPhase(double duration, int type_phase){\n\t\t\tcout<<\"Adding Cell Phase of duration\"<< duration<<\" \\n\";\n\t\t\tstate_durations.push_back(duration);\n\t\t\tstate_types.push_back(type_phase);\n\t\t\tnum_states++;\n\t\t\tif (num_states == 1){// if this is the first state set, also use it for the current cell cycle time\n\t\t\t\tgetPhaseDuration();\n\t\t\t}\n\t\t\tcout<<\"Cell Phase added\\n\";\n\t\t}\n\n\t\tvoid ResetCellCycle(){\n\t\t\ttime_state = 0;\n\t\t\ttime_cycle = 0;\n\t\t\tcell_state = 0;\n\t\t\tgetPhaseDuration();\n\t\t\tdivisions = 0;\n\t\t\tdivide_material = false;\n\t\t}\n\n\t\t// cell_cycle(int nstates,float duration, int type){\n\t\t// \t// The default constructor generates n cycle phases with same duration of certain type\n\t\t// \ttime_state = 0;\n\t\t// \ttime_cycle = 0;\n\t\t// \tdivisions = 0;\n\t\t// \tcell_state = 0;\n\t\t// \tnum_states = nstates;\n\t\t// \tstate_durations = new double[num_states];\n\t\t// \tstate_types = new int[num_states];\n\t\t// \tfor(int i=0;i<nstates;i++){\n\t\t// \t\tstate_durations[i] = duration;\n\t\t// \t\tstate_types[i] = type;\n\t\t// \t} \n\t\t// }\n\n\t\tvoid setPhaseDuration(int phase, double duration, int type_phase){\n\t\t\tstate_durations[phase] = duration;\n\t\t\tstate_types[phase] = type_phase;\n\t\t}\n\n\t\tdouble getPhaseDuration(){\n\t\t// compute the value of the time for the next phase and store it in NextPhaseTime to avoid recomputing\n\t\t\tif (state_types[cell_state] == CONSTANT_PHASE){\n\t\t\t\tcurrentPhaseDuration = state_durations[cell_state]; \n\t\t\t}\n\t\t\telse if (state_types[cell_state] == EXPONENTIAL_PHASE){\n\t\t\t\tcurrentPhaseDuration = state_durations[cell_state] * log(1.0/gsl_rng_uniform_pos(rng)); \n\t\t\t}\n\n\t\t\t// cout<<\"Next Phase duration: \"<<currentPhaseDuration<<'\\n';\n\t\t\treturn currentPhaseDuration;\n\t\t}\n\n\t\tdouble getTimeForNextCellPhase(){\n\t\t\treturn currentPhaseDuration - time_state;\n\t\t}\n\n\t\tint AdvanceNextPhase(){\n\t\t\tcell_state++;\n\t\t\tif (cell_state==num_states){// if the cell reaches the final state\n\t\t\t\tcell_state = 0;\n\t\t\t\ttime_cycle = 0;\n\t\t\t}\n\t\t\ttime_state = 0;\n\t\t\tgetPhaseDuration();\n\t\t\tif (cell_state == 0){ // if we are dividing\n\t\t\t\tdivisions += 1;\n\t\t\t\tdivide_material = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tdivide_material = false;\n\t\t\t}\n\t\t\treturn cell_state;\n\t\t}\n\n\t\tbool MaterialIsDivided(){\n\t\t\treturn divide_material; \n\t\t}\n\n\t\tvoid updateCelltime(double time){\n\t\t\ttime_cycle += time;\n\t\t\ttime_state += time;\n\t\t}\n\n\t\tvoid setCellCyclePositionTime(int phase, double time){\n\t\t\tcell_state = phase;\n\t\t\ttime_state = time;\n\t\t\ttime_cycle = time;\n\t\t}\n\n\t\tvoid printCellProperties(){\n\t\t\tcout<<\"total states \"<<num_states<<'\\n';\n\t\t\tcout<<\"of duration \";\n\t\t\tfor (auto d: state_durations){ cout << d << ' ';};\t\n\t\t\tcout<<\"\\n of type\";\n\t\t\tfor (auto d: state_types){ cout << d << ' ';};\t\t\n\t\t\tcout<<'\\n';\n\t\t}\n\t\n\t\tint getCellPhase(){\n\t\t\treturn cell_state;\n\t\t}\n\n\t\tdouble getPhaseTime(){\n\t\t\treturn time_state;\n\t\t}\n\n\t\tvoid PrintState(){\n\t\t\tcout<< \"cell state: \"<<cell_state<< \" time_state: \"<<time_state<<'\\n';\n\t\t\tcout<< \"currentPhaseDuration: \"<<currentPhaseDuration<<'\\n';\n\t\t\tprintCellProperties();\n\t\t\tcout<< \"time cell has divided: \"<<divisions<<'\\n';\n\t\t\tcout<< \"cell is ready for division: \"<< divide_material<<'\\n';\n\t\t}\n\n};", "meta": {"hexsha": "16d685cf338263b957cdb7d4d4c9ef7bbed5b8c0", "size": 4493, "ext": "h", "lang": "C", "max_stars_repo_path": "cell_cycle.h", "max_stars_repo_name": "2piruben/langil", "max_stars_repo_head_hexsha": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856", "max_stars_repo_licenses": ["MIT"], "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_cycle.h", "max_issues_repo_name": "2piruben/langil", "max_issues_repo_head_hexsha": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856", "max_issues_repo_licenses": ["MIT"], "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_cycle.h", "max_forks_repo_name": "2piruben/langil", "max_forks_repo_head_hexsha": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856", "max_forks_repo_licenses": ["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.9041916168, "max_line_length": 104, "alphanum_fraction": 0.6505675495, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3536836344188672}}
{"text": "/**\n *\n * Copyright (c) 2017-2020  King Abdullah University of Science and Technology\n * All rights reserved.\n *\n * ExaGeoStat is a software package provided by KAUST\n **/\n/**\n *\n * @file MLE_misc.h\n *\n * Header file of  auxiliary functions that are needed by ExaGeoStat.\n *\n * @version 1.1.0\n *\n * @author Sameh Abdulah\n * @date 2020-06-06\n *\n **/\n#ifndef _MLE_MISC_H_\n#define _MLE_MISC_H_\n#include <stdbool.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <unistd.h>\n#include <sys/time.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n#include \"common.h\"\n#include \"descriptor.h\"\n#include \"chameleon/morse_runtime.h\"\n#include <nlopt.h>\n#include <math.h>\n#include <morse.h>\n#include <lapacke.h>\n#include <starpu.h>\n#include <cblas.h>\n#include \"../../include/flops.h\"\n#include <starpu_profiling.h>\n#if defined(CHAMELEON_USE_MPI)\n#include <starpu_mpi.h>\n#else\n#endif\n#if defined(CHAMELEON_USE_CUDA) && !defined(CHAMELEON_SIMULATION)\n#include <starpu_scheduler.h>\n#include <starpu_cuda.h>\n#endif\n#include <gsl/gsl_sf_bessel.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_fft_complex.h>\n#include \"../../include/morse_starpu.h\"\n/** ****************************************************************************\n * PI value\n **/\n#define PI (3.141592653589793)\n/** ****************************************************************************\n * The radius of the  eartch (used by Great Circle Distance (GCD)\n **/\n#define earthRadiusKm 6371.0\n/** ****************************************************************************\n * Start timing macro\n **/\n#define START_TIMING(_t)     _t =- cWtime();\n/** ****************************************************************************\n * Stop timing macro\n **/\n#define STOP_TIMING(_t)      _t += cWtime();\n/*******************************************************************************/\n/**\n *  Internal function to return address of block (m,n) with m,n = block indices\n */\n\n\ninline static void *chameleon_getaddr_null(const MORSE_desc_t *A, int m, int n)\n{\n    (void)A; (void)m; (void)n;\n    return NULL;\n}\n\n\n/**\n *  Internal function to return the leading dimension of element A(m,*) with m,n = block indices\n */\ninline static int chameleon_getblkldd_ccrb(const MORSE_desc_t *A, int m)\n{\n    int mm = m + A->i / A->mb;\n    return ( ((mm+1) == A->lmt) && ((A->lm % A->mb) != 0)) ? A->lm % A->mb : A->mb;\n}\n\n/**\n *  Internal function to return MPI rank of element A(m,n) with m,n = block indices\n */\ninline static int chameleon_getrankof_2d(const MORSE_desc_t *desc, int m, int n)\n{\n\n    if(m>=n)\n        return (m % desc->p) * desc->q + (n % desc->q);\n    else\n        return (n % desc->p) * desc->q + (m % desc->q);\n}\n\n\n/** ****************************************************************************\n * Allocate matrix in different modes\n **/\n#define EXAGEOSTAT_ALLOCATE_MATRIX_TILE(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_ , _lda_, _n_, _smb_, _snb_, _m_, _n2_, _p_, _q_) \\\n    if (data->ooc && _memspace_ == NULL && _mb_ != 1  && _nb_ !=1)                                                         \\\nMORSE_Desc_Create_OOC(_desc_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_, _smb_, _snb_, _m_, _n2_, \\\n        _p_, _q_);             \\\nelse                                                            \\\nMORSE_Desc_Create(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_,_smb_, _snb_ , _m_, _n2_, \\\n        _p_, _q_); \t\\\n\n\n\n\n#define EXAGEOSTAT_ALLOCATE_FULL_MATRIX_TILE(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_ , _lda_, _n_, _smb_, _snb_, _m_, _n2_, _p_, _q_) \\\n    if (data->ooc && _memspace_ == NULL && _mb_ != 1  && _nb_ !=1)                                                         \\\nMORSE_Desc_Create_OOC(_desc_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_, _smb_, _snb_, _m_, _n2_, \\\n        _p_, _q_);             \\\nelse                                                            \\\nMORSE_Desc_Create_User(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_,_smb_, _snb_ , _m_, _n2_, \\\n        _p_, _q_, morse_getaddr_null, morse_getblkldd_ccrb, chameleon_getrankof_2d );\t\\\n\n\n\n#define EXAGEOSTAT_ALLOCATE_DIAG_MATRIX_TILE(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_ , _lda_, _n_, _smb_, _snb_, _m_, _n2_, _p_, _q_) \\\n    if (data->ooc && _memspace_ == NULL && _mb_ != 1  && _nb_ !=1)                                                         \\\nMORSE_Desc_Create_OOC(_desc_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_, _smb_, _snb_, _m_, _n2_, \\\n        _p_, _q_);             \\\nelse                                                            \\\nMORSE_Desc_Create_User(_desc_, _memspace_, _type2_, _mb_, _nb_, _mbXnb_, _lda_, _n_,_smb_, _snb_ , _m_, _n2_, \\\n        _p_, _q_, morse_getaddr_null, morse_getblkldd_ccrb, morse_getrankof_2d_diag );   \\\n\n/** ****************************************************************************\n *  Structure for  identifies two dimensions struct with two vectors (x and y).\n **/\ntypedef struct {\n    double *x;\t\t\t\t///< Values in X dimension.\n    double *y;\t\t\t\t///< Values in Y dimension.\n    double *z;                              ///< Values in Z dimension.\n} location;\n\n\n\n/** ****************************************************************************\n *  Structure for reading real datasets through STARS-H\n **/\ntypedef struct {\n    double xy;                              ///< Locations (x, y)\n    double z;                               ///< Measurements. \n} sdata;\n\n\n/** ****************************************************************************\n *  Structure for output results\n **/\ntypedef struct {\n    int problem_size;                             \n    char* computation;\n    char* kernel;\n    char* ds_type;\n    char* precision;\n    int z_sample;\n    int dense_ts;\n    int lr_ts;\n    int lr_acc;\n    int lr_maxrank;\n    int ncores;\n    int ngpus;\n    int p;\n    int q;\n    int num_params;\n    double *initial_theta;\n    double *starting_theta;\n    double *estimated_theta;\n    double final_loglik;\n    double time_per_iteration;\n    double flops_per_iteration;\n    double total_mle_time;\n    double mse_pred1;\n    double mse_pred2;\n    double mse_pred;\n    double total_pred_time;\n    double total_pred_flops;\n    double mloe;\n    double mmom;\n    char* mloe_exec;\n    double total_mloe_mmom_time;\n    double matrix_gen_mloe_mmom_time;\n    double cho_fact_mloe_mmom_time;\n    double loop_mloe_mmom_time;\n    double total_mloe_mmom_flops;\t\t\n} output;\n\n\n\n/** ****************************************************************************\n *  Structure for  uniquely identifies three different parameters for accuracy\n *  measurments accuracyDenseAppDiff, normDenseAppDiff, and normA.\n **/\n/*typedef struct{\n  double accuracyDenseAppDiff; \t\t///< Accuracy different between dense format and approx format.\n  double normDenseAppDiff;\t\t///< Norm difference between dense format and approx format.\n  double normA;   \t\t\t///< normA.\n  } acc_struct;\n  */\n\n/** ****************************************************************************\n *  Structure for  uniquely identifies different variables that are needed\n *  by  EXAGEOSTAT to  ease arguments pass.\n **/\ntypedef struct\n{\n    double variance;            ///< Variance parameter. \n    double variance1;           ///< Variance1 parameter.\n    double variance2;           ///< Variance2 parameter.\n    char *computation;\t\t    ///< Exact or approx computation.\n    char *c_fun;\t            ///< Matern or pow-exp kernels.\t\n    int test;\t\t\t        ///< Synthetic or real dataset execution.\n    int async;\t\t\t        ///< Running mode: synchronous or asynchronous.\n    int iter_count;\t\t\t    ///< Number of iterations to converge.\n    location  l1;\t\t\t    ///< 2D locations for the first dataset.\n    location lmiss;\t\t\t    ///< 2D locations for the missing data (prediction stage).\n    location lobs;\t\t\t    ///< 2D locations for the observed data (prediction stage).\n    location lm;  \t\t        ///< 2D locations for the median data point.\n    void *descC;\t\t\t    ///< Covariance matrix C descriptor.\n    void *descsubC11;           ///< Covariance sub matrix C11 descriptor.\n    void *descsubC12;           ///< Covariance sub matrix C12 descriptor.\n    void *descsubC21;           ///< Covariance sub matrix C21 descriptor.\n    void *descsubC22;           ///< Covariance sub matrix C22 descriptor.\n    void *descZ;\t\t\t    ///< Measurements Z descriptor.\n    void *descZ1;               ///< Measurements Z1 submatrix descriptor.\n    void *descZ2;               ///< Measurements Z2 submatrix descriptor.\n    double *Adense;\t\t\t    ///< Dense matrix descriptor in the case of approximation mode - accuracy check.\t\n    double *Adense2;\t\t    ///< Dense matrix descriptor2 in the case of approximation mode - accuracy check.\n    void *descZcpy;\t\t\t    ///< A copy of Measurements Z descriptor.\n    void *descdet;\t\t\t    ///< Determinant descriptor.\n    void *descproduct;\t\t    ///< Dot product descriptor.\n    void *descproduct1;         ///< Dot product descriptor.\n    void *descproduct2;         ///< Dot product descriptor.\n    void *descZmiss;\t\t    ///< Missing measurements descriptor.\n    void *descC12;\t\t\t    ///< Covariance Matrix C12 descriptor.\n    void *descC22;\t\t\t    ///< Covariance Matrix C22 descriptor.\n    void *descZactual;\t\t    ///< Actual Measurements Z descriptor.\n    void *descZobs;\t\t\t    ///< observed Measurements Z descriptor.\n    void *descmse1;        \t\t///< Mean Square Error (MSE) descriptor.\n    void *descmse2;             ///< Mean Square Error (MSE) descriptor.\n    void *descmse;              ///< Mean Square Error (MSE) descriptor.\n    void *sequence;\t\t\t    ///< MORSE sequence.\n    void *request;\t\t\t    ///< MORSE request.\n    int verbose;\t\t\t    ///< Verbose indicator.\n    int check;\t\t\t        ///< Check indicator -- approximation mode.\n    int log;\t\t\t        ///< Log files generation indicator, 0--> no, 1--> yes.\n    double avg_exec_time_per_iter;\t///< Avergae execution time per iteration (only used in verbose mode).\n    double total_exec_time;\t\t///< Total execution time (only used in verbose mode).\n    double avg_flops_per_iter;\t///< Avergae flops per iteration (only used in verbose mode).\n    double final_loglik;\t\t///< Final log likelihood value.\n    char *locsFPath;\t\t    ///< Locations file path -- in the case of real dataset (real mode). \n    char *obsFPath;\t\t\t    ///< Observations file path --  in the case of real dataset (real mode).\n    char *obsFPath2;            ///< Observations file path2 (bivariate case) --  in the case of real dataset (real mode).\n    char *actualZFPath;\t\t    ///< Actual observations file path -- in the case of prediction.\n    char *actualZFPath2;        ///< Actual observations file path -- in the case of prediction.\n    char *actualZLocFPath;\t\t///< Actial locations file path -- in the case of prediction.\n    double det;\t\t\t        ///< determinant value.\n    double  dotp;\t\t\t    ///< double dot product value.\n    double  dotp1;              ///< double dot2 product value.\n    double  dotp2;              ///< double dot3 product value.\n    float sdotp;\t\t\t    ///< single dot product value.\n    double mserror;\t\t\t    ///< Mean Square Error (MSE) value.\n    double mserror1;            ///< Mean Square Error (MSE) value, variable 1 in case of bivariate.\n    double mserror2;            ///< Mean Square Error (MSE) value, variable 2 in case of bivariate.\n    char *dm;\t\t\t        ///< Distance metric to be used ed->Euclidian Distance -- gcd->Great Circle Distance.\n    int diag_thick;\t\t        ///< The thick of used diagonal in the case of diagonal approximation approach.\n    char *nFileLog;\t\t\t    ///< log file name (only used if log -->1).\n    FILE *pFileLog;\t\t\t    ///< log file path (only used if log -->1).\n    int hicma_maxrank;\t\t    ///< Max Rank in the case of LR-HiCMA approx\n    int hicma_data_type;        ///< To define the type of the problem to HiCMA (HICMA_STARSH_PROB_GEOSTAT (Synthetic) or HICMA_STARSH_PROB_GEOSTAT_POINT (real))\n    void *hicma_descC;\t\t    ///< HiCMA descC descriptor (for accuracy check).\n    void *hicma_descZ;\t\t    ///< HiCMA descZ descriptor.\n    void *hicma_descCD;\t\t    ///< HiCMA descCD descriptor.\n    void *hicma_descCUV;\t\t///< HiCMA descCUV descriptor.\n    void *hicma_descCrk;\t\t///< HiCMA descCrk descriptor.\n    void *hicma_descZcpy;       ///< A copy of Measurements Z descriptor.\n    void *hicma_descdet;        ///< Determinant descriptor.\n    void *hicma_descproduct;    ///< Dot product descriptor.\n    void *hicma_descC12D;\t\t///< HiCMA descCD descriptor.\t\n    void *hicma_descC12UV;\t\t///< HiCMA descCUV descriptor.\n    void *hicma_descC12rk;\t\t///< HiCMA descCrk descriptor.\n    void *hicma_descC22D;\t\t///< HiCMA descCD descriptor.\t\n    void *hicma_descC22UV;\t\t///< HiCMA descCUV descriptor.\n    void *hicma_descC22rk;\t\t///< HiCMA descCrk descriptor.\n    double hicma_acc;\t\t    ///< Accuracy in the case of LR-HiCMA approx.\n    void *hsequence;            ///< HiCMA sequence.\n    void *hrequest;             ///< HiCMA request.\n    int opt_tol; \t            ///< The parameter tol is a tolerance that is used for the purpose of stopping criteria only.\n    int opt_max_iters;\t        ///< Maximum number of mle iterations.\n    int ooc;                    ///< Support Out-Of-Core execution, 0-->no, 1-->yes.\n    char* kernel_fun;           ///< stationary_matern, or non_stationary_matern.\n    int precision;              ///< (0)Double, (1)Single, and (2)Mixed.\n    //Mixed Precision\n    void *desctemp;             ///< Temporary descriptor for mixed precision Cholesky factorization.\n    void *desctemp22;           ///< Temporary descriptor for mixed precision Cholesky factorization.\n    //MLOE and MMOM\n    void *desck_t;\n    void *desck_a;\n    void *desck_ttmp;\n    void *desck_atmp;\n    void *descK_ttmp;\n    void *descK_t;\n    void *descK_a;\n    void *descexpr1;\n    void *descexpr2;\n    void *descexpr3;\n    void *descexpr4;\n    void *descestimatedalpha;\n    void *desctruthalpha;\n    void *desc_mloe_mmom;\n    double expr1;                 \n    double expr2;                 \n    double expr3;                 \n    double expr4;  \n    double mloe;\n    double mmom;               \n    int mloe_mmom;\n    int mloe_mmom_async;\n    int mspe;\n    char* recovery_file;            \n    char* checkpoint_file;\n    int time_slots;\n    int idw;\n} MLE_data;\n\n\n/** ****************************************************************************\n * Verbose Macro.\n **/\n#define VERBOSE(str)\t\\\n    if (data->verbose == 1 && MORSE_My_Mpi_Rank() == 0){\t\\\n        fprintf(stdout, \"%s\", str);\t\\\n        fflush(stdout);\\\n    }\n\n/** ****************************************************************************\n *  Success Macro.\n **/\n#define SUCCESS(success, str) \\\n    if (success != MORSE_SUCCESS){ \\\n        fprintf(stdout, \"%s\", str);\\\n        fflush(stdout);\\\n        exit(EXIT_FAILURE);\\\n    }\n\noutput results;\n\nvoid pick_random_points(MLE_data *data, double *Zobs, double *Zactual,\n        int nZmiss, int nZobs, int N);\n\nvoid generate_interior_points(MLE_data *data, double *Zobs, double *Zactual,\n        int nZmiss, int nZobs, int N);\n\nvoid split_data(MLE_data * data, location *locations, double *Z,\n        double *Zactual,\n        int *N, int nZmiss);\n\nvoid init_data_values(MLE_data *data);\n\nint locations_obs_zsort_inplace(int n, location *locations, double *z);\n\nvoid zsort_locations_obs(int n, location *locations, double *z);\n\ndouble uniform_distribution(double rangeLow, double rangeHigh);\n\nvoid print_dmatrix(char* desc, int m, int n,\n        double* a, int lda);\n\nvoid print_diagonal(char* desc, int m, double* a,\n        int lda);\n\nvoid print_smatrix(char* desc, int m, int n,\n        float* a, int lda);\n\nlocation* GenerateXYLoc(int n, int seed);\n\nint countlines(char *filename);\n\n\nvoid checkpointing(char *path, int iter_count, double* theta,\n        double loglik, int num_params);\n\nbool recover(char *path, int iter_count, double* theta, \n        double* loglik, int num_params);\n\nvoid write_to_file(char * path, int matrix_size,int ncores,\n        int tile_size, int test, char *computation,\n        int async, char *obsFPath,double total_exec_time,\n        double avg_exec_time_per_iter, double avg_flops_per_iter,\n        int p_grid, int q_grid, double final_loglik, int n);\n\nvoid theta_parser2(double *theta_vec, char * kern, int num_params);\n\nvoid write_vectors(double * zvec, MLE_data * data, int n);\n\nvoid write_to_thetafile(char * path, double *theta, int num_params,\n        int n, double time_per_iter, int total_no_iters,\n        double prediction_error, double mloe,  double mmom);\n//void readObsFile(char *obsfile, int n, double * streamdata);\n\nvoid shuffle(double *array, location* locations, size_t n);\n\nvoid theta_parser(double *initial_theta, double *target_theta,\n        double *starting_theta, char *ikernel, char *kernel,\n        double *lb, double *up, int test, int num_params);\n\nvoid init_optimizer(nlopt_opt* opt, double *lb, double *up,\n        double tol);\n\nvoid print_summary(int test, int N, int ncores, int gpus,\n        int ts, int lts, char *computation,\n        int zvecs, int p_grid, int q_grid, int precision);\n\nint print_result(MLE_data *data, double *starting_theta, int N,\n        int zvecs, int ncores, int ts, int test,\n        double *initial_theta, char *computation,\n        int p_grid, int q_grid, double final_loglik,\n        double prediction_error);\n\ndouble cWtime(void);\n\nvoid readlocfile(char* loc_file, int n,  location* l1);\n\nvoid write_prediction_result(char *path, int matrix_size, int no_missing,\n        double MSE1, double MSE2, double MSE, \n        double solve_time, double flops);\n\nint doesFileExist(const char *filename);\n\nvoid init_log (MLE_data * data);\n\nvoid finalize_log (MLE_data * data);\n//acc_struct check_acc(MLE_data * HICMA_data, int n, int ts);\ndouble core_matern_vector (double x0, double y0, double x1,\n        double y1, double *localtheta, int distance_metric);\n\nvoid pick_random_points2(MLE_data *data, double *Zobs, double *Zactual,\n        int nZmiss, int nZobs, int N);\n\nlocation* GenerateXYLoc_ST(int n, int t_slots, int seed);\nvoid pick_random_points_noshuffle(MLE_data *data, double *Zobs, double *Zactual,\n        int nZmiss, int nZobs, int N);\n\ndouble* pred_idw(MLE_data *data, double *z_miss, double *z_actual, \n        double*z_obs, int nZmiss, int nZobs);\n\nvoid write_to_estimatedtheta(char * path, double *theta, int num_params,\n        int n, double prediction_time,\n        double mloe_mmom_time,\n        double prediction_error1,\n        double prediction_error2,\n        double prediction_error,\n        double mloe,\n        double mmom,\n        int zvecs);\n#endif\n", "meta": {"hexsha": "dc78477919b5a601e75ad74dc8265510bf714056", "size": 18688, "ext": "h", "lang": "C", "max_stars_repo_path": "misc/include/MLE_misc.h", "max_stars_repo_name": "a10Raijin/exageostat", "max_stars_repo_head_hexsha": "84880ccca4bd32072e128ef7f5824953973675a4", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/include/MLE_misc.h", "max_issues_repo_name": "a10Raijin/exageostat", "max_issues_repo_head_hexsha": "84880ccca4bd32072e128ef7f5824953973675a4", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/include/MLE_misc.h", "max_forks_repo_name": "a10Raijin/exageostat", "max_forks_repo_head_hexsha": "84880ccca4bd32072e128ef7f5824953973675a4", "max_forks_repo_licenses": ["BSD-3-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.6772823779, "max_line_length": 161, "alphanum_fraction": 0.6010273973, "num_tokens": 4769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3536500564278384}}
{"text": "#include \"redisgears.h\"\n#include \"redisai.h\"\n#include \"minmax_heap.h\"\n#include <math.h>\n#include \"redisgears_memory.h\"\n#include <cblas.h>\n#include <sys/time.h>\n\n#define STR1(a) #a\n#define STR(e) STR1(e)\n\n#define MIN(a,b) (((a)<(b))?(a):(b))\n#define MAX(a,b) (((a)>(b))?(a):(b))\n\nstatic RedisModuleCtx* staticCtx;\n\nstatic RecordType* ScoreRecordType = NULL;\nstatic RecordType* HeapRecordType = NULL;\n\n#define VEC_SIZE 128\n\n#define VEC_HOLDER_SIZE 1024 * 1024\n\ntypedef struct VecsHolder VecsHolder;\n\ntypedef struct VecDT{\n    size_t index;\n    VecsHolder* holder;\n    RedisModuleString* keyName;\n}VecDT;\n\ntypedef struct VecsHolder{\n    size_t size;\n    VecDT* vecDT[VEC_HOLDER_SIZE];\n    float vecs[VEC_HOLDER_SIZE * VEC_SIZE];\n}VecsHolder;\n\n#define HOLDER_VECDT(h, i) (h->vecDT[i])\n#define HOLDER_VEC(h, i) (h->vecs[i * VEC_SIZE])\n\nVecsHolder** vecList = NULL;\nRedisModuleType *vecRedisDT;\n\ntypedef struct VecReaderCtx{\n    size_t index;\n    Record** pendings;\n    float vec[VEC_SIZE];\n    size_t topK;\n}VecReaderCtx;\n\ntypedef struct TopKArg{\n    size_t topK;\n}TopKArg;\n\ntypedef struct ScoreRecord{\n    Record baseRecord;\n    RedisModuleString* key;\n    float score;\n}ScoreRecord;\n\ntypedef struct HeapRecord{\n    Record baseRecord;\n    heap_t* heap;\n}HeapRecord;\n\nstatic VecReaderCtx* VecReaderCtx_Create(float* data, size_t topK){\n    VecReaderCtx* ctx = RG_ALLOC(sizeof(*ctx));\n    ctx->index = 0;\n    ctx->pendings = array_new(Record*, 10);\n    ctx->topK = topK;\n    if(data){\n        memcpy(ctx->vec, data, VEC_SIZE * sizeof(*data));\n        float denom_vec = cblas_snrm2(VEC_SIZE, ctx->vec, 1);\n        for(size_t i = 0 ; i < VEC_SIZE ; ++i){\n            ctx->vec[i] /= denom_vec;\n        }\n    }\n    return ctx;\n}\n\nstatic void VecReaderCtx_Free(VecReaderCtx* ctx){\n    for(size_t i = 0 ; i < array_len(ctx->pendings) ; ++i){\n        Record* r = ctx->pendings[i];\n        RedisGears_FreeRecord(r);\n    }\n\n    array_free(ctx->pendings);\n\n    RG_FREE(ctx);\n}\n\nstatic Record* to_score_records(ExecutionCtx* rctx, Record *data, void* arg){\n    HeapRecord* hr = (HeapRecord*)data;\n\n    Record* lr = RedisGears_ListRecordCreate(hr->heap->count);\n\n    size_t count = hr->heap->count;\n    for(size_t i = 0 ; i < count ; ++i){\n        ScoreRecord* sr = mmh_pop_min(hr->heap);\n        RedisGears_ListRecordAdd(lr, &sr->baseRecord);\n    }\n\n    RedisGears_FreeRecord(data);\n\n    return lr;\n}\n\nstatic int heap_cmp(const void *a, const void *b, const void *udata){\n    ScoreRecord* s1 = (ScoreRecord*)a;\n    ScoreRecord* s2 = (ScoreRecord*)b;\n    if(s1->score < s2->score){\n        return -1;\n    }else if(s1->score > s2->score){\n        return 1;\n    }else {\n        return 0;\n    }\n}\n\nstatic Record* top_k(ExecutionCtx* rctx, Record *accumulate, Record *r, void* arg){\n    TopKArg* topKArg = arg;\n\n    HeapRecord* heap = (HeapRecord*)accumulate;\n\n    if(!heap){\n        heap = (HeapRecord*)RedisGears_RecordCreate(HeapRecordType);\n        heap->heap = mmh_init_with_size(topKArg->topK, heap_cmp, NULL, (mmh_free_func)RedisGears_FreeRecord);\n    }\n\n    heap_t* h = heap->heap;\n\n    ScoreRecord* currSr = (ScoreRecord*)r;\n\n    // If the queue is not full - we just push the result into it\n    // If the pool size is 0 we always do that, letting the heap grow dynamically\n    if (h->count < topKArg->topK) {\n        mmh_insert(h, r);\n    } else {\n        // find the min result\n        ScoreRecord* sr = mmh_peek_min(h);\n        if(sr->score < currSr->score){\n            void* temp = mmh_pop_min(h);\n            RedisModule_Assert(temp == sr);\n            RedisGears_FreeRecord(&(sr->baseRecord));\n            mmh_insert(h, r);\n        }else{\n            RedisGears_FreeRecord(r);\n        }\n    }\n\n    return &(heap->baseRecord);\n}\n\nstatic void on_done(ExecutionPlan* ctx, void* privateData){\n    RedisModuleBlockedClient *bc = privateData;\n    RedisModuleCtx *rctx = RedisModule_GetThreadSafeContext(bc);\n    RedisGears_ReturnResultsAndErrors(ctx, rctx);\n    RedisModule_UnblockClient(bc, NULL);\n    RedisGears_DropExecution(ctx);\n    RedisModule_FreeThreadSafeContext(rctx);\n}\n\nVecDT* vec_insert(RedisModuleString *keyName, const float* data){\n    VecsHolder* holder = NULL;\n    if(!vecList){\n        vecList = array_new(VecsHolder*, 1);\n    }\n    if(array_len(vecList) == 0){\n        holder = RG_CALLOC(1, sizeof(VecsHolder));\n        vecList = array_append(vecList, holder);\n    }else{\n        holder = vecList[array_len(vecList) - 1];\n    }\n\n    if(holder->size >= VEC_HOLDER_SIZE){\n        // we need to create a new holder\n        holder = RG_CALLOC(1, sizeof(VecsHolder));\n        vecList = array_append(vecList, holder);\n    }\n\n    float* v = &HOLDER_VEC(holder, holder->size);\n    memcpy(v, data, sizeof(float) * VEC_SIZE);\n\n    float demon = cblas_snrm2(VEC_SIZE, v, 1);\n\n    for(size_t i = 0 ; i < VEC_SIZE ; ++i){\n        v[i] /= demon;\n    }\n\n    VecDT* vDT = RG_CALLOC(1, sizeof(*vDT));\n    vDT->holder = holder;\n    vDT->index = holder->size;\n    vDT->keyName = keyName;\n    RedisModule_RetainString(NULL, vDT->keyName);\n    HOLDER_VECDT(holder, holder->size) = vDT;\n\n    ++holder->size;\n\n    return vDT;\n}\n\n/*\n * rg.vec_add <k> <blob>\n */\nint vec_add_command(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){\n    if(argc != 3){\n        return RedisModule_WrongArity(ctx);\n    }\n\n    size_t dataLen;\n    float* data = (float*)RedisModule_StringPtrLen(argv[2], &dataLen);\n    if(dataLen != (VEC_SIZE * sizeof(float))){\n        RedisModule_ReplyWithError(ctx, \"Given blob is not float vector of size \" STR(VEC_SIZE));\n        return REDISMODULE_OK;\n    }\n\n    RedisModuleKey *kp = RedisModule_OpenKey(ctx, argv[1], REDISMODULE_WRITE);\n    if(RedisModule_KeyType(kp) != REDISMODULE_KEYTYPE_EMPTY){\n        RedisModule_ReplyWithError(ctx, \"Key is not empty\");\n        RedisModule_CloseKey(kp);\n        return REDISMODULE_OK;\n    }\n\n    VecDT* vDT = vec_insert(argv[1], data);\n\n    RedisModule_ModuleTypeSetValue(kp, vecRedisDT, vDT);\n\n    RedisModule_CloseKey(kp);\n\n    RedisModule_ReplicateVerbatim(ctx);\n\n    RedisModule_ReplyWithSimpleString(ctx, \"OK\");\n\n    return REDISMODULE_OK;\n}\n\n/*\n * rg.vec_sim <k> <blob>\n */\nint vec_sim_command(RedisModuleCtx *ctx, RedisModuleString **argv, int argc){\n\n    if(argc != 3){\n        return RedisModule_WrongArity(ctx);\n    }\n\n    char* err = NULL;\n\n    long long topK;\n    if(RedisModule_StringToLongLong(argv[1], &topK) != REDISMODULE_OK){\n        RedisModule_ReplyWithError(ctx, \"Failed extracting <k>\");\n        return REDISMODULE_OK;\n    }\n\n    size_t dataSize;\n    float* data = (float*)RedisModule_StringPtrLen(argv[2], &dataSize);\n    if(dataSize != (VEC_SIZE * sizeof(float))){\n        RedisModule_ReplyWithError(ctx, \"Given blob is not at the right size\");\n        return REDISMODULE_OK;\n    }\n\n    TopKArg* topKArg2 = RG_ALLOC(sizeof(*topKArg2));\n    topKArg2->topK = topK;\n\n\n    FlatExecutionPlan* fep = RGM_CreateCtx(VecReader, &err);\n\n    VecReaderCtx* rCtx = VecReaderCtx_Create(data, topK);\n\n    RGM_Collect(fep);\n\n    RGM_Accumulate(fep, top_k, topKArg2);\n\n    RGM_FlatMap(fep, to_score_records, NULL);\n\n    ExecutionPlan* ep = RGM_Run(fep, ExecutionModeAsync, rCtx, NULL, NULL, &err);\n\n    if(!ep){\n        RedisGears_FreeFlatExecution(fep);\n        RedisModule_ReplyWithError(ctx, err);\n        return REDISMODULE_OK;\n    }\n\n    RedisModuleBlockedClient *bc = RedisModule_BlockClient(ctx, NULL, NULL, NULL, 0);\n    RedisGears_AddOnDoneCallback(ep, on_done, bc);\n    RedisGears_FreeFlatExecution(fep);\n\n    return REDISMODULE_OK;\n}\n\nstatic int ScoreRecord_SendReply(Record* base, RedisModuleCtx* rctx){\n    ScoreRecord* sr = (ScoreRecord*)base;\n    RedisModule_ReplyWithArray(rctx, 2);\n    RedisModule_ReplyWithString(rctx, sr->key);\n    RedisModule_ReplyWithDouble(rctx, sr->score);\n    return REDISMODULE_OK;\n}\n\nstatic int ScoreRecord_RecordSerialize(ExecutionCtx* ctx, Gears_BufferWriter* bw, Record* base){\n    ScoreRecord* sr = (ScoreRecord*)base;\n    const char* keyStr = RedisModule_StringPtrLen(sr->key, NULL);\n    RedisGears_BWWriteString(bw, keyStr);\n    RedisGears_BWWriteBuffer(bw, (char*)(&(sr->score)), sizeof(sr->score));\n    return REDISMODULE_OK;\n}\n\nstatic Record* ScoreRecord_RecordDeserialize(ExecutionCtx* ctx, Gears_BufferReader* br){\n    ScoreRecord* sr = (ScoreRecord*)RedisGears_RecordCreate(ScoreRecordType);\n    const char* keyStr = RedisGears_BRReadString(br);\n    sr->key = RedisModule_CreateString(NULL, keyStr, strlen(keyStr));\n    size_t len;\n    char* data = RedisGears_BRReadBuffer(br, &len);\n    RedisModule_Assert(len == sizeof(float));\n    sr->score = *((float*)(data));\n\n    return &sr->baseRecord;\n}\n\nstatic void ScoreRecord_RecordFree(Record* base){\n    ScoreRecord* sr = (ScoreRecord*)base;\n    if(sr->key){\n        RedisModule_FreeString(NULL, sr->key);\n    }\n\n}\n\nstatic int HeapRecord_SendReply(Record* base, RedisModuleCtx* rctx){\n    RedisModule_Assert(false);\n    return REDISMODULE_OK;\n}\n\nstatic int HeapRecord_Serialize(ExecutionCtx* ctx, Gears_BufferWriter* bw, Record* base){\n    RedisModule_Assert(false);\n    return REDISMODULE_OK;\n}\n\nstatic Record* HeapRecord_Deserialize(ExecutionCtx* ctx, Gears_BufferReader* br){\n    RedisModule_Assert(false);\n    return REDISMODULE_OK;\n}\n\nstatic void HeapRecord_Free(Record* base){\n    HeapRecord* hr = (HeapRecord*)base;\n    mmh_free(hr->heap);\n}\n\nstatic void TopKArg_ObjectFree(void* arg){\n    RG_FREE(arg);\n}\n\nstatic void* TopKArg_ArgDuplicate(void* arg){\n    TopKArg* topK = arg;\n    TopKArg* topKDup = RG_ALLOC(sizeof(*topKDup));\n    topKDup->topK = topK->topK;\n    return topKDup;\n}\n\nstatic int TopKArg_ArgSerialize(FlatExecutionPlan* fep, void* arg, Gears_BufferWriter* bw, char** err){\n    TopKArg* topK = arg;\n    RedisGears_BWWriteLong(bw, topK->topK);\n    return REDISMODULE_OK;\n}\n\nstatic void* TopKArg_ArgDeserialize(FlatExecutionPlan* fep, Gears_BufferReader* br, int version, char** err){\n    TopKArg* topKDup = RG_ALLOC(sizeof(*topKDup));\n    topKDup->topK = RedisGears_BRReadLong(br);\n    return topKDup;\n}\n\nstatic char* TopKArg_ArgToString(void* arg){\n    return RG_STRDUP(\"I am topk argument :)\");\n}\n\n#define TopKTypeVersion 1\n\n#define VS_PLUGIN_NAME \"VECTOR_SIM\"\n#define REDISGEARSJVM_PLUGIN_VERSION 1\n\n#define VEC_TYPE_VERSION 1\n\nstatic void* VecDT_Load(RedisModuleIO *rdb, int encver){\n    RedisModuleString *keyName = RedisModule_LoadString(rdb);\n    size_t dataLen;\n    float* data = (float*)RedisModule_LoadStringBuffer(rdb, &dataLen);\n    RedisModule_Assert(dataLen == sizeof(float) * VEC_SIZE);\n\n    VecDT* vDT = vec_insert(keyName, data);\n\n    RedisModule_FreeString(NULL, keyName);\n    RedisModule_Free(data);\n\n    return vDT;\n}\n\nstatic void VecDT_Save(RedisModuleIO *rdb, void *value){\n    VecDT* vDT = value;\n\n    RedisModule_SaveString(rdb, vDT->keyName);\n    RedisModule_SaveStringBuffer(rdb, (char*)&HOLDER_VEC(vDT->holder, vDT->index), sizeof(float) * VEC_SIZE);\n}\n\nstatic void VecDT_Free(void *value){\n    VecDT* vDT = value;\n    VecsHolder* holder = vDT->holder;\n    size_t index = vDT->index;\n\n    RedisModule_FreeString(NULL, vDT->keyName);\n    RG_FREE(vDT);\n\n    if(!holder){\n        // we probably inside flush, the vector DT was detached and we can just return.\n        return;\n    }\n\n    // get the last vector\n    VecsHolder* lastVH = vecList[array_len(vecList) - 1];\n    --lastVH->size;\n    VecDT* lastVDT = HOLDER_VECDT(lastVH, lastVH->size);\n\n\n    if(lastVDT != vDT){\n        // swap last with current\n        memmove(&HOLDER_VEC(holder, index), &HOLDER_VEC(lastVH, lastVH->size), VEC_SIZE * sizeof(float));\n\n        HOLDER_VECDT(holder, index) = lastVDT;\n        lastVDT->holder = holder;\n        lastVDT->index = index;\n    }\n\n    if(lastVH->size == 0){\n        // free the holder, it has no more data.\n        RG_FREE(lastVH);\n        if(array_len(vecList) > 1){\n            vecList = array_trimm_cap(vecList, array_len(vecList) - 1);\n        }else{\n            array_free(vecList);\n            vecList = NULL;\n        }\n    }\n}\n\nstatic float scores[VEC_HOLDER_SIZE];\n\nstatic Record* VecReader_Next(ExecutionCtx* rctx, void* ctx){\n//    struct timeval stop, start;\n    if(!vecList){\n        return NULL;\n    }\n\n    VecReaderCtx* readerCtx = ctx;\n    RedisModuleCtx* redisCtx = RedisGears_GetRedisModuleCtx(rctx);\n    if(array_len(readerCtx->pendings) > 0){\n        return array_pop(readerCtx->pendings);\n    }\n\n    RedisGears_LockHanlderAcquire(redisCtx);\n\n    const float* b1 = readerCtx->vec;\n\n    while(readerCtx->index < array_len(vecList)){\n        VecsHolder* holder = vecList[readerCtx->index++];\n\n        cblas_sgemv(CblasRowMajor, CblasNoTrans, holder->size, VEC_SIZE, 1, holder->vecs, VEC_SIZE, b1, 1, 0, scores, 1);\n\n        for(size_t i = 0 ; i < MIN(holder->size, readerCtx->topK) ; ++i){\n            size_t index = cblas_isamax(holder->size, scores, 1);\n            ScoreRecord* s = (ScoreRecord*)RedisGears_RecordCreate(ScoreRecordType);\n            s->key = HOLDER_VECDT(holder, index)->keyName;\n            RedisModule_RetainString(NULL, s->key);\n            s->score = scores[index];\n            readerCtx->pendings = array_append(readerCtx->pendings, &s->baseRecord);\n            scores[index] = 0;\n        }\n\n        if(array_len(readerCtx->pendings) > 0){\n            RedisGears_LockHanlderRelease(redisCtx);\n            return array_pop(readerCtx->pendings);\n        }\n    }\n\n    RedisGears_LockHanlderRelease(redisCtx);\n\n    return NULL;\n}\n\nstatic void VecReader_Free(void* ctx){\n    VecReaderCtx_Free(ctx);\n}\n\nstatic int VecReader_Serialize(ExecutionCtx* ectx, void* ctx, Gears_BufferWriter* bw){\n    VecReaderCtx* readerCtx = ctx;\n    RedisGears_BWWriteBuffer(bw, (char*)readerCtx->vec, VEC_SIZE * sizeof(float));\n    RedisGears_BWWriteLong(bw, readerCtx->topK);\n    return REDISMODULE_OK;\n}\n\nstatic int VecReader_Deserialize(ExecutionCtx* ectx, void* ctx, Gears_BufferReader* br){\n    VecReaderCtx* readerCtx = ctx;\n    size_t dataLen;\n    float* data = (float*)RedisGears_BRReadBuffer(br, &dataLen);\n    RedisModule_Assert(dataLen == VEC_SIZE * sizeof(*data));\n\n    readerCtx->topK = RedisGears_BRReadLong(br);\n\n    memcpy(readerCtx->vec, data, VEC_SIZE * sizeof(*data));\n\n    return REDISMODULE_OK;\n}\n\nstatic Reader* VecReader_CreateReaderCallback(void* arg){\n    VecReaderCtx* ctx = arg;\n    if(!ctx){\n        ctx = VecReaderCtx_Create(NULL, 0);\n    }\n    Reader* r = RG_ALLOC(sizeof(*r));\n    *r = (Reader){\n        .ctx = ctx,\n        .next = VecReader_Next,\n        .free = VecReader_Free,\n        .serialize = VecReader_Serialize,\n        .deserialize = VecReader_Deserialize,\n    };\n    return r;\n}\n\nRedisGears_ReaderCallbacks VecReader = {\n        .create = VecReader_CreateReaderCallback,\n};\n\nstatic void OnFlush(struct RedisModuleCtx *ctx, RedisModuleEvent eid, uint64_t subevent, void *data){\n    if(subevent != REDISMODULE_SUBEVENT_FLUSHDB_START){\n        return;\n    }\n\n    if(!vecList){\n        return;\n    }\n\n    // before flush we need to clean all the Vector Holders and disconnect the keys\n    for(size_t i = 0 ; i < array_len(vecList) ; ++i){\n        VecsHolder* holder = vecList[i];\n        for(size_t j = 0 ; j < holder->size ; ++j){\n            VecDT* vDT = HOLDER_VECDT(holder, j);\n            vDT->holder = NULL;\n        }\n        RG_FREE(holder);\n    }\n\n    array_free(vecList);\n\n    vecList = NULL;\n}\n\nint RedisGears_OnLoad(RedisModuleCtx *ctx) {\n    openblas_set_num_threads(1);\n\n    if(RedisGears_InitAsGearPlugin(ctx, VS_PLUGIN_NAME, REDISGEARSJVM_PLUGIN_VERSION) != REDISMODULE_OK){\n        RedisModule_Log(ctx, \"warning\", \"Failed initialize RedisGears API\");\n        return REDISMODULE_ERR;\n    }\n\n    RedisModule_Log(ctx, \"warning\", \"OpenBlac num of threads: %d\", openblas_get_num_threads());\n\n    staticCtx = RedisModule_GetThreadSafeContext(NULL);\n\n    RedisModuleTypeMethods vecDT = {\n        .version = REDISMODULE_TYPE_METHOD_VERSION,\n        .rdb_load = VecDT_Load,\n        .rdb_save = VecDT_Save,\n        .free = VecDT_Free,\n    };\n\n    vecRedisDT = RedisModule_CreateDataType(ctx, \"vec_index\", VEC_TYPE_VERSION, &vecDT);\n    if (vecRedisDT == NULL) {\n        RedisModule_Log(ctx, \"error\", \"Could not create vector type\");\n        return REDISMODULE_ERR;\n    }\n\n    RGM_RegisterReader(VecReader);\n\n    ScoreRecordType = RedisGears_RecordTypeCreate(\"ScoreRecord\",\n                                                   sizeof(ScoreRecord),\n                                                   ScoreRecord_SendReply,\n                                                   ScoreRecord_RecordSerialize,\n                                                   ScoreRecord_RecordDeserialize,\n                                                   ScoreRecord_RecordFree);\n\n    HeapRecordType = RedisGears_RecordTypeCreate(\"HeapRecord\",\n                                                 sizeof(HeapRecord),\n                                                 HeapRecord_SendReply,\n                                                 HeapRecord_Serialize,\n                                                 HeapRecord_Deserialize,\n                                                 HeapRecord_Free);\n\n    ArgType* TopKType = RedisGears_CreateType(\"TopKType\",\n                                              TopKTypeVersion,\n                                              TopKArg_ObjectFree,\n                                              TopKArg_ArgDuplicate,\n                                              TopKArg_ArgSerialize,\n                                              TopKArg_ArgDeserialize,\n                                              TopKArg_ArgToString);\n\n    RGM_RegisterMap(to_score_records, NULL);\n    RGM_RegisterAccumulator(top_k, TopKType);\n\n    if (RedisModule_CreateCommand(ctx, \"rg.vec_sim\", vec_sim_command, \"readonly\", 0, 0, 0) != REDISMODULE_OK) {\n        RedisModule_Log(ctx, \"warning\", \"could not register command rg.vec_sim\");\n        return REDISMODULE_ERR;\n    }\n\n    if (RedisModule_CreateCommand(ctx, \"rg.vec_add\", vec_add_command, \"write deny-oom\", 1, 1, 1) != REDISMODULE_OK) {\n        RedisModule_Log(ctx, \"warning\", \"could not register command rg.vec_add\");\n        return REDISMODULE_ERR;\n    }\n\n    RedisModule_SubscribeToServerEvent(ctx, RedisModuleEvent_FlushDB, OnFlush);\n\n    return REDISMODULE_OK;\n}\n", "meta": {"hexsha": "59eb1169f5a4e54c213cf5dd2a2d328614b3fd66", "size": 18174, "ext": "c", "lang": "C", "max_stars_repo_path": "src/vector_similarity.c", "max_stars_repo_name": "rafie/VecSim", "max_stars_repo_head_hexsha": "15a637cc5ea4536d663ce6d5b7f29276a97cab8b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-03T08:56:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T08:56:28.000Z", "max_issues_repo_path": "src/vector_similarity.c", "max_issues_repo_name": "rafie/VecSim", "max_issues_repo_head_hexsha": "15a637cc5ea4536d663ce6d5b7f29276a97cab8b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vector_similarity.c", "max_forks_repo_name": "rafie/VecSim", "max_forks_repo_head_hexsha": "15a637cc5ea4536d663ce6d5b7f29276a97cab8b", "max_forks_repo_licenses": ["BSD-3-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.3602584814, "max_line_length": 121, "alphanum_fraction": 0.6442170133, "num_tokens": 4858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.3535410234080572}}
{"text": "#ifndef libceed_petsc_examples_bps_problem_data_h\n#define libceed_petsc_examples_bps_problem_data_h\n\n#include <ceed.h>\n#include <petsc.h>\n#include \"../include/bcfunctions.h\"\n#include \"../include/structs.h\"\n#include \"../qfunctions/bps/bp1.h\"\n#include \"../qfunctions/bps/bp2.h\"\n#include \"../qfunctions/bps/bp3.h\"\n#include \"../qfunctions/bps/bp4.h\"\n#include \"../qfunctions/bps/common.h\"\n\n// -----------------------------------------------------------------------------\n// BP Option Data\n// -----------------------------------------------------------------------------\n\n// BP options\ntypedef enum {\n  CEED_BP1 = 0, CEED_BP2 = 1, CEED_BP3 = 2,\n  CEED_BP4 = 3, CEED_BP5 = 4, CEED_BP6 = 5\n} BPType;\n\nBPData bp_options[6] = {\n  [CEED_BP1] = {\n    .num_comp_u = 1,\n    .num_comp_x = 3,\n    .topo_dim = 3,\n    .q_data_size = 1,\n    .q_extra = 1,\n    .setup_geo = SetupMassGeo,\n    .setup_rhs = SetupMassRhs,\n    .apply = Mass,\n    .error = Error,\n    .setup_geo_loc = SetupMassGeo_loc,\n    .setup_rhs_loc = SetupMassRhs_loc,\n    .apply_loc = Mass_loc,\n    .error_loc = Error_loc,\n    .in_mode = CEED_EVAL_INTERP,\n    .out_mode = CEED_EVAL_INTERP,\n    .q_mode = CEED_GAUSS,\n    .enforce_bc = PETSC_FALSE,\n    .bc_func = BCsMass\n  },\n  [CEED_BP2] = {\n    .num_comp_u = 3,\n    .num_comp_x = 3,\n    .topo_dim = 3,\n    .q_data_size = 1,\n    .q_extra = 1,\n    .setup_geo = SetupMassGeo,\n    .setup_rhs = SetupMassRhs3,\n    .apply = Mass3,\n    .error = Error3,\n    .setup_geo_loc = SetupMassGeo_loc,\n    .setup_rhs_loc = SetupMassRhs3_loc,\n    .apply_loc = Mass3_loc,\n    .error_loc = Error3_loc,\n    .in_mode = CEED_EVAL_INTERP,\n    .out_mode = CEED_EVAL_INTERP,\n    .q_mode = CEED_GAUSS,\n    .enforce_bc = PETSC_FALSE,\n    .bc_func = BCsMass\n  },\n  [CEED_BP3] = {\n    .num_comp_u = 1,\n    .num_comp_x = 3,\n    .topo_dim = 3,\n    .q_data_size = 7,\n    .q_extra = 1,\n    .setup_geo = SetupDiffGeo,\n    .setup_rhs = SetupDiffRhs,\n    .apply = Diff,\n    .error = Error,\n    .setup_geo_loc = SetupDiffGeo_loc,\n    .setup_rhs_loc = SetupDiffRhs_loc,\n    .apply_loc = Diff_loc,\n    .error_loc = Error_loc,\n    .in_mode = CEED_EVAL_GRAD,\n    .out_mode = CEED_EVAL_GRAD,\n    .q_mode = CEED_GAUSS,\n    .enforce_bc = PETSC_TRUE,\n    .bc_func = BCsDiff\n  },\n  [CEED_BP4] = {\n    .num_comp_u = 3,\n    .num_comp_x = 3,\n    .topo_dim = 3,\n    .q_data_size = 7,\n    .q_extra = 1,\n    .setup_geo = SetupDiffGeo,\n    .setup_rhs = SetupDiffRhs3,\n    .apply = Diff3,\n    .error = Error3,\n    .setup_geo_loc = SetupDiffGeo_loc,\n    .setup_rhs_loc = SetupDiffRhs3_loc,\n    .apply_loc = Diff3_loc,\n    .error_loc = Error3_loc,\n    .in_mode = CEED_EVAL_GRAD,\n    .out_mode = CEED_EVAL_GRAD,\n    .q_mode = CEED_GAUSS,\n    .enforce_bc = PETSC_TRUE,\n    .bc_func = BCsDiff\n  },\n  [CEED_BP5] = {\n    .num_comp_u = 1,\n    .num_comp_x = 3,\n    .topo_dim = 3,\n    .q_data_size = 7,\n    .q_extra = 0,\n    .setup_geo = SetupDiffGeo,\n    .setup_rhs = SetupDiffRhs,\n    .apply = Diff,\n    .error = Error,\n    .setup_geo_loc = SetupDiffGeo_loc,\n    .setup_rhs_loc = SetupDiffRhs_loc,\n    .apply_loc = Diff_loc,\n    .error_loc = Error_loc,\n    .in_mode = CEED_EVAL_GRAD,\n    .out_mode = CEED_EVAL_GRAD,\n    .q_mode = CEED_GAUSS_LOBATTO,\n    .enforce_bc = PETSC_TRUE,\n    .bc_func = BCsDiff\n  },\n  [CEED_BP6] = {\n    .num_comp_u = 3,\n    .num_comp_x = 3,\n    .topo_dim = 3,\n    .q_data_size = 7,\n    .q_extra = 0,\n    .setup_geo = SetupDiffGeo,\n    .setup_rhs = SetupDiffRhs3,\n    .apply = Diff3,\n    .error = Error3,\n    .setup_geo_loc = SetupDiffGeo_loc,\n    .setup_rhs_loc = SetupDiffRhs3_loc,\n    .apply_loc = Diff3_loc,\n    .error_loc = Error3_loc,\n    .in_mode = CEED_EVAL_GRAD,\n    .out_mode = CEED_EVAL_GRAD,\n    .q_mode = CEED_GAUSS_LOBATTO,\n    .enforce_bc = PETSC_TRUE,\n    .bc_func = BCsDiff\n  }\n};\n\n#endif // libceed_petsc_examples_bps_problem_data_h\n", "meta": {"hexsha": "d63e595c52d81a593f788f24c00a986ff73d8072", "size": 3811, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/petsc/include/bpsproblemdata.h", "max_stars_repo_name": "wence-/libCEED", "max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/petsc/include/bpsproblemdata.h", "max_issues_repo_name": "wence-/libCEED", "max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "max_issues_repo_licenses": ["BSD-2-Clause"], "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/petsc/include/bpsproblemdata.h", "max_forks_repo_name": "wence-/libCEED", "max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b", "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.75, "max_line_length": 80, "alphanum_fraction": 0.6100760955, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.3534444011817134}}
{"text": "#include <pthread.h>\n#include <math.h>\n#include <fftw.h>\n#include <stdio.h>\n\n//C -> Very ugly code\n\n//DEFINITION OF COMPLEX NUMBERS\ntypedef struct {\n  double re, im;\n} mycom;\n\n//DEFINITION OF DATA ARRAY NEEDED FOR THE TRANSFORMATION (small space)\ntypedef struct {\n  double* m;\n  double* vi;\n  double* vo;\n  int*    nrop;\n} transdata;\n\n\n//DEFINITION OF DATA ARRAY NEEDED FOR THE TRANSFORMATION (large space)\ntypedef struct {\n  double* m;\n  double* vi;\n  double* vo;\n  long long int*    nrop;\n} ltransdata;\n\n\n//THREAD FUNCTION FOR FORWARD TRANSFORMATION (small space)\nvoid transforeT(void* td){\n  transdata* Td = (transdata *)td;\n  double* Mat       = Td->m;\n  double* Vec_in    = Td->vi;\n  double* Vec_out   = Td->vo;\n  int*       Nrop   = Td->nrop;\n  int x, y;\n  \n  for(x = 0; x < 2* *Nrop; x++){\n    Vec_out[x] = 0.;\n  }\n  \n \n  for(x = 0; x < *Nrop; x++){\n    for(y = 0; y < *Nrop; y++){\n      Vec_out[2*x]    +=     Mat[(x* (*Nrop))+y]*Vec_in[2*y];\n      Vec_out[2*x+1]  +=     Mat[(x* (*Nrop))+y]*Vec_in[2*y+1];\n    }\n  }\n  \n}\n\n//THREAD FUNCTION FOR FORWARD TRANSFORMATION (large space)\nvoid ltransforeT(void* td){\n  ltransdata* Td = (ltransdata *)td;\n  double* Mat       = Td->m;\n  double* Vec_in    = Td->vi;\n  double* Vec_out   = Td->vo;\n  long long int*       Nrop   = Td->nrop;\n  long long int x, y;\n  \n  for(x = 0; x < 2* *Nrop; x++){\n    Vec_out[x] = 0.;\n  }\n  \n \n  for(x = 0; x < *Nrop; x++){\n    for(y = 0; y < *Nrop; y++){\n      Vec_out[2*x]    +=     Mat[(x* (*Nrop))+y]*Vec_in[2*y];\n      Vec_out[2*x+1]  +=     Mat[(x* (*Nrop))+y]*Vec_in[2*y+1];\n    }\n  }\n  \n}\n\n\n//THREAD FUNCTION FOR BACKWARD TRANSFORMATION (small space)\nvoid transbackT(void* td){\n  transdata* Td = (transdata *)td;\n  double* Mat       = Td->m;\n  double* Vec_in    = Td->vi;\n  double* Vec_out   = Td->vo;\n  int*       Nrop   = Td->nrop;\n  int x, y;\n  \n  for(x = 0; x < 2* *Nrop; x++){\n    Vec_out[x] = 0.;\n  }\n  \n  for(x = 0; x < *Nrop; x++){\n    for(y = 0; y < *Nrop; y++){\n      Vec_out[2*y]    +=     Mat[x* *Nrop+y]*Vec_in[2*x];\n      Vec_out[2*y+1]  +=     Mat[x* *Nrop+y]*Vec_in[2*x+1];\n    }\n  }\n  \n}\n\n//THREAD FUNCTION FOR BACKWARD TRANSFORMATION (large space)\nvoid ltransbackT(void* td){\n  ltransdata* Td = (ltransdata *)td;\n  double* Mat       = Td->m;\n  double* Vec_in    = Td->vi;\n  double* Vec_out   = Td->vo;\n  long long int*       Nrop   = Td->nrop;\n  long long int x, y;\n  \n  for(x = 0; x < 2* *Nrop; x++){\n    Vec_out[x] = 0.;\n  }\n  \n  for(x = 0; x < *Nrop; x++){\n    for(y = 0; y < *Nrop; y++){\n      Vec_out[2*y]    +=     Mat[x* *Nrop+y]*Vec_in[2*x];\n      Vec_out[2*y+1]  +=     Mat[x* *Nrop+y]*Vec_in[2*x+1];\n    }\n  }\n  \n}\n\n//MAKE TRANSFORMATION MULTI THREADED (small space) DIR=1 is forward !!\nvoid mk_thread_trans(int dir, double* mat1, double* mat2, mycom* vec_in1, mycom* vec_in2,\n\t\t     mycom* vec_out1, mycom* vec_out2, int* nrop1, int* nrop2){\n  pthread_t thread1, thread2;  \n  int  iret1, iret2;\n  transdata td1, td2;\n\n  td1.m    = mat1;\n  td1.vi   = (double* ) vec_in1;\n  td1.vo   = (double* ) vec_out1;\n  td1.nrop = nrop1;  \n\n  td2.m    = mat2;\n  td2.vi   = (double* ) vec_in2;\n  td2.vo   = (double* ) vec_out2;\n  td2.nrop = nrop2;  \n\n  if(dir == 1){\n    iret1 = pthread_create( &thread1, NULL,  (void* ) &transforeT , (void*) &td1);\n    iret2 = pthread_create( &thread2, NULL,  (void* ) &transforeT , (void*) &td2);\n  }else{\n    iret1 = pthread_create( &thread1, NULL,  (void* ) &transbackT , (void*) &td1);\n    iret2 = pthread_create( &thread2, NULL,  (void* ) &transbackT , (void*) &td2);\n  }\n  \n  \n  pthread_join( thread1, NULL);\n  pthread_join( thread2, NULL); \n  \n}\n\n//MAKE TRANSFORMATION MULTI THREADED (large space) DIR=1 is forward !!\nvoid lmk_thread_trans(int dir, double* mat1, double* mat2, mycom* vec_in1, mycom* vec_in2,\n\t\t      mycom* vec_out1, mycom* vec_out2, long long int* nrop1, long long int* nrop2){\n  pthread_t thread1, thread2;  \n  int  iret1, iret2;\n  ltransdata td1, td2;\n\n  td1.m    = mat1;\n  td1.vi   = (double* ) vec_in1;\n  td1.vo   = (double* ) vec_out1;\n  td1.nrop = nrop1;  \n\n  td2.m    = mat2;\n  td2.vi   = (double* ) vec_in2;\n  td2.vo   = (double* ) vec_out2;\n  td2.nrop = nrop2;  \n\n  if(dir == 1){\n    iret1 = pthread_create( &thread1, NULL,  (void* ) &ltransforeT , (void*) &td1);\n    iret2 = pthread_create( &thread2, NULL,  (void* ) &ltransforeT , (void*) &td2);\n  }else{\n    iret1 = pthread_create( &thread1, NULL,  (void* ) &ltransbackT , (void*) &td1);\n    iret2 = pthread_create( &thread2, NULL,  (void* ) &ltransbackT , (void*) &td2);\n  }\n  \n  \n  pthread_join( thread1, NULL);\n  pthread_join( thread2, NULL); \n  \n}\n", "meta": {"hexsha": "29b08ed6a267f0b14e5aa8ae8a06e3fce5a0bf7b", "size": 4576, "ext": "c", "lang": "C", "max_stars_repo_path": "TC-programs/OLD_CIS3D/POPULS/ops_mt.c", "max_stars_repo_name": "sklinkusch/scripts", "max_stars_repo_head_hexsha": "a717cadb559db823a0d5172545661d5afa2715e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TC-programs/OLD_CIS3D/POPULS/ops_mt.c", "max_issues_repo_name": "sklinkusch/scripts", "max_issues_repo_head_hexsha": "a717cadb559db823a0d5172545661d5afa2715e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TC-programs/OLD_CIS3D/POPULS/ops_mt.c", "max_forks_repo_name": "sklinkusch/scripts", "max_forks_repo_head_hexsha": "a717cadb559db823a0d5172545661d5afa2715e7", "max_forks_repo_licenses": ["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.0054644809, "max_line_length": 90, "alphanum_fraction": 0.5655594406, "num_tokens": 1732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3534158944958701}}
{"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C header for the initialization of the instrumental noise for LIGO/VIRGO detectors.\n *\n *\n */\n\n#ifndef _LLVNOISE_H\n#define _LLVNOISE_H\n\n#define _XOPEN_SOURCE 500\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <stdbool.h>\n#include <string.h>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_bspline.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_min.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_complex.h>\n\n#include \"constants.h\"\n\n\n/************************************************************************/\n/****** Global variables storing min and max f for the noise PSD  *******/\n\nextern double __LLVSimFD_LHONoise_fLow;\nextern double __LLVSimFD_LHONoise_fHigh;\nextern double __LLVSimFD_LLONoise_fLow;\nextern double __LLVSimFD_LLONoise_fHigh;\nextern double __LLVSimFD_VIRGONoise_fLow;\nextern double __LLVSimFD_VIRGONoise_fHigh;\n\n/**************************************************************************/\n/****** Prototypes: functions loading and evaluating the noise PSD  *******/\n\n/* Function parsing the environment variable $LLV_NOISE_DATA_PATH and trying to run LLVSimFD_Noise_Init in each */\nint LLVSimFD_Noise_Init_ParsePath(void);\n/* Function loading the noise data from a directory */\nint LLVSimFD_Noise_Init(const char dir[]);\n\n/* The noise functions themselves */\ndouble NoiseSnLHO(const double f);\ndouble NoiseSnLLO(const double f);\ndouble NoiseSnVIRGO(const double f);\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _LLVNOISE_H */\n", "meta": {"hexsha": "e1bbd48ba99036be2c54526496f793bfdbf6da0f", "size": 1769, "ext": "h", "lang": "C", "max_stars_repo_path": "LLVsim/LLVnoise.h", "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_issues_repo_path": "LLVsim/LLVnoise.h", "max_issues_repo_name": "titodalcanton/flare", "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LLVsim/LLVnoise.h", "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "avg_line_length": 25.2714285714, "max_line_length": 114, "alphanum_fraction": 0.6930469192, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3534158944958701}}
{"text": "/* psl.c\n////\nProvide a library of gsl functions.\n\nFeatures:\n- request calculation via message\n- function lookup\n- inlets-on-demand\n\nAuthor: shakfu\nRepo: https://github.com/shakfu/pd-psl.git\n\n*/\n#include <math.h>\n#include <string.h>\n\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_sf_airy.h>\n#include <gsl/gsl_sf_bessel.h>\n#include <gsl/gsl_sf_clausen.h>\n#include <gsl/gsl_sf_dawson.h>\n#include <gsl/gsl_sf_debye.h>\n\n#include \"m_pd.h\"\n#include \"tinyexpr.h\"\n\n\n// macros and defines\n//  ---------------------------------------------------------------------------\n\n\n#define MAX_ARGS 6\n#define STR_BUF_SIZE 1000\n\n\n// function lookup infratructure\n// ---------------------------------------------------------------------------\n\nunsigned long hash(const char *str) {\n    unsigned int h = 0;\n    int c;\n\n    while ((c = *str++)) \n        h += (h << 1) + c;\n\n    return h;\n}\n\n\nenum FUNC {\n    ADD = 1273,\n    LOG1P = 12931,\n    EXPM1 = 12805,\n    HYPOT = 13148,\n    HYPOT3 = 39495,\n    ACOSH = 11978,\n    ASINH = 12341,\n    ATANH = 12296,\n    LDEXP = 12829,\n    POW_INT = 122216,\n    POW_2 = 13475,\n    POW_3 = 13476,\n    POW_4 = 13477,\n    POW_5 = 13478,\n    POW_6 = 13479,\n    POW_7 = 13480,\n    POW_8 = 13481,\n    POW_9 = 13482,\n    RANDO = 13254,\n    FCMP = 4084,\n    AIRY_AI = 109980,\n    AIRY_BI = 109983,\n    BESSEL_J0 = 987963,\n    BESSEL_J1 = 987964,\n    BESSEL_JN = 988025,\n    BESSEL_Y0 = 988008,\n    BESSEL_Y1 = 988009,\n    BESSEL_YN = 988070,\n    BESSEL_I0 = 987960,\n    BESSEL_I1 = 987961,\n    BESSEL_IN = 988022,\n    CLAUSEN = 110879,\n    DAWSON = 36848,\n    DEBYE_1 = 109891,\n    DEBYE_2 = 109892,\n    DEBYE_3 = 109893,\n    DEBYE_4 = 109894,\n};\n\n\n// forward declarations / prototypes\n// ---------------------------------------------------------------------------\n\n\ntypedef struct _psl t_psl;\n\nvoid select_default_function(t_psl *x, t_symbol *s);\n\n\n// psl class objects\n// ---------------------------------------------------------------------------\n\n\nstatic t_class *psl_class;\n\nstatic t_class *psl_inlet_class;\n\n\n// psl class struct (data-space)\n// ---------------------------------------------------------------------------\n\n\ntypedef void (*unary_func)(t_psl *, t_floatarg);\ntypedef void (*binary_func)(t_psl *, t_floatarg, t_floatarg);\ntypedef void (*tri_func)(t_psl *, t_floatarg, t_floatarg, t_floatarg);\n\n\ntypedef struct _psl_inlet\n{\n    t_class *x_pd;  // minimal pd object.\n    t_psl   *owner; // the owning object to forward inlet messages to.\n    int     id;     // the number of this inlet.\n} t_psl_inlet;\n\n\ntypedef struct _psl {\n    t_object x_obj;\n\n    // assigned function\n    t_symbol *func_name;\n    int nargs;\n\n    // function slots\n    unary_func ufunc;\n    binary_func bfunc;\n    tri_func tfunc;\n\n    // param_array\n    t_float *arg_array;\n\n    // for expression\n    char expr_buffer[MAXPDSTRING];\n\n    // inlets\n    int inlets;          // # of extra inlets in addition to default\n    t_psl_inlet *ins;    // the inlets themselves\n\n    // outlets\n    t_outlet *out_f;\n} t_psl;\n\n\n// psl class methods (operation-space)\n// ---------------------------------------------------------------------------\n\n\n// typed-methods\n\nvoid psl_bang(t_psl *x) {\n    if (x->nargs == 1 && x->inlets == 0) {\n        x->ufunc(x, x->arg_array[0]);\n    }\n\n    if (x->nargs == 2 && x->inlets == 1) {\n        x->bfunc(x, x->arg_array[0], x->arg_array[1]);\n    }\n\n    if (x->nargs == 3 && x->inlets == 2) {\n        x->tfunc(x, x->arg_array[0], x->arg_array[1], x->arg_array[2]);\n\n    }\n\n}\n\nvoid psl_float(t_psl *x, t_floatarg f) {\n    post(\"psl_float: %f\", f);\n    if (x->nargs > 0) {\n        x->arg_array[0] = f;\n        psl_bang(x);\n    } else {\n        post(\"nothing to do: no function selected.\");\n        outlet_float(x->out_f, f);\n    }\n}\n\nvoid psl_list(t_psl *x, t_symbol *s, int argc, t_atom *argv) {\n\n    // atom_post(\"psl_list: \", argc, argv);\n\n    if (s == gensym(\"list\")) {\n        post(\"s: list\");\n\n        if (argc == 0) {\n            return;\n        }\n\n        if (argc == 1) {\n            if (argv->a_type == A_FLOAT) {\n                float f = atom_getfloat(argv);\n                post(\"got float: %f\", f);\n                x->ufunc(x, f);\n                return;\n            }\n        }\n\n        if (argc == 2) {\n            char buf[STR_BUF_SIZE];\n            for (int i = 0; i < argc; i++) {\n                atom_string((argv+i), buf, STR_BUF_SIZE);\n                post(\"arg+%i: %s\", i, buf);\n            }\n            if (argv->a_type == A_FLOAT && (argv + 1)->a_type == A_FLOAT) {\n                float f1 = atom_getfloat(argv+0);\n                float f2 = atom_getfloat(argv+1);\n                post(\"f(%.2f, %.2f)\", f1, f2);\n                x->bfunc(x, f1, f2);\n                return;\n            }\n        }\n\n        if (argc == 3) {\n            char buf[STR_BUF_SIZE];\n            for (int i = 0; i < argc; i++) {\n                atom_string((argv+i), buf, STR_BUF_SIZE);\n                post(\"arg+%i: %s\", i, buf);\n            }\n            if (argv->a_type == A_FLOAT && (argv+1)->a_type == A_FLOAT && (argv+2)->a_type == A_FLOAT) {\n                float f1 = atom_getfloat(argv+0);\n                float f2 = atom_getfloat(argv+1);\n                float f3 = atom_getfloat(argv+2);                \n                post(\"f(%.2f, %.2f, %.2f)\", f1, f2, f3);\n                x->tfunc(x, f1, f2, f3);\n                return;\n            }\n        }\n    }\n\n    post(\"list body\");\n    return;\n\n    // error:\n    //     pd_error(x, \"psl_list error: incorrect arg type\");\n}\n\n\n\nvoid psl_symbol(t_psl *x, t_symbol *s) {\n    post(\"s: %s\", s->s_name);\n\n    // local buffer\n    int length = strlen(s->s_name);\n    char *buf = (char *)malloc(length * sizeof(char));\n    strcpy(buf, s->s_name);\n    post(\"buf: %s\", buf);\n\n    // clear expr_buffer\n    memset(x->expr_buffer, 0, MAXPDSTRING);\n\n    int j = 0;\n    for (int i = 0; i < length; i++) {\n        // remove escape `\\` required for commas\n        if (buf[i] != '\\\\') {\n            x->expr_buffer[j++] = buf[i];\n        } else if (x->expr_buffer[j - 1] == ' ') {\n            j--;\n        }\n    }\n    x->expr_buffer[length] = '\\0';\n    free(buf);\n\n    post(\"x->expr_buffer: %s\", x->expr_buffer);\n\n    te_variable vars[] = {\n        {\"hypot\", gsl_hypot, TE_FUNCTION2, NULL} /* TE_FUNCTION2 used because my_sum takes two arguments. */\n    };\n\n    te_expr *expr = te_compile(x->expr_buffer, vars, 2, 0);\n    const double res = te_eval(expr);\n    te_free(expr);\n    outlet_float(x->out_f, res);\n}\n\n\n\n\n\n\n// message-methods\n\nvoid psl_add(t_psl *x, t_floatarg f1, t_floatarg f2) {\n    outlet_float(x->out_f, f1+f2);\n}\n\nvoid psl_rando(t_psl *x, t_floatarg n, t_floatarg seed) {\n    post(\"rando: n:%.2f seed:%.2f\", n, seed);\n    gsl_rng_env_setup();\n\n    int argc = (int)n;\n    int _seed = (int)seed;\n\n    gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);\n    gsl_rng_set(r, _seed);\n\n    t_atom av[argc];\n    for (int i = 0; i < argc; i++) {\n        SETFLOAT(av + i, gsl_rng_uniform(r));\n    }\n    outlet_list(x->out_f, gensym(\"list\"), argc, av);\n\n    gsl_rng_free(r);\n}\n\nvoid psl_airy_ai(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_airy_Ai(f, GSL_PREC_APPROX));\n}\n\nvoid psl_airy_bi(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_airy_Bi(f, GSL_PREC_APPROX));\n}\n\nvoid psl_log1p(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_log1p(f));\n}\n\nvoid psl_expm1(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_expm1(f));\n}\n\nvoid psl_hypot(t_psl *x, t_floatarg f1, t_floatarg f2) {\n    outlet_float(x->out_f, gsl_hypot(f1, f2));\n}\n\nvoid psl_hypot3(t_psl *x, t_floatarg f1, t_floatarg f2, t_floatarg f3) {\n    outlet_float(x->out_f, gsl_hypot3(f1, f2, f3));\n}\n\nvoid psl_acosh(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_acosh(f));\n}\n\nvoid psl_asinh(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_asinh(f));\n}\n\nvoid psl_atanh(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_atanh(f));\n}\n\nvoid psl_ldexp(t_psl *x, t_floatarg f1, t_floatarg f2) {\n    outlet_float(x->out_f, gsl_ldexp(f1, f2));\n}\n\nvoid psl_pow_int(t_psl *x, t_floatarg f1, t_floatarg f2) {\n    outlet_float(x->out_f, gsl_pow_int(f1, f2));\n}\n\nvoid psl_pow_2(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_pow_2(f));\n}\n\nvoid psl_pow_3(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_pow_3(f));\n}\n\nvoid psl_pow_4(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_pow_4(f));\n}\n\nvoid psl_pow_5(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_pow_5(f));\n}\n\nvoid psl_pow_6(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_pow_6(f));\n}\n\nvoid psl_pow_7(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_pow_7(f));\n}\n\nvoid psl_pow_8(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_pow_8(f));\n}\n\nvoid psl_pow_9(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_pow_9(f));\n}\n\nvoid psl_fcmp(t_psl *x, t_floatarg f1, t_floatarg f2, t_floatarg f3) {\n    outlet_float(x->out_f, gsl_fcmp(f1, f2, f3));\n}\n\nvoid psl_bessel_j0(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_bessel_J0(f));\n}\n\nvoid psl_bessel_j1(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_bessel_J1(f));\n}\n\nvoid psl_bessel_jn(t_psl *x, t_floatarg f1, t_floatarg f2) {\n    outlet_float(x->out_f, gsl_sf_bessel_Jn(f1, f2));\n}\n\nvoid psl_bessel_y0(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_bessel_Y0(f));\n}\n\nvoid psl_bessel_y1(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_bessel_Y1(f));\n}\n\nvoid psl_bessel_yn(t_psl *x, t_floatarg f1, t_floatarg f2) {\n    outlet_float(x->out_f, gsl_sf_bessel_Yn(f1, f2));\n}\n\nvoid psl_bessel_i0(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_bessel_I0(f));\n}\n\nvoid psl_bessel_i1(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_bessel_I1(f));\n}\n\nvoid psl_bessel_in(t_psl *x, t_floatarg f1, t_floatarg f2) {\n    outlet_float(x->out_f, gsl_sf_bessel_In(f1, f2));\n}\n\nvoid psl_clausen(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_clausen(f));\n}\n\nvoid psl_dawson(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_dawson(f));\n}\n\nvoid psl_debye_1(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_debye_1(f));\n}\n\nvoid psl_debye_2(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_debye_2(f));\n}\n\nvoid psl_debye_3(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_debye_3(f));\n}\n\nvoid psl_debye_4(t_psl *x, t_floatarg f) {\n    outlet_float(x->out_f, gsl_sf_debye_4(f));\n}\n\n\n\n// function selection\n//---------------------------------------------------------------------------\n\n\n// set default function from symbol\nvoid select_default_function(t_psl *x, t_symbol *s) {\n    x->func_name = s;\n    post(\"func %s selected\", s->s_name);\n\n    switch (hash(s->s_name)) {\n        case ADD:\n            x->nargs = 2;\n            x->bfunc = &psl_add;\n            break;\n        case LOG1P:\n            x->nargs = 1;\n            x->ufunc = &psl_log1p;\n            break;\n        case EXPM1:\n            x->nargs = 1;\n            x->ufunc = &psl_expm1;\n            break;\n        case HYPOT:\n            x->nargs = 2;\n            x->bfunc = &psl_hypot;\n            break;\n        case HYPOT3:\n            x->nargs = 3;\n            x->tfunc = &psl_hypot3;\n            break;\n        case ACOSH:\n            x->nargs = 1;\n            x->ufunc = &psl_acosh;\n            break;\n        case ASINH:\n            x->nargs = 1;\n            x->ufunc = &psl_asinh;\n            break;\n        case ATANH:\n            x->nargs = 1;\n            x->ufunc = &psl_atanh;\n            break;\n        case LDEXP:\n            x->nargs = 2;\n            x->bfunc = &psl_ldexp;\n            break;\n        case POW_INT:\n            x->nargs = 2;\n            x->bfunc = &psl_pow_int;\n            break;\n        case POW_2:\n            x->nargs = 1;\n            x->ufunc = &psl_pow_2;\n            break;\n        case POW_3:\n            x->nargs = 1;\n            x->ufunc = &psl_pow_3;\n            break;\n        case POW_4:\n            x->nargs = 1;\n            x->ufunc = &psl_pow_4;\n            break;\n        case POW_5:\n            x->nargs = 1;\n            x->ufunc = &psl_pow_5;\n            break;\n        case POW_6:\n            x->nargs = 1;\n            x->ufunc = &psl_pow_6;\n            break;\n        case POW_7:\n            x->nargs = 1;\n            x->ufunc = &psl_pow_7;\n            break;\n        case POW_8:\n            x->nargs = 1;\n            x->ufunc = &psl_pow_8;\n            break;\n        case POW_9:\n            x->nargs = 1;\n            x->ufunc = &psl_pow_9;\n            break;\n        case RANDO:\n            x->nargs = 2;\n            x->bfunc = &psl_rando;\n            break;\n        case FCMP:\n            x->nargs = 3;\n            x->tfunc = &psl_fcmp;\n            break;\n        case AIRY_AI:\n            x->nargs = 1;\n            x->ufunc = &psl_airy_ai;\n            break;\n        case AIRY_BI:\n            x->nargs = 1;\n            x->ufunc = &psl_airy_bi;\n            break;\n        case BESSEL_J0:\n            x->nargs = 1;\n            x->ufunc = &psl_bessel_j0;\n            break;\n        case BESSEL_J1:\n            x->nargs = 1;\n            x->ufunc = &psl_bessel_j1;\n            break;\n        case BESSEL_JN:\n            x->nargs = 2;\n            x->bfunc = &psl_bessel_jn;\n            break;\n        case BESSEL_Y0:\n            x->nargs = 1;\n            x->ufunc = &psl_bessel_y0;\n            break;\n        case BESSEL_Y1:\n            x->nargs = 1;\n            x->ufunc = &psl_bessel_y1;\n            break;\n        case BESSEL_YN:\n            x->nargs = 2;\n            x->bfunc = &psl_bessel_yn;\n            break;\n        case BESSEL_I0:\n            x->nargs = 1;\n            x->ufunc = &psl_bessel_i0;\n            break;\n        case BESSEL_I1:\n            x->nargs = 1;\n            x->ufunc = &psl_bessel_i1;\n            break;\n        case BESSEL_IN:\n            x->nargs = 2;\n            x->bfunc = &psl_bessel_in;\n            break;\n        case CLAUSEN:\n            x->nargs = 1;\n            x->ufunc = &psl_clausen;\n            break;\n        case DAWSON:\n            x->nargs = 1;\n            x->ufunc = &psl_dawson;\n            break;\n        case DEBYE_1:\n            x->nargs = 1;\n            x->ufunc = &psl_debye_1;\n            break;\n        case DEBYE_2:\n            x->nargs = 1;\n            x->ufunc = &psl_debye_2;\n            break;\n        case DEBYE_3:\n            x->nargs = 1;\n            x->ufunc = &psl_debye_3;\n            break;\n        case DEBYE_4:\n            x->nargs = 1;\n            x->ufunc = &psl_debye_4;\n            break;\n        default:\n            post(\"func selection failed, reverting to defaults\");\n            break;\n   }\n}\n\n\n// psl-inlet funcs\n// ---------------------------------------------------------------------------\n\n\nstatic void psl_inlet_float(t_psl_inlet *x, float f)\n{\n    x->owner->arg_array[x->id+1] = f;\n    // outlet_float(x->owner->out_f, x->id + f);\n    post(\"x->owner->arg_array[x->id]: %.02f\", x->owner->arg_array[x->id+1]);\n    psl_bang(x->owner);\n}\n\n\n// psl class constructor\n// ---------------------------------------------------------------------------\n\n\nvoid *psl_new(t_symbol *s) {\n    t_psl *x = (t_psl *)pd_new(psl_class);\n\n    // initialize variables\n    x->nargs = 0;\n    x->inlets = 0;\n    x->ufunc = NULL;\n    x->bfunc = NULL;\n    x->tfunc = NULL;\n\n    select_default_function(x, s);\n    // sets x->nargs to correct number\n\n    // create inlets\n    x->inlets = x->nargs - 1;\n    x->ins = (t_psl_inlet *)getbytes(x->inlets * sizeof(*x->ins));\n    x->arg_array = malloc(x->inlets * sizeof(float));\n    \n    for (int i=0; i < x->inlets; i++) {\n        x->ins[i].x_pd = psl_inlet_class;\n        x->ins[i].owner = x;\n        x->ins[i].id = i;\n        x->arg_array[i] = 0.0;\n        inlet_new((t_object *)x, &(x->ins[i].x_pd), 0, 0);\n    }\n\n\n    // initialize outlets\n    x->out_f = outlet_new(&x->x_obj, &s_float);\n\n    return (void *)x;\n}\n\n\n// psl class destructor\n// ---------------------------------------------------------------------------\n\n\n// TODO: not sure if this is correct!\nvoid psl_free(t_psl *x) {\n    free(x->arg_array);\n    freebytes(x->ins, x->inlets * sizeof(*x->ins));\n    post(\"DONE\");\n}\n\n\n// psl class setup\n// ---------------------------------------------------------------------------\n\n\nvoid psl_setup(void) {\n\n    psl_inlet_class = class_new(gensym(\"psl-inlet\"), \n                                0, 0, \n                                sizeof(t_psl_inlet),\n                                CLASS_PD,\n                                0);\n\n    if (psl_inlet_class) {\n        class_addfloat(psl_inlet_class, (t_method)psl_inlet_float);\n    }\n\n    psl_class = class_new(gensym(\"psl\"),\n                        (t_newmethod)psl_new,\n                        (t_method)psl_free,  // destructor\n                        sizeof(t_psl), \n                        CLASS_DEFAULT, \n                        A_DEFSYMBOL, \n                        0);\n\n    // typed methods\n    class_addbang(psl_class, psl_bang);\n    class_addfloat(psl_class, psl_float);\n    class_addlist(psl_class, psl_list);\n    class_addsymbol(psl_class, psl_symbol);\n\n\n    // message methods\n\n    // class-addmethods\n    class_addmethod(psl_class, (t_method)psl_add,  gensym(\"add\"), A_DEFFLOAT, A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_log1p,  gensym(\"log1p\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_expm1,  gensym(\"expm1\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_hypot,  gensym(\"hypot\"), A_DEFFLOAT, A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_hypot3,  gensym(\"hypot3\"), A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_acosh,  gensym(\"acosh\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_asinh,  gensym(\"asinh\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_atanh,  gensym(\"atanh\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_ldexp,  gensym(\"ldexp\"), A_DEFFLOAT, A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_pow_int,  gensym(\"pow_int\"), A_DEFFLOAT, A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_pow_2,  gensym(\"pow_2\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_pow_3,  gensym(\"pow_3\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_pow_4,  gensym(\"pow_4\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_pow_5,  gensym(\"pow_5\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_pow_6,  gensym(\"pow_6\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_pow_7,  gensym(\"pow_7\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_pow_8,  gensym(\"pow_8\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_pow_9,  gensym(\"pow_9\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_rando,  gensym(\"rando\"), A_DEFFLOAT, A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_fcmp,  gensym(\"fcmp\"), A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_airy_ai,  gensym(\"airy_ai\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_airy_bi,  gensym(\"airy_bi\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_bessel_j0,  gensym(\"bessel_j0\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_bessel_j1,  gensym(\"bessel_j1\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_bessel_jn,  gensym(\"bessel_jn\"), A_DEFFLOAT, A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_bessel_y0,  gensym(\"bessel_y0\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_bessel_y1,  gensym(\"bessel_y1\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_bessel_yn,  gensym(\"bessel_yn\"), A_DEFFLOAT, A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_bessel_i0,  gensym(\"bessel_i0\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_bessel_i1,  gensym(\"bessel_i1\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_bessel_in,  gensym(\"bessel_in\"), A_DEFFLOAT, A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_clausen,  gensym(\"clausen\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_dawson,  gensym(\"dawson\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_debye_1,  gensym(\"debye_1\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_debye_2,  gensym(\"debye_2\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_debye_3,  gensym(\"debye_3\"), A_DEFFLOAT, 0);\n    class_addmethod(psl_class, (t_method)psl_debye_4,  gensym(\"debye_4\"), A_DEFFLOAT, 0);\n\n    // create alias\n    class_addcreator((t_newmethod)psl_new, gensym(\"gsl\"), A_DEFSYMBOL, 0);\n\n    // set name of default help file\n    class_sethelpsymbol(psl_class, gensym(\"help-psl\"));\n}\n", "meta": {"hexsha": "fe82b88a1e62f24b546326863d7cf063fa473332", "size": 20769, "ext": "c", "lang": "C", "max_stars_repo_path": "psl.c", "max_stars_repo_name": "shakfu/pd-psl", "max_stars_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "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": "psl.c", "max_issues_repo_name": "shakfu/pd-psl", "max_issues_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "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": "psl.c", "max_forks_repo_name": "shakfu/pd-psl", "max_forks_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad", "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.2559055118, "max_line_length": 111, "alphanum_fraction": 0.5490394338, "num_tokens": 6749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.35336121297313206}}
{"text": "/* monte/vegas.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n/* Author: MJB */\n/* Modified by: Brian Gough, 12/2000 */\n\n/* This is an implementation of the adaptive Monte-Carlo algorithm\n   of G. P. Lepage, originally described in J. Comp. Phys. 27, 192(1978).\n   The current version of the algorithm was described in the Cornell\n   preprint CLNS-80/447 of March, 1980.\n\n   This code follows most closely the c version by D.R.Yennie, coded\n   in 1984.\n\n   The input coordinates are x[j], with upper and lower limits xu[j]\n   and xl[j].  The integration length in the j-th direction is\n   delx[j].  Each coordinate x[j] is rescaled to a variable y[j] in\n   the range 0 to 1.  The range is divided into bins with boundaries\n   xi[i][j], where i=0 corresponds to y=0 and i=bins to y=1.  The grid\n   is refined (ie, bins are adjusted) using d[i][j] which is some\n   variation on the squared sum.  A third parameter used in defining\n   the real coordinate using random numbers is called z.  It ranges\n   from 0 to bins.  Its integer part gives the lower index of the bin\n   into which a call is to be placed, and the remainder gives the\n   location inside the bin.\n\n   When stratified sampling is used the bins are grouped into boxes,\n   and the algorithm allocates an equal number of function calls to\n   each box.\n\n   The variable alpha controls how \"stiff\" the rebinning algorithm is.  \n   alpha = 0 means never change the grid.  Alpha is typically set between\n   1 and 2.\n\n   */\n\n/* configuration headers */\n#include <config.h>\n\n/* standard headers */\n#include <math.h>\n#include <stdio.h>\n\n/* gsl headers */\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_monte_vegas.h>\n\n/* lib-specific headers */\n#define BINS_MAX 50\t\t/* even integer, will be divided by two */\n\n/* A separable grid with coordinates and values */\n#define COORD(s,i,j) ((s)->xi[(i)*(s)->dim + (j)])\n#define NEW_COORD(s,i) ((s)->xin[(i)])\n#define VALUE(s,i,j) ((s)->d[(i)*(s)->dim + (j)])\n\n/* predeclare functions */\n\ntypedef int coord;\n\nstatic void init_grid (gsl_monte_vegas_state * s, double xl[], double xu[],\n\t\tsize_t dim);\nstatic void reset_grid_values (gsl_monte_vegas_state * s);\nstatic void init_box_coord (gsl_monte_vegas_state * s, coord box[]);\nstatic int change_box_coord (gsl_monte_vegas_state * s, coord box[]);\nstatic void accumulate_distribution (gsl_monte_vegas_state * s, coord bin[],\n                                     double y);\nstatic void random_point (double x[], coord bin[], double *bin_vol,\n                          const coord box[], \n                          const double xl[], const double xu[],\n                          gsl_monte_vegas_state * s, gsl_rng * r);\nstatic void resize_grid (gsl_monte_vegas_state * s, unsigned int bins);\nstatic void refine_grid (gsl_monte_vegas_state * s);\n\nstatic void print_lim (gsl_monte_vegas_state * state,\n                       double xl[], double xu[], unsigned long dim);\nstatic void print_head (gsl_monte_vegas_state * state,\n                        unsigned long num_dim, unsigned long calls,\n                        unsigned int it_num, \n                        unsigned int bins, unsigned int boxes);\nstatic void print_res (gsl_monte_vegas_state * state,\n                       unsigned int itr, double res, double err, \n                       double cum_res, double cum_err,\n                       double chi_sq);\nstatic void print_dist (gsl_monte_vegas_state * state, unsigned long dim);\nstatic void print_grid (gsl_monte_vegas_state * state, unsigned long dim);\n\nint\ngsl_monte_vegas_integrate (gsl_monte_function * f,\n\t\t\t   double xl[], double xu[],\n\t\t\t   size_t dim, size_t calls,\n\t\t\t   gsl_rng * r,\n\t\t\t   gsl_monte_vegas_state * state,\n\t\t\t   double *result, double *abserr)\n{\n  double cum_int, cum_sig;\n  size_t i, k, it;\n\n  if (dim != state->dim)\n    {\n      GSL_ERROR (\"number of dimensions must match allocated size\", GSL_EINVAL);\n    }\n\n  for (i = 0; i < dim; i++)\n    {\n      if (xu[i] <= xl[i])\n\t{\n\t  GSL_ERROR (\"xu must be greater than xl\", GSL_EINVAL);\n\t}\n\n      if (xu[i] - xl[i] > GSL_DBL_MAX)\n\t{\n\t  GSL_ERROR (\"Range of integration is too large, please rescale\",\n\t\t     GSL_EINVAL);\n\t}\n    }\n\n  if (state->stage == 0)\n    {\n      init_grid (state, xl, xu, dim);\n\n      if (state->verbose >= 0)\n\t{\n\t  print_lim (state, xl, xu, dim);\n\t}\n    }\n\n  if (state->stage <= 1)\n    {\n      state->wtd_int_sum = 0;\n      state->sum_wgts = 0;\n      state->chi_sum = 0;\n      state->it_num = 1;\n      state->samples = 0;\n    }\n\n  if (state->stage <= 2)\n    {\n      unsigned int bins = state->bins_max;\n      unsigned int boxes = 1;\n\n      if (state->mode != GSL_VEGAS_MODE_IMPORTANCE_ONLY)\n\t{\n\t  /* shooting for 2 calls/box */\n\n\t  boxes = floor (pow (calls / 2.0, 1.0 / dim));\n\t  state->mode = GSL_VEGAS_MODE_IMPORTANCE;\n\n\t  if (2 * boxes >= state->bins_max)\n\t    {\n\t      /* if bins/box < 2 */\n\t      int box_per_bin = GSL_MAX (boxes / state->bins_max, 1);\n\n\t      bins = GSL_MIN(boxes / box_per_bin, state->bins_max);\n\t      boxes = box_per_bin * bins;\n\n\t      state->mode = GSL_VEGAS_MODE_STRATIFIED;\n\t    }\n\t}\n\n      {\n\tdouble tot_boxes = pow ((double) boxes, (double) dim);\n\tstate->calls_per_box = GSL_MAX (calls / tot_boxes, 2);\n\tcalls = state->calls_per_box * tot_boxes;\n      }\n\n      /* total volume of x-space/(avg num of calls/bin) */\n      state->jac = state->vol * pow ((double) bins, (double) dim) / calls;\n\n      state->boxes = boxes;\n\n      /* If the number of bins changes from the previous invocation, bins\n         are expanded or contracted accordingly, while preserving bin\n         density */\n\n      if (bins != state->bins)\n\t{\n\t  resize_grid (state, bins);\n\n\t  if (state->verbose > 1)\n\t    {\n\t      print_grid (state, dim);\n\t    }\n\t}\n\n      if (state->verbose >= 0)\n\t{\n\t  print_head (state,\n\t\t      dim, calls, state->it_num, state->bins, state->boxes);\n\t}\n    }\n\n  state->it_start = state->it_num;\n\n  cum_int = 0.0;\n  cum_sig = 0.0;\n\n  state->chisq = 0.0;\n\n  for (it = 0; it < state->iterations; it++)\n    {\n      double intgrl = 0.0, intgrl_sq = 0.0;\n      double sig = 0.0;\n      double wgt;\n      size_t calls_per_box = state->calls_per_box;\n      double jacbin = state->jac;\n      double *x = state->x;\n      coord *bin = state->bin;\n\n      state->it_num = state->it_start + it;\n\n      reset_grid_values (state);\n      init_box_coord (state, state->box);\n      \n      do\n\t{\n          double m = 0, q = 0;\n\t  double f_sq_sum = 0.0;\n\n\t  for (k = 0; k < calls_per_box; k++)\n\t    {\n\t      double fval, bin_vol;\n\n\t      random_point (x, bin, &bin_vol, state->box, xl, xu, state, r);\n\n\t      fval = jacbin * bin_vol * GSL_MONTE_FN_EVAL (f, x);\n\n              /* recurrence for mean and variance */\n\n              {\n                double d = fval - m;\n                m += d / (k + 1.0);\n                q += d * d * (k / (k + 1.0));\n              }\n\n\t      if (state->mode != GSL_VEGAS_MODE_STRATIFIED)\n\t\t{\n                  double f_sq = fval * fval;\n\t\t  accumulate_distribution (state, bin, f_sq);\n\t\t}\n\t    }\n\n\t  intgrl += m * calls_per_box;\n\n\t  f_sq_sum = q * calls_per_box ;\n\n\t  sig += f_sq_sum ;\n\n\t  if (state->mode == GSL_VEGAS_MODE_STRATIFIED)\n\t    {\n\t      accumulate_distribution (state, bin, f_sq_sum);\n\t    }\n\t}\n      while (change_box_coord (state, state->box));\n\n      /* Compute final results for this iteration   */\n\n      sig = sig / (calls_per_box - 1.0)  ;\n\n      if (sig > 0) \n        {\n          wgt = 1.0 / sig;\n        }\n      else if (state->sum_wgts > 0) \n        {\n          wgt = state->sum_wgts / state->samples;\n        }\n      else \n        {\n          wgt = 0.0;\n        }\n        \n     intgrl_sq = intgrl * intgrl;\n\n     state->result = intgrl;\n     state->sigma  = sqrt(sig);\n\n     if (wgt > 0.0)\n       {\n         state->samples++ ;\n         state->sum_wgts += wgt;\n         state->wtd_int_sum += intgrl * wgt;\n         state->chi_sum += intgrl_sq * wgt;\n\n         cum_int = state->wtd_int_sum / state->sum_wgts;\n         cum_sig = sqrt (1 / state->sum_wgts);\n\n         if (state->samples > 1)\n           {\n             state->chisq = (state->chi_sum - state->wtd_int_sum * cum_int) /\n               (state->samples - 1.0);\n           }\n       }\n     else\n       {\n         cum_int += (intgrl - cum_int) / (it + 1.0);\n         cum_sig = 0.0;\n       }         \n\n\n      if (state->verbose >= 0)\n\t{\n\t  print_res (state,\n\t\t     state->it_num, intgrl, sqrt (sig), cum_int, cum_sig,\n\t\t     state->chisq);\n\t  if (it + 1 == state->iterations && state->verbose > 0)\n\t    {\n\t      print_grid (state, dim);\n\t    }\n\t}\n\n      if (state->verbose > 1)\n\t{\n          print_dist (state, dim);\n        }\n\n      refine_grid (state);\n\n      if (state->verbose > 1)\n\t{\n\t  print_grid (state, dim);\n\t}\n\n    }\n\n  /* By setting stage to 1 further calls will generate independent\n     estimates based on the same grid, although it may be rebinned. */\n\n  state->stage = 1;  \n\n  *result = cum_int;\n  *abserr = cum_sig;\n\n  return GSL_SUCCESS;\n}\n\n\n\ngsl_monte_vegas_state *\ngsl_monte_vegas_alloc (size_t dim)\n{\n  gsl_monte_vegas_state *s =\n    (gsl_monte_vegas_state *) malloc (sizeof (gsl_monte_vegas_state));\n\n  if (s == 0)\n    {\n      GSL_ERROR_VAL (\"failed to allocate space for vegas state struct\",\n\t\t     GSL_ENOMEM, 0);\n    }\n\n  s->delx = (double *) malloc (dim * sizeof (double));\n\n  if (s->delx == 0)\n    {\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for delx\", GSL_ENOMEM, 0);\n    }\n\n  s->d = (double *) malloc (BINS_MAX * dim * sizeof (double));\n\n  if (s->d == 0)\n    {\n      free (s->delx);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for d\", GSL_ENOMEM, 0);\n    }\n\n  s->xi = (double *) malloc ((BINS_MAX + 1) * dim * sizeof (double));\n\n  if (s->xi == 0)\n    {\n      free (s->d);\n      free (s->delx);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for xi\", GSL_ENOMEM, 0);\n    }\n\n  s->xin = (double *) malloc ((BINS_MAX + 1) * sizeof (double));\n\n  if (s->xin == 0)\n    {\n      free (s->xi);\n      free (s->d);\n      free (s->delx);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for xin\", GSL_ENOMEM, 0);\n    }\n\n  s->weight = (double *) malloc (BINS_MAX * sizeof (double));\n\n  if (s->weight == 0)\n    {\n      free (s->xin);\n      free (s->xi);\n      free (s->d);\n      free (s->delx);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for xin\", GSL_ENOMEM, 0);\n    }\n\n  s->box = (coord *) malloc (dim * sizeof (coord));\n\n  if (s->box == 0)\n    {\n      free (s->weight);\n      free (s->xin);\n      free (s->xi);\n      free (s->d);\n      free (s->delx);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for box\", GSL_ENOMEM, 0);\n    }\n\n  s->bin = (coord *) malloc (dim * sizeof (coord));\n\n  if (s->bin == 0)\n    {\n      free (s->box);\n      free (s->weight);\n      free (s->xin);\n      free (s->xi);\n      free (s->d);\n      free (s->delx);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for bin\", GSL_ENOMEM, 0);\n    }\n\n  s->x = (double *) malloc (dim * sizeof (double));\n\n  if (s->x == 0)\n    {\n      free (s->bin);\n      free (s->box);\n      free (s->weight);\n      free (s->xin);\n      free (s->xi);\n      free (s->d);\n      free (s->delx);\n      free (s);\n      GSL_ERROR_VAL (\"failed to allocate space for x\", GSL_ENOMEM, 0);\n    }\n\n  s->dim = dim;\n  s->bins_max = BINS_MAX;\n\n  gsl_monte_vegas_init (s);\n\n  return s;\n}\n\n/* Set some default values and whatever */\nint\ngsl_monte_vegas_init (gsl_monte_vegas_state * state)\n{\n  state->stage = 0;\n  state->alpha = 1.5;\n  state->verbose = -1;\n  state->iterations = 5;\n  state->mode = GSL_VEGAS_MODE_IMPORTANCE;\n  state->chisq = 0;\n  state->bins = state->bins_max;\n  state->ostream = stdout;\n\n  return GSL_SUCCESS;\n}\n\nvoid\ngsl_monte_vegas_free (gsl_monte_vegas_state * s)\n{\n  free (s->x);\n  free (s->delx);\n  free (s->d);\n  free (s->xi);\n  free (s->xin);\n  free (s->weight);\n  free (s->box);\n  free (s->bin);\n  free (s);\n}\n\nstatic void\ninit_box_coord (gsl_monte_vegas_state * s, coord box[])\n{\n  size_t i;\n\n  size_t dim = s->dim;\n\n  for (i = 0; i < dim; i++)\n    {\n      box[i] = 0;\n    }\n}\n\n/* change_box_coord steps through the box coord like\n   {0,0}, {0, 1}, {0, 2}, {0, 3}, {1, 0}, {1, 1}, {1, 2}, ...\n*/\nstatic int\nchange_box_coord (gsl_monte_vegas_state * s, coord box[])\n{\n  int j = s->dim - 1;\n\n  int ng = s->boxes;\n\n  while (j >= 0)\n    {\n      box[j] = (box[j] + 1) % ng;\n\n      if (box[j] != 0)\n\t{\n\t  return 1;\n\t}\n\n      j--;\n    }\n\n  return 0;\n}\n\nstatic void\ninit_grid (gsl_monte_vegas_state * s, double xl[], double xu[], size_t dim)\n{\n  size_t j;\n\n  double vol = 1.0;\n\n  s->bins = 1;\n\n  for (j = 0; j < dim; j++)\n    {\n      double dx = xu[j] - xl[j];\n      s->delx[j] = dx;\n      vol *= dx;\n\n      COORD (s, 0, j) = 0.0;\n      COORD (s, 1, j) = 1.0;\n    }\n\n  s->vol = vol;\n}\n\n\nstatic void\nreset_grid_values (gsl_monte_vegas_state * s)\n{\n  size_t i, j;\n\n  size_t dim = s->dim;\n  size_t bins = s->bins;\n\n  for (i = 0; i < bins; i++)\n    {\n      for (j = 0; j < dim; j++)\n\t{\n\t  VALUE (s, i, j) = 0.0;\n\t}\n    }\n}\n\nstatic void\naccumulate_distribution (gsl_monte_vegas_state * s, coord bin[], double y)\n{\n  size_t j;\n  size_t dim = s->dim;\n\n  for (j = 0; j < dim; j++)\n    {\n      int i = bin[j];\n      VALUE (s, i, j) += y;\n    }\n}\n\nstatic void\nrandom_point (double x[], coord bin[], double *bin_vol,\n\t      const coord box[], const double xl[], const double xu[],\n\t      gsl_monte_vegas_state * s, gsl_rng * r)\n{\n  /* Use the random number generator r to return a random position x\n     in a given box.  The value of bin gives the bin location of the\n     random position (there may be several bins within a given box) */\n\n  double vol = 1.0;\n\n  size_t j;\n\n  size_t dim = s->dim;\n  size_t bins = s->bins;\n  size_t boxes = s->boxes;\n\n  DISCARD_POINTER(xu); /* prevent warning about unused parameter */\n\n  for (j = 0; j < dim; ++j)\n    {\n      /* box[j] + ran gives the position in the box units, while z\n         is the position in bin units.  */\n\n      double z = ((box[j] + gsl_rng_uniform_pos (r)) / boxes) * bins;\n\n      int k = z;\n\n      double y, bin_width;\n\n      bin[j] = k;\n\n      if (k == 0)\n\t{\n\t  bin_width = COORD (s, 1, j);\n\t  y = z * bin_width;\n\t}\n      else\n\t{\n\t  bin_width = COORD (s, k + 1, j) - COORD (s, k, j);\n\t  y = COORD (s, k, j) + (z - k) * bin_width;\n\t}\n\n      x[j] = xl[j] + y * s->delx[j];\n\n      vol *= bin_width;\n    }\n\n  *bin_vol = vol;\n}\n\n\nstatic void\nresize_grid (gsl_monte_vegas_state * s, unsigned int bins)\n{\n  size_t j, k;\n  size_t dim = s->dim;\n\n  /* weight is ratio of bin sizes */\n\n  double pts_per_bin = (double) s->bins / (double) bins;\n\n  for (j = 0; j < dim; j++)\n    {\n      double xold;\n      double xnew = 0;\n      double dw = 0;\n      int i = 1;\n\n      for (k = 1; k <= s->bins; k++)\n\t{\n\t  dw += 1.0;\n\t  xold = xnew;\n\t  xnew = COORD (s, k, j);\n\n\t  for (; dw > pts_per_bin; i++)\n\t    {\n\t      dw -= pts_per_bin;\n\t      NEW_COORD (s, i) = xnew - (xnew - xold) * dw;\n\t    }\n\t}\n\n      for (k = 1 ; k < bins; k++)\n        {\n          COORD(s, k, j) = NEW_COORD(s, k);\n        }\n\n      COORD (s, bins, j) = 1;\n    }\n\n  s->bins = bins;\n}\n\nstatic void\nrefine_grid (gsl_monte_vegas_state * s)\n{\n  size_t i, j, k;\n  size_t dim = s->dim;\n  size_t bins = s->bins;\n\n  for (j = 0; j < dim; j++)\n    {\n      double grid_tot_j, tot_weight;\n      double * weight = s->weight;\n\n      double oldg = VALUE (s, 0, j);\n      double newg = VALUE (s, 1, j);\n\n      VALUE (s, 0, j) = (oldg + newg) / 2;\n      grid_tot_j = VALUE (s, 0, j);\n\n      /* This implements gs[i][j] = (gs[i-1][j]+gs[i][j]+gs[i+1][j])/3 */\n\n      for (i = 1; i < bins - 1; i++)\n\t{\n\t  double rc = oldg + newg;\n\t  oldg = newg;\n\t  newg = VALUE (s, i + 1, j);\n\t  VALUE (s, i, j) = (rc + newg) / 3;\n\t  grid_tot_j += VALUE (s, i, j);\n\t}\n      VALUE (s, bins - 1, j) = (newg + oldg) / 2;\n\n      grid_tot_j += VALUE (s, bins - 1, j);\n\n      tot_weight = 0;\n\n      for (i = 0; i < bins; i++)\n\t{\n\t  weight[i] = 0;\n\n\t  if (VALUE (s, i, j) > 0)\n\t    {\n\t      oldg = grid_tot_j / VALUE (s, i, j);\n\t      /* damped change */\n\t      weight[i] = pow (((oldg - 1) / oldg / log (oldg)), s->alpha);\n\t    }\n\n\t  tot_weight += weight[i];\n\n#ifdef DEBUG\n          printf(\"weight[%d] = %g\\n\", i, weight[i]);\n#endif\n\t}\n\n      {\n\tdouble pts_per_bin = tot_weight / bins;\n\n\tdouble xold;\n\tdouble xnew = 0;\n\tdouble dw = 0;\n\ti = 1;\n\n\tfor (k = 0; k < bins; k++)\n\t  {\n\t    dw += weight[k];\n\t    xold = xnew;\n\t    xnew = COORD (s, k + 1, j);\n\n\t    for (; dw > pts_per_bin; i++)\n\t      {\n\t\tdw -= pts_per_bin;\n\t\tNEW_COORD (s, i) = xnew - (xnew - xold) * dw / weight[k];\n\t      }\n\t  }\n\n        for (k = 1 ; k < bins ; k++)\n          {\n            COORD(s, k, j) = NEW_COORD(s, k);\n          }\n\n\tCOORD (s, bins, j) = 1;\n      }\n    }\n}\n\n\nstatic void\nprint_lim (gsl_monte_vegas_state * state,\n\t   double xl[], double xu[], unsigned long dim)\n{\n  unsigned long j;\n\n  fprintf (state->ostream, \"The limits of integration are:\\n\");\n  for (j = 0; j < dim; ++j)\n    fprintf (state->ostream, \"\\nxl[%lu]=%f    xu[%lu]=%f\", j, xl[j], j, xu[j]);\n  fprintf (state->ostream, \"\\n\");\n  fflush (state->ostream);\n}\n\nstatic void\nprint_head (gsl_monte_vegas_state * state,\n\t    unsigned long num_dim, unsigned long calls,\n\t    unsigned int it_num, unsigned int bins, unsigned int boxes)\n{\n  fprintf (state->ostream,\n\t   \"\\nnum_dim=%lu, calls=%lu, it_num=%d, max_it_num=%d \",\n\t   num_dim, calls, it_num, state->iterations);\n  fprintf (state->ostream,\n\t   \"verb=%d, alph=%.2f,\\nmode=%d, bins=%d, boxes=%d\\n\",\n\t   state->verbose, state->alpha, state->mode, bins, boxes);\n  fprintf (state->ostream,\n\t   \"\\n       single.......iteration                   \");\n  fprintf (state->ostream, \"accumulated......results   \\n\");\n\n  fprintf (state->ostream,\n\t   \"iteration     integral    sigma             integral   \");\n  fprintf (state->ostream, \"      sigma     chi-sq/it\\n\\n\");\n  fflush (state->ostream);\n\n}\n\nstatic void\nprint_res (gsl_monte_vegas_state * state,\n\t   unsigned int itr, \n           double res, double err, \n           double cum_res, double cum_err,\n\t   double chi_sq)\n{\n  fprintf (state->ostream,\n\t   \"%4d        %6.4e %10.2e          %6.4e      %8.2e  %10.2e\\n\",\n\t   itr, res, err, cum_res, cum_err, chi_sq);\n  fflush (state->ostream);\n}\n\nstatic void\nprint_dist (gsl_monte_vegas_state * state, unsigned long dim)\n{\n  unsigned long i, j;\n  int p = state->verbose;\n  if (p < 1)\n    return;\n\n  for (j = 0; j < dim; ++j)\n    {\n      fprintf (state->ostream, \"\\n axis %lu \\n\", j);\n      fprintf (state->ostream, \"      x   g\\n\");\n      for (i = 0; i < state->bins; i++)\n\t{\n\t  fprintf (state->ostream, \"weight [%11.2e , %11.2e] = \", \n                   COORD (state, i, j), COORD(state,i+1,j));\n\t  fprintf (state->ostream, \" %11.2e\\n\", VALUE (state, i, j));\n\n\t}\n      fprintf (state->ostream, \"\\n\");\n    }\n  fprintf (state->ostream, \"\\n\");\n  fflush (state->ostream);\n\n}\n\nstatic void\nprint_grid (gsl_monte_vegas_state * state, unsigned long dim)\n{\n  unsigned long i, j;\n  int p = state->verbose;\n  if (p < 1)\n    return;\n\n  for (j = 0; j < dim; ++j)\n    {\n      fprintf (state->ostream, \"\\n axis %lu \\n\", j);\n      fprintf (state->ostream, \"      x   \\n\");\n      for (i = 0; i <= state->bins; i++)\n\t{\n\t  fprintf (state->ostream, \"%11.2e\", COORD (state, i, j));\n\t  if (i % 5 == 4)\n\t    fprintf (state->ostream, \"\\n\");\n\t}\n      fprintf (state->ostream, \"\\n\");\n    }\n  fprintf (state->ostream, \"\\n\");\n  fflush (state->ostream);\n\n}\n\n", "meta": {"hexsha": "cbc792db222588de0d60465dfd06752847398b0f", "size": 20096, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/monte/vegas.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/monte/vegas.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/monte/vegas.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 23.2323699422, "max_line_length": 79, "alphanum_fraction": 0.5593152866, "num_tokens": 6261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3532147684513263}}
{"text": "/**\n *\n * @file test_dotu.c\n *\n * @author Samuel  D. Relton\n * @author Pedro   V. Lara\n * @author Mawussi Zounon\n * @date 2016-06-15\n * @precisions normal z -> c\n *\n **/\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include<time.h>\n#ifdef BBLAS_WITH_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 \"bblas_z.h\"\n\n\n#undef REAL\n#define COMPLEX\n\n\n\nint main(int argc, char *argv[])\n{\n  //Set parameters to initilize random value generation\n  __time_t t;\n  srand((unsigned) time(&t));\n  int IONE     = 1;\n  int ISEED[4] ={0,0,0,1};\n  \n  // Generation of batch_count value between 100 and 1000\n  int batch_min = 100;\n  int batch_max = 10000;\n  int batch_count = rand() % (batch_max - batch_min + 1) + batch_min;\n\n  // Generation of x and y vector sizes\n  int * n = (int *) malloc(batch_count*sizeof(int));\n  int n_max = 1000;\n  int n_min = 10;\n  for(int iter=0; iter < batch_count; iter++)\n    n[iter] = rand() % (n_max - n_min + 1) + n_min;\n\n  // common calling parameters\n  int * incx = (int*) malloc(batch_count*sizeof(int));\n  int * incy = (int*) malloc(batch_count*sizeof(int));\n  int * info = (int *) malloc(batch_count*sizeof(int));\n  enum BBLAS_OPTS batch_opts = BBLAS_VARIABLE;\n\n  //Generation of x and y vectors  and the result vector\n  // for using variable api\n  BBLAS_Complex64_t ** x, ** y, *result;\n  x = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t*));\n  y = (BBLAS_Complex64_t **) malloc(batch_count*sizeof(BBLAS_Complex64_t*));\n  result = (BBLAS_Complex64_t *) malloc(batch_count*sizeof(BBLAS_Complex64_t));\n  \n  for(int iter=0; iter < batch_count; iter++){\n    x[iter] = (BBLAS_Complex64_t*) malloc(n[iter]*sizeof(BBLAS_Complex64_t));\n    y[iter] = (BBLAS_Complex64_t*) malloc(n[iter]*sizeof(BBLAS_Complex64_t));\n    \n#if defined(BBLAS_WITH_MKL)\n    LAPACKE_zlarnv_work(IONE, ISEED, n[iter], (MKL_Complex16*) x[iter]);\n    LAPACKE_zlarnv_work(IONE, ISEED, n[iter], (MKL_Complex16*) y[iter]);\n#else\n    LAPACKE_zlarnv_work(IONE, ISEED, n[iter], x[iter]);\n    LAPACKE_zlarnv_work(IONE, ISEED, n[iter], y[iter]);\n#endif\n    // set values of incx and incy\n    incx[iter] = 1;\n    incy[iter] = 1;\n  }\n\n  //Calling variable api\n  printf(\"Calling variable api: batchv_zdotu_sub \\n\");\n  batchv_zdotu_sub(\n\t\t  (const int *) n,\n\t\t  (BBLAS_Complex64_t const * const *) x,\n\t\t  (const int *) incx,\n\t\t  (BBLAS_Complex64_t const * const *) y,\n\t\t  (const int *) incy,\n\t\t  result,\n\t\t  (const int) batch_count, info);\n  \n  //Calling tag api to solve variable problem\n  printf(\"Calling tag api to solve variable problem: batch_zdotu_sub\\n\");\n  \n    batch_zdotu_sub(\n\t\t  (const int *) n,\n\t\t  (BBLAS_Complex64_t const * const *) x,\n\t\t  (const int *) incx,\n\t\t  (BBLAS_Complex64_t const * const *) y,\n\t\t  (const int *) incy,\n\t\t  result,\n\t\t  (const int) batch_count,\n\t\t  (const enum BBLAS_OPTS) batch_opts,\n\t\t  info);\n\n    //Free x and y vectors\n    printf(\"Free x and y vectors after variable case\\n\");\n    \n    for(int iter=0; iter < batch_count; iter++){\n      free(x[iter]);\n      free(y[iter]);\n    }\n    // free n incx and incy and info\n    free(n);\n    free(incx);\n    free(incy);\n    free(info);\n    \n    // Calling fixe api\n    //Generation of x and y vectors, result will be overwritten\n    int n_fixe = rand() % (n_max - n_min + 1) + n_min;\n    int incx_fixe = 1;\n    int incy_fixe = 1;\n    int * info_fixe = (int*)malloc(sizeof(int));\n    \n    for(int iter=0; iter < batch_count; iter++){\n      x[iter] = (BBLAS_Complex64_t*) malloc(n_fixe*sizeof(BBLAS_Complex64_t));\n      y[iter] = (BBLAS_Complex64_t*) malloc(n_fixe*sizeof(BBLAS_Complex64_t));\n      \n#if defined(BBLAS_WITH_MKL)\n      LAPACKE_zlarnv_work(IONE, ISEED, n_fixe, (MKL_Complex16*) x[iter]);\n      LAPACKE_zlarnv_work(IONE, ISEED, n_fixe, (MKL_Complex16*) y[iter]);\n#else\n      LAPACKE_zlarnv_work(IONE, ISEED, n_fixe, x[iter]);\n      LAPACKE_zlarnv_work(IONE, ISEED, n_fixe, y[iter]);\n#endif\n    }\n  //Calling fixe api\n    printf(\"Calling fixe api: batchf_zdotu_sub \\n\");\n  batchf_zdotu_sub(\n\t\t  (const int ) n_fixe,\n\t\t  (BBLAS_Complex64_t const * const *) x,\n\t\t  (const int) incx_fixe,\n\t\t  (BBLAS_Complex64_t const * const *) y,\n\t\t  (const int) incy_fixe,\n\t\t  result,\n\t\t  (const int) batch_count, info_fixe);\n\n  //Calling tag api to solve fixed batch  problem\n  printf(\"Calling tag api to solve fixed batch  problem: batch_zdotu_sub \\n\");\n  batch_opts = BBLAS_FIXED;\n\n  batch_zdotu_sub(\n\t\t  (const int *) &n_fixe,\n\t\t  (BBLAS_Complex64_t const * const *) x,\n\t\t  (const int *) &incx_fixe,\n\t\t  (BBLAS_Complex64_t const * const *) y,\n\t\t  (const int *) &incy_fixe,\n\t\t  result,\n\t\t  (const int) batch_count,\n\t\t  (const enum BBLAS_OPTS) batch_opts,\n\t\t  info_fixe);\n  //Free x and y vectors\n  printf(\"Free memory after the call to fixed batch case\\n\");\n  \n  for(int iter=0; iter < batch_count; iter++){\n    free(x[iter]);\n    free(y[iter]);\n  }\n\n  //Creation of variable specific to group api\n  int group_min = 1;\n  int group_max = 10;\n  int group_count = rand() % (group_max - group_min + 1) + group_min;\n  int * group_size = (int *) malloc(group_count*sizeof(int));\n  int tmp_size = batch_count/group_count;\n  \n  //Set value for group_size\n  for(int iter=0; iter < group_count-1; iter++)\n    group_size[iter] = tmp_size;\n  \n  //Set last value of group_size\n  group_size[group_count-1] = batch_count - (tmp_size*(group_count-1));\n\n  //Allocate memory for vectors\n\n  int *n_group    = (int *) malloc(group_count*sizeof(int));\n  int *incx_group = (int *) malloc(group_count*sizeof(int));\n  int *incy_group = (int *) malloc(group_count*sizeof(int));\n  int *info_group = (int *) malloc(group_count*sizeof(int));\n  int offset = 0;\n  //Set vector entries\n\n  for(int group_iter = 0; group_iter < group_count ; group_iter++){\n    n_group[group_iter] = rand() % (n_max - n_min + 1) + n_min;\n    incx_group[group_iter] = 1;\n    incy_group[group_iter] = 1;\n\n    for (int iter = 0; iter < group_size[group_iter]; iter++){\n      x[offset+iter] = (BBLAS_Complex64_t*) malloc(n_group[group_iter]*sizeof(BBLAS_Complex64_t));\n      y[offset+iter] = (BBLAS_Complex64_t*) malloc(n_group[group_iter]*sizeof(BBLAS_Complex64_t));\n\n#if defined(BBLAS_WITH_MKL)\n      LAPACKE_zlarnv_work(IONE, ISEED, n_group[group_iter], (MKL_Complex16*) x[offset+iter]);\n      LAPACKE_zlarnv_work(IONE, ISEED, n_group[group_iter], (MKL_Complex16*) y[offset+iter]);\n#else\n      LAPACKE_zlarnv_work(IONE, ISEED, n_group[group_iter], x[offset+iter]);\n      LAPACKE_zlarnv_work(IONE, ISEED, n_group[group_iter], y[offset+iter]);\n#endif\n    }\n    offset += group_size[group_iter];\n  }\n\n  //Calling group api\n  printf(\"Calling group api:batchg_zdotu_sub\\n\");\n   batchg_zdotu_sub(\n\t\t    (const int *)n_group,\n\t\t    (BBLAS_Complex64_t const * const *)x,\n\t\t    (const int *)incx_group,\n\t\t    (BBLAS_Complex64_t const * const *)y,\n\t\t    (const int *)incy_group,\n\t\t    result,\n\t\t    (const int)group_count,\n\t\t    (const int *) group_size,\n\t\t    info_group);\n\n   //Free allocated memories\n  for(int iter=0; iter < batch_count; iter++){\n    free(x[iter]);\n    free(y[iter]);\n  }\n  free(result);\n  free(x);\n  free(y);\n  free(n_group);\n  free(incx_group);\n  free(incy_group);\n  free(group_size);\n  free(info_group);\n  return 0;\n}\n", "meta": {"hexsha": "d3907650d7c8a1fd91602eb61310c7662ce1c8f3", "size": 7268, "ext": "c", "lang": "C", "max_stars_repo_path": "examples/test_dotu.c", "max_stars_repo_name": "mawussi/BBLAS-group", "max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z", "max_issues_repo_path": "examples/test_dotu.c", "max_issues_repo_name": "sdrelton/bblas_api_test", "max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_issues_repo_licenses": ["BSD-2-Clause"], "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/test_dotu.c", "max_forks_repo_name": "sdrelton/bblas_api_test", "max_forks_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "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.0330578512, "max_line_length": 98, "alphanum_fraction": 0.6574023115, "num_tokens": 2326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3532147608096484}}
{"text": "/**\n *\n * @file qwrapper_cgemv.c\n *\n *  PLASMA core_blas quark wrapper\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Mark Gates\n * @author Mathieu Faverge\n * @date 2010-11-15\n * @generated c Tue Jan  7 11:44:59 2014\n *\n **/\n#include <cblas.h>\n#include \"common.h\"\n\n/***************************************************************************//**\n *\n **/\nvoid QUARK_CORE_cgemv(Quark *quark, Quark_Task_Flags *task_flags,\n                      PLASMA_enum trans, int m, int n,\n                      PLASMA_Complex32_t alpha, const PLASMA_Complex32_t *A, int lda,\n                                                const PLASMA_Complex32_t *x, int incx,\n                      PLASMA_Complex32_t beta,        PLASMA_Complex32_t *y, int incy)\n{\n    DAG_CORE_GEMV;\n    QUARK_Insert_Task(quark, CORE_cgemv_quark, task_flags,\n        sizeof(PLASMA_enum),             &trans,  VALUE,\n        sizeof(int),                     &m,      VALUE,\n        sizeof(int),                     &n,      VALUE,\n        sizeof(PLASMA_Complex32_t),      &alpha,  VALUE,\n        sizeof(PLASMA_Complex32_t)*m*n,  A,               INPUT,\n        sizeof(int),                     &lda,    VALUE,\n        sizeof(PLASMA_Complex32_t)*n,    x,               INPUT,\n        sizeof(int),                     &incx,   VALUE,\n        sizeof(PLASMA_Complex32_t),      &beta,   VALUE,\n        sizeof(PLASMA_Complex32_t)*m,    y,               INOUT,\n        sizeof(int),                     &incy,   VALUE,\n        0);\n}\n\n/***************************************************************************//**\n *\n **/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_cgemv_quark = PCORE_cgemv_quark\n#define CORE_cgemv_quark PCORE_cgemv_quark\n#endif\nvoid CORE_cgemv_quark(Quark *quark)\n{\n    PLASMA_enum trans;\n    int m, n, lda, incx, incy;\n    PLASMA_Complex32_t alpha, beta;\n    const PLASMA_Complex32_t *A, *x;\n    PLASMA_Complex32_t *y;\n\n    quark_unpack_args_11( quark, trans, m, n, alpha, A, lda, x, incx, beta, y, incy );\n    cblas_cgemv(\n        CblasColMajor,\n        (CBLAS_TRANSPOSE)trans,\n        m, n,\n        CBLAS_SADDR(alpha), A, lda,\n                            x, incx,\n        CBLAS_SADDR(beta),  y, incy);\n}\n", "meta": {"hexsha": "c47cf35dbedca8bf97e66c256d7c4ee69c156101", "size": 2291, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas-qwrapper/qwrapper_cgemv.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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_blas-qwrapper/qwrapper_cgemv.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_blas-qwrapper/qwrapper_cgemv.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.6911764706, "max_line_length": 86, "alphanum_fraction": 0.5189873418, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3529772702705141}}
{"text": "#pragma once\n#include <boost/operators.hpp>\n#include <cmath>\n#include <gsl/gsl>\n#include <iostream>\n#include <nlohmann/json.hpp>\n#include <numeric>\n\nnamespace Simulator {\ntemplate <class T, class Category> class UnitBase : public boost::multiplicative<T, double> {\n  public:\n    UnitBase() = default;\n    explicit constexpr UnitBase(double val) : _val(val) {}\n    explicit constexpr UnitBase(long double val) : _val(gsl::narrow_cast<double>(val)) {}\n    explicit constexpr UnitBase(int val) : _val(gsl::narrow<double>(val)) {}\n    explicit constexpr UnitBase(std::int64_t val) : _val(gsl::narrow<double>(val)) {}\n\n    explicit constexpr operator double() const noexcept { return _val; }\n    explicit constexpr operator int() const noexcept { return gsl::narrow_cast<int>(_val); }\n    explicit constexpr operator std::int64_t() const noexcept { return gsl::narrow_cast<std::int64_t>(_val); }\n    explicit constexpr operator float() const noexcept { return gsl::narrow_cast<float>(_val); }\n\n    constexpr bool operator<(const T &rhs) const noexcept { return _val < rhs._val; }\n    constexpr bool operator<=(const T &rhs) const noexcept { return _val <= rhs._val; }\n    constexpr bool operator>(const T &rhs) const noexcept { return _val > rhs._val; }\n    constexpr bool operator>=(const T &rhs) const noexcept { return _val >= rhs._val; }\n    constexpr bool operator==(const T &rhs) const noexcept { return _val == rhs._val; }\n    constexpr bool operator!=(const T &rhs) const noexcept { return !(*this == rhs); }\n\n    constexpr T &operator+=(const T &rhs) noexcept {\n        _val += rhs._val;\n        return static_cast<T &>(*this);\n    }\n\n    template <class U> constexpr T operator+(const UnitBase<U, Category> &rhs) const noexcept {\n        auto ret = *this;\n        return ret += rhs;\n    }\n\n    constexpr T &operator-=(const T &rhs) noexcept {\n        _val -= rhs._val;\n        return static_cast<T &>(*this);\n    }\n\n    template <class U> constexpr T operator-(const UnitBase<U, Category> &rhs) const noexcept {\n        auto ret = *this;\n        return ret -= rhs;\n    }\n\n    constexpr T &operator*=(double rhs) noexcept {\n        _val *= rhs;\n        return static_cast<T &>(*this);\n    }\n\n    constexpr T &operator/=(double rhs) noexcept {\n        _val /= rhs;\n        return static_cast<T &>(*this);\n    }\n\n    constexpr T operator-() const noexcept { return T(-_val); }\n\n    constexpr double operator/(const T &rhs) const noexcept { return _val / rhs._val; }\n\n    friend constexpr T abs(const T &x) noexcept { return T(std::abs(x._val)); }\n    friend constexpr T round(const T &x) noexcept { return T(std::round(x._val)); }\n    friend constexpr T floor(const T &x) noexcept { return T(std::floor(x._val)); }\n    friend constexpr T ceil(const T &x) noexcept { return T(std::ceil(x._val)); }\n    friend constexpr T fmod(const T &x, const T &y) { return T(std::fmod(x._val, y._val)); }\n    friend std::string to_string(const T &x) { return std::to_string(x._val); }\n\n    friend std::ostream &operator<<(std::ostream &os, const T &rhs) { return os << to_string(rhs); }\n    friend std::istream &operator>>(std::istream &is, T &rhs) {\n        is >> rhs._val;\n        return is;\n    }\n    [[nodiscard]] constexpr double getValue() const noexcept { return _val; }\n\n  protected:\n    double _val = 0;\n};\n\n// NOLINTNEXTLINE\n#define DEFINE_UNIT(name, cat, s)                                                                                      \\\n    class name : public UnitBase<name, cat> {                                                                          \\\n      public:                                                                                                          \\\n        static constexpr name infinity() { return name(std::numeric_limits<double>::infinity()); }                     \\\n        using category = cat;                                                                                          \\\n        static constexpr double scale = (s);                                                                           \\\n        using UnitBase<name, cat>::UnitBase;                                                                           \\\n        constexpr name(const UnitBase<name, cat> &other) : UnitBase<name, cat>(other) {}                               \\\n        template <class U>                                                                                             \\\n        constexpr name(const UnitBase<U, cat> &other) : UnitBase<name, cat>(other.getValue() * (U::scale / scale)) {   \\\n            static_assert(U::scale == U::scale && scale == scale);                                                     \\\n        }                                                                                                              \\\n    };                                                                                                                 \\\n    inline void from_json(const nlohmann::json &j, name &v) { v = name(j.get<double>()); }                             \\\n    inline void to_json(nlohmann::json &j, const name &v) { j = v.getValue(); }\n\nstruct MasteryCategory {};\nDEFINE_UNIT(Mastery, MasteryCategory, 1.0);\nstruct CriticalRatingCategory {};\nDEFINE_UNIT(CriticalRating, CriticalRatingCategory, 1.0);\nstruct AlacrityRatingCategory {};\nDEFINE_UNIT(AlacrityRating, AlacrityRatingCategory, 1.0);\nstruct PowerCategory {};\nDEFINE_UNIT(Power, PowerCategory, 1.0);\nstruct ForceTechDamageCategory {};\nDEFINE_UNIT(FTPower, ForceTechDamageCategory, 1.0);\nstruct AccuracyRatingCategory {};\nDEFINE_UNIT(AccuracyRating, AccuracyRatingCategory, 1.0);\nstruct TimeCategory {};\nDEFINE_UNIT(Second, TimeCategory, 1.0);\nDEFINE_UNIT(Minute, TimeCategory, 60.0);\nconstexpr Second _tinyTime{1e-7};\nstruct HealthCategory {};\nDEFINE_UNIT(HealthPoints, HealthCategory, 1.0);\nstruct ArmorCatergory {};\nDEFINE_UNIT(Armor, ArmorCatergory, 1.0);\nstruct EnergyCategory {};\nDEFINE_UNIT(EnergyCost, EnergyCategory, 1.0);\n} // namespace Simulator\n", "meta": {"hexsha": "5e37ef31da979a9d3cbe4c055e449b472ed52091", "size": 5973, "ext": "h", "lang": "C", "max_stars_repo_path": "Simulator/SimulatorBase/detail/units.h", "max_stars_repo_name": "tomcool420/SimulatorSWTOR", "max_stars_repo_head_hexsha": "4d2866f997fc3f75b69a97dd5fc474227185de81", "max_stars_repo_licenses": ["MIT"], "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/SimulatorBase/detail/units.h", "max_issues_repo_name": "tomcool420/SimulatorSWTOR", "max_issues_repo_head_hexsha": "4d2866f997fc3f75b69a97dd5fc474227185de81", "max_issues_repo_licenses": ["MIT"], "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/SimulatorBase/detail/units.h", "max_forks_repo_name": "tomcool420/SimulatorSWTOR", "max_forks_repo_head_hexsha": "4d2866f997fc3f75b69a97dd5fc474227185de81", "max_forks_repo_licenses": ["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.9590163934, "max_line_length": 120, "alphanum_fraction": 0.5621965511, "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5, "lm_q1q2_score": 0.3528925139185056}}
{"text": "#include \"defines.h\"\n#include <string.h>\n#include \"lib.h\"\n#include <gsl/gsl_cblas.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_eigen.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_blas.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n\n\n\n\nextern REAL * opa;\nextern int NTERMS;\n\n/**\n * @param float * w \n * @param float * sig\n * @param float * spectro \n * @param int nspectro \n * @param float * spectra\n * @param float * d_spectra \n * @param float * beta \n * @param float * alpha \n * \n * */\nint covarm(REAL *w,REAL *sig,float *spectro,int nspectro,REAL *spectra,REAL  *d_spectra,REAL *beta,REAL *alpha){\t\n\t\n\tint j,i,bt_nf,bt_nc,aux_nf,aux_nc;\n\n\tREAL AP[NTERMS*NTERMS*NPARMS],BT[NPARMS*NTERMS];\n\t\n\tREAL *BTaux,*APaux;\n\n\t//printf(\"\\nVALORES DEL SIGMA SQUARE\\n\");\n\n\tfor(j=0;j<NPARMS;j++){\n\t\tfor(i=0;i<nspectro;i++){\n\t\t\topa[i]= w[j]*(spectra[i+nspectro*j]-spectro[i+nspectro*j]);\n\t\t}\n\n\t\tBTaux=BT+(j*NTERMS);\n\t\tAPaux=AP+(j*NTERMS*NTERMS);\n\t\tmultmatrixIDLValueSigma(opa,nspectro,1,d_spectra+j*nspectro*NTERMS,NTERMS,nspectro,BTaux,&bt_nf,&bt_nc,sig+(nspectro*j)); //bt de tam NTERMS x 1\n\t\tmultmatrix_transpose_sigma(d_spectra+j*nspectro*NTERMS,NTERMS,nspectro,d_spectra+j*nspectro*NTERMS,NTERMS,nspectro,APaux,&aux_nf,&aux_nc,w[j], sig+(nspectro*j));//ap de tam NTERMS x NTERMS\n\t\t\n\t}\n\n\ttotalParcialf(BT,NPARMS,NTERMS,beta); //beta de tam 1 x NTERMS\n\ttotalParcialMatrixf(AP,NTERMS,NTERMS,NPARMS,alpha); //alpha de tam NTERMS x NTERMS\n\t\n\treturn 1;\n}\n\n/**\n * @param REAL * W \n * @param REAL * sig\n * @param float * spectro \n * @param int nspectro \n * @param REAL * spectra \n * @param REAL * d_spectra \n * @param REAL * beta \n * @param REAL * alpha \n * \n * */\nint covarm2(REAL *w,REAL *sig,float *spectro,int nspectro,REAL *spectra,REAL  *d_spectra,REAL *beta,REAL *alpha){\t\n\t\n\tint j,i,h,k,aux_nf,aux_nc;\n\n\tREAL AP[NTERMS*NTERMS*NPARMS],BT[NPARMS*NTERMS];\n\t\n\tREAL *BTaux,*APaux;\n\tREAL sum,sum2;\n\n\tfor(j=0;j<NPARMS;j++){\n\t\tfor(i=0;i<nspectro;i++){\n\t\t\topa[i]= w[j]*(spectra[i+nspectro*j]-spectro[i+nspectro*j]);\n\t\t}\n\n\t\tBTaux=BT+(j*NTERMS);\n\t\tAPaux=AP+(j*NTERMS*NTERMS);\n\t\t\n\t\tfor ( i = 0; i < NTERMS; i++){\n\t\t    for ( h = 0; h < NTERMS; h++){\n\t\t\t\tsum=0;\n\t\t\t\tif(i==0){\n\t\t\t\t\tsum2=0;\n\t\t\t\t}\n\t\t\t\tfor ( k = 0;  k < nspectro; k++){\n\t\t\t\t\tREAL dAux = (*(d_spectra+j*nspectro*NTERMS+h*nspectro+k));\n\t\t\t\t\tsum += (*(d_spectra+j*nspectro*NTERMS+i*nspectro+k) * dAux ) * (w[j]/sig[nspectro*j+k]);\n\t\t\t\t\t\n\t\t\t\t\tif(i==0){\n\t\t\t\t\t\tsum2+= ((opa[k] * dAux  ))/sig[nspectro*j+k];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tAPaux[NTERMS*i+h] = sum;\n\t\t\t\tif(i==0){\n\t\t\t\t\tBTaux[h] = sum2;\n\t\t\t\t}\t\t\t\t\n     \t\t} \n\t\t\n\t\t}\t\t\n\t}\n\n\ttotalParcialf(BT,NPARMS,NTERMS,beta); //beta de tam 1 x NTERMS\n\ttotalParcialMatrixf(AP,NTERMS,NTERMS,NPARMS,alpha); //alpha de tam NTERMS x NTERMS\n\t\n\treturn 1;\n}\n\n/**\n * @param spectra: array with synthetic spectro \n * @param nspectro: size of spectro\n * @param spectro: original spectro\n * @param w: array of weight for I,Q,U,V \n * @param sig: array with sigma for I,Q,U,V \n * @param nfree: (nspectro * NPARMS) - NTERMS, NPARAMs is 4 and NTERMS 11. \n * */\nREAL fchisqr(REAL * spectra,int nspectro,float *spectro,REAL *w,REAL *sig,REAL nfree){\n\t\n\tREAL TOT,dif1,dif2,dif3,dif4;\t\n\tREAL opa1,opa2,opa3,opa4;\n\tint i,j;\n\n\tTOT=0;\n\topa1=0;\n\topa2=0;\n\topa3=0;\n\topa4=0;\n\tfor(i=0;i<nspectro;i++){\n\t\tdif1=spectra[i]-spectro[i];\n\t\tdif2=spectra[i+nspectro]-spectro[i+nspectro];\n\t\tdif3=spectra[i+nspectro*2]-spectro[i+nspectro*2];\n\t\tdif4=spectra[i+nspectro*3]-spectro[i+nspectro*3];\n\n\t\topa1+= (((dif1*dif1)*w[0])/(sig[i]));\n\t\topa2+= (((dif2*dif2)*w[1])/(sig[i+nspectro]));\n\t\topa3+= (((dif3*dif3)*w[2])/(sig[i+nspectro*2]));\n\t\topa4+= (((dif4*dif4)*w[3])/(sig[i+nspectro*3]));\n\t}\n\tTOT+= opa1+opa2+opa3+opa4;\n\n\treturn TOT/nfree;\n\t\n}\n\n\n/*\n\n\tMultiplica la matriz a (tama\u00f1o naf,nac)\n\tpor la matriz b (de tama\u00f1o nbf,nbc)\n\tal estilo IDL, es decir, filas de a por columnas de b,\n\tel resultado se almacena en resultOut (de tama\u00f1o fil,col)\n\n\tEl tama\u00f1o de salida (fil,col) corresponde con (nbf,nac).\n\n\tEl tama\u00f1o de columnas de b, nbc, debe de ser igual al de filas de a, naf.\n\n*/\n\n/**\n * @param REAL * a \n * @param int naf\n * @param int nac \n * @param REAL * b\n * @param int nbf\n * @param int nbc \n * @param REAL * result \n * @param int * fil \n * @param int * col \n * @param REAL value \n * */\nint multmatrixIDLValue(REAL *a,int naf,int nac,REAL *b,int nbf,int nbc,REAL *result,int *fil,int *col,REAL value){\n    \n   int i,j,k;\n   REAL sum;\n\t\n\tif(naf==nbc){\n\t\t(*fil)=nbf;\n\t\t(*col)=nac;\n\n\t\tfor ( i = 0; i < nbf; i++){\n\t\t    for ( j = 0; j < nac; j++){\n\t\t\t\tsum=0;\n\t\t\t\tfor ( k = 0;  k < naf; k++){\n\t\t\t\t\tsum += a[k*nac+j] * b[i*nbc+k];\n\t\t\t\t}\n\t\t\t\tresult[((nac)*i)+j] = sum/value;\n      \t\t} \n\t\t}\n\t\treturn 1;\n\t}\n\telse\n\t\tprintf(\"\\n \\n Error en multmatrixIDLValue no coinciden nac y nbf!!!! ..\\n\\n\");\n\treturn 0;\n}\n\n/**\n * \n * */\nint multmatrixIDLValueSigma(REAL *a,int naf,int nac,REAL *b,int nbf,int nbc,REAL *result,int *fil,int *col, REAL * sigma){\n    \n   int i,j,k;\n   REAL sum;\n\t\n\tif(naf==nbc){\n\t\t(*fil)=nbf;\n\t\t(*col)=nac;\n\n\t\tfor ( i = 0; i < nbf; i++){\n\t\t\t\tsum=0;\n\t\t\t\tfor ( k = 0;  k < naf; k++){\n\t\t\t\t\t\tsum += (((a[k] * b[i*nbc+k])))/sigma[k];\n\t\t\t\t}\n\t\t\t\tresult[i] = sum; \n\t\t}\n\t\treturn 1;\n\t}\n\telse\n\t\tprintf(\"\\n \\n Error en multmatrixIDLValue no coinciden nac y nbf!!!! ..\\n\\n\");\n\treturn 0;\n}\n\n/**\n * @param REAL * A\n * @param int f \n * @param int c\n * @param REAL * result\n * */\nvoid totalParcialf(REAL * A, int f,int c,REAL * result){\n\n\tint i,j;\n\tREAL sum;\n\tfor(i=0;i<c;i++){\n\t\tsum = 0;\n\t\tfor(j=0;j<f;j++){\n\t\t\tsum+=A[j*c+i];\n\t\t}\n\t\tresult[i] = sum;\n\t}\n}\n\n/**\n * @param REAL * A\n * @param int f\n * @param int c\n * @param int p\n * @param REAL * result \n * */\nvoid totalParcialMatrixf(REAL * A, int f,int c,int p,REAL *result){\n\n\tint i,j,k;\n\tREAL sum;\n\tfor(i=0;i<f;i++)\n\t\tfor(j=0;j<c;j++){\n\t\t\tsum=0;\n\t\t\tfor(k=0;k<p;k++)\n\t\t\t\tsum+=A[i*c+j+f*c*k];\n\t\t\tresult[i*c+j] = sum;\n\t\t}\n}\n\n\n/**\n * @param PRECISION * a \n * @param int naf \n * @param int nac \n * @param PRECISION * b \n * @param int nbf \n * @param int nbc \n * @param PRECISION * result \n * @param int * fil \n * @param int * col \n * \n * Multiply matrix \"a\"(naf,nac) with matrix \"b\" (nbf,nbc). Algebraic matrix multiplication style, that is, \n * columns of \"a\" by rows of \"b\". The result is stored in \"result\"(fil,col). \n * The size of columns of \"a\", nac, must be the same of rows of \"b\", nbf. \n * */\nint multmatrix(PRECISION *a,int naf,int nac, PRECISION *b,int nbf,int nbc,PRECISION *result,int *fil,int *col){\n    \n    int i,j,k;\n    PRECISION sum;\n    \n\tif(nac==nbf){\n\t\t(*fil)=naf;\n\t\t(*col)=nbc;\n\n\t\tfor ( i = 0; i < naf; i++)\n\t\t    for ( j = 0; j < nbc; j++){\n\t\t\t\tsum=0;\n\t\t\t\tfor ( k = 0;  k < nbf; k++){\n\t\t\t\t\tsum += a[i*nac+k] * b[k*nbc+j];\n\t\t\t\t}\n\t\t\t\tresult[(*col)*i+j] = sum;\n      \t\t} \n\t\treturn 1;\n\t}\n\treturn 0;\n\n}\n\n\n\n/**\n * @param REAL * a\n * @param int naf \n * @param int nac \n * @param REAL *b\n * @param int nbf\n * @param int nbc \n * @param REAL * result \n * @param int * fil \n * @param int * col \n * @param REAL value\n * */\nint multmatrix_transpose(REAL *a,int naf,int nac, REAL *b,int nbf,int nbc,REAL *result,int *fil,int *col,REAL value){\n    \n    int i,j,k;\n    REAL sum;\n    \n\tif(nac==nbc){\n\t\t(*fil)=naf;\n\t\t(*col)=nbf;\n\t\t\n\t\tfor ( i = 0; i < naf; i++){\n\t\t    for ( j = 0; j < nbf; j++){\n\t\t\t\tsum=0;\n\t\t\t\tfor ( k = 0;  k < nbc; k++){\n\t\t\t\t\tsum += a[i*nac+k] * b[j*nbc+k];\n\t\t\t\t}\n\n\t\t\t\tresult[(*col)*i+j] = (sum)*value;\n     \t\t} \n\t\t\n\t\t}\n\t\treturn 1;\n\t}else{\n\t\tprintf(\"\\n \\n Error en multmatrix_transpose no coinciden nac y nbc!!!! ..\\n\\n\");\n\t}\n\n\treturn 0;\n}\n\n/**\n * @param REAL * a\n * @param int naf \n * @param int nac \n * @param REAL *b\n * @param int nbf\n * @param int nbc \n * @param REAL * result \n * @param int * fil \n * @param int * col \n * @param REAL weigth\n * @param REAL * sigma \n * \n * */\nint multmatrix_transpose_sigma(REAL *a,int naf,int nac, REAL *b,int nbf,int nbc,REAL *result,int *fil,int *col,REAL weigth, REAL * sigma){\n    \n    int i,j,k;\n    REAL sum;\n    \n\tif(nac==nbc){\n\t\t(*fil)=naf;\n\t\t(*col)=nbf;\n\t\t\n\t\tfor ( i = 0; i < naf; i++){\n\t\t    for ( j = 0; j < nbf; j++){\n\t\t\t\tsum=0;\n\t\t\t\tfor ( k = 0;  k < nbc; k++){\n\t\t\t\t\t\tsum += (a[i*nac+k] * b[j*nbc+k]) * (weigth/sigma[k]);\n\t\t\t\t}\n\n\t\t\t\tresult[(*col)*i+j] = sum;\n     \t\t} \n\t\t\n\t\t}\n\t\treturn 1;\n\t}else{\n\t\tprintf(\"\\n \\n Error en multmatrix_transpose no coinciden nac y nbc!!!! ..\\n\\n\");\n\t}\n\n\treturn 0;\n}\n//Media de un vector de longitud numl\n\n\n\n/**\n * @param int nspectro\n */\nint CalculaNfree(int nspectro)\n{\n\tint nfree;\n\tnfree = 0;\n\n\tnfree = (nspectro * NPARMS) - NTERMS;\n\n\treturn nfree;\n}\n\n/**\n * @param const char * path\n * */\nint isDirectory(const char *path) {\n   struct stat statbuf;\n   if (stat(path, &statbuf) != 0)\n       return 0;\n   return S_ISDIR(statbuf.st_mode);\n}\n\n/**\n * @param tpuntero * cabeza\n * @param char * fileName\n * */\nvoid insert_in_linked_list (tpuntero *cabeza, char * fileName){\n    tpuntero nuevo; \n    nuevo = malloc(sizeof(tnodo)); \n    strcpy(nuevo->d_name,fileName); \n    nuevo->next = *cabeza; \n    *cabeza = nuevo; \n}\n \n/**\n * @param tpuntero  cabeza\n * @param char * fileName\n * */\nint checkNameInLista(tpuntero cabeza,char * fileName){\n\tint found = 0;\n    while(cabeza != NULL && !found){ //Mientras cabeza no sea NULL\n\t\tif(strcmp(cabeza->d_name,fileName)==0)\n\t\t\tfound = 1;\n\t\telse\n        \tcabeza = cabeza->next; //Pasamos al siguiente nodo\n    }\n\treturn found;\n}\n \n\n/**\n * @param tpuntero * cabeza\n * */\n\nvoid deleteList(tpuntero *cabeza){ \n    tpuntero actual; //Puntero auxiliar para eliminar correctamente la lista\n  \n    while(*cabeza != NULL){ //Mientras cabeza no sea NULL\n        actual = *cabeza; //Actual toma el valor de cabeza\n        *cabeza = (*cabeza)->next; //Cabeza avanza 1 posicion en la lista\n        free(actual); //Se libera la memoria de la posicion de Actual (el primer nodo), y cabeza queda apuntando al que ahora es el primero\n    }\n}", "meta": {"hexsha": "5041c1603e6a041d2c47df6c11f0c106460b6aeb", "size": 9792, "ext": "c", "lang": "C", "max_stars_repo_path": "p-milos/src/lib.c", "max_stars_repo_name": "dcalc/hrt_pipeline", "max_stars_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_stars_repo_licenses": ["MIT"], "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-milos/src/lib.c", "max_issues_repo_name": "dcalc/hrt_pipeline", "max_issues_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-11-05T14:03:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T14:18:48.000Z", "max_forks_repo_path": "p-milos/src/lib.c", "max_forks_repo_name": "dcalc/hrt_pipeline", "max_forks_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-14T12:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T19:10:00.000Z", "avg_line_length": 21.3333333333, "max_line_length": 190, "alphanum_fraction": 0.5893586601, "num_tokens": 3614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.35284781563730305}}
{"text": "#pragma once\n\n#include \"mexObjectiveFunction.h\"\n\n#include <nlopt.h>\n#include <mex.h>\n\nstruct mexConstraintFunction\n{\n  static double con_fun(unsigned n, const double *x, double *gradient, void *d_);\n  static void vcon_fun(unsigned m, double *result, unsigned n, const double* x, double* grad, void* f_data);\n\n  bool isvector;\n  nlopt_func fun;   // (unsigned n, const double *x, double *fc, void *func_data)\n  nlopt_mfunc mfun; // (unsigned m, double *result, unsigned n, const double *x, double *fc, void *func_data)\n\n  mxArray *prhs[2];          // feval mexMatlabCall input arguments for objective function evaluation\n  \n  nlopt_opt &opt;\n  mxArray *&lasterror;        // mexObjectiveFunction's to store trapped MException \n  bool &stop;                 // mexObjectiveFunction's to flag if user issued a stop\n  \n  mexConstraintFunction(mxArray * mxFun, mexObjectiveFunction &data);\n  ~mexConstraintFunction();\nprivate:\n  double evalFun(unsigned n, const double *x, double *gradient);\n  void evalVecFun(unsigned m, unsigned n, const double* x, double *c, double* Cgrad);\n  bool call_matlab_feval_with_trap(int nlhs, mxArray *plhs[], const int n, const double *x);\n};\n", "meta": {"hexsha": "12772a0aaf5accb415bc75b833471c94e79dbec2", "size": 1170, "ext": "h", "lang": "C", "max_stars_repo_path": "+nlopt/@options/mexConstraintFunction.h", "max_stars_repo_name": "hokiedsp/matlab-nlopt", "max_stars_repo_head_hexsha": "19d3de4d2d3ad80a247dfc95fb1e43faae92a19f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-30T06:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-02T05:57:14.000Z", "max_issues_repo_path": "+nlopt/@options/mexConstraintFunction.h", "max_issues_repo_name": "hokiedsp/matlab-nlopt", "max_issues_repo_head_hexsha": "19d3de4d2d3ad80a247dfc95fb1e43faae92a19f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-22T03:36:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-25T01:13:12.000Z", "max_forks_repo_path": "+nlopt/@options/mexConstraintFunction.h", "max_forks_repo_name": "hokiedsp/matlab-nlopt", "max_forks_repo_head_hexsha": "19d3de4d2d3ad80a247dfc95fb1e43faae92a19f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-23T09:52:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T02:23:20.000Z", "avg_line_length": 39.0, "max_line_length": 109, "alphanum_fraction": 0.7162393162, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.352729129824959}}
{"text": "// Copyright 2019 Victor Hugo Schulz\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF 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 STAR_IDENTIFICATION_H\n#define STAR_IDENTIFICATION_H\n\nextern \"C\"{\n#include <cblas.h>\n}\n#include <algorithm>\n#include <limits>\n#include <vector>\n#include <string.h>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include \"structures_st.h\"\n#include \"centroiding.h\"\n#include \"standard_structures.h\"\n\nnamespace st {\n\nenum Stmode {REFERENCE, REFERENCE_BIN, BINARY, BINARY_INDEX, K};\n\nclass StarIdentification\n{\npublic:\n    StarIdentification();\n    ~StarIdentification();\n    std_str::Sky identifyStars(std_str::Sky csky);\n    void reload();\n\n    StarIdConfiguration config;\nprivate:\n    void bit_descriptor (unsigned long *bucket, unsigned int bucket_size, std::vector<cv::Point2d> &translated);\n    void initialize_catalog(void *ptr, size_t size, std::string filename);\n    void translate_rotate (std::vector<cv::Point2d> &translated, double &nn_dist, std::vector<std_str::Star> stars, uint ref);\n    int normalized_coordinate (double pixel_coordinate);\n    int cell(double x, double y);\n    void descriptor(std::vector<int> &desc, std::vector<cv::Point2d> &translated);\n    void pixel_to_unit_vector(cv::Point3d *unit_vector, cv::Point2d star);\n    int array_intersection(int* array0, int size0, int* array1, int size1, int max_element);\n    int binSearch(double what);\n    int binSearch2(float what, float *data, int len);\n    int classify(int *max, int *desc_size, std::vector<cv::Point2d> &translated);\n    int classifyK(int *max, int *desc_size, std::vector<cv::Point2d> &translated, double nn_angle);\n    int classify_binary(int *max, int *desc_size, std::vector<cv::Point2d> &translated, double nn_angle);\n    int classify_binary_index(int *max, int *desc_size, std::vector<cv::Point2d> &translated, double nn_angle);\n    int classify_binary_ref(int *max, int *desc_size, std::vector<cv::Point2d> &translated);\n    void classifier(std::vector<Candidate> &candidates, std::vector<std_str::Star> stars);\n    cv::Point3d cross(cv::Point3d a, cv::Point3d b);\n    double vector_angle(cv::Point3d a, cv::Point3d b);\n    void filter(std::vector<Candidate> & cluster, double fov);\n    void cluster (std::vector<std::vector<Candidate> > &output, std::vector<Candidate> &candidates, double v_fov);\n    std::vector<Candidate>* verify (std::vector<std::vector<Candidate> > &clustered);\n    double fov(double size, double focus);\n    std_str::Star to_star(Candidate cd);\n    std::vector<std_str::Star> format_output(std::vector<Candidate> *verified);\n    void loadConfig();\n    void loadDatabase();\n\n    double **ref_cat;\n    unsigned long long **bin_cat;\n    short **lut_cat;\n    float **lut_nn_cat;\n    short *index;\n\n    Stmode mode;\n};\n\n}\n\n#endif // STAR_IDENTIFICATION_H\n", "meta": {"hexsha": "218b0f7618eafc03d7d0cd32648fad12bf0f1f9e", "size": 3375, "ext": "h", "lang": "C", "max_stars_repo_path": "src/tcp_dut_client/star_identification.h", "max_stars_repo_name": "schulz89/Verification-Platform-for-Star-Trackers", "max_stars_repo_head_hexsha": "5216feb8036506503713c0c1f89728ecc40b3d5c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-06T10:32:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T21:14:26.000Z", "max_issues_repo_path": "src/tcp_dut_client/star_identification.h", "max_issues_repo_name": "schulz89/Verification-Platform-for-Star-Trackers", "max_issues_repo_head_hexsha": "5216feb8036506503713c0c1f89728ecc40b3d5c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-30T06:25:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-30T06:25:21.000Z", "max_forks_repo_path": "src/tcp_dut_client/star_identification.h", "max_forks_repo_name": "schulz89/Verification-Platform-for-Star-Trackers", "max_forks_repo_head_hexsha": "5216feb8036506503713c0c1f89728ecc40b3d5c", "max_forks_repo_licenses": ["Apache-2.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.3522727273, "max_line_length": 126, "alphanum_fraction": 0.7285925926, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3527287798141549}}
{"text": "#include <math.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_spline.h>\n#include <galpy_potentials.h>\n// Reflex Motion potential - based on Moving Object Potential\n// 3 arguments: amp, t0, tf\nvoid constrain_range2(double * d) {\n  // Constrains index to be within interpolation range\n  if (*d < 0) *d = 0.0;\n  if (*d > 1) *d = 1.0;\n}\ndouble ReflexMotionRforce(double R,double z, double phi,\n\t\t\t\t   double t,\n\t\t\t\t   struct potentialArg * potentialArgs){\n  double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z,obj_R,obj_phi,RF;\n  double * args= potentialArgs->args;\n  //Get args\n  amp= *args;\n  t0= *(args+1);\n  tf= *(args+2);\n  d_ind= (t-t0)/(tf-t0);\n  x= R*cos(phi);\n  y= R*sin(phi);\n  constrain_range2(&d_ind);\n  // Interpolate x, y, z\n  obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);\n  obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,\n\t\t\t *(potentialArgs->acc1d+1));\n  obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,\n\t\t\t *(potentialArgs->acc1d+2));\n  // Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);\n  obj_R = pow(pow(obj_x,2) + pow(obj_y,2),0.5);\n  obj_phi = atan2(obj_y,obj_x);\n  // Calculate R force\n  RF= calcRforce(obj_R,obj_z,obj_phi,t,potentialArgs->nwrapped,\n\t\t potentialArgs->wrappedPotentialArg);\n  return -amp*RF*(cos(phi)*cos(obj_phi)+sin(phi)*sin(obj_phi));\n}\n\ndouble ReflexMotionzforce(double R,double z,double phi,\n\t\t\t\t      double t,\n\t\t\t\t      struct potentialArg * potentialArgs){\n  double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z, obj_R, obj_phi;\n  double * args= potentialArgs->args;\n  //Get args\n  amp= *args;\n  t0= *(args+1);\n  tf= *(args+2);\n  d_ind= (t-t0)/(tf-t0);\n  x= R*cos(phi);\n  y= R*sin(phi);\n  constrain_range2(&d_ind);\n  // Interpolate x, y, z\n  obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);\n  obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,\n\t\t\t *(potentialArgs->acc1d+1));\n  obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,\n\t\t\t *(potentialArgs->acc1d+2));\n  // Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);\n  obj_R = pow(pow(obj_x,2) + pow(obj_y,2),0.5);\n  obj_phi = atan2(obj_y,obj_x);\n  \n  // Calculate z force\n  return -amp * calczforce(obj_R,obj_z,obj_phi,t,potentialArgs->nwrapped,\n\t\t\t   potentialArgs->wrappedPotentialArg);\n}\n\ndouble ReflexMotionphiforce(double R,double z,double phi,\n\t\t\t\t\tdouble t,\n\t\t\t\t\tstruct potentialArg * potentialArgs){\n  double amp,t0,tf,d_ind,x,y,obj_x,obj_y,obj_z, obj_R, obj_phi, RF;\n  double * args= potentialArgs->args;\n  //Get args\n  amp= *args;\n  t0= *(args+1);\n  tf= *(args+2);\n  d_ind= (t-t0)/(tf-t0);\n  x= R*cos(phi);\n  y= R*sin(phi);\n  constrain_range2(&d_ind);\n  // Interpolate x, y, z\n  obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);\n  obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,\n\t\t\t *(potentialArgs->acc1d+1));\n  obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,\n\t\t\t *(potentialArgs->acc1d+2));\n  // Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);\n  obj_R = pow(pow(obj_x,2) + pow(obj_y,2),0.5);\n  obj_phi = atan2(obj_y,obj_x);\n\n  // Calculate phiforce\n  RF= calcRforce(obj_R,obj_z,obj_phi,t,potentialArgs->nwrapped,\n\t\t potentialArgs->wrappedPotentialArg);\n  return amp*RF*(sin(phi)*cos(obj_phi)-cos(phi)*sin(obj_phi));\n}\n\n// double MovingObjectPotentialPlanarRforce(double R, double phi,\n// \t\t\t\t      double t,\n// \t\t\t\t      struct potentialArg * potentialArgs){\n//  double amp,t0,tf,d_ind,x,y,obj_x,obj_y,Rdist,RF;\n//  double * args= potentialArgs->args;\n  //Get args\n//  amp= *args;\n//  t0= *(args+1);\n//  tf= *(args+2);\n//  d_ind= (t-t0)/(tf-t0);\n//  x= R*cos(phi);\n//  y= R*sin(phi);\n//  constrain_range(&d_ind);\n  // Interpolate x, y\n//  obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);\n//  obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,\n//\t\t\t *(potentialArgs->acc1d+1));\n//  Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);\n  // Calculate R force\n//  RF= calcPlanarRforce(Rdist, phi, t, potentialArgs->nwrapped,\n//\t\t       potentialArgs->wrappedPotentialArg);\n//  return -amp*RF*(cos(phi)*(obj_x-x)+sin(phi)*(obj_y-y))/Rdist;\n//}\n\n// double MovingObjectPotentialPlanarphiforce(double R, double phi,\n//\t\t\t\t\tdouble t,\n//\t\t\t\t\tstruct potentialArg * potentialArgs){\n//  double amp,t0,tf,d_ind,x,y,obj_x,obj_y,Rdist,RF;\n//  double * args= potentialArgs->args;\n  // Get args\n//  amp= *args;\n//  t0= *(args+1);\n//  tf= *(args+2);\n//  d_ind= (t-t0)/(tf-t0);\n//  x= R*cos(phi);\n//  y= R*sin(phi);\n//  constrain_range(&d_ind);\n  // Interpolate x, y\n//  obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);\n//  obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,\n//\t\t\t *(potentialArgs->acc1d+1));\n//  Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);\n  // Calculate phiforce\n//  RF= calcPlanarRforce(Rdist, phi, t, potentialArgs->nwrapped,\n//\t\t       potentialArgs->wrappedPotentialArg);\n//  return -amp*RF*R*(cos(phi)*(obj_y-y)-sin(phi)*(obj_x-x))/Rdist;\n//}\n", "meta": {"hexsha": "401f0f0445e19b4ac851b12a01774927adb9b9cb", "size": 4966, "ext": "c", "lang": "C", "max_stars_repo_path": "galpy/potential/potential_c_ext/ReflexMotion.c", "max_stars_repo_name": "radsouza/galpy", "max_stars_repo_head_hexsha": "83e9b3de53c59d51e3bb44751baf41d766ec5a52", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "galpy/potential/potential_c_ext/ReflexMotion.c", "max_issues_repo_name": "radsouza/galpy", "max_issues_repo_head_hexsha": "83e9b3de53c59d51e3bb44751baf41d766ec5a52", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "galpy/potential/potential_c_ext/ReflexMotion.c", "max_forks_repo_name": "radsouza/galpy", "max_forks_repo_head_hexsha": "83e9b3de53c59d51e3bb44751baf41d766ec5a52", "max_forks_repo_licenses": ["BSD-3-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.4861111111, "max_line_length": 81, "alphanum_fraction": 0.6619009263, "num_tokens": 1709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8056321796478254, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.35272469989241223}}
{"text": "#include <lapacke.h>\nint main() { LAPACKE_dlapy2(0, 0); }\n", "meta": {"hexsha": "76f8ebca6147b55d2effa06acf7137813317241b", "size": 58, "ext": "c", "lang": "C", "max_stars_repo_path": "config/check_lapacke.c", "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_issues_repo_path": "config/check_lapacke.c", "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 514.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_forks_repo_path": "config/check_lapacke.c", "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "avg_line_length": 19.3333333333, "max_line_length": 36, "alphanum_fraction": 0.6551724138, "num_tokens": 24, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.35235861122492623}}
{"text": "/*! \\file Exceptions.h\n *  \\brief header file that defines exceptions\n */\n// Function.h\n\n#ifndef NBODYEXCEPTION_H\n#define NBODYEXCEPTION_H\n\n#include <exception>\n#include <string>\n#include <utility>\n\n#include <gsl/gsl_errno.h>\n\nnamespace Math\n{\n\nclass gsl_error : public std::exception {\n\nprivate:\n\tint gsl_errno;\n\tstd::string errmsg;\n\npublic:\n\tgsl_error(int gsl_errno) :\n\t\tgsl_errno(gsl_errno),\n\t\terrmsg(gsl_strerror(gsl_errno))\n\t{\n\t}\n\n\tint get_gsl_errno() {\n\t\treturn gsl_errno;\n\t}\n\n\tconst char *what() const noexcept\n\t{\n\t\treturn errmsg.c_str();\n\t}\n\n};\n\ntemplate<typename Func, typename ... Args>\nvoid gsl_invoke(Func &&f, Args ... args)\n{\n\tint status = f(std::forward<Args>(args)...);\n\tif (status != GSL_SUCCESS) {\n\t\tthrow gsl_error(status);\n\t}\n}\n\n}\n\n\n#endif\n", "meta": {"hexsha": "d5915010e901e059865e82b623404bf88b34efca", "size": 760, "ext": "h", "lang": "C", "max_stars_repo_path": "src/Math/Exceptions.h", "max_stars_repo_name": "ICRAR/NBodylib", "max_stars_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_stars_repo_licenses": ["MIT"], "max_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/Exceptions.h", "max_issues_repo_name": "ICRAR/NBodylib", "max_issues_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-05-21T16:49:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T06:31:03.000Z", "max_forks_repo_path": "src/Math/Exceptions.h", "max_forks_repo_name": "ICRAR/NBodylib", "max_forks_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-04-23T02:58:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T00:21:57.000Z", "avg_line_length": 13.8181818182, "max_line_length": 46, "alphanum_fraction": 0.6881578947, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.35231816993081766}}
{"text": "/**\n *\n * @file zcgels.c\n *\n *  PLASMA computational routines\n *  PLASMA is a software package provided by Univ. of Tennessee,\n *  Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Emmanuel Agullo\n * @date 2010-11-15\n * @precisions mixed zc -> ds\n *\n **/\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <lapacke.h>\n#include \"common.h\"\n\n#define PLASMA_zlag2c(_descA, _descSB)                \\\n  plasma_parallel_call_4(plasma_pzlag2c,              \\\n                         PLASMA_desc,      (_descA),  \\\n                         PLASMA_desc,      (_descSB), \\\n                         PLASMA_sequence*, sequence,  \\\n                         PLASMA_request*,  request)\n\n#define PLASMA_clag2z(_descSA, _descB)                \\\n  plasma_parallel_call_4(plasma_pclag2z,              \\\n                         PLASMA_desc,      (_descSA), \\\n                         PLASMA_desc,      (_descB),  \\\n                         PLASMA_sequence*, sequence,  \\\n                         PLASMA_request*,  request)\n\n#define PLASMA_zlange(_norm, _descA, _result, _work)   \\\n  _result = 0;                                         \\\n  plasma_parallel_call_6(plasma_pzlange,               \\\n                         PLASMA_enum,      (_norm),    \\\n                         PLASMA_desc,      (_descA),   \\\n                         double*,          (_work),    \\\n                         double*,          &(_result), \\\n                         PLASMA_sequence*, sequence,   \\\n                         PLASMA_request*,  request);\n\n#define PLASMA_zlacpy(_descA, _descB)                        \\\n  plasma_parallel_call_5(plasma_pzlacpy,                     \\\n                         PLASMA_enum,      PlasmaUpperLower, \\\n                         PLASMA_desc,      (_descA),         \\\n                         PLASMA_desc,      (_descB),         \\\n                         PLASMA_sequence*, sequence,         \\\n                         PLASMA_request*,  request)\n\n#define PLASMA_zgeadd(_alpha, _descA, _descB)           \\\n  plasma_parallel_call_5(plasma_pzgeadd,                \\\n                         PLASMA_Complex64_t, (_alpha), \\\n                         PLASMA_desc,        (_descA), \\\n                         PLASMA_desc,        (_descB), \\\n                         PLASMA_sequence*,   sequence, \\\n                         PLASMA_request*,    request)\n\n/***************************************************************************//**\n *\n * @ingroup PLASMA_Complex64_t\n *\n *  PLASMA_zcgels - Solves overdetermined or underdetermined linear systems involving an M-by-N\n *  matrix A using the QR or the LQ factorization of A.  It is assumed that A has full rank.\n *  The following options are provided:\n *\n *  # trans = PlasmaNoTrans and M >= N: find the least squares solution of an overdetermined\n *    system, i.e., solve the least squares problem: minimize || B - A*X ||.\n *\n *  # trans = PlasmaNoTrans and M < N:  find the minimum norm solution of an underdetermined\n *    system A * X = B.\n *\n *  Several right hand side vectors B and solution vectors X can be handled in a single call;\n *  they are stored as the columns of the M-by-NRHS right hand side matrix B and the N-by-NRHS\n *  solution matrix X.\n *\n *  PLASMA_zcgels first attempts to factorize the matrix in COMPLEX and use this\n *  factorization within an iterative refinement procedure to produce a\n *  solution with COMPLEX*16 normwise backward error quality (see below).\n *  If the approach fails the method switches to a COMPLEX*16\n *  factorization and solve.\n *\n *  The iterative refinement is not going to be a winning strategy if\n *  the ratio COMPLEX performance over COMPLEX*16 performance is too\n *  small. A reasonable strategy should take the number of right-hand\n *  sides and the size of the matrix into account. This might be done\n *  with a call to ILAENV in the future. Up to now, we always try\n *  iterative refinement.\n *\n *  The iterative refinement process is stopped if ITER > ITERMAX or\n *  for all the RHS we have: RNRM < N*XNRM*ANRM*EPS*BWDMAX\n *  where:\n *\n *  - ITER is the number of the current iteration in the iterative refinement process\n *  - RNRM is the infinity-norm of the residual\n *  - XNRM is the infinity-norm of the solution\n *  - ANRM is the infinity-operator-norm of the matrix A\n *  - EPS is the machine epsilon returned by DLAMCH('Epsilon').\n *\n *  Actually, in its current state (PLASMA 2.1.0), the test is slightly relaxed.\n *\n *  The values ITERMAX and BWDMAX are fixed to 30 and 1.0D+00 respectively.\n *\n *  We follow Bjorck's algorithm proposed in \"Iterative Refinement of Linear\n *  Least Squares solutions I\", BIT, 7:257-278, 1967.\n *\n *******************************************************************************\n *\n * @param[in] trans\n *          Intended usage:\n *          = PlasmaNoTrans:   the linear system involves A;\n *          = PlasmaConjTrans: the linear system involves A**H.\n *          Currently only PlasmaNoTrans is supported.\n *\n * @param[in] M\n *          The number of rows of the matrix A. M >= 0.\n *\n * @param[in] N\n *          The number of columns of the matrix A. N >= 0.\n *\n * @param[in] NRHS\n *          The number of right hand sides, i.e., the number of columns of the matrices B and X.\n *          NRHS >= 0.\n *\n * @param[in] A\n *          The M-by-N matrix A. This matrix is not modified.\n *\n * @param[in] LDA\n *          The leading dimension of the array A. LDA >= max(1,M).\n *\n * @param[in] B\n *          The M-by-NRHS matrix B of right hand side vectors, stored columnwise. Not modified.\n *\n * @param[in] LDB\n *          The leading dimension of the array B. LDB >= MAX(1,M,N).\n *\n * @param[out] X\n *          If return value = 0, the solution vectors, stored columnwise.\n *          if M >= N, rows 1 to N of X contain the least squares solution vectors; the residual\n *          sum of squares for the solution in each column is given by the sum of squares of the\n *          modulus of elements N+1 to M in that column;\n *          if M < N, rows 1 to N of X contain the minimum norm solution vectors;\n *\n * @param[in] LDX\n *          The leading dimension of the array X. LDX >= MAX(1,M,N).\n *\n * @param[out] ITER\n *          The number of the current iteration in the iterative refinement process\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *          \\retval <0 if -i, the i-th argument had an illegal value\n *\n *******************************************************************************\n *\n * @sa PLASMA_zcgels_Tile\n * @sa PLASMA_zcgels_Tile_Async\n * @sa PLASMA_dsgels\n * @sa PLASMA_zgels\n *\n ******************************************************************************/\nint PLASMA_zcgels(PLASMA_enum trans, int M, int N, int NRHS,\n                  PLASMA_Complex64_t *A, int LDA,\n                  PLASMA_Complex64_t *B, int LDB,\n                  PLASMA_Complex64_t *X, int LDX, int *ITER)\n{\n    int i, j;\n    int NB, NBNB, MT, NT, NTRHS;\n    int status;\n    PLASMA_desc  descA;\n    PLASMA_desc  descB;\n    PLASMA_desc *descT;\n    PLASMA_desc  descX;\n    plasma_context_t *plasma;\n    PLASMA_sequence *sequence = NULL;\n    PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_zcgels\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n\n    *ITER = 0;\n\n    /* Check input arguments */\n    if (trans != PlasmaNoTrans   &&\n        trans != PlasmaConjTrans &&\n        trans != PlasmaTrans )\n    {\n        plasma_error(\"PLASMA_zcgels\", \"illegal value of trans\");\n        return -1;\n    }\n    if (trans != PlasmaNoTrans) {\n        plasma_error(\"PLASMA_zcgels\", \"only PlasmaNoTrans supported\");\n        return PLASMA_ERR_NOT_SUPPORTED;\n    }\n    if (M < 0) {\n        plasma_error(\"PLASMA_zcgels\", \"illegal value of M\");\n        return -2;\n    }\n    if (N < 0) {\n        plasma_error(\"PLASMA_zcgels\", \"illegal value of N\");\n        return -3;\n    }\n    if (NRHS < 0) {\n        plasma_error(\"PLASMA_zcgels\", \"illegal value of NRHS\");\n        return -4;\n    }\n    if (LDA < max(1, M)) {\n        plasma_error(\"PLASMA_zcgels\", \"illegal value of LDA\");\n        return -6;\n    }\n    if (LDB < max(1, max(M, N))) {\n        plasma_error(\"PLASMA_zcgels\", \"illegal value of LDB\");\n        return -9;\n    }\n    if (LDX < max(1, max(M, N))) {\n        plasma_error(\"PLASMA_zcgels\", \"illegal value of LDX\");\n        return -10;\n    }\n    /* Quick return */\n    if (min(M, min(N, NRHS)) == 0) {\n        for (i = 0; i < max(M, N); i++)\n            for (j = 0; j < NRHS; j++)\n                B[j*LDB+i] = 0.0;\n        return PLASMA_SUCCESS;\n    }\n\n    /* Tune NB & IB depending on M, N & NRHS; Set NBNB */\n    status = plasma_tune(PLASMA_FUNC_ZCGELS, M, N, NRHS);\n    if (status != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_zcgels\", \"plasma_tune() failed\");\n        return status;\n    }\n\n    /* Set MT, NT & NTRHS */\n    NB    = PLASMA_NB;\n    NBNB  = NB*NB;\n    NT    = (N%NB==0) ? (N/NB) : (N/NB+1);\n    MT    = (M%NB==0) ? (M/NB) : (M/NB+1);\n    NTRHS = (NRHS%NB==0) ? (NRHS/NB) : (NRHS/NB+1);\n    printf(\"M %d, N %d, NRHS %d, NB %d, MT %d, NT %d, NTRHS %d\\n\", M, N, NRHS, NB, MT, NT, NTRHS);\n\n    plasma_sequence_create(plasma, &sequence);\n\n    descA = plasma_desc_init(\n                PlasmaComplexDouble,\n                NB, NB, NBNB,\n                M, N, 0, 0, M, N);\n\n    if (M >= N) {\n        descB = plasma_desc_init(\n            PlasmaComplexDouble,\n            NB, NB, NBNB,\n            M, NRHS, 0, 0, M, NRHS);\n\n        descX = plasma_desc_init(\n            PlasmaComplexDouble,\n            NB, NB, NBNB,\n            M, NRHS, 0, 0, M, NRHS);\n\n    }\n    else {\n        descB = plasma_desc_init(\n            PlasmaComplexDouble,\n            NB, NB, NBNB,\n            N, NRHS, 0, 0, N, NRHS);\n\n        descX = plasma_desc_init(\n            PlasmaComplexDouble,\n            NB, NB, NBNB,\n            N, NRHS, 0, 0, N, NRHS);\n    }\n\n    /* DOUBLE PRECISION INITIALIZATION */\n    /* Allocate memory for matrices in block layout */\n    if (plasma_desc_mat_alloc(&descA) || plasma_desc_mat_alloc(&descB) || plasma_desc_mat_alloc(&descX)) {\n        plasma_error(\"PLASMA_zcgels\", \"plasma_shared_alloc() failed\");\n        plasma_desc_mat_free(&descA);\n        plasma_desc_mat_free(&descB);\n        plasma_desc_mat_free(&descX);\n        return PLASMA_ERR_OUT_OF_RESOURCES;\n    }\n\n    plasma_parallel_call_5(plasma_pzlapack_to_tile,\n        PLASMA_Complex64_t*, A,\n        int, LDA,\n        PLASMA_desc, descA,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, &request);\n\n    plasma_parallel_call_5(plasma_pzlapack_to_tile,\n        PLASMA_Complex64_t*, B,\n        int, LDB,\n        PLASMA_desc, descB,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, &request);\n\n    /* Allocate workspace */\n    PLASMA_Alloc_Workspace_zgels_Tile(M, N, &descT);\n\n    /* Call the native interface */\n    status = PLASMA_zcgels_Tile_Async(PlasmaNoTrans, &descA, descT, &descB, &descX, ITER,\n                                      sequence, &request);\n\n    if (status == PLASMA_SUCCESS) {\n        plasma_parallel_call_5(plasma_pztile_to_lapack,\n            PLASMA_desc, descX,\n            PLASMA_Complex64_t*, X,\n            int, LDX,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, &request);\n    }\n    plasma_dynamic_sync();\n\n    PLASMA_Dealloc_Handle_Tile(&descT);\n    plasma_sequence_destroy(plasma, sequence);\n    plasma_desc_mat_free(&descA);\n    plasma_desc_mat_free(&descB);\n    plasma_desc_mat_free(&descX);\n    return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup PLASMA_Complex64_t_Tile\n *\n *  PLASMA_zcgels_Tile - Solves overdetermined or underdetermined linear system of equations\n *  using the tile QR or the tile LQ factorization and mixed-precision iterative refinement.\n *  Tile equivalent of PLASMA_zcgesv().\n *  Operates on matrices stored by tiles.\n *  All matrices are passed through descriptors.\n *  All dimensions are taken from the descriptors.\n *\n *******************************************************************************\n *\n * @param[in] trans\n *          Intended usage:\n *          = PlasmaNoTrans:   the linear system involves A;\n *          = PlasmaConjTrans: the linear system involves A**H.\n *          Currently only PlasmaNoTrans is supported.\n *\n * @param[in,out] A\n *          - If the iterative refinement converged, A is not modified;\n *          - otherwise, it fell back to double precision solution, and\n *          on exit the M-by-N matrix A contains:\n *          if M >= N, A is overwritten by details of its QR factorization as returned by\n *                     PLASMA_zgeqrf;\n *          if M < N, A is overwritten by details of its LQ factorization as returned by\n *                      PLASMA_zgelqf.\n *\n * @param[out] T\n *          On exit:\n *          - if the iterative refinement converged, T is not modified;\n *          - otherwise, it fell back to double precision solution,\n *          and then T is an auxiliary factorization data.\n *\n * @param[in,out] B\n *          On entry, the M-by-NRHS matrix B of right hand side vectors, stored columnwise;\n *          On exit, if return value = 0, B is overwritten by the solution vectors, stored\n *          columnwise:\n *          if M >= N, rows 1 to N of B contain the least squares solution vectors; the residual\n *          sum of squares for the solution in each column is given by the sum of squares of the\n *          modulus of elements N+1 to M in that column;\n *          if M < N, rows 1 to N of B contain the minimum norm solution vectors;\n *\n * @param[in] B\n *          The descriptor of the M-by-NRHS matrix B of right hand side vectors, stored columnwise. Not modified.\n *\n * @param[in,out] X\n *          On entry, it's only the descriptor where to store the result.\n *          On exit, if return value = 0, X is the solution vectors, stored columnwise:\n *          if M >= N, rows 1 to N of X contain the least squares solution vectors; the residual\n *          sum of squares for the solution in each column is given by the sum of squares of the\n *          modulus of elements N+1 to M in that column;\n *          if M < N, rows 1 to N of X contain the minimum norm solution vectors;\n *\n * @param[out] ITER\n *          If > 0, ITER is the number of the current iteration in the iterative refinement process.\n *          -ITERMAX-1, if the refinment step failed and the double precision factorization has been used.\n *\n *******************************************************************************\n *\n * @return\n *          \\retval PLASMA_SUCCESS successful exit\n *\n *******************************************************************************\n *\n * @sa PLASMA_zcgels\n * @sa PLASMA_zcgels_Tile_Async\n * @sa PLASMA_dsgels_Tile\n * @sa PLASMA_zgels_Tile\n *\n ******************************************************************************/\nint PLASMA_zcgels_Tile(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T,\n                       PLASMA_desc *B, PLASMA_desc *X, int *ITER)\n{\n    plasma_context_t *plasma;\n    PLASMA_sequence *sequence = NULL;\n    PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n    int status;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_zcgels_Tile\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n    plasma_sequence_create(plasma, &sequence);\n    status = PLASMA_zcgels_Tile_Async(trans, A, T, B, X, ITER, sequence, &request);\n    if (status != PLASMA_SUCCESS)\n        return status;\n    plasma_dynamic_sync();\n    status = sequence->status;\n    plasma_sequence_destroy(plasma, sequence);\n    return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup PLASMA_Complex64_t_Tile_Async\n *\n *  PLASMA_zcgels_Tile_Async - Solves overdetermined or underdetermined linear\n *  system of equations using the tile QR or the tile LQ factorization and\n *  mixed-precision iterative refinement.\n *  Non-blocking equivalent of PLASMA_zcgels_Tile().\n *  May return before the computation is finished.\n *  Allows for pipelining of operations at runtime.\n *\n *******************************************************************************\n *\n * @param[in] sequence\n *          Identifies the sequence of function calls that this call belongs to\n *          (for completion checks and exception handling purposes).\n *\n * @param[out] request\n *          Identifies this function call (for exception handling purposes).\n *\n *******************************************************************************\n *\n * @sa PLASMA_zcgels\n * @sa PLASMA_zcgels_Tile\n * @sa PLASMA_dsgels_Tile_Async\n * @sa PLASMA_zgels_Tile_Async\n *\n ******************************************************************************/\nint PLASMA_zcgels_Tile_Async(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T,\n                             PLASMA_desc *B, PLASMA_desc *X, int *ITER,\n                             PLASMA_sequence *sequence, PLASMA_request *request)\n{\n    int M, N, NRHS, NB, NBNB, MT, NT, NTRHS;\n    PLASMA_desc descA;\n    PLASMA_desc descT;\n    PLASMA_desc descB;\n    PLASMA_desc descX;\n    plasma_context_t *plasma;\n    double *work;\n\n    const int itermax = 30;\n    const double bwdmax = 1.0;\n    const PLASMA_Complex64_t negone = -1.0;\n    const PLASMA_Complex64_t one = 1.0;\n    int iiter;\n    double Anorm, cte, eps, Rnorm, Xnorm;\n    *ITER=0;\n\n    plasma = plasma_context_self();\n    if (plasma == NULL) {\n        plasma_fatal_error(\"PLASMA_zcgels_Tile\", \"PLASMA not initialized\");\n        return PLASMA_ERR_NOT_INITIALIZED;\n    }\n    if (sequence == NULL) {\n        plasma_fatal_error(\"PLASMA_zcgels_Tile\", \"NULL sequence\");\n        return PLASMA_ERR_UNALLOCATED;\n    }\n    if (request == NULL) {\n        plasma_fatal_error(\"PLASMA_zcgels_Tile\", \"NULL request\");\n        return PLASMA_ERR_UNALLOCATED;\n    }\n    /* Check sequence status */\n    if (sequence->status == PLASMA_SUCCESS)\n        request->status = PLASMA_SUCCESS;\n    else\n        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n\n    /* Check descriptors for correctness */\n    if (plasma_desc_check(A) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_zcgels_Tile\", \"invalid first descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descA = *A;\n    }\n    if (plasma_desc_check(T) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_zcgels_Tile\", \"invalid second descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descT = *T;\n    }\n    if (plasma_desc_check(B) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_zcgels_Tile\", \"invalid third descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descB = *B;\n    }\n    if (plasma_desc_check(X) != PLASMA_SUCCESS) {\n        plasma_error(\"PLASMA_zcgels_Tile\", \"invalid fourth descriptor\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    } else {\n        descX = *X;\n    }\n    /* Check input arguments */\n    if (descA.nb != descA.mb || descB.nb != descB.mb || descX.nb != descX.mb) {\n        plasma_error(\"PLASMA_zcgels_Tile\", \"only square tiles supported\");\n        return PLASMA_ERR_ILLEGAL_VALUE;\n    }\n    if (trans != PlasmaNoTrans) {\n        plasma_error(\"PLASMA_zcgels_Tile\", \"only PlasmaNoTrans supported\");\n        return PLASMA_ERR_NOT_SUPPORTED;\n    }\n    /* Quick return  - currently NOT equivalent to LAPACK's:\n    if (min(M, min(N, NRHS)) == 0) {\n        for (i = 0; i < max(M, N); i++)\n            for (j = 0; j < NRHS; j++)\n                B[j*LDB+i] = 0.0;\n        return PLASMA_SUCCESS;\n    }\n    */\n\n    if (0 == 0) {\n    // START SPECIFIC\n\n    /* Set M, M, NRHS, NB, MT, NT & NTRHS */\n    M    = descA.lm;\n    N    = descA.ln;\n    NRHS = descB.ln;\n    NB   = descA.nb;\n    NBNB = NB*NB;\n\n    MT = (M%NB==0) ? (M/NB) : (M/NB+1);\n    NT = (N%NB==0) ? (N/NB) : (N/NB+1);\n    NTRHS = (NRHS%NB==0) ? (NRHS/NB) : (NRHS/NB+1);\n    printf(\"M %d, N %d, NRHS %d, NB %d, MT %d, NT %d, NTRHS %d\\n\", M, N, NRHS, NB, MT, NT, NTRHS);\n\n    work = (double *)plasma_shared_alloc(plasma, PLASMA_SIZE, PlasmaRealDouble);\n    if (work == NULL) {\n        plasma_error(\"PLASMA_zcgesv\", \"plasma_shared_alloc() failed\");\n        plasma_shared_free(plasma, work);\n        return PLASMA_ERR_OUT_OF_RESOURCES;\n    }\n\n    PLASMA_desc descR = plasma_desc_init(\n        PlasmaComplexDouble,\n        NB, NB, NBNB,\n        M, NRHS, 0, 0, M, NRHS);\n\n    if (plasma_desc_mat_alloc(&descR)) {\n        plasma_error(\"PLASMA_zcgesv\", \"plasma_shared_alloc() failed\");\n        plasma_desc_mat_free(&descR);\n        plasma_shared_free(plasma, work);\n        return PLASMA_ERR_OUT_OF_RESOURCES;\n    }\n\n    PLASMA_desc descSA = plasma_desc_init(\n            PlasmaComplexFloat,\n            NB, NB, NBNB,\n            M, N, 0, 0, M, N);\n\n    PLASMA_desc descST = plasma_desc_init(\n            PlasmaComplexFloat,\n            IB, NB, IBNB,\n            M, N, 0, 0, M, N);\n\n    PLASMA_desc descSX = plasma_desc_init(\n            PlasmaComplexFloat,\n            NB, NB, NBNB,\n            M, NRHS, 0, 0, M, NRHS);\n\n    /* Allocate memory for single precision matrices in block layout */\n    if (plasma_desc_mat_alloc(&descSA) || plasma_desc_mat_alloc(&descST) || plasma_desc_mat_alloc(&descSX)) {\n        plasma_error(\"PLASMA_zcgesv\", \"plasma_shared_alloc() failed\");\n        plasma_desc_mat_free(&descSA);\n        plasma_desc_mat_free(&descST);\n        plasma_desc_mat_free(&descSX);\n        plasma_desc_mat_free(&descR);\n        plasma_shared_free(plasma, work);\n        return PLASMA_ERR_OUT_OF_RESOURCES;\n    }\n\n    /* Compute some constants */\n    PLASMA_zlange(PlasmaInfNorm, descA, Anorm, work);\n    eps = LAPACKE_dlamch_work('e');\n\n    printf(\"Anorm=%e, cte=%e\\n\", Anorm, cte);\n\n    /* Convert B from double precision to single precision and store\n       the result in SX. */\n    PLASMA_zlag2c(descB, descSX);\n    if (sequence->status != PLASMA_SUCCESS)\n        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n\n    /* Convert A from double precision to single precision and store\n       the result in SA. */\n    PLASMA_zlag2c(descA, descSA);\n    if (sequence->status != PLASMA_SUCCESS)\n        return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);\n\n    if (descSA.m >= descSA.n) {\n\n        /* Compute the QR factorization of SA */\n        printf(\"Facto\\n\"); fflush(stdout);\n        plasma_parallel_call_4(plasma_pcgeqrf,\n            PLASMA_desc, descSA,\n            PLASMA_desc, descST,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        printf(\"Solve\\n\"); fflush(stdout);\n        plasma_parallel_call_5(plasma_pcunmqr,\n            PLASMA_desc, descSA,\n            PLASMA_desc, descSX,\n            PLASMA_desc, descST,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        plasma_parallel_call_9(plasma_pctrsm,\n            PLASMA_enum, PlasmaLeft,\n            PLASMA_enum, PlasmaUpper,\n            PLASMA_enum, PlasmaNoTrans,\n            PLASMA_enum, PlasmaNonUnit,\n            PLASMA_Complex32_t, 1.0,\n            PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.n, descSA.n),\n            PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.n, descSX.n),\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n    }\n    else {\n        plasma_parallel_call_3(plasma_pztile_zero,\n            PLASMA_desc, plasma_desc_submatrix(descSX, descSA.m, 0, descSA.n-descSA.m, descSX.n),\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        plasma_parallel_call_4(plasma_pcgelqf,\n            PLASMA_desc, descSA,\n            PLASMA_desc, descST,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        plasma_parallel_call_9(plasma_pctrsm,\n            PLASMA_enum, PlasmaLeft,\n            PLASMA_enum, PlasmaLower,\n            PLASMA_enum, PlasmaNoTrans,\n            PLASMA_enum, PlasmaNonUnit,\n            PLASMA_Complex32_t, 1.0,\n            PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.m, descSA.m),\n            PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.m, descSX.n),\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        plasma_parallel_call_5(plasma_pcunmlq,\n            PLASMA_desc, descSA,\n            PLASMA_desc, descSX,\n            PLASMA_desc, descST,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n    }\n\n    /* Convert SX back to double precision */\n    PLASMA_clag2z(descSX, descX);\n\n    /* Compute R = B - AX. */\n    printf(\"R = B - Ax\\n\"); fflush(stdout);\n    printf(\"R = B - Ax ... cpy\\n\"); fflush(stdout);\n    PLASMA_zlacpy(descB,descR);\n    printf(\"R = B - Ax ... gemm\\n\"); fflush(stdout);\n\n    plasma_parallel_call_9(plasma_pzgemm,\n        PLASMA_enum, PlasmaNoTrans,\n        PLASMA_enum, PlasmaNoTrans,\n        PLASMA_Complex64_t, negone,\n        PLASMA_desc, descA,\n        PLASMA_desc, descX,\n        PLASMA_Complex64_t, one,\n        PLASMA_desc, descR,\n        PLASMA_sequence*, sequence,\n        PLASMA_request*, request);\n\n    /* Check whether the NRHS normwise backward error satisfies the\n       stopping criterion. If yes return. Note that ITER=0 (already set). */\n    printf(\"Norm of X and R\\n\"); fflush(stdout);\n    PLASMA_zlange(PlasmaInfNorm, descX, Xnorm, work);\n    PLASMA_zlange(PlasmaInfNorm, descR, Rnorm, work);\n\n    /* Wait the end of Anorm, Xnorm and Bnorm computations */\n    plasma_dynamic_sync();\n\n    cte = Anorm*eps*((double) N)*bwdmax;\n    if (Rnorm < Xnorm * cte){\n        /* The NRHS normwise backward errors satisfy the\n           stopping criterion. We are good to exit. */\n        plasma_desc_mat_free(&descSA);\n        plasma_desc_mat_free(&descST);\n        plasma_desc_mat_free(&descSX);\n        plasma_desc_mat_free(&descR);\n        plasma_shared_free(plasma, work);\n        return PLASMA_SUCCESS;\n    }\n\n    printf(\"Rnorm=%e, Xnorm * cte=%e, Rnorm=%e, cte=%e\\n\", Rnorm, Xnorm * cte, Rnorm, cte);\n\n    /* Iterative refinement */\n    for (iiter = 0; iiter < itermax; iiter++){\n\n        /* Convert R from double precision to single precision\n           and store the result in SX. */\n        PLASMA_zlag2c(descR, descSX);\n\n        /* Solve the system SA*SX = SR */\n        if (descSA.m >= descSA.n) {\n\n            plasma_parallel_call_5(plasma_pcunmqr,\n                PLASMA_desc, descSA,\n                PLASMA_desc, descSX,\n                PLASMA_desc, descST,\n                PLASMA_sequence*, sequence,\n                PLASMA_request*, request);\n\n            plasma_parallel_call_9(plasma_pctrsm,\n                PLASMA_enum, PlasmaLeft,\n                PLASMA_enum, PlasmaUpper,\n                PLASMA_enum, PlasmaNoTrans,\n                PLASMA_enum, PlasmaNonUnit,\n                PLASMA_Complex32_t, 1.0,\n                PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.n, descSA.n),\n                PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.n, descSX.n),\n                PLASMA_sequence*, sequence,\n                PLASMA_request*, request);\n        } else {\n            plasma_parallel_call_9(plasma_pctrsm,\n                PLASMA_enum, PlasmaLeft,\n                PLASMA_enum, PlasmaLower,\n                PLASMA_enum, PlasmaNoTrans,\n                PLASMA_enum, PlasmaNonUnit,\n                PLASMA_Complex32_t, 1.0,\n                PLASMA_desc, plasma_desc_submatrix(descSA, 0, 0, descSA.m, descSA.m),\n                PLASMA_desc, plasma_desc_submatrix(descSX, 0, 0, descSA.m, descSX.n),\n                PLASMA_sequence*, sequence,\n                PLASMA_request*, request);\n\n            plasma_parallel_call_5(plasma_pcunmlq,\n                PLASMA_desc, descSA,\n                PLASMA_desc, descSX,\n                PLASMA_desc, descST,\n                PLASMA_sequence*, sequence,\n                PLASMA_request*, request);\n        }\n\n\n        /* Convert SX back to double precision and update the current\n           iterate. */\n        PLASMA_clag2z(descSX, descR);\n        PLASMA_zgeadd(one, descR, descX);\n\n        /* Compute R = B - AX. */\n        PLASMA_zlacpy(descB,descR);\n        plasma_parallel_call_9(plasma_pzgemm,\n            PLASMA_enum, PlasmaNoTrans,\n            PLASMA_enum, PlasmaNoTrans,\n            PLASMA_Complex64_t, negone,\n            PLASMA_desc, descA,\n            PLASMA_desc, descX,\n            PLASMA_Complex64_t, one,\n            PLASMA_desc, descR,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        /* Check whether the NRHS normwise backward errors satisfy the\n           stopping criterion. If yes, set ITER=IITER>0 and return. */\n        PLASMA_zlange(PlasmaInfNorm, descX, Xnorm, work);\n        PLASMA_zlange(PlasmaInfNorm, descR, Rnorm, work);\n\n        /* Wait the end of Xnorm and Bnorm computations */\n        plasma_dynamic_sync();\n\n        printf(\"Rnorm=%e, Xnorm * cte=%e, Rnorm=%e, cte=%e\\n\", Rnorm, Xnorm * cte, Rnorm, cte);\n\n        if (Rnorm < Xnorm * cte){\n            /* The NRHS normwise backward errors satisfy the\n               stopping criterion. We are good to exit. */\n            *ITER = iiter;\n\n            plasma_desc_mat_free(&descSA);\n            plasma_desc_mat_free(&descST);\n            plasma_desc_mat_free(&descSX);\n            plasma_desc_mat_free(&descR);\n            plasma_shared_free(plasma, work);\n            return PLASMA_SUCCESS;\n        }\n    }\n\n    /* We have performed ITER=itermax iterations and never satisified\n       the stopping criterion, set up the ITER flag accordingly and\n       follow up on double precision routine. */\n    *ITER = -itermax - 1;\n\n    plasma_desc_mat_free(&descSA);\n    plasma_desc_mat_free(&descST);\n    plasma_desc_mat_free(&descSX);\n    plasma_desc_mat_free(&descR);\n    plasma_shared_free(plasma, work);\n\n    printf(\"Go back DOUBLE\\n\");\n    // END SPECIFIC\n    }\n\n    /* Single-precision iterative refinement failed to converge to a\n       satisfactory solution, so we resort to double precision. */\n    PLASMA_zlacpy(descB, descX);\n\n    if (descA.m >= descA.n) {\n        plasma_parallel_call_4(plasma_pzgeqrf,\n            PLASMA_desc, descA,\n            PLASMA_desc, descT,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        plasma_parallel_call_5(plasma_pzunmqr,\n            PLASMA_desc, descA,\n            PLASMA_desc, descX,\n            PLASMA_desc, descT,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        plasma_parallel_call_9(plasma_pztrsm,\n            PLASMA_enum, PlasmaLeft,\n            PLASMA_enum, PlasmaUpper,\n            PLASMA_enum, PlasmaNoTrans,\n            PLASMA_enum, PlasmaNonUnit,\n            PLASMA_Complex64_t, 1.0,\n            PLASMA_desc, plasma_desc_submatrix(descA, 0, 0, descA.n, descA.n),\n            PLASMA_desc, plasma_desc_submatrix(descX, 0, 0, descA.n, descX.n),\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n    }\n    else {\n        plasma_parallel_call_3(plasma_pztile_zero,\n            PLASMA_desc, plasma_desc_submatrix(descX, descA.m, 0, descA.n-descA.m, descX.n),\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        plasma_parallel_call_4(plasma_pzgelqf,\n            PLASMA_desc, descA,\n            PLASMA_desc, descT,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        plasma_parallel_call_9(plasma_pztrsm,\n            PLASMA_enum, PlasmaLeft,\n            PLASMA_enum, PlasmaLower,\n            PLASMA_enum, PlasmaNoTrans,\n            PLASMA_enum, PlasmaNonUnit,\n            PLASMA_Complex64_t, 1.0,\n            PLASMA_desc, plasma_desc_submatrix(descA, 0, 0, descA.m, descA.m),\n            PLASMA_desc, plasma_desc_submatrix(descX, 0, 0, descA.m, descX.n),\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n\n        plasma_parallel_call_5(plasma_pzunmlq,\n            PLASMA_desc, descA,\n            PLASMA_desc, descX,\n            PLASMA_desc, descT,\n            PLASMA_sequence*, sequence,\n            PLASMA_request*, request);\n    }\n    return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "c25ec07f0117765e7eb4fd97f9b2c4f9702ca968", "size": 32316, "ext": "c", "lang": "C", "max_stars_repo_path": "compute/zcgels.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/zcgels.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/zcgels.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-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.7227272727, "max_line_length": 113, "alphanum_fraction": 0.5838284441, "num_tokens": 8584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3517318167336957}}
{"text": "/* movstat/sumacc.c\n *\n * Moving window sum accumulator\n * \n * Copyright (C) 2018 Patrick Alken\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include <config.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_vector.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_movstat.h>\n\ntypedef double ringbuf_type_t;\n\n#include \"ringbuf.c\"\n\ntypedef struct\n{\n  double sum;     /* current window sum */\n  ringbuf *rbuf;  /* ring buffer storing current window */\n} sumacc_state_t;\n\nstatic size_t\nsumacc_size(const size_t n)\n{\n  size_t size = 0;\n\n  size += sizeof(sumacc_state_t);\n  size += ringbuf_size(n);\n\n  return size;\n}\n\nstatic int\nsumacc_init(const size_t n, void * vstate)\n{\n  sumacc_state_t * state = (sumacc_state_t *) vstate;\n\n  state->sum = 0.0;\n\n  state->rbuf = (ringbuf *) ((unsigned char *) vstate + sizeof(sumacc_state_t));\n  ringbuf_init(n, state->rbuf);\n\n  return GSL_SUCCESS;\n}\n\nstatic int\nsumacc_insert(const double x, void * vstate)\n{\n  sumacc_state_t * state = (sumacc_state_t *) vstate;\n\n  if (ringbuf_is_full(state->rbuf))\n    {\n      /* subtract oldest element from sum */\n      state->sum -= ringbuf_peek_back(state->rbuf);\n    }\n\n  /* add new element to sum and ring buffer */\n  state->sum += x;\n  ringbuf_insert(x, state->rbuf);\n\n  return GSL_SUCCESS;\n}\n\nstatic int\nsumacc_delete(void * vstate)\n{\n  sumacc_state_t * state = (sumacc_state_t *) vstate;\n\n  if (!ringbuf_is_empty(state->rbuf))\n    {\n      state->sum -= ringbuf_peek_back(state->rbuf);\n      ringbuf_pop_back(state->rbuf);\n    }\n\n  return GSL_SUCCESS;\n}\n\nstatic int\nsumacc_get(void * params, double * result, const void * vstate)\n{\n  const sumacc_state_t * state = (const sumacc_state_t *) vstate;\n  (void) params;\n  *result = state->sum;\n  return GSL_SUCCESS;\n}\n\nstatic const gsl_movstat_accum sum_accum_type =\n{\n  sumacc_size,\n  sumacc_init,\n  sumacc_insert,\n  sumacc_delete,\n  sumacc_get\n};\n\nconst gsl_movstat_accum *gsl_movstat_accum_sum = &sum_accum_type;\n", "meta": {"hexsha": "dbd9c71c21f26bab1c9966c7fec516e8a91edecf", "size": 2616, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/movstat/sumacc.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_issues_repo_path": "gsl-2.6/movstat/sumacc.c", "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_forks_repo_path": "test/lib/gsl-2.6/movstat/sumacc.c", "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "avg_line_length": 23.1504424779, "max_line_length": 81, "alphanum_fraction": 0.7071865443, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529716, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.35166586004830763}}
{"text": "#ifndef LASER_SCANNER_H_WSZJIY40\n#define LASER_SCANNER_H_WSZJIY40\n\n#include <cmath>\n#include <gsl/gsl>\n#include <sens_loc/camera_models/concepts.h>\n#include <sens_loc/math/constants.h>\n#include <sens_loc/math/coordinate.h>\n#include <sens_loc/math/scaling.h>\n#include <stdexcept>\n#include <type_traits>\n\nnamespace sens_loc::camera_models {\n\nnamespace detail {\ntemplate <typename Real>\nReal get_d_phi(int width) noexcept {\n    static_assert(std::is_floating_point_v<Real>);\n    // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)\n    return Real(2.) * math::pi<Real> / Real(width);\n}\n}  // namespace detail\n\n/// This struct contains the parameters for describing the equirectangular\n/// projection of a laser scan.\n///\n/// The scan is expected to be 360\u00b0 in horizontal direction and som\n/// varying degree in vertical direction.\n/// The conversions and projections are mainly conversion from a\n/// spherical coordinate-system to a cartesian.\n/// \\tparam Real precision of the parameters and calculations.\n///\n/// \\note the coordinate convention for spherical coordinates is as follows:\n///   - \\f$\\varphi \\in [0, 2 \\pi] \\mapsto u\\f$ note that this wraps around\n///   - \\f$\\theta \\in [0, \\pi] \\mapsto v\\f$ - not wrapping!\n///   - it is possible to have a different range for \\f$\\theta\\f$ but not for\n///     \\f$\\varphi\\f$.\n///\n/// \\tparam Real floating point type that determines the precision of the\n/// calculations.\n/// \\sa is_intrinsic_v\ntemplate <typename Real = float>\nclass equirectangular {\n  public:\n    static_assert(std::is_floating_point_v<Real>);\n    using real_type = Real;\n\n    /// Default initialize all parameters to zero.\n    equirectangular() = default;\n\n    /// Construct a equirectangular image for the full sphere.\n    ///\n    /// \\param width width of the image, this maps to 360\u00b0 field of vie\n    /// horizontally which wraps around\n    /// \\param height height of the image, this\n    /// maps to 180\u00b0 field of view vertically which does __NOT__ wrap\n    equirectangular(int width, int height) noexcept\n        : _w(width)\n        , _h(height)\n        , d_phi(detail::get_d_phi<Real>(width))\n        , d_theta(math::pi<Real> / Real(height))\n        , theta_min(Real(0.)) {\n        Expects(width > 0);\n        Expects(height > 0);\n        ensure_invariant();\n    }\n\n    /// Construct the model with a custom \\f$\\theta\\f$-range. This model does\n    /// __NOT__ map to the whole sphere, but is not a cylindrical coordinate\n    /// system as well!\n    /// \\param width,height image dimensions\n    /// \\param theta_range minimum and maximum angle on the unit-sphere in\n    /// vertical direction.\n    equirectangular(int                       width,\n                    int                       height,\n                    math::numeric_range<Real> theta_range) noexcept\n        : _w(width)\n        , _h(height)\n        , d_phi(detail::get_d_phi<Real>(width))\n        , d_theta((theta_range.max - theta_range.min) / Real(height))\n        , theta_min(theta_range.min) {\n        Expects(width > 0);\n        Expects(height > 0);\n        Expects(theta_range.min >= 0.);\n        Expects(theta_range.max <= math::pi<Real>);\n        ensure_invariant();\n    }\n\n    /// Construct the model with a minimum angle \\p theta_min and an angle\n    /// increment \\p d_theta.\n    ///\n    /// \\param width,height image dimensions\n    /// \\param theta_min,d_theta vertical resolution configuration\n    /// \\throws if the \\f$\\theta\\f$-angle would be out of the range with the\n    /// configuration this constructor throws an exception.\n    equirectangular(int width, int height, Real theta_min, Real d_theta)\n        : _w(width)\n        , _h(height)\n        , d_phi(detail::get_d_phi<Real>(width))\n        , d_theta(d_theta)\n        , theta_min(theta_min) {\n        const Real theta_max = theta_min + height * d_theta;\n        if (theta_max > math::pi<Real>)\n            throw std::invalid_argument(\"angle increment too big\");\n        ensure_invariant();\n    }\n\n    /// Return the width of the image corresponding to this intrinsic.\n    [[nodiscard]] int w() const noexcept { return _w; }\n    /// Return the height of the image corresponding to this intrinsic.\n    [[nodiscard]] int h() const noexcept { return _h; }\n\n    /// This methods calculates the inverse projection of the equirectangular\n    /// model to get the direction of the lightray for the pixel at \\p p.\n    ///\n    /// \\tparam _Real either integer pixels or floating point for subpixels\n    /// \\param p non-negative pixel coordinates\n    /// \\post \\f$\\lVert result \\rVert_2 = 1.\\f$\n    /// \\returns normalized vector in camera coordinates - unit sphere\n    /// coordinate\n    /// \\note if \\p _Real is an integer-type the value is itself backprojected,\n    /// which usually means the bottom left corner of the pixel and __NOT__\n    /// its center!\n    template <typename _Real = int>\n    [[nodiscard]] math::sphere_coord<Real>\n    pixel_to_sphere(const math::pixel_coord<_Real>& p) const noexcept;\n\n    /// Project points in camera coordinates to pixel coordinates.\n    /// \\note if the point can not be projected (coordinate not in view) the\n    /// pixel coordinate {-1, -1} is returned.\n    /// \\sa equirectangular::project_to_sphere\n    template <typename _Real = Real>\n    [[nodiscard]] math::pixel_coord<_Real>\n    camera_to_pixel(const math::camera_coord<Real>& p) const noexcept;\n\n  private:\n    void ensure_invariant() const noexcept {\n        Ensures(d_phi > Real(0.));\n        Ensures(d_theta > Real(0.));\n        Ensures(theta_min >= Real(0.));\n\n        // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)\n        Ensures(std::abs(d_phi * _w - Real(2.) * math::pi<Real>) < 0.00001);\n        // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)\n        Ensures(theta_min + _h * d_theta <= math::pi<Real> + 0.00001);\n    }\n\n    int  _w        = 0;   ///< width of a laser-scan image\n    int  _h        = 0;   ///< height of a laser-scan image.\n    Real d_phi     = 0.;  ///< Angle increment in u-direction.\n    Real d_theta   = 0.;  ///< Angle increment in v-direction.\n    Real theta_min = 0.;  ///< Smallest angle in v-direction.\n};\n\ntemplate <typename Real>\ntemplate <typename _Real>\ninline math::sphere_coord<Real>\nequirectangular<Real>::pixel_to_sphere(const math::pixel_coord<_Real>& p) const\n    noexcept {\n    static_assert(std::is_arithmetic_v<_Real>);\n    Expects(p.u() >= Real(0.0));\n    Expects(p.v() < Real(w()));\n    Expects(p.u() >= Real(0.0));\n    Expects(p.v() < Real(h()));\n\n    const Real phi   = p.u() * d_phi - math::pi<Real>;\n    const Real theta = theta_min + (p.v() * d_theta);\n\n    Ensures(phi >= -math::pi<Real>);\n    Ensures(phi <= math::pi<Real>);\n    Ensures(theta >= Real(0.));\n    Ensures(theta <= math::pi<Real>);\n\n    using std::cos;\n    using std::sin;\n    math::sphere_coord<Real> s{sin(theta) * cos(phi), sin(theta) * sin(phi),\n                               cos(theta)};\n    // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)\n    Ensures(std::abs(s.norm() - Real(1.0)) < 0.000001);\n    return s;\n}\n\ntemplate <typename Real>\ntemplate <typename _Real>\ninline math::pixel_coord<_Real>\nequirectangular<Real>::camera_to_pixel(const math::camera_coord<Real>& p) const\n    noexcept {\n    static_assert(std::is_arithmetic_v<_Real>);\n\n    const Real r = std::sqrt(p.X() * p.X() + p.Y() * p.Y() + p.Z() * p.Z());\n    if (r == Real(0.0))\n        return {_Real(-1), _Real(-1)};\n\n    const Real theta = std::acos(p.Z() / r);\n    const Real phi   = std::atan2(p.Y(), p.X());\n\n    Ensures(r >= Real(0.0));\n    Ensures(phi >= -math::pi<Real>);\n    Ensures(phi <= math::pi<Real>);\n    Ensures(theta >= Real(0.));\n    Ensures(theta <= math::pi<Real>);\n\n    const _Real u = gsl::narrow_cast<_Real>((phi + math::pi<Real>) / d_phi);\n    const _Real v = gsl::narrow_cast<_Real>(theta / d_theta);\n\n    if (u < _Real(0.0) || u > gsl::narrow_cast<Real>(w()) || v < _Real(0.0) ||\n        v > gsl::narrow_cast<Real>(h()))\n        return {_Real(-1), _Real(-1)};\n\n    return {u, v};\n}\n}  // namespace sens_loc::camera_models\n\n#endif /* end of include guard: LASER_SCANNER_H_WSZJIY40 */\n", "meta": {"hexsha": "25254a763d0055a0024584d79f6a47ab63bfa811", "size": 8088, "ext": "h", "lang": "C", "max_stars_repo_path": "src/include/sens_loc/camera_models/equirectangular.h", "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_issues_repo_path": "src/include/sens_loc/camera_models/equirectangular.h", "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/sens_loc/camera_models/equirectangular.h", "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6186046512, "max_line_length": 79, "alphanum_fraction": 0.6386003956, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3516201636608466}}
{"text": "// ************************************************\r\n// rand_helpers.h\r\n// authors: Lee Howes and David B. Thomas\r\n//\r\n// Contains support code for the random number\r\n// generation necessary for initialising the \r\n// cuda simulations correctly.\r\n// \r\n// Ziggurat code taken from Marsaglia's\r\n// paper.\r\n// ************************************************\r\n\r\n#ifndef __rand_helpers_h\r\n#define __rand_helpers_h\r\n\r\n// RNG choices\r\n#define USE_ZIGGURAT 0\r\n#define USE_GSL 0\r\n\r\n\r\n#include <math.h>\r\n#include <assert.h>\r\n\r\n#if USE_GSL\r\n#include <gsl/gsl_rng.h>\r\n#include <gsl/gsl_randist.h>\r\n#endif\r\n\r\n\r\nunsigned Kiss()\r\n{\r\n\tstatic unsigned z=362436069, w=521288629, jsr=123456789, jcong=380116160;\r\n\r\n\tz=36969*(z&65535)+(z>>16);\r\n\tw=18000*(w&65535)+(w>>16);\r\n\tunsigned mwc=(z<<16)+w;\r\n\tjsr^=(jsr<<17);\r\n\tjsr^=(jsr>>13);\r\n\tjsr^=(jsr<<5);\r\n\tjcong=69069*jcong+1234567;\r\n\treturn (mwc^jcong)+jsr;\r\n}\r\n\r\ndouble Rand()\r\n{\r\n\tunsigned long long x=Kiss();\r\n\tx=(x<<32)|Kiss();\r\n\treturn x*5.4210108624275221703311375920553e-20;\r\n}\r\n\r\n#if USE_GSL\r\nconst gsl_rng_type **t, **t0;\r\ngsl_rng *rng;\r\nbool initialised = false;\r\n\r\nvoid initRand()\r\n{\r\n    gsl_rng_env_setup();\r\n\r\n    t0 = gsl_rng_types_setup ();\r\n\r\n    printf (\"Available generators:\\n\");\r\n\r\n    for (t = t0; *t != 0; t++)\r\n    {\r\n        printf (\"%s\\n\", (*t)->name);\r\n        if( strcmp(\"mt19937_1999\", (*t)->name) == 0 ) break;\r\n    }\r\n\r\n    rng = gsl_rng_alloc (*t);\r\n}\r\n\r\ndouble RandN()\r\n{\r\n    return gsl_ran_gaussian_ziggurat  (rng, 1.0);\r\n\r\n}\r\n#else\r\n\r\n#if USE_ZIGGURAT\r\n\r\n/* Period parameters */  \r\n#define CPU_MT_N 624\r\n#define CPU_MT_M 397\r\n#define MATRIX_A 0x9908b0dfUL   /* constant vector a */\r\n#define CPU_MT_UPPER_MASK 0x80000000UL /* most significant w-r bits */\r\n#define CPU_MT_LOWER_MASK 0x7fffffffUL /* least significant r bits */\r\n\r\n// MT\r\nunsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4;\r\n\r\nstatic unsigned long mt[CPU_MT_N]; /* the array for the state vector  */\r\nstatic int mti=CPU_MT_N+1; /* mti==N+1 means mt[N] is not initialized */\r\n\r\n/* initializes mt[N] with a seed */\r\nvoid init_genrand(unsigned long s)\r\n{\r\n    mt[0]= s & 0xffffffffUL;\r\n    for (mti=1; mti<CPU_MT_N; mti++) {\r\n        mt[mti] = \r\n\t    (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); \r\n        /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */\r\n        /* In the previous versions, MSBs of the seed affect   */\r\n        /* only MSBs of the array mt[].                        */\r\n        /* 2002/01/09 modified by Makoto Matsumoto             */\r\n        mt[mti] &= 0xffffffffUL;\r\n        /* for >32 bit machines */\r\n    }\r\n}\r\n\r\n/* initialize by an array with array-length */\r\n/* init_key is the array for initializing keys */\r\n/* key_length is its length */\r\n/* slight change for C++, 2004/2/26 */\r\nvoid init_by_array(unsigned long init_key[], int key_length)\r\n{\r\n    int i, j, k;\r\n    init_genrand(19650218UL);\r\n    i=1; j=0;\r\n    k = (CPU_MT_N>key_length ? CPU_MT_N : key_length);\r\n    for (; k; k--) {\r\n        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))\r\n          + init_key[j] + j; /* non linear */\r\n        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */\r\n        i++; j++;\r\n        if (i>=CPU_MT_N) { mt[0] = mt[CPU_MT_N-1]; i=1; }\r\n        if (j>=key_length) j=0;\r\n    }\r\n    for (k=CPU_MT_N-1; k; k--) {\r\n        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))\r\n          - i; /* non linear */\r\n        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */\r\n        i++;\r\n        if (i>=CPU_MT_N) { mt[0] = mt[CPU_MT_N-1]; i=1; }\r\n    }\r\n\r\n    mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ \r\n}\r\n\r\n/* generates a random number on [0,0xffffffff]-interval */\r\nunsigned long genrand_int32(void)\r\n{\r\n    unsigned long y;\r\n    static unsigned long mag01[2]={0x0UL, MATRIX_A};\r\n    /* mag01[x] = x * MATRIX_A  for x=0,1 */\r\n\r\n    if (mti >= CPU_MT_N) { /* generate N words at one time */\r\n        int kk;\r\n\r\n        if (mti == CPU_MT_N+1)   /* if init_genrand() has not been called, */\r\n            init_genrand(5489UL); /* a default initial seed is used */\r\n\r\n        for (kk=0;kk<CPU_MT_N-CPU_MT_M;kk++) {\r\n            y = (mt[kk]&CPU_MT_UPPER_MASK)|(mt[kk+1]&CPU_MT_LOWER_MASK);\r\n            mt[kk] = mt[kk+CPU_MT_M] ^ (y >> 1) ^ mag01[y & 0x1UL];\r\n        }\r\n        for (;kk<CPU_MT_N-1;kk++) {\r\n            y = (mt[kk]&CPU_MT_UPPER_MASK)|(mt[kk+1]&CPU_MT_LOWER_MASK);\r\n            mt[kk] = mt[kk+(CPU_MT_M-CPU_MT_N)] ^ (y >> 1) ^ mag01[y & 0x1UL];\r\n        }\r\n        y = (mt[CPU_MT_N-1]&CPU_MT_UPPER_MASK)|(mt[0]&CPU_MT_LOWER_MASK);\r\n        mt[CPU_MT_N-1] = mt[CPU_MT_M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];\r\n\r\n        mti = 0;\r\n    }\r\n  \r\n    y = mt[mti++];\r\n\r\n    /* Tempering */\r\n    y ^= (y >> 11);\r\n    y ^= (y << 7) & 0x9d2c5680UL;\r\n    y ^= (y << 15) & 0xefc60000UL;\r\n    y ^= (y >> 18);\r\n\r\n    return y;\r\n}\r\n\r\ndouble genrand_real2(void)\r\n{\r\n    return genrand_int32()*(1.0/4294967296.0); \r\n    /* divided by 2^32 */\r\n}\r\n\r\ndouble genrand_real3(void)\r\n{\r\n    return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); \r\n    /* divided by 2^32 */\r\n}\r\n\r\n\r\n// ZIGGURAT\r\n#define abs(X) abs((int)X)\r\n//#define SHR3 (jz=jsr, jsr^=(jsr<<13), jsr^=(jsr>>17), jsr^=(jsr<<5),jz+jsr)\r\n#define SHR3 genrand_int32()\r\n//#define UNI (.5 + (signed) SHR3 * .2328306e-9)\r\n#define UNI genrand_real3()  \r\n#define RandN() (hz=SHR3, iz=hz&127, (abs(hz)<kn[iz])? hz*wn[iz] : nfix())\r\n\r\nstatic unsigned long iz,jz,jsr=123456789,kn[128],ke[256];\r\nstatic long hz; static float wn[128],fn[128], we[256],fe[256];\r\n\r\nfloat nfix(void) { /*provides RNOR if #define cannot */\r\n    const float r = 3.442620f; static float x, y;\r\n    for(;;){ x=hz*wn[iz];\r\n        if(iz==0){ \r\n            do{\r\n                x=-log(UNI)*0.2904764; \r\n                y=-log(UNI);\r\n            } while(y+y<x*x);\r\n            return (hz>0)? r+x : -r-x;\r\n        }\r\n        if( fn[iz]+UNI*(fn[iz-1]-fn[iz]) < exp(-.5*x*x) ) return x;\r\n        hz=SHR3; iz=hz&127;if(abs(hz)<kn[iz]) return (hz*wn[iz]);\r\n    } \r\n}\r\n\r\n\r\n/*--------This procedure sets the seed and creates the tables------*/\r\nvoid initRand() {\r\n    unsigned long jsrseed = 123456789;\r\n    const double m1 = 2147483648.0, m2 = 4294967296.;\r\n    double dn=3.442619855899,tn=dn,vn=9.91256303526217e-3, q;\r\n    double de=7.697117470131487, te=de, ve=3.949659822581572e-3;\r\n    int i; jsr=jsrseed;\r\n\r\n    /* Tables for RNOR: */ q=vn/exp(-.5*dn*dn);\r\n    kn[0]=(dn/q)*m1; kn[1]=0;\r\n    wn[0]=q/m1; wn[127]=dn/m1;\r\n    fn[0]=1.; fn[127]=exp(-.5*dn*dn);\r\n    for(i=126;i>=1;i--) {\r\n        dn=sqrt(-2.*log(vn/dn+exp(-.5*dn*dn)));\r\n        kn[i+1]=(dn/tn)*m1; tn=dn;\r\n        fn[i]=exp(-.5*dn*dn); wn[i]=dn/m1; \r\n    }\r\n\r\n    /* Tables for REXP */ q = ve/exp(-de);\r\n    ke[0]=(de/q)*m2; ke[1]=0;\r\n    we[0]=q/m2; we[255]=de/m2;\r\n    fe[0]=1.; fe[255]=exp(-de);\r\n    for(i=254;i>=1;i--) {\r\n        de=-log(ve/de+exp(-de));\r\n        ke[i+1]= (de/te)*m2; te=de;\r\n        fe[i]=exp(-de); we[i]=de/m2;\r\n    }\r\n\r\n    init_by_array(init, length);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#else\r\n\r\nvoid initRand()\r\n{\r\n\r\n}\r\n\r\ndouble RandN()\r\n{\r\n\tstatic bool cached=false;\r\n\tstatic double cn;\r\n\r\n\tif(cached){\r\n\t\tcached=false;\r\n\t\treturn cn;\r\n\t}\r\n\r\n\tdouble a=std::sqrt(-2*std::log(Rand()));\r\n\tdouble b=6.283185307179586476925286766559*Rand();\r\n\tcn=std::sin(b)*a;\r\n\tcached=true;\r\n\treturn std::cos(b)*a;\r\n}\r\n#endif // USE_ZIGGURAT\r\n#endif // USE_GSL\r\n\r\ndouble MakeChi2Scale(unsigned N)\r\n{\r\n\tconst double chic1 = std::sqrt ( std::sqrt (1.0 - 1.0 / N));\r\n\tconst double chic2 = std::sqrt (1.0 - chic1 * chic1);\r\n\treturn chic1+chic2*RandN();\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "6f267e05a594ab33a4d48d430337083056ea0a26", "size": 7561, "ext": "h", "lang": "C", "max_stars_repo_path": "rng-wallace-sycl/rand_helpers.h", "max_stars_repo_name": "fodinabor/HeCBench", "max_stars_repo_head_hexsha": "0b1d2e815d27c3e9dc89be19f44e5f95f4813805", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rng-wallace-sycl/rand_helpers.h", "max_issues_repo_name": "fodinabor/HeCBench", "max_issues_repo_head_hexsha": "0b1d2e815d27c3e9dc89be19f44e5f95f4813805", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rng-wallace-sycl/rand_helpers.h", "max_forks_repo_name": "fodinabor/HeCBench", "max_forks_repo_head_hexsha": "0b1d2e815d27c3e9dc89be19f44e5f95f4813805", "max_forks_repo_licenses": ["BSD-3-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.1626297578, "max_line_length": 79, "alphanum_fraction": 0.5435788917, "num_tokens": 2591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.3516196290165543}}
{"text": "// The top most header - contains switches and constants\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <time.h>\n#include <gsl/gsl_rng.h>\n\n#define Pi   acos(-1.0)\n\n#define real double\n\n// Cell shape and size\n//#define circle\n#define square\n#define Dia 40  // Cell radius or square side\n#define thickness 40\n\n// clamped or hinged MTs\n\nint iprint, iter, t;\nchar datadir[64] ;\n", "meta": {"hexsha": "5d37305615aa3d2e07d2c5a73f118b0483818294", "size": 413, "ext": "h", "lang": "C", "max_stars_repo_path": "switches.h", "max_stars_repo_name": "misragaurav/SingleMicrotubuleBuckling", "max_stars_repo_head_hexsha": "27a5d17028e9bd1a526e5374f633741657e68f49", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "switches.h", "max_issues_repo_name": "misragaurav/SingleMicrotubuleBuckling", "max_issues_repo_head_hexsha": "27a5d17028e9bd1a526e5374f633741657e68f49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "switches.h", "max_forks_repo_name": "misragaurav/SingleMicrotubuleBuckling", "max_forks_repo_head_hexsha": "27a5d17028e9bd1a526e5374f633741657e68f49", "max_forks_repo_licenses": ["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.9565217391, "max_line_length": 56, "alphanum_fraction": 0.7070217918, "num_tokens": 112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3512072834121589}}
{"text": "/*\nODE: a program to get optime Runge-Kutta and multi-steps methods.\n\nCopyright 2011-2019, Javier Burguete Tolosa.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice,\n\t\tthis list of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\t\tthis list of conditions and the following disclaimer in the\n\t\tdocumentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\nSHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/**\n * \\file steps.c\n * \\brief Source file with common variables and functions to optimize\n *   multi-steps methods.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2011-2019.\n */\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <libxml/parser.h>\n#include <glib.h>\n#include <libintl.h>\n#include <gsl/gsl_rng.h>\n#include \"config.h\"\n#include \"utils.h\"\n#include \"optimize.h\"\n#include \"steps.h\"\n\n#define a0(x) x[0]\n///< a0 multi-steps coefficient.\n#define b0(x) x[1]\n///< b0 multi-steps coefficient.\n#define a1(x) x[2]\n///< a1 multi-steps coefficient.\n#define b1(x) x[3]\n///< b1 multi-steps coefficient.\n#define a2(x) x[4]\n///< a2 multi-steps coefficient.\n#define b2(x) x[5]\n///< b2 multi-steps coefficient.\n#define a3(x) x[6]\n///< a3 multi-steps coefficient.\n#define b3(x) x[7]\n///< b3 multi-steps coefficient.\n#define a4(x) x[8]\n///< a4 multi-steps coefficient.\n#define b4(x) x[9]\n///< b4 multi-steps coefficient.\n#define a5(x) x[10]\n///< a5 multi-steps coefficient.\n#define b5(x) x[11]\n///< b5 multi-steps coefficient.\n#define a6(x) x[12]\n///< a6 multi-steps coefficient.\n#define b6(x) x[13]\n///< b6 multi-steps coefficient.\n#define a7(x) x[14]\n///< a7 multi-steps coefficient.\n#define b7(x) x[15]\n///< b7 multi-steps coefficient.\n#define a8(x) x[16]\n///< a8 multi-steps coefficient.\n#define b8(x) x[17]\n///< b8 multi-steps coefficient.\n#define a9(x) x[18]\n///< a9 multi-steps coefficient.\n#define b9(x) x[19]\n///< b9 multi-steps coefficient.\n#define a10(x) x[20]\n///< a10 multi-steps coefficient.\n#define b10(x) x[21]\n///< b10 multi-steps coefficient.\n#define a11(x) x[22]\n///< a11 multi-steps coefficient.\n#define b11(x) x[23]\n///< b11 multi-steps coefficient.\n#define a12(x) x[24]\n///< a12 multi-steps coefficient.\n#define b12(x) x[25]\n///< b12 multi-steps coefficient.\n#define c(a, b) (b / a)\n///< macro to calculate the c multi-steps coefficients.\n#define c0(x) (c(a0(x), b0(x)))\n///< c0 multi-steps coefficient.\n#define c1(x) (c(a1(x), b1(x)))\n///< c1 multi-steps coefficient.\n#define c2(x) (c(a2(x), b2(x)))\n///< c2 multi-steps coefficient.\n#define c3(x) (c(a3(x), b3(x)))\n///< c3 multi-steps coefficient.\n#define c4(x) (c(a4(x), b4(x)))\n///< c4 multi-steps coefficient.\n#define c5(x) (c(a5(x), b5(x)))\n///< c5 multi-steps coefficient.\n#define c6(x) (c(a6(x), b6(x)))\n///< c6 multi-steps coefficient.\n#define c7(x) (c(a7(x), b7(x)))\n///< c7 multi-steps coefficient.\n#define c8(x) (c(a8(x), b8(x)))\n///< c8 multi-steps coefficient.\n#define c9(x) (c(a9(x), b9(x)))\n///< c9 multi-steps coefficient.\n#define c10(x) (c(a10(x), b10(x)))\n///< c10 multi-steps coefficient.\n#define c11(x) (c(a11(x), b11(x)))\n///< c11 multi-steps coefficient.\n#define c12(x) (c(a11(x), b11(x)))\n///< c12 multi-steps coefficient.\n\n/**\n * Function to get the coefficients on a 3 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_3_2 (Optimize * optimize) ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  b2 (x) = r[2];\n  b1 (x) = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) - 1.L);\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) - b1 (x) - b2 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 3 steps 3th order multi-steps method.\n */\nstatic int\nsteps_3_3 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x);\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) - b1 (x) - b2 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 4 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_4_2 (Optimize * optimize) ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  b3 (x) = r[3];\n  b2 (x) = r[4];\n  b1 (x) =\n    0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x) - 6.L * b3 (x) -\n            1.L);\n  b0 (x) =\n    1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) - b1 (x) - b2 (x) - b3 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 4 steps 3th order multi-steps method.\n */\nstatic int\nsteps_4_3 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  b3 (x) = r[3];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) - 6.L * b3 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x));\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) - b1 (x) - b2 (x)\n    - b3 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 4 steps 4th order multi-steps method.\n */\nstatic int\nsteps_4_4 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x);\n  solve_3 (A, B, C, D);\n  b3 (x) = D[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = D[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = D[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) - b1 (x) - b2 (x)\n    - b3 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 5 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_5_2 (Optimize * optimize) ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  b4 (x) = r[4];\n  b3 (x) = r[5];\n  b2 (x) = r[6];\n  b1 (x) = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)\n                   + 16.L * a4 (x) - 6.L * b3 (x) - 8.L * b4 (x) - 1.L);\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 5 steps 3th order multi-steps method.\n */\nstatic int\nsteps_5_3 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  b4 (x) = r[4];\n  b3 (x) = r[5];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    - 6.L * b3 (x) - 8.L * b4 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)\n    - 48.L * b4 (x);\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 5 steps 4th order multi-steps method.\n */\nstatic int\nsteps_5_4 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  b4 (x) = r[4];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    - 8.L * b4 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    - 48.L * b4 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)\n    + 256.L * (a4 (x) - b4 (x));\n  solve_3 (A, B, C, D);\n  b3 (x) = D[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = D[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = D[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 5 steps 5th order multi-steps method.\n */\nstatic int\nsteps_5_5 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x);\n  solve_4 (A, B, C, D, E);\n  b4 (x) = E[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = E[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = E[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = E[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 6 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_6_2 (Optimize * optimize) ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  b5 (x) = r[5];\n  b4 (x) = r[6];\n  b3 (x) = r[7];\n  b2 (x) = r[8];\n  b1 (x) = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)\n                   + 16.L * a4 (x) + 25.L * a5 (x) - 6.L * b3 (x) - 8.L * b4 (x)\n                   - 10.L * b5 (x) - 1.L);\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 6 steps 3th order multi-steps method.\n */\nstatic int\nsteps_6_3 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  b5 (x) = r[5];\n  b4 (x) = r[6];\n  b3 (x) = r[7];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) - 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)\n    + 125.L * a5 (x) - 48.L * b4 (x) - 75.L * b5 (x);\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 6 steps 4th order multi-steps method.\n */\nstatic int\nsteps_6_4 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  b5 (x) = r[5];\n  b4 (x) = r[6];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) - 8.L * b4 (x) - 10.L * b5 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) - 48.L * b4 (x) - 75.L * b5 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)\n    + 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) - 500.L * b5 (x);\n  solve_3 (A, B, C, D);\n  b3 (x) = D[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = D[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = D[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 6 steps 5th order multi-steps method.\n */\nstatic int\nsteps_6_5 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  b5 (x) = r[5];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) - 10.L * b5 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) - 75.L * b5 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) - 500.L * b5 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * (a5 (x) - b5 (x));\n  solve_4 (A, B, C, D, E);\n  b4 (x) = E[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = E[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = E[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = E[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 6 steps 6th order multi-steps method.\n */\nstatic int\nsteps_6_6 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[5], B[5], C[5], D[5], E[5], F[5];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x);\n  solve_5 (A, B, C, D, E, F);\n  b5 (x) = F[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = F[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = F[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = F[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = F[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 7 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_7_2 (Optimize * optimize) ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  b6 (x) = r[6];\n  b5 (x) = r[7];\n  b4 (x) = r[8];\n  b3 (x) = r[9];\n  b2 (x) = r[10];\n  b1 (x)\n    = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x) + 16.L * a4 (x)\n              + 25.L * a5 (x) + 36.L * a6 (x) - 6.L * b3 (x) - 8.L * b4 (x)\n              - 10.L * b5 (x) - 12.L * b6 (x) - 1.L);\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)\n    - b6 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 7 steps 3th order multi-steps method.\n */\nstatic int\nsteps_7_3 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  b6 (x) = r[6];\n  b5 (x) = r[7];\n  b4 (x) = r[8];\n  b3 (x) = r[9];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x) - 6.L * b3 (x) - 8.L * b4 (x)\n    - 10.L * b5 (x) - 12.L * b6 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) - 48.L * b4 (x) - 75.L * b5 (x)\n    - 108.L * b6 (x);\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)\n    - b6 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 7 steps 4th order multi-steps method.\n */\nstatic int\nsteps_7_4 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  b6 (x) = r[6];\n  b5 (x) = r[7];\n  b4 (x) = r[8];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x) - 8.L * b4 (x) - 10.L * b5 (x)\n    - 12.L * b6 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) - 48.L * b4 (x) - 75.L * b5 (x)\n    - 108.L * b6 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)\n    + 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)\n    - 500.L * b5 (x) - 864.L * b6 (x);\n  solve_3 (A, B, C, D);\n  b3 (x) = D[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = D[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = D[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)\n    - b6 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 7 steps 5th order multi-steps method.\n */\nstatic int\nsteps_7_5 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  b6 (x) = r[6];\n  b5 (x) = r[7];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x) - 10.L * b5 (x) - 12.L * b6 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) - 75.L * b5 (x) - 108.L * b6 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) - 500.L * b5 (x) - 864.L * b6 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) - 6480.L * b6 (x);\n  solve_4 (A, B, C, D, E);\n  b4 (x) = E[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = E[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = E[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = E[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)\n    - b6 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 7 steps 6th order multi-steps method.\n */\nstatic int\nsteps_7_6 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[5], B[5], C[5], D[5], E[5], F[5];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  b6 (x) = r[6];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x) - 12.L * b6 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) - 108.L * b6 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) - 864.L * b6 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) - 6480.L * b6 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x));\n  solve_5 (A, B, C, D, E, F);\n  b5 (x) = F[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = F[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = F[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = F[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = F[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)\n    - b6 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 7 steps 7th order multi-steps method.\n */\nstatic int\nsteps_7_7 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x);\n  solve_6 (A, B, C, D, E, F, G);\n  b6 (x) = G[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = G[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = G[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = G[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = G[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = G[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)\n    - b6 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 8 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_8_2 (Optimize * optimize) ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  b7 (x) = r[7];\n  b6 (x) = r[8];\n  b5 (x) = r[9];\n  b4 (x) = r[10];\n  b3 (x) = r[11];\n  b2 (x) = r[12];\n  b1 (x)\n    = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x) + 16.L * a4 (x)\n              + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 6.L * b3 (x)\n              - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x)\n              - 1.L);\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)\n    - b4 (x) - b5 (x) - b6 (x) - b7 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 8 steps 3th order multi-steps method.\n */\nstatic int\nsteps_8_3 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  b7 (x) = r[7];\n  b6 (x) = r[8];\n  b5 (x) = r[9];\n  b4 (x) = r[10];\n  b3 (x) = r[11];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 6.L * b3 (x)\n    - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) - 48.L * b4 (x)\n    - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x);\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)\n    - b4 (x) - b5 (x) - b6 (x) - b7 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 8 steps 4th order multi-steps method.\n */\nstatic int\nsteps_8_4 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  b7 (x) = r[7];\n  b6 (x) = r[8];\n  b5 (x) = r[9];\n  b4 (x) = r[10];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 8.L * b4 (x)\n    - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) - 48.L * b4 (x)\n    - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)\n    + 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)\n    + 2401.L * a7 (x) - 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x);\n  solve_3 (A, B, C, D);\n  b3 (x) = D[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = D[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = D[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)\n    - b4 (x) - b5 (x) - b6 (x) - b7 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 8 steps 5th order multi-steps method.\n */\nstatic int\nsteps_8_5 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  b7 (x) = r[7];\n  b6 (x) = r[8];\n  b5 (x) = r[9];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 10.L * b5 (x)\n    - 12.L * b6 (x) - 14.L * b7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) - 75.L * b5 (x)\n    - 108.L * b6 (x) - 147.L * b7 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) - 500.L * b5 (x)\n    - 864.L * b6 (x) - 1372.L * b7 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)\n    - 6480.L * b6 (x) - 12005.L * b7 (x);\n  solve_4 (A, B, C, D, E);\n  b4 (x) = E[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = E[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = E[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = E[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)\n    - b4 (x) - b5 (x) - b6 (x) - b7 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 8 steps 6th order multi-steps method.\n */\nstatic int\nsteps_8_6 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[5], B[5], C[5], D[5], E[5], F[5];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  b7 (x) = r[7];\n  b6 (x) = r[8];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 12.L * b6 (x)\n    - 14.L * b7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) - 108.L * b6 (x)\n    - 147.L * b7 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) - 864.L * b6 (x)\n    - 1372.L * b7 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) - 6480.L * b6 (x)\n    - 12005.L * b7 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)\n    - 100842.L * b7 (x);\n  solve_5 (A, B, C, D, E, F);\n  b5 (x) = F[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = F[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = F[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = F[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = F[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)\n    - b4 (x) - b5 (x) - b6 (x) - b7 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 8 steps 7th order multi-steps method.\n */\nstatic int\nsteps_8_7 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  b7 (x) = r[7];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 14.L * b7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) - 147.L * b7 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) - 1372.L * b7 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) - 12005.L * b7 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    - 100842.L * b7 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x));\n  solve_6 (A, B, C, D, E, F, G);\n  b6 (x) = G[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = G[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = G[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = G[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = G[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = G[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)\n    - b4 (x) - b5 (x) - b6 (x) - b7 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 8 steps 8th order multi-steps method.\n */\nstatic int\nsteps_8_8 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = 14.L;\n  H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 147.L;\n  H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = 1372.L;\n  H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 12005.L;\n  H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = 100842.L;\n  H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 823543.L;\n  H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x);\n  A[6] = 8.L;\n  B[6] = 1024.L;\n  C[6] = 17496.L;\n  D[6] = 131072.L;\n  E[6] = 625000.L;\n  F[6] = 2239488.L;\n  G[6] = 6588344.L;\n  H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)\n    + 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x);\n  solve_7 (A, B, C, D, E, F, G, H);\n  b7 (x) = H[6];\n  if (isnan (b7 (x)))\n    return 0;\n  b6 (x) = H[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = H[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = H[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = H[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = H[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = H[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)\n    - b4 (x) - b5 (x) - b6 (x) - b7 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 9 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_9_2 (Optimize * optimize) ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  b8 (x) = r[8];\n  b7 (x) = r[9];\n  b6 (x) = r[10];\n  b5 (x) = r[11];\n  b4 (x) = r[12];\n  b3 (x) = r[13];\n  b2 (x) = r[14];\n  b1 (x)\n    = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)\n              + 16.L * (a4 (x) - b8 (x)) + 25.L * a5 (x) + 36.L * a6 (x)\n              + 49.L * a7 (x) + 64.L * a8 (x) - 6.L * b3 (x) - 8.L * b4 (x)\n              - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 1.L);\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 9 steps 3th order multi-steps method.\n */\nstatic int\nsteps_9_3 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  b8 (x) = r[8];\n  b7 (x) = r[9];\n  b6 (x) = r[10];\n  b5 (x) = r[11];\n  b4 (x) = r[12];\n  b3 (x) = r[13];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    - 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x)\n    - 14.L * b7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    - 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x)\n    - 192.L * b8 (x);\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 9 steps 4th order multi-steps method.\n */\nstatic int\nsteps_9_4 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  b8 (x) = r[8];\n  b7 (x) = r[9];\n  b6 (x) = r[10];\n  b5 (x) = r[11];\n  b4 (x) = r[12];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    - 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x)\n    - 192.L * b8 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)\n    + 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)\n    + 2401.L * a7 (x) + 4096.L * a8 (x) - 500.L * b5 (x) - 864.L * b6 (x)\n    - 1372.L * b7 (x) - 2048.L * b8 (x);\n  solve_3 (A, B, C, D);\n  b3 (x) = D[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = D[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = D[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 9 steps 5th order multi-steps method.\n */\nstatic int\nsteps_9_5 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  b8 (x) = r[8];\n  b7 (x) = r[9];\n  b6 (x) = r[10];\n  b5 (x) = r[11];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    - 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)\n    + 32768.L * a8 (x) - 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x);\n  solve_4 (A, B, C, D, E);\n  b4 (x) = E[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = E[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = E[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = E[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 9 steps 6th order multi-steps method.\n */\nstatic int\nsteps_9_6 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[5], B[5], C[5], D[5], E[5], F[5];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  b8 (x) = r[8];\n  b7 (x) = r[9];\n  b6 (x) = r[10];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    - 12.L * b6 (x) - 14.L * b7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    - 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) - 100842.L * b7 (x) - 196608.L * b8 (x);\n  solve_5 (A, B, C, D, E, F);\n  b5 (x) = F[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = F[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = F[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = F[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = F[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 9 steps 7th order multi-steps method.\n */\nstatic int\nsteps_9_7 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  b8 (x) = r[8];\n  b7 (x) = r[9];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    - 14.L * b7 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    - 147.L * b7 (x) - 192.L * b8 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    - 1372.L * b7 (x) - 2048.L * b8 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    - 12005.L * b7 (x) - 20480.L * b8 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) - 100842.L * b7 (x) - 196608.L * b8 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x))\n    + 2097152.L * a8 (x) - 1835008.L * b8 (x);\n  solve_6 (A, B, C, D, E, F, G);\n  b6 (x) = G[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = G[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = G[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = G[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = G[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = G[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 9 steps 8th order multi-steps method.\n */\nstatic int\nsteps_9_8 (Optimize * optimize) ///< Optimize struct.\n{\n  long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  b8 (x) = r[8];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = 14.L;\n  H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 147.L;\n  H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    - 192.L * b8 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = 1372.L;\n  H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    - 2048.L * b8 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 12005.L;\n  H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    - 20480.L * b8 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = 100842.L;\n  H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) - 196608.L * b8 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 823543.L;\n  H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x)\n    + 2097152.L * a8 (x) - 1835008.L * b8 (x);\n  A[6] = 8.L;\n  B[6] = 1024.L;\n  C[6] = 17496.L;\n  D[6] = 131072.L;\n  E[6] = 625000.L;\n  F[6] = 2239488.L;\n  G[6] = 6588344.L;\n  H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)\n    + 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x)\n    + 16777216.L * (a8 (x) - b8 (x));\n  solve_7 (A, B, C, D, E, F, G, H);\n  b7 (x) = H[6];\n  if (isnan (b7 (x)))\n    return 0;\n  b6 (x) = H[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = H[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = H[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = H[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = H[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = H[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)\n    - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 10 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_10_2 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  b9 (x) = r[9];\n  b8 (x) = r[10];\n  b7 (x) = r[11];\n  b6 (x) = r[12];\n  b5 (x) = r[13];\n  b4 (x) = r[14];\n  b3 (x) = r[15];\n  b2 (x) = r[16];\n  b1 (x)\n    = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)\n              + 16.L * (a4 (x) - b8 (x)) + 25.L * a5 (x) + 36.L * a6 (x)\n              + 49.L * a7 (x) + 64.L * a8 (x) + 81.L * a9 (x) - 6.L * b3 (x)\n              - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x)\n              - 18.L * b9 (x) - 1.L);\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)\n    - b9 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 10 steps 3th order multi-steps method.\n */\nstatic int\nsteps_10_3 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  b9 (x) = r[9];\n  b8 (x) = r[10];\n  b7 (x) = r[11];\n  b6 (x) = r[12];\n  b5 (x) = r[13];\n  b4 (x) = r[14];\n  b3 (x) = r[15];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) - 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x)\n    - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) - 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x)\n    - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x);\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)\n    - b9 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 10 steps 4th order multi-steps method.\n */\nstatic int\nsteps_10_4 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  b9 (x) = r[9];\n  b8 (x) = r[10];\n  b7 (x) = r[11];\n  b6 (x) = r[12];\n  b5 (x) = r[13];\n  b4 (x) = r[14];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x)\n    - 14.L * b7 (x) - 18.L * b9 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) - 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x)\n    - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)\n    + 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)\n    + 2401.L * a7 (x) + 4096.L * a8 (x) + 6561.L * a9 (x) - 500.L * b5 (x)\n    - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x);\n  solve_3 (A, B, C, D);\n  b3 (x) = D[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = D[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = D[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)\n    - b9 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 10 steps 5th order multi-steps method.\n */\nstatic int\nsteps_10_5 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  b9 (x) = r[9];\n  b8 (x) = r[10];\n  b7 (x) = r[11];\n  b6 (x) = r[12];\n  b5 (x) = r[13];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x)\n    - 18.L * b9 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x)\n    - 192.L * b8 (x) - 243.L * b9 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) - 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x)\n    - 2048.L * b8 (x) - 2916.L * b9 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)\n    + 32768.L * a8 (x) + 59049.L * a9 (x) - 6480.L * b6 (x) - 12005.L * b7 (x)\n    - 20480.L * b8 (x) - 32805.L * b9 (x);\n  solve_4 (A, B, C, D, E);\n  b4 (x) = E[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = E[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = E[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = E[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)\n    - b9 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 10 steps 6th order multi-steps method.\n */\nstatic int\nsteps_10_6 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[5], B[5], C[5], D[5], E[5], F[5];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  b9 (x) = r[9];\n  b8 (x) = r[10];\n  b7 (x) = r[11];\n  b6 (x) = r[12];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x)\n    - 243.L * b9 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x)\n    - 2916.L * b9 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) - 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x)\n    - 32805.L * b9 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) - 100842.L * b7 (x)\n    - 196608.L * b8 (x) - 354294.L * b9 (x);\n  solve_5 (A, B, C, D, E, F);\n  b5 (x) = F[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = F[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = F[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = F[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = F[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)\n    - b9 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 10 steps 7th order multi-steps method.\n */\nstatic int\nsteps_10_7 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  b9 (x) = r[9];\n  b8 (x) = r[10];\n  b7 (x) = r[11];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) - 14.L * b7 (x) - 18.L * b9 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) - 12005.L * b7 (x) - 20480.L * b8 (x) - 32805.L * b9 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) - 100842.L * b7 (x)\n    - 196608.L * b8 (x) - 354294.L * b9 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x))\n    + 2097152.L * a8 (x) + 4782969.L * a9 (x) - 1835008.L * b8 (x)\n    - 3720087.L * b9 (x);\n  solve_6 (A, B, C, D, E, F, G);\n  b6 (x) = G[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = G[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = G[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = G[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = G[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = G[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)\n    - b9 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 10 steps 8th order multi-steps method.\n */\nstatic int\nsteps_10_8 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  b9 (x) = r[9];\n  b8 (x) = r[10];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = 14.L;\n  H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) - 18.L * b9 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 147.L;\n  H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) - 192.L * b8 (x) - 243.L * b9 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = 1372.L;\n  H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) - 2048.L * b8 (x) - 2916.L * b9 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 12005.L;\n  H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) - 20480.L * b8 (x) - 32805.L * b9 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = 100842.L;\n  H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) - 196608.L * b8 (x)\n    - 354294.L * b9 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 823543.L;\n  H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x)\n    + 2097152.L * a8 (x) + 4782969.L * a9 (x) - 1835008.L * b8 (x)\n    - 3720087.L * b9 (x);\n  A[6] = 8.L;\n  B[6] = 1024.L;\n  C[6] = 17496.L;\n  D[6] = 131072.L;\n  E[6] = 625000.L;\n  F[6] = 2239488.L;\n  G[6] = 6588344.L;\n  H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)\n    + 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x)\n    + 16777216.L * (a8 (x) - b8 (x)) + 43046721.L * a9 (x)\n    - 38263752.L * b9 (x);\n  solve_7 (A, B, C, D, E, F, G, H);\n  b7 (x) = H[6];\n  if (isnan (b7 (x)))\n    return 0;\n  b6 (x) = H[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = H[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = H[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = H[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = H[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = H[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)\n    - b9 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 11 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_11_2 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  b10 (x) = r[10];\n  b9 (x) = r[11];\n  b8 (x) = r[12];\n  b7 (x) = r[13];\n  b6 (x) = r[14];\n  b5 (x) = r[15];\n  b4 (x) = r[16];\n  b3 (x) = r[17];\n  b2 (x) = r[18];\n  b1 (x)\n    = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)\n              + 16.L * (a4 (x) - b8 (x)) + 25.L * a5 (x) + 36.L * a6 (x)\n              + 49.L * a7 (x) + 64.L * a8 (x) + 81.L * a9 (x) + 100.L * a10 (x)\n              - 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x)\n              - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x) - 1.L);\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)\n    - b7 (x) - b8 (x) - b9 (x) - b10 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 11 steps 3th order multi-steps method.\n */\nstatic int\nsteps_11_3 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  b10 (x) = r[10];\n  b9 (x) = r[11];\n  b8 (x) = r[12];\n  b7 (x) = r[13];\n  b6 (x) = r[14];\n  b5 (x) = r[15];\n  b4 (x) = r[16];\n  b3 (x) = r[17];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) - 6.L * b3 (x) - 8.L * b4 (x)\n    - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x)\n    - 20.L * b10 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) - 48.L * b4 (x) - 75.L * b5 (x)\n    - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x)\n    - 300.L * b10 (x);\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)\n    - b7 (x) - b8 (x) - b9 (x) - b10 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 11 steps 4th order multi-steps method.\n */\nstatic int\nsteps_11_4 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  b10 (x) = r[10];\n  b9 (x) = r[11];\n  b8 (x) = r[12];\n  b7 (x) = r[13];\n  b6 (x) = r[14];\n  b5 (x) = r[15];\n  b4 (x) = r[16];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) - 8.L * b4 (x) - 10.L * b5 (x)\n    - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) - 48.L * b4 (x) - 75.L * b5 (x)\n    - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x)\n    - 300.L * b10 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)\n    + 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)\n    + 2401.L * a7 (x) + 4096.L * a8 (x) + 6561.L * a9 (x) + 10000.L * a10 (x)\n    - 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x)\n    - 2916.L * b9 (x) - 4000.L * b10 (x);\n  solve_3 (A, B, C, D);\n  b3 (x) = D[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = D[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = D[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)\n    - b7 (x) - b8 (x) - b9 (x) - b10 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 11 steps 5th order multi-steps method.\n */\nstatic int\nsteps_11_5 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  b10 (x) = r[10];\n  b9 (x) = r[11];\n  b8 (x) = r[12];\n  b7 (x) = r[13];\n  b6 (x) = r[14];\n  b5 (x) = r[15];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) - 10.L * b5 (x) - 12.L * b6 (x)\n    - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) - 75.L * b5 (x) - 108.L * b6 (x)\n    - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) - 500.L * b5 (x) - 864.L * b6 (x)\n    - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)\n    + 32768.L * a8 (x) + 59049.L * a9 (x) + 100000.L * a10 (x) - 6480.L * b6 (x)\n    - 12005.L * b7 (x) - 20480.L * b8 (x) - 32805.L * b9 (x)\n    - 50000.L * b10 (x);\n  solve_4 (A, B, C, D, E);\n  b4 (x) = E[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = E[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = E[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = E[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)\n    - b7 (x) - b8 (x) - b9 (x) - b10 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 11 steps 6th order multi-steps method.\n */\nstatic int\nsteps_11_6 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[5], B[5], C[5], D[5], E[5], F[5];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  b10 (x) = r[10];\n  b9 (x) = r[11];\n  b8 (x) = r[12];\n  b7 (x) = r[13];\n  b6 (x) = r[14];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) - 12.L * b6 (x) - 14.L * b7 (x)\n    - 18.L * b9 (x) - 20.L * b10 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) - 108.L * b6 (x) - 147.L * b7 (x)\n    - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) - 864.L * b6 (x) - 1372.L * b7 (x)\n    - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) + 100000.L * a10 (x) - 6480.L * b6 (x) - 12005.L * b7 (x)\n    - 20480.L * b8 (x) - 32805.L * b9 (x) - 50000.L * b10 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)\n    - 100842.L * b7 (x) - 196608.L * b8 (x) - 354294.L * b9 (x)\n    - 600000.L * b10 (x);\n  solve_5 (A, B, C, D, E, F);\n  b5 (x) = F[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = F[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = F[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = F[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = F[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)\n    - b7 (x) - b8 (x) - b9 (x) - b10 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 11 steps 7th order multi-steps method.\n */\nstatic int\nsteps_11_7 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  b10 (x) = r[10];\n  b9 (x) = r[11];\n  b8 (x) = r[12];\n  b7 (x) = r[13];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) - 14.L * b7 (x) - 18.L * b9 (x)\n    - 20.L * b10 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) - 147.L * b7 (x) - 192.L * b8 (x)\n    - 243.L * b9 (x) - 300.L * b10 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) - 1372.L * b7 (x) - 2048.L * b8 (x)\n    - 2916.L * b9 (x) - 4000.L * b10 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) + 100000.L * a10 (x) - 12005.L * b7 (x)\n    - 20480.L * b8 (x) - 32805.L * b9 (x) - 50000.L * b10 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)\n    - 100842.L * b7 (x) - 196608.L * b8 (x) - 354294.L * b9 (x)\n    - 600000.L * b10 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x))\n    + 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)\n    - 1835008.L * b8 (x) - 3720087.L * b9 (x) - 7000000.L * b10 (x);\n  solve_6 (A, B, C, D, E, F, G);\n  b6 (x) = G[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = G[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = G[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = G[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = G[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = G[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)\n    - b7 (x) - b8 (x) - b9 (x) - b10 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 11 steps 8th order multi-steps method.\n */\nstatic int\nsteps_11_8 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  b10 (x) = r[10];\n  b9 (x) = r[11];\n  b8 (x) = r[12];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = 14.L;\n  H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) - 18.L * b9 (x) - 20.L * b10 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 147.L;\n  H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) - 192.L * b8 (x) - 243.L * b9 (x)\n    - 300.L * b10 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = 1372.L;\n  H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) - 2048.L * b8 (x) - 2916.L * b9 (x)\n    - 4000.L * b10 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 12005.L;\n  H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) + 100000.L * a10 (x) - 20480.L * b8 (x)\n    - 32805.L * b9 (x) - 50000.L * b10 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = 100842.L;\n  H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)\n    - 196608.L * b8 (x) - 354294.L * b9 (x) - 600000.L * b10 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 823543.L;\n  H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x)\n    + 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)\n    - 1835008.L * b8 (x) - 3720087.L * b9 (x) - 7000000.L * b10 (x);\n  A[6] = 8.L;\n  B[6] = 1024.L;\n  C[6] = 17496.L;\n  D[6] = 131072.L;\n  E[6] = 625000.L;\n  F[6] = 2239488.L;\n  G[6] = 6588344.L;\n  H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)\n    + 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x)\n    + 16777216.L * (a8 (x) - b8 (x)) + 43046721.L * a9 (x)\n    + 100000000.L * a10 (x) - 38263752.L * b9 (x) - 80000000.L * b10 (x);\n  solve_7 (A, B, C, D, E, F, G, H);\n  b7 (x) = H[6];\n  if (isnan (b7 (x)))\n    return 0;\n  b6 (x) = H[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = H[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = H[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = H[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = H[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = H[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)\n    - b7 (x) - b8 (x) - b9 (x) - b10 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 12 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_12_2 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  b11 (x) = r[11];\n  b10 (x) = r[12];\n  b9 (x) = r[13];\n  b8 (x) = r[14];\n  b7 (x) = r[15];\n  b6 (x) = r[16];\n  b5 (x) = r[17];\n  b4 (x) = r[18];\n  b3 (x) = r[19];\n  b2 (x) = r[20];\n  b1 (x)\n    = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)\n              + 16.L * (a4 (x) - b8 (x)) + 25.L * a5 (x) + 36.L * a6 (x)\n              + 49.L * a7 (x) + 64.L * a8 (x) + 81.L * a9 (x) + 100.L * a10 (x)\n              + 121.L * a11 (x) - 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x)\n              - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x)\n              - 22.L * b11 (x) - 1.L);\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)\n    - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 12 steps 3th order multi-steps method.\n */\nstatic int\nsteps_12_3 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  b11 (x) = r[11];\n  b10 (x) = r[12];\n  b9 (x) = r[13];\n  b8 (x) = r[14];\n  b7 (x) = r[15];\n  b6 (x) = r[16];\n  b5 (x) = r[17];\n  b4 (x) = r[18];\n  b3 (x) = r[19];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 6.L * b3 (x)\n    - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x)\n    - 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 48.L * b4 (x)\n    - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x)\n    - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x);\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)\n    - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 12 steps 4th order multi-steps method.\n */\nstatic int\nsteps_12_4 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  b11 (x) = r[11];\n  b10 (x) = r[12];\n  b9 (x) = r[13];\n  b8 (x) = r[14];\n  b7 (x) = r[15];\n  b6 (x) = r[16];\n  b5 (x) = r[17];\n  b4 (x) = r[18];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 8.L * b4 (x)\n    - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x)\n    - 20.L * b10 (x) - 22.L * b11 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 48.L * b4 (x)\n    - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x)\n    - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)\n    + 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)\n    + 2401.L * a7 (x) + 4096.L * a8 (x) + 6561.L * a9 (x) + 10000.L * a10 (x)\n    + 14641.L * a11 (x) - 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x)\n    - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x) - 5324.L * b11 (x);\n  solve_3 (A, B, C, D);\n  b3 (x) = D[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = D[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = D[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)\n    - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 12 steps 5th order multi-steps method.\n */\nstatic int\nsteps_12_5 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  b11 (x) = r[11];\n  b10 (x) = r[12];\n  b9 (x) = r[13];\n  b8 (x) = r[14];\n  b7 (x) = r[15];\n  b6 (x) = r[16];\n  b5 (x) = r[17];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 10.L * b5 (x)\n    - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x)\n    - 22.L * b11 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 75.L * b5 (x)\n    - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x)\n    - 300.L * b10 (x) - 363.L * b11 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x) - 500.L * b5 (x)\n    - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x)\n    - 4000.L * b10 (x) - 5324.L * b11 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)\n    + 32768.L * a8 (x) + 59049.L * a9 (x) + 100000.L * a10 (x)\n    + 161051.L * a11 (x) - 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x)\n    - 32805.L * b9 (x) - 50000.L * b10 (x) - 73205.L * b11 (x);\n  solve_4 (A, B, C, D, E);\n  b4 (x) = E[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = E[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = E[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = E[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)\n    - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 12 steps 6th order multi-steps method.\n */\nstatic int\nsteps_12_6 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[5], B[5], C[5], D[5], E[5], F[5];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  b11 (x) = r[11];\n  b10 (x) = r[12];\n  b9 (x) = r[13];\n  b8 (x) = r[14];\n  b7 (x) = r[15];\n  b6 (x) = r[16];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 12.L * b6 (x)\n    - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 108.L * b6 (x)\n    - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x)\n    - 363.L * b11 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x) - 864.L * b6 (x)\n    - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x)\n    - 5324.L * b11 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)\n    - 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x) - 32805.L * b9 (x)\n    - 50000.L * b10 (x) - 73205.L * b11 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)\n    + 1771561.L * a11 (x) - 100842.L * b7 (x) - 196608.L * b8 (x)\n    - 354294.L * b9 (x) - 600000.L * b10 (x) - 966306.L * b11 (x);\n  solve_5 (A, B, C, D, E, F);\n  b5 (x) = F[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = F[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = F[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = F[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = F[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)\n    - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 12 steps 7th order multi-steps method.\n */\nstatic int\nsteps_12_7 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  b11 (x) = r[11];\n  b10 (x) = r[12];\n  b9 (x) = r[13];\n  b8 (x) = r[14];\n  b7 (x) = r[15];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 14.L * b7 (x)\n    - 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 147.L * b7 (x)\n    - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x) - 1372.L * b7 (x)\n    - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x) - 5324.L * b11 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)\n    - 12005.L * b7 (x) - 20480.L * b8 (x) - 32805.L * b9 (x) - 50000.L * b10 (x)\n    - 73205.L * b11 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)\n    + 1771561.L * a11 (x) - 100842.L * b7 (x) - 196608.L * b8 (x)\n    - 354294.L * b9 (x) - 600000.L * b10 (x) - 966306.L * b11 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x))\n    + 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)\n    + 19487171.L * a11 (x) - 1835008.L * b8 (x) - 3720087.L * b9 (x)\n    - 7000000.L * b10 (x) - 12400927.L * b11 (x);\n  solve_6 (A, B, C, D, E, F, G);\n  b6 (x) = G[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = G[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = G[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = G[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = G[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = G[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)\n    - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 12 steps 8th order multi-steps method.\n */\nstatic int\nsteps_12_8 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  b11 (x) = r[11];\n  b10 (x) = r[12];\n  b9 (x) = r[13];\n  b8 (x) = r[14];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = 14.L;\n  H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 18.L * b9 (x)\n    - 20.L * b10 (x) - 22.L * b11 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 147.L;\n  H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 192.L * b8 (x)\n    - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = 1372.L;\n  H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x) - 2048.L * b8 (x)\n    - 2916.L * b9 (x) - 4000.L * b10 (x) - 5324.L * b11 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 12005.L;\n  H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)\n    - 20480.L * b8 (x) - 32805.L * b9 (x) - 50000.L * b10 (x)\n    - 73205.L * b11 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = 100842.L;\n  H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)\n    + 1771561.L * a11 (x) - 196608.L * b8 (x) - 354294.L * b9 (x)\n    - 600000.L * b10 (x) - 966306.L * b11 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 823543.L;\n  H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x)\n    + 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)\n    + 19487171.L * a11 (x) - 1835008.L * b8 (x) - 3720087.L * b9 (x)\n    - 7000000.L * b10 (x) - 12400927.L * b11 (x);\n  A[6] = 8.L;\n  B[6] = 1024.L;\n  C[6] = 17496.L;\n  D[6] = 131072.L;\n  E[6] = 625000.L;\n  F[6] = 2239488.L;\n  G[6] = 6588344.L;\n  H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)\n    + 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x)\n    + 16777216.L * (a8 (x) - b8 (x)) + 43046721.L * a9 (x)\n    + 100000000.L * a10 (x) + 214358881.L * a11 (x) - 38263752.L * b9 (x)\n    - 80000000.L * b10 (x) - 155897368.L * b11 (x);\n  solve_7 (A, B, C, D, E, F, G, H);\n  b7 (x) = H[6];\n  if (isnan (b7 (x)))\n    return 0;\n  b6 (x) = H[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = H[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = H[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = H[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = H[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = H[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)\n    - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 13 steps 2nd order multi-steps method.\n */\nstatic int\nsteps_13_2 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  a12 (x) = r[11];\n  b12 (x) = r[12];\n  b11 (x) = r[13];\n  b10 (x) = r[14];\n  b9 (x) = r[15];\n  b8 (x) = r[16];\n  b7 (x) = r[17];\n  b6 (x) = r[18];\n  b5 (x) = r[19];\n  b4 (x) = r[20];\n  b3 (x) = r[21];\n  b2 (x) = r[22];\n  b1 (x)\n    = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)\n              + 16.L * (a4 (x) - b8 (x)) + 25.L * a5 (x) + 36.L * a6 (x)\n              + 49.L * a7 (x) + 64.L * a8 (x) + 81.L * a9 (x) + 100.L * a10 (x)\n              + 121.L * a11 (x) + 144.L * a12 (x) - 6.L * b3 (x) - 8.L * b4 (x)\n              - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x)\n              - 20.L * b10 (x) - 22.L * b11 (x) - 24.L * b12 (x) - 1.L);\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)\n    - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)\n    - b11 (x) - b12 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 13 steps 3th order multi-steps method.\n */\nstatic int\nsteps_13_3 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[2], B[2], C[2];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  a12 (x) = r[11];\n  b12 (x) = r[12];\n  b11 (x) = r[13];\n  b10 (x) = r[14];\n  b9 (x) = r[15];\n  b8 (x) = r[16];\n  b7 (x) = r[17];\n  b6 (x) = r[18];\n  b5 (x) = r[19];\n  b4 (x) = r[20];\n  b3 (x) = r[21];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)\n    - 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x)\n    - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x)\n    - 24.L * b12 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)\n    - 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x)\n    - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x)\n    - 432.L * b12 (x);\n  solve_2 (A, B, C);\n  b2 (x) = C[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = C[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)\n    - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)\n    - b11 (x) - b12 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 13 steps 4th order multi-steps method.\n */\nstatic int\nsteps_13_4 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[3], B[3], C[3], D[3];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  a12 (x) = r[11];\n  b12 (x) = r[12];\n  b11 (x) = r[13];\n  b10 (x) = r[14];\n  b9 (x) = r[15];\n  b8 (x) = r[16];\n  b7 (x) = r[17];\n  b6 (x) = r[18];\n  b5 (x) = r[19];\n  b4 (x) = r[20];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)\n    - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x)\n    - 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x) - 24.L * b12 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)\n    - 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x)\n    - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x)\n    - 432.L * b12 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)\n    + 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)\n    + 2401.L * a7 (x) + 4096.L * a8 (x) + 6561.L * a9 (x) + 10000.L * a10 (x)\n    + 14641.L * a11 (x) + 20736.L * a12 (x) - 500.L * b5 (x) - 864.L * b6 (x)\n    - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x)\n    - 5324.L * b11 (x) - 6912.L * b12 (x);\n  solve_3 (A, B, C, D);\n  b3 (x) = D[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = D[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = D[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)\n    - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)\n    - b11 (x) - b12 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 13 steps 5th order multi-steps method.\n */\nstatic int\nsteps_13_5 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[4], B[4], C[4], D[4], E[4];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  a12 (x) = r[11];\n  b12 (x) = r[12];\n  b11 (x) = r[13];\n  b10 (x) = r[14];\n  b9 (x) = r[15];\n  b8 (x) = r[16];\n  b7 (x) = r[17];\n  b6 (x) = r[18];\n  b5 (x) = r[19];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)\n    - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x)\n    - 20.L * b10 (x) - 22.L * b11 (x) - 24.L * b12 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)\n    - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x)\n    - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x) - 432.L * b12 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x)\n    + 20736.L * a12 (x) - 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x)\n    - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x) - 5324.L * b11 (x)\n    - 6912.L * b12 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)\n    + 32768.L * a8 (x) + 59049.L * a9 (x) + 100000.L * a10 (x)\n    + 161051.L * a11 (x) + 248832.L * a12 (x) - 6480.L * b6 (x)\n    - 12005.L * b7 (x) - 20480.L * b8 (x) - 32805.L * b9 (x) - 50000.L * b10 (x)\n    - 73205.L * b11 (x) - 103680.L * b12 (x);\n  solve_4 (A, B, C, D, E);\n  b4 (x) = E[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = E[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = E[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = E[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)\n    - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)\n    - b11 (x) - b12 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 13 steps 6th order multi-steps method.\n */\nstatic int\nsteps_13_6 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[5], B[5], C[5], D[5], E[5], F[5];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  a12 (x) = r[11];\n  b12 (x) = r[12];\n  b11 (x) = r[13];\n  b10 (x) = r[14];\n  b9 (x) = r[15];\n  b8 (x) = r[16];\n  b7 (x) = r[17];\n  b6 (x) = r[18];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)\n    - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x)\n    - 22.L * b11 (x) - 24.L * b12 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)\n    - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x)\n    - 300.L * b10 (x) - 363.L * b11 (x) - 432.L * b12 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x)\n    + 20736.L * a12 (x) - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x)\n    - 2916.L * b9 (x) - 4000.L * b10 (x) - 5324.L * b11 (x) - 6912.L * b12 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)\n    + 248832.L * a12 (x) - 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x)\n    - 32805.L * b9 (x) - 50000.L * b10 (x) - 73205.L * b11 (x)\n    - 103680.L * b12 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)\n    + 1771561.L * a11 (x) + 2985984.L * a12 (x) - 100842.L * b7 (x)\n    - 196608.L * b8 (x) - 354294.L * b9 (x) - 600000.L * b10 (x)\n    - 966306.L * b11 (x) - 1492992.L * b12 (x);\n  solve_5 (A, B, C, D, E, F);\n  b5 (x) = F[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = F[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = F[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = F[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = F[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)\n    - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)\n    - b11 (x) - b12 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 13 steps 7th order multi-steps method.\n */\nstatic int\nsteps_13_7 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  a12 (x) = r[11];\n  b12 (x) = r[12];\n  b11 (x) = r[13];\n  b10 (x) = r[14];\n  b9 (x) = r[15];\n  b8 (x) = r[16];\n  b7 (x) = r[17];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)\n    - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x)\n    - 24.L * b12 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)\n    - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x)\n    - 363.L * b11 (x) - 432.L * b12 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x)\n    + 20736.L * a12 (x) - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x)\n    - 4000.L * b10 (x) - 5324.L * b11 (x) - 6912.L * b12 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)\n    + 248832.L * a12 (x) - 12005.L * b7 (x) - 20480.L * b8 (x)\n    - 32805.L * b9 (x) - 50000.L * b10 (x) - 73205.L * b11 (x)\n    - 103680.L * b12 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)\n    + 1771561.L * a11 (x) + 2985984.L * a12 (x) - 100842.L * b7 (x)\n    - 196608.L * b8 (x) - 354294.L * b9 (x) - 600000.L * b10 (x)\n    - 966306.L * b11 (x) - 1492992.L * b12 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x))\n    + 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)\n    + 19487171.L * a11 (x) + 35831808.L * a12 (x) - 1835008.L * b8 (x)\n    - 3720087.L * b9 (x) - 7000000.L * b10 (x) - 12400927.L * b11 (x)\n    - 20901888.L * b12 (x);\n  solve_6 (A, B, C, D, E, F, G);\n  b6 (x) = G[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = G[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = G[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = G[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = G[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = G[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)\n    - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)\n    - b11 (x) - b12 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);\n  return 1;\n}\n\n/**\n * Function to get the coefficients on a 13 steps 8th order multi-steps method.\n */\nstatic int\nsteps_13_8 (Optimize * optimize)        ///< Optimize struct.\n{\n  long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];\n  long double *x, *r;\n  x = optimize->coefficient;\n  r = optimize->random_data;\n  a1 (x) = r[0];\n  a2 (x) = r[1];\n  a3 (x) = r[2];\n  a4 (x) = r[3];\n  a5 (x) = r[4];\n  a6 (x) = r[5];\n  a7 (x) = r[6];\n  a8 (x) = r[7];\n  a9 (x) = r[8];\n  a10 (x) = r[9];\n  a11 (x) = r[10];\n  a12 (x) = r[11];\n  b12 (x) = r[12];\n  b11 (x) = r[13];\n  b10 (x) = r[14];\n  b9 (x) = r[15];\n  b8 (x) = r[16];\n  A[0] = 2.L;\n  B[0] = 4.L;\n  C[0] = 6.L;\n  D[0] = 8.L;\n  E[0] = 10.L;\n  F[0] = 12.L;\n  G[0] = 14.L;\n  H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))\n    + 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)\n    + 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)\n    - 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x) - 24.L * b12 (x);\n  A[1] = 3.L;\n  B[1] = 12.L;\n  C[1] = 27.L;\n  D[1] = 48.L;\n  E[1] = 75.L;\n  F[1] = 108.L;\n  G[1] = 147.L;\n  H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)\n    + 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)\n    + 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)\n    - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x)\n    - 432.L * b12 (x);\n  A[2] = 4.L;\n  B[2] = 32.L;\n  C[2] = 108.L;\n  D[2] = 256.L;\n  E[2] = 500.L;\n  F[2] = 864.L;\n  G[2] = 1372.L;\n  H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)\n    + 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)\n    + 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x)\n    + 20736.L * a12 (x) - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x)\n    - 5324.L * b11 (x) - 6912.L * b12 (x);\n  A[3] = 5.L;\n  B[3] = 80.L;\n  C[3] = 405.L;\n  D[3] = 1280.L;\n  E[3] = 3125.L;\n  F[3] = 6480.L;\n  G[3] = 12005.L;\n  H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)\n    + 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)\n    + 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)\n    + 248832.L * a12 (x) - 20480.L * b8 (x) - 32805.L * b9 (x)\n    - 50000.L * b10 (x) - 73205.L * b11 (x) - 103680.L * b12 (x);\n  A[4] = 6.L;\n  B[4] = 192.L;\n  C[4] = 1458.L;\n  D[4] = 6144.L;\n  E[4] = 18750.L;\n  F[4] = 46656.L;\n  G[4] = 100842.L;\n  H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)\n    + 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)\n    + 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)\n    + 1771561.L * a11 (x) + 2985984.L * a12 (x) - 196608.L * b8 (x)\n    - 354294.L * b9 (x) - 600000.L * b10 (x) - 966306.L * b11 (x)\n    - 1492992.L * b12 (x);\n  A[5] = 7.L;\n  B[5] = 448.L;\n  C[5] = 5103.L;\n  D[5] = 28672.L;\n  E[5] = 109375.L;\n  F[5] = 326592.L;\n  G[5] = 823543.L;\n  H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)\n    + 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x)\n    + 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)\n    + 19487171.L * a11 (x) + 35831808.L * a12 (x) - 1835008.L * b8 (x)\n    - 3720087.L * b9 (x) - 7000000.L * b10 (x) - 12400927.L * b11 (x)\n    - 20901888.L * b12 (x);\n  A[6] = 8.L;\n  B[6] = 1024.L;\n  C[6] = 17496.L;\n  D[6] = 131072.L;\n  E[6] = 625000.L;\n  F[6] = 2239488.L;\n  G[6] = 6588344.L;\n  H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)\n    + 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x)\n    + 16777216.L * (a8 (x) - b8 (x)) + 43046721.L * a9 (x)\n    + 100000000.L * a10 (x) + 214358881.L * a11 (x) + 429981696.L * a12 (x)\n    - 38263752.L * b9 (x) - 80000000.L * b10 (x) - 155897368.L * b11 (x)\n    - 286654464.L * b12 (x);\n  solve_7 (A, B, C, D, E, F, G, H);\n  b7 (x) = H[6];\n  if (isnan (b7 (x)))\n    return 0;\n  b6 (x) = H[5];\n  if (isnan (b6 (x)))\n    return 0;\n  b5 (x) = H[4];\n  if (isnan (b5 (x)))\n    return 0;\n  b4 (x) = H[3];\n  if (isnan (b4 (x)))\n    return 0;\n  b3 (x) = H[2];\n  if (isnan (b3 (x)))\n    return 0;\n  b2 (x) = H[1];\n  if (isnan (b2 (x)))\n    return 0;\n  b1 (x) = H[0];\n  if (isnan (b1 (x)))\n    return 0;\n  b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)\n    + 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)\n    + 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)\n    - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)\n    - b11 (x) - b12 (x);\n  a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)\n    - a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);\n  return 1;\n}\n\n/**\n * Function to print on a file the coefficients of the multi-steps methods.\n */\nstatic void\nsteps_print (Optimize * optimize,       ///< Optimize struct.\n             FILE * file)       ///< file.\n{\n  long double *x;\n  unsigned int i;\n  x = optimize->coefficient;\n  for (i = 0; i < optimize->nsteps; ++i)\n    {\n      fprintf (file, \"a%u:%.19Le;\\n\", i, x[2 * i]);\n      fprintf (file, \"b%u:%.19Le;\\n\", i, x[2 * i + 1]);\n      fprintf (file, \"c%u:%.19Le;\\n\", i, c (x[2 * i], x[2 * i + 1]));\n    }\n}\n\n/**\n * Function to print a maxima format file to check the accuracy order of a\n * multi-steps method.\n */\nstatic void\nsteps_print_maxima (FILE * file,        ///< file.\n                    unsigned int nsteps,        ///< steps number.\n                    unsigned int order) ///< accuracy order.\n{\n  int m;\n  unsigned int i, j, k, l;\n\n  // 0th order\n  fprintf (file, \"a0\");\n  for (i = 1; i < nsteps; ++i)\n    fprintf (file, \"+a%u\", i);\n  fprintf (file, \"-1b0;\\n\");\n\n  // 1st order\n  fprintf (file, \"b0\");\n  for (i = 1; i < nsteps; ++i)\n    fprintf (file, \"+b%u\", i);\n  for (i = 1; i < nsteps; ++i)\n    fprintf (file, \"-%ub0*a%u\", i, i);\n  fprintf (file, \"-1b0;\\n\");\n\n  // high order\n  for (j = 2, m = 1; j <= order; ++j, m = -m)\n    {\n      for (i = 1; i < nsteps; ++i)\n        {\n          for (k = 1, l = i; k < j; ++k)\n            l *= i;\n          fprintf (file, \"-%ub0*a%u\", l, i);\n        }\n      for (i = 1; i < nsteps; ++i)\n        {\n          for (k = 2, l = i * j; k < j; ++k)\n            l *= i;\n          fprintf (file, \"+%ub0*b%u\", l, i);\n        }\n      fprintf (file, \"+%db0;\\n\", m);\n    }\n}\n\n/**\n * Function to get the objective function of a 3 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_3 (Optimize * optimize) ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to get the objective function of a 4 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_4 (Optimize * optimize) ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (a3 (x) < -LDBL_EPSILON)\n    k += a3 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (b3 (x) < -LDBL_EPSILON)\n    k += b3 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c3 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to get the objective function of a 5 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_5 (Optimize * optimize) ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (a3 (x) < -LDBL_EPSILON)\n    k += a3 (x);\n  if (a4 (x) < -LDBL_EPSILON)\n    k += a4 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (b3 (x) < -LDBL_EPSILON)\n    k += b3 (x);\n  if (b4 (x) < -LDBL_EPSILON)\n    k += b4 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c3 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c4 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to get the objective function of a 6 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_6 (Optimize * optimize) ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (a3 (x) < -LDBL_EPSILON)\n    k += a3 (x);\n  if (a4 (x) < -LDBL_EPSILON)\n    k += a4 (x);\n  if (a5 (x) < -LDBL_EPSILON)\n    k += a5 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (b3 (x) < -LDBL_EPSILON)\n    k += b3 (x);\n  if (b4 (x) < -LDBL_EPSILON)\n    k += b4 (x);\n  if (b5 (x) < -LDBL_EPSILON)\n    k += b5 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c3 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c4 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c5 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to get the objective function of a 7 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_7 (Optimize * optimize) ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (a3 (x) < -LDBL_EPSILON)\n    k += a3 (x);\n  if (a4 (x) < -LDBL_EPSILON)\n    k += a4 (x);\n  if (a5 (x) < -LDBL_EPSILON)\n    k += a5 (x);\n  if (a6 (x) < -LDBL_EPSILON)\n    k += a6 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (b3 (x) < -LDBL_EPSILON)\n    k += b3 (x);\n  if (b4 (x) < -LDBL_EPSILON)\n    k += b4 (x);\n  if (b5 (x) < -LDBL_EPSILON)\n    k += b5 (x);\n  if (b6 (x) < -LDBL_EPSILON)\n    k += b6 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c3 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c4 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c5 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c6 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to get the objective function of a 8 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_8 (Optimize * optimize) ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (a3 (x) < -LDBL_EPSILON)\n    k += a3 (x);\n  if (a4 (x) < -LDBL_EPSILON)\n    k += a4 (x);\n  if (a5 (x) < -LDBL_EPSILON)\n    k += a5 (x);\n  if (a6 (x) < -LDBL_EPSILON)\n    k += a6 (x);\n  if (a7 (x) < -LDBL_EPSILON)\n    k += a7 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (b3 (x) < -LDBL_EPSILON)\n    k += b3 (x);\n  if (b4 (x) < -LDBL_EPSILON)\n    k += b4 (x);\n  if (b5 (x) < -LDBL_EPSILON)\n    k += b5 (x);\n  if (b6 (x) < -LDBL_EPSILON)\n    k += b6 (x);\n  if (b7 (x) < -LDBL_EPSILON)\n    k += b7 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c3 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c4 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c5 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c6 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c7 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to get the objective function of a 9 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_9 (Optimize * optimize) ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (a3 (x) < -LDBL_EPSILON)\n    k += a3 (x);\n  if (a4 (x) < -LDBL_EPSILON)\n    k += a4 (x);\n  if (a5 (x) < -LDBL_EPSILON)\n    k += a5 (x);\n  if (a6 (x) < -LDBL_EPSILON)\n    k += a6 (x);\n  if (a7 (x) < -LDBL_EPSILON)\n    k += a7 (x);\n  if (a8 (x) < -LDBL_EPSILON)\n    k += a8 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (b3 (x) < -LDBL_EPSILON)\n    k += b3 (x);\n  if (b4 (x) < -LDBL_EPSILON)\n    k += b4 (x);\n  if (b5 (x) < -LDBL_EPSILON)\n    k += b5 (x);\n  if (b6 (x) < -LDBL_EPSILON)\n    k += b6 (x);\n  if (b7 (x) < -LDBL_EPSILON)\n    k += b7 (x);\n  if (b8 (x) < -LDBL_EPSILON)\n    k += b8 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c3 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c4 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c5 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c6 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c7 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c8 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to get the objective function of a 10 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_10 (Optimize * optimize)        ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (a3 (x) < -LDBL_EPSILON)\n    k += a3 (x);\n  if (a4 (x) < -LDBL_EPSILON)\n    k += a4 (x);\n  if (a5 (x) < -LDBL_EPSILON)\n    k += a5 (x);\n  if (a6 (x) < -LDBL_EPSILON)\n    k += a6 (x);\n  if (a7 (x) < -LDBL_EPSILON)\n    k += a7 (x);\n  if (a8 (x) < -LDBL_EPSILON)\n    k += a8 (x);\n  if (a9 (x) < -LDBL_EPSILON)\n    k += a9 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (b3 (x) < -LDBL_EPSILON)\n    k += b3 (x);\n  if (b4 (x) < -LDBL_EPSILON)\n    k += b4 (x);\n  if (b5 (x) < -LDBL_EPSILON)\n    k += b5 (x);\n  if (b6 (x) < -LDBL_EPSILON)\n    k += b6 (x);\n  if (b7 (x) < -LDBL_EPSILON)\n    k += b7 (x);\n  if (b8 (x) < -LDBL_EPSILON)\n    k += b8 (x);\n  if (b9 (x) < -LDBL_EPSILON)\n    k += b9 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c3 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c4 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c5 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c6 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c7 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c8 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c9 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to get the objective function of a 11 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_11 (Optimize * optimize)        ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (a3 (x) < -LDBL_EPSILON)\n    k += a3 (x);\n  if (a4 (x) < -LDBL_EPSILON)\n    k += a4 (x);\n  if (a5 (x) < -LDBL_EPSILON)\n    k += a5 (x);\n  if (a6 (x) < -LDBL_EPSILON)\n    k += a6 (x);\n  if (a7 (x) < -LDBL_EPSILON)\n    k += a7 (x);\n  if (a8 (x) < -LDBL_EPSILON)\n    k += a8 (x);\n  if (a9 (x) < -LDBL_EPSILON)\n    k += a9 (x);\n  if (a10 (x) < -LDBL_EPSILON)\n    k += a10 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (b3 (x) < -LDBL_EPSILON)\n    k += b3 (x);\n  if (b4 (x) < -LDBL_EPSILON)\n    k += b4 (x);\n  if (b5 (x) < -LDBL_EPSILON)\n    k += b5 (x);\n  if (b6 (x) < -LDBL_EPSILON)\n    k += b6 (x);\n  if (b7 (x) < -LDBL_EPSILON)\n    k += b7 (x);\n  if (b8 (x) < -LDBL_EPSILON)\n    k += b8 (x);\n  if (b9 (x) < -LDBL_EPSILON)\n    k += b9 (x);\n  if (b10 (x) < -LDBL_EPSILON)\n    k += b10 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c3 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c4 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c5 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c6 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c7 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c8 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c9 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c10 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to get the objective function of a 12 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_12 (Optimize * optimize)        ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (a3 (x) < -LDBL_EPSILON)\n    k += a3 (x);\n  if (a4 (x) < -LDBL_EPSILON)\n    k += a4 (x);\n  if (a5 (x) < -LDBL_EPSILON)\n    k += a5 (x);\n  if (a6 (x) < -LDBL_EPSILON)\n    k += a6 (x);\n  if (a7 (x) < -LDBL_EPSILON)\n    k += a7 (x);\n  if (a8 (x) < -LDBL_EPSILON)\n    k += a8 (x);\n  if (a9 (x) < -LDBL_EPSILON)\n    k += a9 (x);\n  if (a10 (x) < -LDBL_EPSILON)\n    k += a10 (x);\n  if (a11 (x) < -LDBL_EPSILON)\n    k += a11 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (b3 (x) < -LDBL_EPSILON)\n    k += b3 (x);\n  if (b4 (x) < -LDBL_EPSILON)\n    k += b4 (x);\n  if (b5 (x) < -LDBL_EPSILON)\n    k += b5 (x);\n  if (b6 (x) < -LDBL_EPSILON)\n    k += b6 (x);\n  if (b7 (x) < -LDBL_EPSILON)\n    k += b7 (x);\n  if (b8 (x) < -LDBL_EPSILON)\n    k += b8 (x);\n  if (b9 (x) < -LDBL_EPSILON)\n    k += b9 (x);\n  if (b10 (x) < -LDBL_EPSILON)\n    k += b10 (x);\n  if (b11 (x) < -LDBL_EPSILON)\n    k += b11 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c3 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c4 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c5 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c6 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c7 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c8 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c9 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c10 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c11 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to get the objective function of a 13 steps mult-steps method.\n * \n * \\return objective function value.\n */\nstatic long double\nsteps_objective_13 (Optimize * optimize)        ///< Optimize struct.\n{\n  register long double *x;\n  register long double k, C;\n  x = optimize->coefficient;\n  k = 0.L;\n  if (a0 (x) < -LDBL_EPSILON)\n    k += a0 (x);\n  if (a1 (x) < -LDBL_EPSILON)\n    k += a1 (x);\n  if (a2 (x) < -LDBL_EPSILON)\n    k += a2 (x);\n  if (a3 (x) < -LDBL_EPSILON)\n    k += a3 (x);\n  if (a4 (x) < -LDBL_EPSILON)\n    k += a4 (x);\n  if (a5 (x) < -LDBL_EPSILON)\n    k += a5 (x);\n  if (a6 (x) < -LDBL_EPSILON)\n    k += a6 (x);\n  if (a7 (x) < -LDBL_EPSILON)\n    k += a7 (x);\n  if (a8 (x) < -LDBL_EPSILON)\n    k += a8 (x);\n  if (a9 (x) < -LDBL_EPSILON)\n    k += a9 (x);\n  if (a10 (x) < -LDBL_EPSILON)\n    k += a10 (x);\n  if (a11 (x) < -LDBL_EPSILON)\n    k += a11 (x);\n  if (a12 (x) < -LDBL_EPSILON)\n    k += a12 (x);\n  if (k < -LDBL_EPSILON)\n    return 30.L - k;\n  k = 0.L;\n  if (b0 (x) < -LDBL_EPSILON)\n    k += b0 (x);\n  if (b1 (x) < -LDBL_EPSILON)\n    k += b1 (x);\n  if (b2 (x) < -LDBL_EPSILON)\n    k += b2 (x);\n  if (b3 (x) < -LDBL_EPSILON)\n    k += b3 (x);\n  if (b4 (x) < -LDBL_EPSILON)\n    k += b4 (x);\n  if (b5 (x) < -LDBL_EPSILON)\n    k += b5 (x);\n  if (b6 (x) < -LDBL_EPSILON)\n    k += b6 (x);\n  if (b7 (x) < -LDBL_EPSILON)\n    k += b7 (x);\n  if (b8 (x) < -LDBL_EPSILON)\n    k += b8 (x);\n  if (b9 (x) < -LDBL_EPSILON)\n    k += b9 (x);\n  if (b10 (x) < -LDBL_EPSILON)\n    k += b10 (x);\n  if (b11 (x) < -LDBL_EPSILON)\n    k += b11 (x);\n  if (b12 (x) < -LDBL_EPSILON)\n    k += b12 (x);\n  if (k < -LDBL_EPSILON)\n    return 20.L - k;\n  k = 0.L;\n  C = c0 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c1 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c2 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c3 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c4 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c5 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c6 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c7 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c8 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c9 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c10 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c11 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  C = c12 (x);\n  if (C < -LDBL_EPSILON)\n    return 20.L;\n  if (!isnan (C))\n    k = fmaxl (k, C);\n  if (k == 0.L || k > 20.L)\n    return 20.L;\n  return k;\n}\n\n/**\n * Function to select the multi-steps method.\n *\n * \\return 1 on success, 0 on error.\n */\nstatic inline int\nsteps_select (Optimize * optimize,      ///< Optimize struct.\n              unsigned int nsteps,      ///< number of steps.\n              unsigned int order)       ///< order of accuracy.\n{\n  static long double (*objective[14]) (Optimize *) =\n  {\n  NULL,\n      NULL,\n      NULL,\n      &steps_objective_3,\n      &steps_objective_4,\n      &steps_objective_5,\n      &steps_objective_6,\n      &steps_objective_7,\n      &steps_objective_8,\n      &steps_objective_9,\n      &steps_objective_10,\n      &steps_objective_11, &steps_objective_12, &steps_objective_13};\n  static int (*method[14][9]) (Optimize *) =\n  {\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &steps_3_2, &steps_3_3, NULL, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &steps_4_2, &steps_4_3, &steps_4_4, NULL, NULL, NULL, NULL},\n    {\n    NULL, NULL, &steps_5_2, &steps_5_3, &steps_5_4, &steps_5_5, NULL, NULL,\n        NULL},\n    {\n    NULL, NULL, &steps_6_2, &steps_6_3, &steps_6_4, &steps_6_5, &steps_6_6,\n        NULL, NULL},\n    {\n    NULL, NULL, &steps_7_2, &steps_7_3, &steps_7_4, &steps_7_5, &steps_7_6,\n        &steps_7_7, NULL},\n    {\n    NULL, NULL, &steps_8_2, &steps_8_3, &steps_8_4, &steps_8_5, &steps_8_6,\n        &steps_8_7, &steps_8_8},\n    {\n    NULL, NULL, &steps_9_2, &steps_9_3, &steps_9_4, &steps_9_5, &steps_9_6,\n        &steps_9_7, &steps_9_8},\n    {\n    NULL, NULL, &steps_10_2, &steps_10_3, &steps_10_4, &steps_10_5,\n        &steps_10_6, &steps_10_7, &steps_10_8},\n    {\n    NULL, NULL, &steps_11_2, &steps_11_3, &steps_11_4, &steps_11_5,\n        &steps_11_6, &steps_11_7, &steps_11_8},\n    {\n    NULL, NULL, &steps_12_2, &steps_12_3, &steps_12_4, &steps_12_5,\n        &steps_12_6, &steps_12_7, &steps_12_8},\n    {\n    NULL, NULL, &steps_13_2, &steps_13_3, &steps_13_4, &steps_13_5,\n        &steps_13_6, &steps_13_7, &steps_13_8}\n  };\n#if DEBUG_STEPS\n  fprintf (stderr, \"steps_run: start\\n\");\n#endif\n  if (nsteps < 3 || nsteps > 14 || order < 2 || order > 8)\n    goto exit_on_error;\n  optimize->nsteps = nsteps;\n  optimize->order = order;\n  optimize->size = 2 * nsteps;\n  optimize->nfree = optimize->size - order - 1;\n  optimize->minimum0\n    = (long double *) g_slice_alloc (optimize->nfree * sizeof (long double));\n  optimize->interval0\n    = (long double *) g_slice_alloc (optimize->nfree * sizeof (long double));\n  optimize->random_type\n    = (unsigned int *) g_slice_alloc (optimize->nfree * sizeof (unsigned int));\n  optimize->data = NULL;\n  optimize->objective = objective[nsteps];\n  optimize->method = method[nsteps][order];\n  if (!optimize->method)\n    goto exit_on_error;\n#if DEBUG_STEPS\n  fprintf (stderr, \"steps_select: end\\n\");\n#endif\n  return 1;\n\nexit_on_error:\n  error_message = g_strdup (_(\"Unknown method\"));\n#if DEBUG_STEPS\n  fprintf (stderr, \"steps_select: end\\n\");\n#endif\n  return 0;\n}\n\n/**\n * Function to read the multi-steps method data on a XML node.\n *\n * \\return 1 on success, 0 on error.\n */\nint\nsteps_run (xmlNode * node,      ///< XML node.\n           gsl_rng ** rng)      ///< array of gsl_rng structs.\n{\n  Optimize s[nthreads];\n  char filename[64];\n  gchar *buffer;\n  FILE *file;\n  long double *value_optimal;\n  long double optimal;\n  int code;\n  unsigned int i, j, nsteps, order, nfree;\n\n#if DEBUG_STEPS\n  fprintf (stderr, \"steps_run: start\\n\");\n#endif\n\n  nsteps = xml_node_get_uint (node, XML_STEPS, &code);\n  if (code)\n    {\n      error_message = g_strdup (_(\"Bad steps number\"));\n      goto exit_on_error;\n    }\n  order = xml_node_get_uint (node, XML_ORDER, &code);\n  if (code)\n    {\n      error_message = g_strdup (_(\"Bad order\"));\n      goto exit_on_error;\n    }\n  if (!steps_select (s, nsteps, order))\n    goto exit_on_error;\n  if (!optimize_read (s, node))\n    goto exit_on_error;\n  nfree = s->nfree;\n  value_optimal = (long double *) g_slice_alloc (nfree * sizeof (long double));\n  optimize_create (s, &optimal, value_optimal);\n  node = node->children;\n  for (i = 0; i < nfree; ++i, node = node->next)\n    if (!read_variable (node, s->minimum0, s->interval0, s->random_type, i))\n      goto exit_on_error;\n  for (i = 1; i < nthreads; ++i)\n    memcpy (s + i, s, sizeof (Optimize));\n  j = rank * nthreads;\n  for (i = 0; i < nthreads; ++i)\n    optimize_init (s + i, rng[j + i], i);\n\n  // Method bucle\n  printf (\"Optimize bucle\\n\");\n  optimize_bucle (s);\n\n  // Print the optimal coefficients\n  printf (\"Print the optimal coefficients\\n\");\n  memcpy (s->random_data, s->value_optimal, nfree * sizeof (long double));\n  code = s->method (s);\n  snprintf (filename, 64, \"steps-%u-%u.mc\", nsteps, order);\n  file = fopen (filename, \"w\");\n  print_maxima_precision (file);\n  steps_print (s, file);\n  steps_print_maxima (file, nsteps, order);\n  fclose (file);\n  snprintf (filename, 64, \"sed -i 's/e+/b+/g' steps-%u-%u.mc\", nsteps, order);\n  code = system (filename);\n  snprintf (filename, 64, \"sed -i 's/e-/b-/g' steps-%u-%u.mc\", nsteps, order);\n  code = system (filename);\n\n  // Free memory\n  g_slice_free1 (nfree * sizeof (unsigned int), s->random_type);\n  g_slice_free1 (nfree * sizeof (long double), s->interval0);\n  g_slice_free1 (nfree * sizeof (long double), s->minimum0);\n  for (i = 0; i < nthreads; ++i)\n    optimize_delete (s + i);\n  g_slice_free1 (nfree * sizeof (long double), value_optimal);\n\n#if DEBUG_STEPS\n  fprintf (stderr, \"steps_run: end\\n\");\n#endif\n  return 1;\n\nexit_on_error:\n  buffer = error_message;\n  error_message = g_strconcat (\"Multi-steps:\\n\", buffer, NULL);\n  g_free (buffer);\n#if DEBUG_STEPS\n  fprintf (stderr, \"steps_run: end\\n\");\n#endif\n  return 0;\n}\n", "meta": {"hexsha": "fb8f88850df833dd440cb98e89802e6e1abd5330", "size": 162152, "ext": "c", "lang": "C", "max_stars_repo_path": "steps.c", "max_stars_repo_name": "jburguete/ode", "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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": "steps.c", "max_issues_repo_name": "jburguete/ode", "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "steps.c", "max_forks_repo_name": "jburguete/ode", "max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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.0782683983, "max_line_length": 80, "alphanum_fraction": 0.4330998076, "num_tokens": 85677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3511709017424895}}
{"text": "/* rng/ranlxd.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough\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 (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n */\n\n#include <config.h>\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n\n/* This is an implementation of Martin Luescher's second generation\n   double-precision (48-bit) version of the RANLUX generator. \n\n   Thanks to Martin Luescher for providing information on this\n   generator.\n\n*/\n\nstatic inline unsigned long int ranlxd_get (void *vstate);\nstatic double ranlxd_get_double (void *vstate);\nstatic void ranlxd_set_lux (void *state, unsigned long int s, unsigned int luxury);\nstatic void ranlxd1_set (void *state, unsigned long int s);\nstatic void ranlxd2_set (void *state, unsigned long int s);\n\nstatic const int next[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0};\n\nstatic const double one_bit = 1.0 / 281474976710656.0;\t/* 1/2^48 */\n\n#define RANLUX_STEP(x1,x2,i1,i2,i3)      \\\n          x1=xdbl[i1] - xdbl[i2];        \\\n          if (x2 < 0)                    \\\n          {                              \\\n            x1-=one_bit;                 \\\n            x2+=1;                       \\\n          }                              \\\n         xdbl[i3]=x2\n\ntypedef struct\n  {\n    double xdbl[12]; \n    double carry;\n    unsigned int ir;\n    unsigned int jr;\n    unsigned int ir_old;\n    unsigned int pr;\n  }\nranlxd_state_t;\n\nstatic inline void increment_state (ranlxd_state_t * state);\n\nstatic inline void\nincrement_state (ranlxd_state_t * state)\n{\n  int k, kmax;\n  double y1, y2, y3;\n\n  double *xdbl = state->xdbl;\n  double carry = state->carry;\n  unsigned int ir = state->ir;\n  unsigned int jr = state->jr;\n\n  for (k = 0; ir > 0; ++k)\n    {\n      y1 = xdbl[jr] - xdbl[ir];\n      y2 = y1 - carry;\n      if (y2 < 0)\n\t{\n\t  carry = one_bit;\n\t  y2 += 1;\n\t}\n      else\n\t{\n\t  carry = 0;\n\t}\n      xdbl[ir] = y2;\n      ir = next[ir];\n      jr = next[jr];\n    }\n\n  kmax = state->pr - 12;\n\n  for (; k <= kmax; k += 12)\n    {\n      y1 = xdbl[7] - xdbl[0];\n      y1 -= carry;\n\n      RANLUX_STEP (y2, y1, 8, 1, 0);\n      RANLUX_STEP (y3, y2, 9, 2, 1);\n      RANLUX_STEP (y1, y3, 10, 3, 2);\n      RANLUX_STEP (y2, y1, 11, 4, 3);\n      RANLUX_STEP (y3, y2, 0, 5, 4);\n      RANLUX_STEP (y1, y3, 1, 6, 5);\n      RANLUX_STEP (y2, y1, 2, 7, 6);\n      RANLUX_STEP (y3, y2, 3, 8, 7);\n      RANLUX_STEP (y1, y3, 4, 9, 8);\n      RANLUX_STEP (y2, y1, 5, 10, 9);\n      RANLUX_STEP (y3, y2, 6, 11, 10);\n\n      if (y3 < 0)\n\t{\n\t  carry = one_bit;\n\t  y3 += 1;\n\t}\n      else\n\t{\n\t  carry = 0;\n\t}\n      xdbl[11] = y3;\n    }\n\n  kmax = state->pr;\n\n  for (; k < kmax; ++k)\n    {\n      y1 = xdbl[jr] - xdbl[ir];\n      y2 = y1 - carry;\n      if (y2 < 0)\n\t{\n\t  carry = one_bit;\n\t  y2 += 1;\n\t}\n      else\n\t{\n\t  carry = 0;\n\t}\n      xdbl[ir] = y2;\n      ir = next[ir];\n      jr = next[jr];\n    }\n  state->ir = ir;\n  state->ir_old = ir;\n  state->jr = jr;\n  state->carry = carry;\n}\n\nstatic inline unsigned long int\nranlxd_get (void *vstate)\n{\n  return ranlxd_get_double (vstate) * 4294967296.0;\t/* 2^32 */\n}\n\nstatic double\nranlxd_get_double (void *vstate)\n{\n  ranlxd_state_t *state = (ranlxd_state_t *) vstate;\n\n  int ir = state->ir;\n\n  state->ir = next[ir];\n\n  if (state->ir == state->ir_old)\n    increment_state (state);\n\n  return state->xdbl[state->ir];\n}\n\nstatic void\nranlxd_set_lux (void *vstate, unsigned long int s, unsigned int luxury)\n{\n  ranlxd_state_t *state = (ranlxd_state_t *) vstate;\n\n  int ibit, jbit, i, k, l, xbit[31];\n  double x, y;\n\n  long int seed;\n\n  if (s == 0)\n    s = 1;\t\t\t/* default seed is 1 */\n\n  seed = s;\n\n  i = seed & 0xFFFFFFFFUL;\n\n  for (k = 0; k < 31; ++k)\n    {\n      xbit[k] = i % 2;\n      i /= 2;\n    }\n\n  ibit = 0;\n  jbit = 18;\n\n  for (k = 0; k < 12; ++k)\n    {\n      x = 0;\n\n      for (l = 1; l <= 48; ++l)\n\t{\n\t  y = (double) ((xbit[ibit] + 1) % 2);\n\t  x += x + y;\n\t  xbit[ibit] = (xbit[ibit] + xbit[jbit]) % 2;\n\t  ibit = (ibit + 1) % 31;\n\t  jbit = (jbit + 1) % 31;\n\t}\n      state->xdbl[k] = one_bit * x;\n    }\n\n  state->carry = 0;\n  state->ir = 11;\n  state->jr = 7;\n  state->ir_old = 0;\n  state->pr = luxury;\n}\n\nstatic void\nranlxd1_set (void *vstate, unsigned long int s)\n{\n  ranlxd_set_lux (vstate, s, 202);\n}\n\nstatic void\nranlxd2_set (void *vstate, unsigned long int s)\n{\n  ranlxd_set_lux (vstate, s, 397);\n}\n\nstatic const gsl_rng_type ranlxd1_type =\n{\"ranlxd1\",\t\t\t/* name */\n 0xffffffffUL,\t\t\t/* RAND_MAX */\n 0,\t\t\t\t/* RAND_MIN */\n sizeof (ranlxd_state_t),\n &ranlxd1_set,\n &ranlxd_get,\n &ranlxd_get_double};\n\nstatic const gsl_rng_type ranlxd2_type =\n{\"ranlxd2\",\t\t\t/* name */\n 0xffffffffUL,\t\t\t/* RAND_MAX */\n 0,\t\t\t\t/* RAND_MIN */\n sizeof (ranlxd_state_t),\n &ranlxd2_set,\n &ranlxd_get,\n &ranlxd_get_double};\n\nconst gsl_rng_type *gsl_rng_ranlxd1 = &ranlxd1_type;\nconst gsl_rng_type *gsl_rng_ranlxd2 = &ranlxd2_type;\n", "meta": {"hexsha": "233ca31a4d9b757ef62d5237b4881da8dbb9c208", "size": 5409, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/ranlxd.c", "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "code/em/treba/gsl-1.0/rng/ranlxd.c", "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_licenses": ["Apache-2.0"], "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/em/treba/gsl-1.0/rng/ranlxd.c", "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "avg_line_length": 21.636, "max_line_length": 83, "alphanum_fraction": 0.5786651877, "num_tokens": 1953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.35101172611546494}}
{"text": "#include <cblas.h>\n#ifdef LAPACKE_FOLDER\n#include <lapacke/lapacke.h>\n#else\n#include <lapacke.h>\n#endif\n\n#include \"math.h\"\n#include \"minimal_opencv.h\"\n#include \"stdbool.h\"\n#include \"stdio.h\"\n#include \"string.h\"\n\n#include <limits.h>\n#include <stdarg.h>\n\n#include \"linmath.h\"\n\n#ifdef _WIN32\n#define SURVIVE_LOCAL_ONLY\n#include <malloc.h>\n#define alloca _alloca\n#else\n#define SURVIVE_LOCAL_ONLY __attribute__((visibility(\"hidden\")))\n#endif\n\nSURVIVE_LOCAL_ONLY int cvRound(float f) { return roundf(f); }\n#define CV_Error(code, msg) assert(0 && msg); // cv::error( code, msg, CV_Func, __FILE__, __LINE__ )\n\nconst int DECOMP_SVD = 1;\nconst int DECOMP_LU = 2;\n\nvoid print_mat(const CvMat *M);\n\nstatic size_t mat_size_bytes(const CvMat *mat) { return (size_t)CV_ELEM_SIZE(mat->type) * mat->cols * mat->rows; }\n\nSURVIVE_LOCAL_ONLY void cvCopy(const CvMat *srcarr, CvMat *dstarr, const CvMat *mask) {\n\tassert(mask == 0 && \"This isn't implemented yet\");\n\tassert(srcarr->rows == dstarr->rows);\n\tassert(srcarr->cols == dstarr->cols);\n\tassert(dstarr->type == srcarr->type);\n\tmemcpy(CV_RAW_PTR(dstarr), CV_RAW_PTR(srcarr), mat_size_bytes(srcarr));\n}\n\n#ifdef USE_FLOAT\n#define cblas_gemm cblas_sgemm\n#define cblas_symm cblas_ssymm\n#define LAPACKE_getrs LAPACKE_sgetrs\n#define LAPACKE_getrf LAPACKE_sgetrf\n#define LAPACKE_getri LAPACKE_sgetri\n#define LAPACKE_gelss LAPACKE_sgelss\n#define LAPACKE_gesvd LAPACKE_sgesvd\n#else\n#define cblas_gemm cblas_dgemm\n#define cblas_symm cblas_dsymm\n#define LAPACKE_getrs LAPACKE_dgetrs\n#define LAPACKE_getrf LAPACKE_dgetrf\n#define LAPACKE_getri LAPACKE_dgetri\n#define LAPACKE_gelss LAPACKE_dgelss\n#define LAPACKE_gesvd LAPACKE_dgesvd\n#endif\n\n// dst = alpha * src1 * src2 + beta * src3 or dst = alpha * src2 * src1 + beta * src3 where src1 is symm\nSURVIVE_LOCAL_ONLY void cvSYMM(const CvMat *src1, const CvMat *src2, double alpha, const CvMat *src3, double beta,\n\t\t\t\t\t\t\t   CvMat *dst, bool src1First) {\n\n\tint rows1 = src1->rows;\n\tint cols1 = src1->cols;\n\n\tint rows2 = src2->rows;\n\tint cols2 = src2->cols;\n\n\tif (src3) {\n\t\tint rows3 = src3->rows;\n\t\tint cols3 = src3->cols;\n\t\tassert(rows3 == dst->rows);\n\t\tassert(cols3 == dst->cols);\n\t}\n\n\t// assert(src3 == 0 || beta != 0);\n\tassert(cols1 == rows2);\n\tassert(rows1 == dst->rows);\n\tassert(cols2 == dst->cols);\n\n\tlapack_int lda = src1->cols;\n\tlapack_int ldb = src2->cols;\n\n\tif (src3)\n\t\tcvCopy(src3, dst, 0);\n\telse\n\t\tbeta = 0;\n\n\tassert(CV_RAW_PTR(dst) != CV_RAW_PTR(src1));\n\tassert(CV_RAW_PTR(dst) != CV_RAW_PTR(src2));\n\t/*\n\t\tvoid cblas_dsymm(OPENBLAS_CONST enum CBLAS_ORDER Order,\n\t\t\t\t\t\t OPENBLAS_CONST enum CBLAS_SIDE Side,\n\t\t\t\t\t\t OPENBLAS_CONST enum CBLAS_UPLO Uplo,\n\t\t\t\t\t\t OPENBLAS_CONST blasint M,\n\t\t\t\t\t\t OPENBLAS_CONST blasint N,\n\t\t\t\t\t\t OPENBLAS_CONST double alpha,\n\t\t\t\t\t\t OPENBLAS_CONST double *A,\n\t\t\t\t\t\t OPENBLAS_CONST blasint lda,\n\t\t\t\t\t\t OPENBLAS_CONST double *B,\n\t\t\t\t\t\t OPENBLAS_CONST blasint ldb,\n\t\t\t\t\t\t OPENBLAS_CONST double beta,\n\t\t\t\t\t\t double *C,\n\t\t\t\t\t\t OPENBLAS_CONST blasint ldc);\n\t*/\n\tcblas_symm(CblasRowMajor, src1First ? CblasLeft : CblasRight, CblasUpper, dst->rows, dst->cols, alpha,\n\t\t\t   CV_RAW_PTR(src1), lda, CV_RAW_PTR(src2), ldb, beta, CV_RAW_PTR(dst), dst->cols);\n}\n\n// Special case dst = alpha * src2 * src1 * src2' + beta * src3\nvoid mulBABt(const CvMat *src1, const CvMat *src2, double alpha, const CvMat *src3, double beta, CvMat *dst) {\n\tsize_t dims = src2->rows;\n\tassert(src2->cols == src2->rows);\n\tCREATE_STACK_MAT(tmp, dims, dims);\n\n\t// This has been profiled; and weirdly enough the SYMM version is slower for a 19x19 matrix. Guessing access order\n\t// or some other cache thing matters more than the additional 2x multiplications.\n//#define USE_SYM\n#ifdef USE_SYM\n\tcvSYMM(src1, src2, 1, 0, 0, &tmp, false);\n\tcvGEMM(&tmp, src2, alpha, src3, beta, dst, CV_GEMM_B_T);\n#else\n\tcvGEMM(src1, src2, 1, 0, 0, &tmp, CV_GEMM_B_T);\n\tcvGEMM(src2, &tmp, alpha, src3, beta, dst, 0);\n#endif\n}\n// dst = alpha * src1 * src2 + beta * src3\nSURVIVE_LOCAL_ONLY void cvGEMM(const CvMat *src1, const CvMat *src2, double alpha, const CvMat *src3, double beta,\n\t\t\t\t\t\t\t   CvMat *dst, int tABC) {\n\n\tint rows1 = (tABC & CV_GEMM_A_T) ? src1->cols : src1->rows;\n\tint cols1 = (tABC & CV_GEMM_A_T) ? src1->rows : src1->cols;\n\n\tint rows2 = (tABC & CV_GEMM_B_T) ? src2->cols : src2->rows;\n\tint cols2 = (tABC & CV_GEMM_B_T) ? src2->rows : src2->cols;\n\n\tif (src3) {\n\t\tint rows3 = (tABC & CV_GEMM_C_T) ? src3->cols : src3->rows;\n\t\tint cols3 = (tABC & CV_GEMM_C_T) ? src3->rows : src3->cols;\n\t\tassert(rows3 == dst->rows);\n\t\tassert(cols3 == dst->cols);\n\t}\n\n\t// assert(src3 == 0 || beta != 0);\n\tassert(cols1 == rows2);\n    assert(rows1 == dst->rows);\n    assert(cols2 == dst->cols);\n\n\tlapack_int lda = src1->cols;\n\tlapack_int ldb = src2->cols;\n\t\n\tif (src3)\n\t\tcvCopy(src3, dst, 0);\n\telse\n\t\tbeta = 0;\n\n\tassert(CV_RAW_PTR(dst) != CV_RAW_PTR(src1));\n\tassert(CV_RAW_PTR(dst) != CV_RAW_PTR(src2));\n\n\tcblas_gemm(CblasRowMajor, (tABC & CV_GEMM_A_T) ? CblasTrans : CblasNoTrans,\n\t\t\t   (tABC & CV_GEMM_B_T) ? CblasTrans : CblasNoTrans, dst->rows, dst->cols, cols1, alpha, CV_RAW_PTR(src1),\n\t\t\t   lda, CV_RAW_PTR(src2), ldb, beta, CV_RAW_PTR(dst), dst->cols);\n}\n\n// dst = scale * src ^ t * src     iff order == 1\n// dst = scale *     src * src ^ t iff order == 0\nSURVIVE_LOCAL_ONLY void cvMulTransposed(const CvMat *src, CvMat *dst, int order, const CvMat *delta, double scale) {\n\tlapack_int rows = src->rows;\n\tlapack_int cols = src->cols;\n\n\tlapack_int drows = order == 0 ? dst->rows : dst->cols;\n\tassert(drows == dst->cols);\n\tassert(order == 1 ? (dst->cols == src->cols) : (dst->cols == src->rows));\n\tassert(delta == 0 && \"This isn't implemented yet\");\n\tdouble beta = 0;\n\n\tbool isAT = order == 1;\n\tbool isBT = !isAT;\n\n\tlapack_int dstCols = dst->cols;\n\n\tcblas_gemm(CblasRowMajor, isAT ? CblasTrans : CblasNoTrans, isBT ? CblasTrans : CblasNoTrans, dst->rows, dst->cols,\n\t\t\t   order == 1 ? src->rows : src->cols, scale, CV_RAW_PTR(src), src->cols, CV_RAW_PTR(src), src->cols, beta,\n\t\t\t   CV_RAW_PTR(dst), dstCols);\n}\n\nSURVIVE_LOCAL_ONLY void *cvAlloc(size_t size) { return malloc(size); }\n\nstatic void icvCheckHuge(CvMat *arr) {\n\tif ((int64_t)arr->step * arr->rows > INT_MAX)\n\t\tarr->type &= ~CV_MAT_CONT_FLAG;\n}\n\nstatic CvMat *cvInitMatHeader(CvMat *arr, int rows, int cols, int type) {\n\ttype = CV_MAT_TYPE(type);\n\n\tassert(!(rows < 0 || cols < 0));\n\n\tint min_step = CV_ELEM_SIZE(type);\n\tassert(!(min_step <= 0));\n\tmin_step *= cols;\n\n\tarr->step = min_step;\n\tarr->type = CV_MAT_MAGIC_VAL | type | CV_MAT_CONT_FLAG;\n\tarr->rows = rows;\n\tarr->cols = cols;\n\tarr->data.ptr = 0;\n\tarr->refcount = 0;\n\tarr->hdr_refcount = 1;\n\n\ticvCheckHuge(arr);\n\treturn arr;\n}\n\nSURVIVE_LOCAL_ONLY CvMat *cvCreateMatHeader(int rows, int cols, int type) {\n\treturn cvInitMatHeader((CvMat *)cvAlloc(sizeof(CvMat)), rows, cols, type);\n}\n\n/* the alignment of all the allocated buffers */\n#define CV_MALLOC_ALIGN 16\n\n/* IEEE754 constants and macros */\n#define CV_TOGGLE_FLT(x) ((x) ^ ((int)(x) < 0 ? 0x7fffffff : 0))\n#define CV_TOGGLE_DBL(x) ((x) ^ ((int64)(x) < 0 ? CV_BIG_INT(0x7fffffffffffffff) : 0))\n\n#define CV_DbgAssert assert\n\nstatic inline void *cvAlignPtr(const void *ptr, int align) {\n\tCV_DbgAssert((align & (align - 1)) == 0);\n\treturn (void *)(((size_t)ptr + align - 1) & ~(size_t)(align - 1));\n}\n\nSURVIVE_LOCAL_ONLY void cvCreateData(CvMat *arr) {\n\tif (CV_IS_MAT_HDR_Z(arr)) {\n\t\tsize_t step, total_size;\n\t\tCvMat *mat = (CvMat *)arr;\n\t\tstep = mat->step;\n\n\t\tif (mat->rows == 0 || mat->cols == 0)\n\t\t\treturn;\n\n\t\tif (mat->data.ptr != 0)\n\t\t\tCV_Error(CV_StsError, \"Data is already allocated\");\n\n\t\tif (step == 0)\n\t\t\tstep = CV_ELEM_SIZE(mat->type) * mat->cols;\n\n\t\tint64_t _total_size = (int64_t)step * mat->rows + sizeof(int) + CV_MALLOC_ALIGN;\n\t\ttotal_size = (size_t)_total_size;\n\t\tif (_total_size != (int64_t)total_size)\n\t\t\tCV_Error(CV_StsNoMem, \"Too big buffer is allocated\");\n\t\tmat->refcount = (int *)cvAlloc((size_t)total_size);\n\t\tmat->data.ptr = (uchar *)cvAlignPtr(mat->refcount + 1, CV_MALLOC_ALIGN);\n\t\t*mat->refcount = 1;\n\t} else if (CV_IS_MATND_HDR(arr)) {\n\t\tassert(\"There is no support for ND types\");\n\t} else\n\t\tCV_Error(CV_StsBadArg, \"unrecognized or unsupported array type\");\n}\n\n#define CV_CREATE_MAT_HEADER_ALLOCA(stack_mat, rows, cols, type)                                                       \\\n\tCvMat *stack_mat = cvInitMatHeader(alloca(sizeof(CvMat)), rows, cols, type);\n\n#define CV_CREATE_MAT_ALLOCA(stack_mat, height, width, type)                                                           \\\n\tCV_CREATE_MAT_HEADER_ALLOCA(stack_mat, height, width, type);                                                       \\\n\tstack_mat->data.ptr = alloca(mat_size_bytes(stack_mat));\n\nSURVIVE_LOCAL_ONLY CvMat *cvCreateMat(int height, int width, int type) {\n\tCvMat *arr = cvCreateMatHeader(height, width, type);\n\tcvCreateData(arr);\n\n\treturn arr;\n}\n\n#define CREATE_CV_STACK_MAT(name, rows, cols, type)\t\t\\\n  FLT *_##name = alloca(rows * cols * sizeof(FLT));\t\t\\\n  CvMat name = cvMat(rows, cols, SURVIVE_CV_F, _##name);\n\nSURVIVE_LOCAL_ONLY double cvInvert(const CvMat *srcarr, CvMat *dstarr, int method) {\n\tlapack_int inf;\n\tlapack_int rows = srcarr->rows;\n\tlapack_int cols = srcarr->cols;\n\tlapack_int lda = srcarr->cols;\n\n\tcvCopy(srcarr, dstarr, 0);\n\tFLT *a = CV_RAW_PTR(dstarr);\n\n#ifdef DEBUG_PRINT\n\tprintf(\"a: \\n\");\n\tprint_mat(srcarr);\n#endif\n\tif (method == DECOMP_LU) {\n\t\tlapack_int *ipiv = alloca(sizeof(lapack_int) * MIN(srcarr->rows, srcarr->cols));\n\t\tinf = LAPACKE_getrf(LAPACK_ROW_MAJOR, rows, cols, a, lda, ipiv);\n\t\tassert(inf == 0);\n\n\t\tinf = LAPACKE_getri(LAPACK_ROW_MAJOR, rows, a, lda, ipiv);\n\t\tassert(inf >= 0);\n\t\tif (inf > 0) {\n\t\t\tprintf(\"Warning: Singular matrix: \\n\");\n\t\t\t// print_mat(srcarr);\n\t\t}\n\n\t\t//free(ipiv);\n\n\t} else if (method == DECOMP_SVD) {\n\t\t// TODO: There is no way this needs this many allocations,\n\t\t// but in my defense I was very tired when I wrote this code\n\t  CREATE_CV_STACK_MAT(w, 1, MIN(dstarr->rows, dstarr->cols), dstarr->type);\n\t  CREATE_CV_STACK_MAT(u, dstarr->cols, dstarr->cols, dstarr->type);\n\t  CREATE_CV_STACK_MAT(v, dstarr->rows, dstarr->rows, dstarr->type);\n\t  CREATE_CV_STACK_MAT(um, w.cols, w.cols, w.type);\n\n\t\tcvSVD(dstarr, &w, &u, &v, 0);\n\n\t\tcvSetZero(&um);\n\t\tfor (int i = 0; i < w.cols; i++) {\n\t\t\tcvmSet(&um, i, i, 1. / (_w)[i]);\n\t\t}\n\n\t\tCvMat *tmp = cvCreateMat(dstarr->cols, dstarr->rows, dstarr->type);\n\t\tcvGEMM(&v, &um, 1, 0, 0, tmp, CV_GEMM_A_T);\n\t\tcvGEMM(tmp, &u, 1, 0, 0, dstarr, CV_GEMM_B_T);\n\n\t\tcvReleaseMat(&tmp);\n\t} else {\n\t\tassert(0 && \"Bad argument\");\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\n#define CV_CLONE_MAT_ALLOCA(stack_mat, mat)                                                                            \\\n\tCV_CREATE_MAT_ALLOCA(stack_mat, mat->rows, mat->cols, mat->type)                                                   \\\n\tcvCopy(mat, stack_mat, 0);\n\nSURVIVE_LOCAL_ONLY CvMat *cvCloneMat(const CvMat *mat) {\n\tCvMat *rtn = cvCreateMat(mat->rows, mat->cols, mat->type);\n\tcvCopy(mat, rtn, 0);\n\treturn rtn;\n}\n\nSURVIVE_LOCAL_ONLY int cvSolve(const CvMat *Aarr, const CvMat *xarr, CvMat *Barr, int method) {\n\tlapack_int inf;\n\tlapack_int arows = Aarr->rows;\n\tlapack_int acols = Aarr->cols;\n\tlapack_int xcols = xarr->cols;\n\tlapack_int xrows = xarr->rows;\n\tlapack_int lda = acols; // Aarr->step / sizeof(double);\n\tlapack_int type = CV_MAT_TYPE(Aarr->type);\n\n\tif (method == DECOMP_LU) {\n\t\tassert(Aarr->cols == Barr->rows);\n\t\tassert(xarr->rows == Aarr->rows);\n\t\tassert(Barr->cols == xarr->cols);\n\t\tassert(type == CV_MAT_TYPE(Barr->type) && (type == CV_32F || type == CV_64F));\n\n\t\tcvCopy(xarr, Barr, 0);\n\t\tFLT *a_ws = alloca(mat_size_bytes(Aarr));\n\t\tmemcpy(a_ws, CV_RAW_PTR(Aarr), mat_size_bytes(Aarr));\n\n\t\tlapack_int brows = Barr->rows;\n\t\tlapack_int bcols = Barr->cols;\n\t\tlapack_int ldb = bcols; // Barr->step / sizeof(double);\n\n\t\tlapack_int *ipiv = alloca(sizeof(lapack_int) * MIN(Aarr->rows, Aarr->cols));\n\n\t\tinf = LAPACKE_getrf(LAPACK_ROW_MAJOR, arows, acols, (a_ws), lda, ipiv);\n\t\tassert(inf >= 0);\n\t\tif (inf > 0) {\n\t\t\tprintf(\"Warning: Singular matrix: \\n\");\n\t\t\t// print_mat(a_ws);\n\t\t}\n\n#ifdef DEBUG_PRINT\n\t\tprintf(\"Solve A * x = B:\\n\");\n\t\t// print_mat(a_ws);\n\t\tprint_mat(Barr);\n#endif\n\n\t\tinf = LAPACKE_getrs(LAPACK_ROW_MAJOR, CblasNoTrans, arows, bcols, (a_ws), lda, ipiv, CV_RAW_PTR(Barr), ldb);\n\t\tassert(inf == 0);\n\n\t\t//free(ipiv);\n\t\t// cvReleaseMat(&a_ws);\n\t} else if (method == DECOMP_SVD) {\n\n#ifdef DEBUG_PRINT\n\t\tprintf(\"Solve |b - A * x|:\\n\");\n\t\tprint_mat(Aarr);\n\t\tprint_mat(xarr);\n#endif\n\t\tbool xLargerThanB = xarr->rows > acols;\n\t\tCvMat *xCpy = 0;\n\t\tif (xLargerThanB) {\n\t\t\tCV_CLONE_MAT_ALLOCA(xCpyStack, xarr);\n\t\t\txCpy = xCpyStack;\n\t\t} else {\n\t\t\txCpy = Barr;\n\t\t\tmemcpy(CV_RAW_PTR(Barr), CV_RAW_PTR(xarr), mat_size_bytes(xarr));\n\t\t}\n\n\t\t// CvMat *aCpy = cvCloneMat(Aarr);\n\t\tFLT *aCpy = alloca(mat_size_bytes(Aarr));\n\t\tmemcpy(aCpy, CV_RAW_PTR(Aarr), mat_size_bytes(Aarr));\n\n\t\tFLT *S = alloca(sizeof(FLT) * MIN(arows, acols));\n\t\t// FLT *S = malloc(sizeof(FLT) * MIN(arows, acols));\n\t\tFLT rcond = -1;\n\t\tlapack_int *rank = alloca(sizeof(lapack_int) * MIN(arows, acols));\n\t\t// lapack_int *rank = malloc(sizeof(lapack_int) * MIN(arows, acols));\n\t\tlapack_int inf = LAPACKE_gelss(LAPACK_ROW_MAJOR, arows, acols, xcols, (aCpy), acols, CV_RAW_PTR(xCpy), xcols, S,\n\t\t\t\t\t\t\t\t\t   rcond, rank);\n\t\tassert(Barr->rows == acols);\n\t\tassert(Barr->cols == xCpy->cols);\n\n\t\tif (xLargerThanB) {\n\t\t\txCpy->rows = acols;\n\t\t\tcvCopy(xCpy, Barr, 0);\n\t\t\t// cvReleaseMat(&xCpy);\n\t\t}\n\n\t\t// cvReleaseMat(&aCpy);\n#ifdef DEBUG_PRINT\n\t\tprint_mat(Barr);\n#endif\n\t\tassert(inf == 0);\n\t}\n\treturn 0;\n}\n\nSURVIVE_LOCAL_ONLY void cvTranspose(const CvMat *M, CvMat *dst) {\n\tbool inPlace = M == dst || CV_RAW_PTR(M) == CV_RAW_PTR(dst);\n\tFLT *src = CV_RAW_PTR(M);\n\n\tif (inPlace) {\n\t\tsrc = alloca(mat_size_bytes(M));\n\t\tmemcpy(src, CV_RAW_PTR(M), mat_size_bytes(M));\n\t} else {\n\t  assert(M->rows == dst->cols);\n\t  assert(M->cols == dst->rows);\n\t}\n\n\tfor (unsigned i = 0; i < M->rows; i++) {\n\t\tfor (unsigned j = 0; j < M->cols; j++) {\n\t\t\tCV_RAW_PTR(dst)[j * M->rows + i] = src[i * M->cols + j];\n\t\t}\n\t}\n}\n\nSURVIVE_LOCAL_ONLY void cvSVD(CvMat *aarr, CvMat *warr, CvMat *uarr, CvMat *varr, int flags) {\n\tchar jobu = 'A';\n\tchar jobvt = 'A';\n\n\tlapack_int inf;\n\n\tif ((flags & CV_SVD_MODIFY_A) == 0) {\n\t\taarr = cvCloneMat(aarr);\n\t}\n\n\tif (uarr == 0)\n\t\tjobu = 'N';\n\tif (varr == 0)\n\t\tjobvt = 'N';\n\n\tFLT *pw, *pu, *pv;\n\tlapack_int arows = aarr->rows, acols = aarr->cols;\n\n\tpw = warr ? CV_RAW_PTR(warr) : (FLT *)alloca(sizeof(FLT) * arows * acols);\n\tpu = uarr ? CV_RAW_PTR(uarr) : (FLT *)alloca(sizeof(FLT) * arows * arows);\n\tpv = varr ? CV_RAW_PTR(varr) : (FLT *)alloca(sizeof(FLT) * acols * acols);\n\n\tlapack_int ulda = uarr ? uarr->cols : acols;\n\tlapack_int plda = varr ? varr->cols : acols;\n\n\tFLT *superb = alloca(sizeof(FLT) * MIN(arows, acols));\n\tinf = LAPACKE_gesvd(LAPACK_ROW_MAJOR, jobu, jobvt, arows, acols, CV_RAW_PTR(aarr), acols, pw, pu, ulda, pv, plda,\n\t\t\t\t\t\tsuperb);\n\n\t// free(superb);\n\n\tswitch (inf) {\n\tcase -6:\n\t\tassert(false && \"matrix has NaNs\");\n\t\tbreak;\n\tcase 0:\n\t\tbreak;\n\tdefault:\n\t\tassert(inf == 0);\n\t}\n\n\tif (uarr && (flags & CV_SVD_U_T)) {\n\t\tcvTranspose(uarr, uarr);\n\t}\n\n\tif (varr && (flags & CV_SVD_V_T) == 0) {\n\t\tcvTranspose(varr, varr);\n\t}\n\n\tif ((flags & CV_SVD_MODIFY_A) == 0) {\n\t\tcvReleaseMat(&aarr);\n\t}\n}\n\nSURVIVE_LOCAL_ONLY void cvSetZero(CvMat *arr) {\n\tfor (int i = 0; i < arr->rows; i++)\n\t\tfor (int j = 0; j < arr->cols; j++)\n\t\t\tCV_RAW_PTR(arr)[i * arr->cols + j] = 0;\n}\nSURVIVE_LOCAL_ONLY void cvSetIdentity(CvMat *arr) {\n\tfor (int i = 0; i < arr->rows; i++)\n\t\tfor (int j = 0; j < arr->cols; j++)\n\t\t\tCV_RAW_PTR(arr)[i * arr->cols + j] = i == j;\n}\n\nSURVIVE_LOCAL_ONLY void cvReleaseMat(CvMat **mat) {\n\tassert(*(*mat)->refcount == 1);\n\tfree((*mat)->refcount);\n\tfree(*mat);\n\t*mat = 0;\n}\n\nSURVIVE_LOCAL_ONLY double cvDet(const CvMat *M) {\n\tassert(M->rows == M->cols);\n\tassert(M->rows <= 3 && \"cvDet unimplemented for matrices >3\");\n\n\tFLT *m = CV_RAW_PTR(M);\n\n\tswitch (M->rows) {\n\tcase 1:\n\t\treturn m[0];\n\tcase 2: {\n\t\treturn m[0] * m[3] - m[1] * m[2];\n\t}\n\tcase 3: {\n\t\tFLT m00 = m[0], m01 = m[1], m02 = m[2], m10 = m[3], m11 = m[4], m12 = m[5], m20 = m[6], m21 = m[7], m22 = m[8];\n\n\t\treturn m00 * (m11 * m22 - m12 * m21) - m01 * (m10 * m22 - m12 * m20) + m02 * (m10 * m21 - m11 * m20);\n\t}\n\tdefault:\n\t\tabort();\n\t}\n}\n", "meta": {"hexsha": "fcabb47d269a8e7fd67cc3c9d5b898bd8f731ab0", "size": 16155, "ext": "c", "lang": "C", "max_stars_repo_path": "redist/minimal_opencv.c", "max_stars_repo_name": "tiiuae/libsurvive", "max_stars_repo_head_hexsha": "b966a6c0942889f7a4d6a34dd21488bb9a06ffc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "redist/minimal_opencv.c", "max_issues_repo_name": "tiiuae/libsurvive", "max_issues_repo_head_hexsha": "b966a6c0942889f7a4d6a34dd21488bb9a06ffc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "redist/minimal_opencv.c", "max_forks_repo_name": "tiiuae/libsurvive", "max_forks_repo_head_hexsha": "b966a6c0942889f7a4d6a34dd21488bb9a06ffc6", "max_forks_repo_licenses": ["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.4262295082, "max_line_length": 120, "alphanum_fraction": 0.6511296812, "num_tokens": 5517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764746, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.350881975460756}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <limits.h>\n#include <float.h>\n#include \"parmt_postProcess.h\"\n#ifdef PARMT_USE_INTEL\n#include <mkl_cblas.h>\n#else\n#include <cblas.h>\n#endif\n#include \"iscl/array/array.h\"\n#include \"iscl/memory/memory.h\"\n\nstatic double *diff(const int n, const double *__restrict__ x, int *ierr);\nstatic int computePadding8i(const int n);\n\nint marginal_getOptimum(const int nloc, const int nm, const int nb,\n                        const int ng, const int nk, const int ns, const int nt,\n                        const double *__restrict__ phi,\n                        int *jloc, int *jm, int *jb, int *jg,\n                        int *jk, int *js, int *jt)\n{\n    int ib, ig, ik, iloc, imax, im, imt, indx, is, it, nmt;\n    enum isclError_enum ierr;\n    nmt = nm*nb*ng*nk*ns*nt;\n    imax = array_argmax64f(nmt*nloc, phi, &ierr);\n    for (iloc=0; iloc<nloc; iloc++)\n    {\n        for (im=0; im<nm; im++)\n        {\n            for (ib=0; ib<nb; ib++)\n            {\n                for (ig=0; ig<ng; ig++)\n                {\n                    for (ik=0; ik<nk; ik++)\n                    {\n                        for (is=0; is<ns; is++)\n                        {\n                            for (it=0; it<nt; it++)\n                            {\n                                imt = im*nb*ng*nk*ns*nt\n                                    + ib*ng*nk*ns*nt\n                                    + ig*nk*ns*nt\n                                    + ik*ns*nt\n                                    + is*nt\n                                    + it;\n                                indx = iloc*nmt + imt;\n                                if (indx == imax)\n                                {\n                                    *jloc = iloc;\n                                    *jm = im;\n                                    *jb = ib;\n                                    *jg = ig;\n                                    *jk = ik;\n                                    *js = is;\n                                    *jt = it;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n         }\n     }\n     return 0;\n}\n/*!\n * @brief Computes the marginal PDF at lune points using Eqn 48 of\n *        Tape and Tape 2015.\n *\n * @param[in] nloc       number of locations in grid-search.  \n * @param[in] nm         number of moment magnitudes in grid search\n * @param[in] nb         number of colatitudes\n * @param[in] betas      colatitudes (radians) of lune points [nb]\n * @param[in] ng         number of longitudes\n * @param[in] gammas     longitudes (radians) of lune points [ng]\n * @param[in] nk         number of strike angles\n * @param[in] kappas     fault strike angles (radians) [nk]\n * @param[in] ns         number of slip angles\n * @param[in] sigmas     fault slip angles (radians) [ns]\n * @param[in] nh         number of dip angles\n * @param[in] h          related to dip angles (radians) [nh]\n * @param[in] phi        objective function computed throughout grid-search\n *                       space to marginalize [nloc*nm*nb*ng*nk*ns*nh]\n * @param[out] luneMPDF  marginalized lune [nb x ng].  the ib, ig'th \n *                       colatitude and longitude is given by ib*ng + ig.\n *   \n * @result 0 indicates success\n *\n * @author Ben Baker\n *\n * @copyright ISTI distributed under Apache 2\n *\n * @bug There is inadequate handling of moment tensor scaling and locs\n  *     is a misnomer.  Technically this can only loop in 1D and I would\n *      require the cell volumes for position to loop on locations.\n */\nint marginal_computeLuneMPDF(const int nloc,\n                             const int nm,\n                             const int nb, const double *__restrict__ betas,\n                             const int ng, const double *__restrict__ gammas,\n                             const int nk, const double *__restrict__ kappas,\n                             const int ns, const double *__restrict__ sigmas,\n                             const int nh, const double *__restrict__ h,\n                             const double *__restrict__ phi,\n                             double *__restrict__ luneMPDF)\n{\n    const char *fcnm = \"marginal_computeLuneMPDF\\0\";\n    int ib, ierr, ig, igIb, ih, ik, iloc, im, imt, indx, is, nmt;\n    double *cos3g, *dh, *dk, *ds, *twoSinB3;\n    double sinb, sinb3, dkdsdh, dV;\n    nmt = nm*nb*ng*nk*ns*nh;\n    memset(luneMPDF, 0, (size_t) (ng*nb)*sizeof(double));\n    if (nk < 2 || ns < 2 || nh < 2)\n    {\n        if (nk < 2){printf(\"%s: Error nk must be > 1\\n\", fcnm);}\n        if (ns < 2){printf(\"%s: Error ns must be > 1\\n\", fcnm);}\n        if (nh < 2){printf(\"%s: Error nh must be > 1\\n\", fcnm);}\n    }\n    // Differentiate weights for Riemann quadrature\n    dk = diff(nk, kappas, &ierr);\n    ds = diff(ns, sigmas, &ierr);\n    dh = diff(nh, h, &ierr);\n    // theta goes from 0 to pi/2 as h goes from 1 to 0 hence it's \n    // orientation is reversed from our ini file (recall that it asks\n    // for theta and not h) and hence -dh is not conducive to quadrature.\n    cblas_dscal(nh-1, -1.0, dh, 1);\n    // Precompute the trigonemetric terms\n    twoSinB3 = memory_calloc64f(nb);\n    for (ib=0; ib<nb; ib++)\n    {\n        twoSinB3[ib] = 2.0*pow(sin(betas[ib]), 3);\n    }\n    cos3g = memory_calloc64f(ng);\n    for (ig=0; ig<ng; ig++)\n    {\n        cos3g[ig] = cos(3.0*gammas[ig]);\n    }\n    // Marginalize the lune \n    for (iloc=0; iloc<nloc; iloc++)\n    {\n        for (im=0; im<nm; im++)\n        {\n            for (ib=0; ib<nb; ib++)\n            {\n                for (ig=0; ig<ng; ig++)\n                {\n                    for (ik=0; ik<nk-1; ik++)\n                    {\n                        for (is=0; is<ns-1; is++)\n                        {\n                            for (ih=0; ih<nh-1; ih++)\n                            {\n                                imt = im*nb*ng*nk*ns*nh\n                                    + ib*ng*nk*ns*nh\n                                    + ig*nk*ns*nh\n                                    + ik*ns*nh\n                                    + is*nh\n                                    + ih;\n                                igIb = ib*ng + ig;\n                                indx = iloc*nmt + imt;\n                                //sinb = sin(betas[ib]);\n                                //sinb3 = (sinb*sinb)*sinb;\n                                //twoSinb3 = 2.0*sinb3;\n                                //cos3g = cos(3.0*gammas[ig]);\n                                dkdsdh = (dk[ik]*ds[is])*dh[ih];\n                                dV = twoSinB3[ib]*cos3g[ig]*dkdsdh;\n                                luneMPDF[igIb] = luneMPDF[igIb] + phi[indx]*dV;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    memory_free64f(&dh);\n    memory_free64f(&dk);\n    memory_free64f(&ds);\n    memory_free64f(&twoSinB3);\n    memory_free64f(&cos3g);\n    return 0;\n}\n\nint marginal_computeLuneUVMPDF(const int nloc,\n                               const int nm, \n                               const int nu, const double *__restrict__ us,\n                               const int nv, const double *__restrict__ vs,\n                               const int nk, const double *__restrict__ kappas,\n                               const int ns, const double *__restrict__ sigmas,\n                               const int nh, const double *__restrict__ hs,\n                               const double *__restrict__ phi,\n                               double *__restrict__ luneMPDF)\n{\n    const char *fcnm = \"marginal_computeLuneMPDF\\0\";\n    int ierr, ih, ik, iloc, im, imt, indx, is, iu, iuIv, iv, nmt;\n    double *dh, *dk, *ds, *du, *dv;\n    double dudv, dkdsdh, dV; \n    const double sqrt8 = sqrt(8.0);\n    nmt = nm*nu*nv*nk*ns*nh;\n    memset(luneMPDF, 0, (size_t) (nu*nv)*sizeof(double));\n    if (nk < 2 || ns < 2 || nh < 2)\n    {   \n        if (nk < 2){printf(\"%s: Error nk must be > 1\\n\", fcnm);}\n        if (ns < 2){printf(\"%s: Error ns must be > 1\\n\", fcnm);}\n        if (nh < 2){printf(\"%s: Error nh must be > 1\\n\", fcnm);}\n    }   \n    // Differentiate weights for Riemann quadrature\n    dk = diff(nk, kappas, &ierr);\n    ds = diff(ns, sigmas, &ierr);\n    dh = diff(nh, hs,     &ierr);\n/*\n    du = diff(nu, us,     &ierr);\n    dv = diff(nv, vs,     &ierr);\nfor (int i=0; i<nu; i++)\n{\n  printf(\"du: %f: \\n\", du[i]);\n}\nfor (int i=0; i<nv; i++)\n{\n printf(\"dv: %f: \\n\", dv[i]);\n}\n*/\n    // theta goes from 0 to pi/2 as h goes from 1 to 0 hence it's \n    // orientation is reversed from our ini file (recall that it asks\n    // for theta and not h) and hence -dh is not conducive to quadrature.\n    cblas_dscal(nh-1, -1.0, dh, 1); \n    // Marginalize the lune \n    for (iloc=0; iloc<nloc; iloc++)\n    {\n        for (im=0; im<nm; im++)\n        {\n            for (iu=0; iu<nu; iu++)\n            {\n                for (iv=0; iv<nv; iv++)\n                {   \n                    for (ik=0; ik<nk-1; ik++)\n                    {   \n                        for (is=0; is<ns-1; is++)\n                        {   \n                            for (ih=0; ih<nh-1; ih++)\n                            {\n                                imt = im*nu*nv*nk*ns*nh\n                                    + iu*nv*nk*ns*nh\n                                    + iv*nk*ns*nh\n                                    + ik*ns*nh\n                                    + is*nh\n                                    + ih;\n                                iuIv = iv*nu + iu;\n                                indx = iloc*nmt + imt;\n                                //sinb = sin(betas[ib]);\n                                //sinb3 = (sinb*sinb)*sinb;\n                                //twoSinb3 = 2.0*sinb3;\n                                //cos3g = cos(3.0*gammas[ig]);\n                                dudv = sqrt8; //du[iu]*dv[iv];\n                                dkdsdh = (dk[ik]*ds[is])*dh[ih];\n                                dV = dudv*dkdsdh;\n                                luneMPDF[iuIv] = luneMPDF[iuIv] + phi[indx]*dV;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n/*\n    memory_free64f(&du);\n    memory_free64f(&dv);\n*/\n    memory_free64f(&dk);\n    memory_free64f(&ds);\n    memory_free64f(&dh);\n    return 0;\n}\n//============================================================================//\nint marginal_computeDepthMPDF(const int nloc,\n                              const int nm, const double *__restrict__ M0s,\n                              const int nb, const double *__restrict__ betas,\n                              const int ng, const double *__restrict__ gammas,\n                              const int nk, const double *__restrict__ kappas,\n                              const int ns, const double *__restrict__ sigmas,\n                              const int nt, const double *__restrict__ thetas,\n                              const double *__restrict__ phi,\n                              double *__restrict__ depMagMPDF,\n                              double *__restrict__ depMPDF)\n{\n    const char *fcnm = \"marginal_computeDepthMPDF\\0\";\n    double *cos3g, *db,  *dg, *dk, *dm, *ds, *dt, *twoSinB4, *sint,\n           arg, dbdg, dkdsdt, dV5, geom, sum;\n    int ib, ierr, ig, ik, iloc, im, imt, indx, is, it, jloc;\n    ierr = 0;\n    memset(depMPDF, 0, (size_t) nloc*sizeof(double));\n    memset(depMagMPDF, 0, (size_t) (nloc*nm)*sizeof(double));\n    // Cell spacings for for Riemann quadrature\n    dm = memory_calloc64f(nm);\n    db = memory_calloc64f(nb);\n    dg = memory_calloc64f(ng);\n    dk = memory_calloc64f(nk);\n    ds = memory_calloc64f(ns);\n    dt = memory_calloc64f(nt);\n    ierr += postprocess_computeBetaCellSpacing(nb,  betas, db);\n    ierr += postprocess_computeGammaCellSpacing(ng, gammas, dg);\n    ierr += postprocess_computeKappaCellSpacing(nk, kappas, dk);\n    ierr += postprocess_computeSigmaCellSpacing(ns, sigmas, ds);\n    ierr += postprocess_computeThetaCellSpacing(nt, thetas, dt);\n    ierr += postprocess_computeM0CellSpacing(nm, M0s, dm);\nprintf(\"%s: for now i'm setting dm = 1 and dl = 1\\n\", fcnm);\narray_set64f_work(nm, 1.0, dm);\n    if (ierr != 0)\n    {\n        printf(\"%s: Failed to compute cell spacing\\n\", fcnm);\n        return -1;\n    }\n    if (array_min64f(nm, dm, &ierr) <= 0.0 ||\n        array_min64f(nb, db, &ierr) <= 0.0 ||\n        array_min64f(ng, dg, &ierr) <= 0.0 ||\n        array_min64f(nk, dk, &ierr) <= 0.0 ||\n        array_min64f(ns, ds, &ierr) <= 0.0 ||\n        array_min64f(nt, dt, &ierr) <= 0.0)\n    {\n        printf(\"%s: Negative jacobian\\n\", fcnm);\n        return -1;\n    }\n    // Compute the geometric factors\n    twoSinB4 = memory_calloc64f(nb);\n    for (ib=0; ib<nb; ib++)\n    {\n        twoSinB4[ib] = 2.0*pow(sin(betas[ib]), 4);\n    }\n    sint = memory_calloc64f(nt);\n    for (it=0; it<nt; it++)\n    {\n        sint[it] = sin(thetas[it]);\n    }\n    cos3g = memory_calloc64f(ng);\n    for (ig=0; ig<ng; ig++)\n    {\n        cos3g[ig] = cos(3.0*gammas[ig]);\n    }\n    if (array_min64f(nb, twoSinB4, &ierr) <= 0.0 ||\n        array_min64f(nt, sint, &ierr) <= 0.0 ||\n        array_min64f(ng, cos3g, &ierr) <= 0.0)\n    {\n        printf(\"%s: Warning negative jacobian from geometric factors\\n\", fcnm);\n    }\n    for (iloc=0; iloc<nloc; iloc++)\n    {\n        for (im=0; im<nm; im++)\n        { \n            for (ib=0; ib<nb; ib++)\n            { \n                for (ig=0; ig<ng; ig++)\n                { \n                    for (ik=0; ik<nk; ik++)\n                    {\n                        for (is=0; is<ns; is++)\n                        {\n                            for (it=0; it<nt; it++)\n                            {\n                                imt = iloc*nm*nb*ng*nk*ns*nt\n                                    +      im*nb*ng*nk*ns*nt\n                                    +         ib*ng*nk*ns*nt\n                                    +            ig*nk*ns*nt\n                                    +               ik*ns*nt\n                                    +                  is*nt\n                                    +                     it;\n                                dkdsdt = (dk[ik]*ds[is])*dt[it];\n                                dbdg = db[ib]*dg[ig];\n                                geom = (twoSinB4[ib]*cos3g[ig])*sint[it];\n                                dV5 = geom*(dbdg*dkdsdt);\n                                //if (dV5 < 0.0){printf(\"error\\n\");}\n                                arg = phi[imt]*dV5;\n                                jloc = im*nloc + iloc;\n                                depMagMPDF[jloc] = depMagMPDF[jloc] + arg;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    // Integrate out the depMagMPDF\n    for (iloc=0; iloc<nloc; iloc++)\n    {\n        for (im=0; im<nm; im++)\n        {\n            jloc = im*nloc + iloc;\n            depMPDF[iloc] = depMPDF[iloc] +  depMagMPDF[jloc]*dm[im];\n        }\n    }\n    memory_free64f(&cos3g);\n    memory_free64f(&sint);\n    memory_free64f(&twoSinB4);\n    memory_free64f(&db);\n    memory_free64f(&dg);\n    memory_free64f(&dk);\n    memory_free64f(&ds);\n    memory_free64f(&dt);\n    memory_free64f(&dm);\n    return ierr;\n}\n//============================================================================//\ndouble marginal_computeNormalization(\n    const int nloc, const double *__restrict__ deps,\n    const int nm, const double *__restrict__ M0s,\n    const int nb, const double *__restrict__ betas,\n    const int ng, const double *__restrict__ gammas,\n    const int nk, const double *__restrict__ kappas,\n    const int ns, const double *__restrict__ sigmas,\n    const int nt, const double *__restrict__ thetas,\n    const double *__restrict__ phi,\n    int *ierr)\n{\n    const char *fcnm = \"marginal_computeNormalization\\0\";\n    double *cos3g, *db,  *dg, *dk, *dl, *dm, *ds, *dt, *twoSinB4, *sint,\n           dbdg, dkdsdt, dV2, dV5, dV7, geom, sum;\n    int ib, ig, ik, iloc, im, imt, is, it, nmt;\n    *ierr = 0;\n    sum = 0.0;\n    nmt = nm*nb*ng*nk*ns*nt;\n    // Cell spacings for for Riemann quadrature\n    dl = memory_calloc64f(nloc);\n    dm = memory_calloc64f(nm);\n    db = memory_calloc64f(nb);\n    dg = memory_calloc64f(ng);\n    dk = memory_calloc64f(nk);\n    ds = memory_calloc64f(ns);\n    dt = memory_calloc64f(nt);\n    *ierr += postprocess_computeBetaCellSpacing(nb,  betas, db);\n    *ierr += postprocess_computeGammaCellSpacing(ng, gammas, dg);\n    *ierr += postprocess_computeKappaCellSpacing(nk, kappas, dk);\n    *ierr += postprocess_computeSigmaCellSpacing(ns, sigmas, ds);\n    *ierr += postprocess_computeThetaCellSpacing(nt, thetas, dt);\n    *ierr += postprocess_computeM0CellSpacing(nm, M0s, dm);\n    *ierr += postprocess_computeM0CellSpacing(nloc, deps, dl); \nprintf(\"%s: for now i'm setting dm = 1 and dl = 1\\n\", fcnm);\narray_set64f_work(nm, 1.0, dm);\narray_set64f_work(nloc, 1.0, dl);\n    if (*ierr != 0)\n    {\n        printf(\"%s; Error computing normalization\\n\", fcnm);\n        return sum;\n    }\n    if (array_min64f(nloc, dl, ierr) <= 0.0 ||\n        array_min64f(nm, dm, ierr) <= 0.0 ||\n        array_min64f(nb, db, ierr) <= 0.0 || \n        array_min64f(ng, dg, ierr) <= 0.0 ||\n        array_min64f(nk, dk, ierr) <= 0.0 ||\n        array_min64f(ns, ds, ierr) <= 0.0 ||\n        array_min64f(nt, dt, ierr) <= 0.0)\n    {\n        printf(\"%s: Negative jacobian\\n\", fcnm);\n        *ierr = 1;\n        return sum;\n    } \n    // Compute the geometric factors\n    twoSinB4 = memory_calloc64f(nb);\n    for (ib=0; ib<nb; ib++)\n    {\n        twoSinB4[ib] = 2.0*pow(sin(betas[ib]), 4);\n    }\n    sint = memory_calloc64f(nt);\n    for (it=0; it<nt; it++)\n    {\n        sint[it] = sin(thetas[it]);\n    }\n    cos3g = memory_calloc64f(ng);\n    for (ig=0; ig<ng; ig++)\n    {\n        cos3g[ig] = cos(3.0*gammas[ig]);\n    }\n    sum = 0.0;\n    for (iloc=0; iloc<nloc; iloc++)\n    {\n        for (im=0; im<nm; im++)\n        {\n            for (ib=0; ib<nb; ib++)\n            {\n                for (ig=0; ig<ng; ig++)\n                {\n                    for (ik=0; ik<nk; ik++)\n                    {\n                        for (is=0; is<ns; is++)\n                        {\n                            for (it=0; it<nt; it++)\n                            {\n                                imt = iloc*nm*nb*ng*nk*ns*nt\n                                    +      im*nb*ng*nk*ns*nt\n                                    +         ib*ng*nk*ns*nt\n                                    +            ig*nk*ns*nt\n                                    +               ik*ns*nt\n                                    +                  is*nt\n                                    +                     it;\n                                dkdsdt = (dk[ik]*ds[is])*dt[it];\n                                dbdg = db[ib]*dg[ig];\n                                geom = (twoSinB4[ib]*cos3g[ig])*sint[it];\n                                dV5 = geom*(dbdg*dkdsdt);\n                                dV2 = dl[iloc]*dm[im];   \n                                dV7 = dV5*dV2;\n                                sum = sum + phi[imt]*dV7;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    memory_free64f(&cos3g);\n    memory_free64f(&sint);\n    memory_free64f(&twoSinB4);\n    memory_free64f(&db);\n    memory_free64f(&dg);\n    memory_free64f(&dk);\n    memory_free64f(&ds);\n    memory_free64f(&dt);\n    memory_free64f(&dl);\n    memory_free64f(&dm);\n    return sum;\n}\n//============================================================================//\nint marginal_computeMarginalBeachball(\n    const int nloc,\n    const int nm, \n    const int nb, const double *__restrict__ betas,\n    const int ng, const double *__restrict__ gammas,\n    const int nk, const double *__restrict__ kappas,\n    const int ns, const double *__restrict__ sigmas,\n    const int nt, const double *__restrict__ thetas,\n    const double *__restrict__ phi\n    )\n{\n    const char *fcnm = \"marginal_computeMarginalBeachball\\0\";\n    const double M0loc = 1.0/sqrt(2.0);\n    double pAxis[3], nAxis[3], tAxis[3];\n    double *bb, *bbAvg, *bbWt, *cos3g, *db,  *dg, *dk, *ds, *dt,\n           *twoSinB4, *sint, *xw1, *yw1, dbdg, dkdsdt, dV5, geom, xscal;\n    int ib, ig, ik, ierr, iloc, im, imt, indx, is, it, j, jmt, jndx,\n        ldi, nmt, nmtBB;\n    int8_t *bmap;\n    size_t nwork;\n    const int nxp = 51;\n    const int nyp = nxp;\n    const double xc = 1.5;\n    const double yc = xc;\n    const double rad = 1.0;\n    nmt = nm*nb*ng*nk*ns*nt;\n    nmtBB = nb*ng*nk*ns*nt;\n    ldi = nxp*nyp + computePadding8i(nxp*nyp);\nprintf(\"%d %d\\n\", ldi, nxp*nyp);\n    nwork = (size_t)(nmtBB)*(size_t) (ldi);\n    if (nwork > INT_MAX)\n    {\n        printf(\"%s: Insufficient space for bb\\n\", fcnm);\n        return -1;\n    }\n    xw1 = memory_calloc64f(nxp*nyp);\n    yw1 = memory_calloc64f(nxp*nyp);\n    bmap = (int8_t *) calloc(nwork, sizeof(int8_t));\n    bbAvg = memory_calloc64f(nxp*nyp);\n    bbWt = memory_calloc64f(nxp*nyp);\n    bb = memory_calloc64f(nxp*nyp);\n    printf(\"%s: Drawing...\\n\", fcnm);\n    for (ib=0; ib<nb; ib++)\n    {\n        printf(\"%s: Drawing beta: %d\\n\", fcnm, ib+1);\n        for (ig=0; ig<ng; ig++)\n        {\n            for (ik=0; ik<nk; ik++)\n            {\n                for (is=0; is<ns; is++)\n                {\n                    for (it=0; it<nt; it++)\n                    {\n                        postprocess_tt2tnp(betas[ib], gammas[ig], kappas[ik],\n                                           sigmas[is], thetas[it],\n                                           pAxis, nAxis, tAxis);\n                        jmt = ib*ng*nk*ns*nt\n                            + ig*nk*ns*nt\n                            + ik*ns*nt\n                            + is*nt\n                            + it;\n                        jndx = jmt*ldi;\n                        postprocess_tnp2beachballPolarity(nxp, xc, yc, rad,\n                                                       pAxis, nAxis, tAxis,\n                                                       xw1, yw1, &bmap[jndx]);\n                    }\n                }\n            }\n        }\n    }\n    // Differentiate weights for Riemann quadrature\n    db = diff(nb, betas,  &ierr);\n    dg = diff(ng, gammas, &ierr);\n    dk = diff(nk, kappas, &ierr);\n    ds = diff(ns, sigmas, &ierr);\n    dt = diff(nt, thetas, &ierr);\n    // Compute the geometric factors\n    twoSinB4 = memory_calloc64f(nb);\n    for (ib=0; ib<nb; ib++)\n    {\n        twoSinB4[ib] = 2.0*pow(sin(betas[ib]), 4);\n    }\n    sint = memory_calloc64f(nt);\n    for (it=0; it<nt; it++)\n    {\n        sint[it] = sin(thetas[it]);\n    }\n    cos3g = memory_calloc64f(ng);\n    for (ig=0; ig<ng; ig++)\n    {\n        cos3g[ig] = cos(3.0*gammas[ig]);\n    }\nprintf(\"integrating\\n\");\n    // Stack the result\n    for (iloc=0; iloc<nloc; iloc++)\n    {\n        for (im=0; im<nm; im++)\n        {\n            for (ib=0; ib<nb; ib++)\n            {\n                for (ig=0; ig<ng; ig++)\n                {\n                    for (ik=0; ik<nk; ik++)\n                    {\n                        for (is=0; is<ns; is++)\n                        {\n                            for (it=0; it<nt; it++)\n                            {\n                                imt = im*nb*ng*nk*ns*nt\n                                    + ib*ng*nk*ns*nt\n                                    + ig*nk*ns*nt\n                                    + ik*ns*nt\n                                    + is*nt\n                                    + it; \n                                indx = iloc*nmt + imt;\n                                dkdsdt = (dk[ik]*ds[is])*dt[it];\n                                dbdg = db[ib]*dg[ig];\n                                geom = (twoSinB4[ib]*cos3g[ig])*sint[it];\n                                dV5 = geom*(dbdg*dkdsdt); \n//if (dV5 < 0.0){printf(\"error %f %f %f %f %f %f %f\\n\", dV5, dbdg, dkdsdt, geom, twoSinB4[ib], cos3g[ig], sint[it]);}\n                                xscal = (phi[indx] - 1);//*dV5;\n                                jmt = ib*ng*nk*ns*nt\n                                    + ig*nk*ns*nt\n                                    + ik*ns*nt\n                                    + is*nt\n                                    + it;\n                                jndx = jmt*ldi;\n                                for (j=0; j<nxp*nxp; j++)\n                                {\n                                    bb[j] = bb[j] + xscal*(double) bmap[jndx+j];\n//                                    bbAvg[j] = bbAvg[j] + (double) bmap[jndx+j];\n//                                    bbWt[j] = bbWt[j] + (double) bmap[jndx+j]*dV5;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\nprintf(\"dumping result\\n\");\nint ix, iy;\n    FILE *fwork;\n    fwork = fopen(\"depmag/beachball.txt\", \"w\");\n    for (iy=0; iy<nyp; iy++)\n    {\n        for (ix=0; ix<nxp; ix++)\n        {\n            int k = iy*nxp + ix;\n            fprintf(fwork, \"%e %e %e %e %e %d\\n\", xw1[k], yw1[k], bb[k], bbAvg[k], bbWt[k], bmap[nmtBB/2*ldi+k]);\n        }\n        fprintf(fwork, \"\\n\");\n    }\n    fclose(fwork);\n    memory_free64f(&bbAvg);\n    memory_free64f(&bbWt);\n    memory_free64f(&xw1);\n    memory_free64f(&yw1);\n    memory_free64f(&cos3g);\n    memory_free64f(&sint);\n    memory_free64f(&twoSinB4);\n    memory_free64f(&db);\n    memory_free64f(&dg);\n    memory_free64f(&dk);\n    memory_free64f(&ds);\n    memory_free64f(&dt);\n    free(bmap);\n    return 0;\n}\n\nstatic double *diff(const int n, const double *__restrict__ x, int *ierr)\n{\n    double *d;\n    int i;\n    d = array_set64f(n, 1.0, ierr);\n    for (i=0; i<n; i++)\n    {\n        if (i < n - 1)\n        {\n            d[i] = x[i+1] - x[i];\n        }\n        else\n        {\n            d[i] = x[i] - x[i-1];\n        }\n    }\n    return d;\n}\n\n/*! Related to beta */\n/*\nstatic double g11(void)\n{\n    return 1;\n}\n*/\n\n/*! Related to gamma */\n/*\nstatic double g22(const double sinBeta)\n{\n    return sinBeta*sinBeta;\n}\n*/\n\n/*! Related to kappa */\n/*\nstatic double g33( )\n{\n    const double twoSqrt3 = 3.4641016151377544;\n    coss2 = coss*coss;\n    g33 = 0.5*((4.0 + (-2.0 + 3.0*(1.0 - cos2t))*coss2)*cos2g\n        + twoSqrt3*sin2g*sins*sin2t)*sin2b;\n}\n*/\n\n/*! Related to sigma */\n/*\nstatic void g44( )\n{\n    for (ib=0; ib<nb; ib++)\n    {\n        for (ig=0; ig<ng; ig++)\n        {\n            g33 = (2.0 - cos(2.0*gamma))*sinb2;\n            for (ik=0; ik<nk; ik++)\n            { \n                for (is=0; is<ns; is++)\n                {\n                    for (it=0; it<nt; it++)\n                    {\n\n                    }\n                }\n            }\n        }\n    }\n    return;\n}\n*/\n\n/*!\n * @brief Computes the determinant of the upper 3 x 3 matrix \n */\n/*\nstatic void computeDet123(const int nmt,\n                          const double *__restrict__ g11,\n                          const double *__restrict__ g22,\n                          const double *__restrict__ g33,\n                          double *__restrict__ det)\n{\n    int i;\n    for (i=0; i<nmt; i++)\n    {\n        det[i] = (g11[i]*g22[i])*g33;\n    }\n    return \n}\n\nstatic void computeDet124(const int nmt,\n                          const double *__restrict__ g11,\n                          const double *__restrict__ g22,\n                          const double *__restrict__ g44,\n                          double *__restrict__ det)\n{\n    computeDet123(nmt, g11, g22, g44, det);\n    return;\n}\n\nstatic void computeDet125(const int nmt,\n                          const double *__restrict__ g11,\n                          const double *__restrict__ g22,\n                          const double *__restrict__ g55,\n                          double *__restrict__ det)\n{\n    computeDet123(nmt, g11, g22, g55, det);\n    return;\n}\n*/\n\n\n\nint marginal_write1DToGnuplot(const char *fname,\n                              const int nx, const double *__restrict__ xlocs,\n                              const double *__restrict__ vals)\n{\n    FILE *fout;\n    int ix;\n    fout = fopen(fname, \"w\");\n    for (ix=0; ix<nx; ix++)\n    {\n        fprintf(fout, \"%.8e %.10e\\n\", xlocs[ix], vals[ix]);\n    }\n    fclose(fout);\n    return 0;\n}\n\nint marginal_write2DToGnuplot(const char *fname,\n                              const int nx, const double *__restrict__ xlocs,\n                              const int ny, const double *__restrict__ ylocs,\n                              const double *__restrict__ vals)\n{\n    FILE *fout;\n    int ix, ixy, iy;\n    fout = fopen(fname, \"w\");\n    for (iy=0; iy<ny; iy++)\n    {\n        for (ix=0; ix<nx; ix++)\n        {\n            ixy = iy*nx + ix;\n            fprintf(fout, \"%.8e %.8e %.10e\\n\", xlocs[ix], ylocs[iy], vals[ixy]);\n        }\n        fprintf(fout, \"\\n\");\n    } \n    fclose(fout);\n    return 0;\n}\n//============================================================================//\nstatic int computePadding8i(const int n)\n{\n    size_t mod, pad;\n    int ipad;\n    // Set space and make G matrix\n    pad = 0;\n    mod = ((size_t) n*sizeof(int8_t))%64;\n    if (mod != 0)\n    {\n        pad = (64 - mod)/sizeof(int8_t);\n    }\n    ipad = (int) pad;\n    return ipad;\n}\n", "meta": {"hexsha": "9a3284206019043513df507566f8ddd9722fb741", "size": 29246, "ext": "c", "lang": "C", "max_stars_repo_path": "postprocess/marginal.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "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": "postprocess/marginal.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "postprocess/marginal.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "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": 34.2459016393, "max_line_length": 117, "alphanum_fraction": 0.4303494495, "num_tokens": 8215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.3506727190819081}}
{"text": "/*\n\n\ngcc-mp-4.8 -O3 cudaddottest.c common.c -o cudaddottest -I../../../../netlib/CBLAS -I/usr/local/cuda/include/ -L/usr/local/cuda/lib -lcublas\nexport DYLD_LIBRARY_PATH=/usr/local/cuda/lib\n./cudaddottest  > ../../../results/mac_os_x-x86_64-ddot-cuda_nooh.csv\n\n*/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <cblas.h>\n#include \"common.h\"\n#include <cublas.h>\n\nvoid checkStatus(char* message, cublasStatus status) {\n    if (status != CUBLAS_STATUS_SUCCESS) {\n    \tfprintf (stderr, \"!!!! %s fail %d\\n\", message, status);\n    \texit(EXIT_FAILURE);\n    }\n}\n\nlong benchmark(int size) {\n\tlong requestStart, requestEnd;\n\tint incx = 1, incy = 1, n = size;\n\tdouble *cuA, *cuB;\n\tcublasStatus status;\n\t\n\n    double* a = random_array(size);\n    double* b = random_array(size);\n\n\tstatus = cublasAlloc(n, sizeof(double),(void**)&cuA);\n\tcheckStatus(\"A\", status);\n\tstatus = cublasAlloc(n, sizeof(double),(void**)&cuB);\n\tcheckStatus(\"B\", status);\n\t\n\tstatus = cublasSetVector(n, sizeof(double), a, incx, cuA, incx);\n\tcheckStatus(\"setA\", status);\n\n\tstatus = cublasSetVector(n, sizeof(double), b, incy, cuB, incy);\n\tcheckStatus(\"setB\", status);\n\n\trequestStart = currentTimeNanos();\n\n\tcublasDdot(n, cuA, incx, cuB, incy);\n\n\trequestEnd = currentTimeNanos();\n\t\n\tstatus = cublasFree(cuA);\n\tcheckStatus(\"freeA\", status);\n\tstatus = cublasFree(cuB);\n\tcheckStatus(\"freeB\", status);\n\n    free(a);\n    free(b);\n\n    return (requestEnd - requestStart);\n  }\n\nmain()\n{\n\tcublasStatus status;\n\n\tstatus = cublasInit();\n\tcheckStatus(\"init\",  status);\t\n\t\n\tsrand(time(NULL));\n\n    double factor = 6.0 / 100.0;\n    int i, j;\n    for (i = 0 ; i < 10 ; i++) {\n        for (j = 1 ; j <= 100 ; j++) {\n            int size = (int) pow(10.0, factor * j);\n            if (size < 10) continue;\n            long took = benchmark(size);\n            printf(\"\\\"%d\\\",\\\"%lu\\\"\\n\", size, took);\n        }\n    }\n}", "meta": {"hexsha": "206da6481e80a56afaedab458a00afe8477e8ac2", "size": 1877, "ext": "c", "lang": "C", "max_stars_repo_path": "perf/src/main/c/cudaddottest.c", "max_stars_repo_name": "debasish83/netlib-java", "max_stars_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 624.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T02:29:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:06:35.000Z", "max_issues_repo_path": "perf/src/main/c/cudaddottest.c", "max_issues_repo_name": "debasish83/netlib-java", "max_issues_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T10:34:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-24T14:20:38.000Z", "max_forks_repo_path": "perf/src/main/c/cudaddottest.c", "max_forks_repo_name": "debasish83/netlib-java", "max_forks_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 154.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T22:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T04:58:57.000Z", "avg_line_length": 23.1728395062, "max_line_length": 139, "alphanum_fraction": 0.6185402238, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.350433140426293}}
{"text": "#ifndef DIRICHLETSAMPLE_H\n#define DIRICHLETSAMPLE_H\n\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <sys/time.h>\nusing namespace std;\n\n\nstd::vector<double> DirSample(std::vector<double> alpha, int k, int N);\n\n#endif\n", "meta": {"hexsha": "bb95e20964554d4002557f9d0d8d8424717e0be8", "size": 289, "ext": "h", "lang": "C", "max_stars_repo_path": "10_DirichletSample.h", "max_stars_repo_name": "KathrynLaing/CPNLearning", "max_stars_repo_head_hexsha": "b5123f7f1fe5adda8a63a73ed117c67e282cea69", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "10_DirichletSample.h", "max_issues_repo_name": "KathrynLaing/CPNLearning", "max_issues_repo_head_hexsha": "b5123f7f1fe5adda8a63a73ed117c67e282cea69", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "10_DirichletSample.h", "max_forks_repo_name": "KathrynLaing/CPNLearning", "max_forks_repo_head_hexsha": "b5123f7f1fe5adda8a63a73ed117c67e282cea69", "max_forks_repo_licenses": ["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.0625, "max_line_length": 71, "alphanum_fraction": 0.7474048443, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3502411947157023}}
{"text": "#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\nint main(void)\n{\n  int i; double z; gsl_rng *r;\n  r = gsl_rng_alloc(gsl_rng_mt19937);\n  gsl_rng_set(r,0);\n  for (i=0;i<10;i++) {\n    z = gsl_ran_gaussian(r,1.0);\n    printf(\"z(%d) = %f\\n\",i,z);\n  }\n  exit(EXIT_SUCCESS);\n}", "meta": {"hexsha": "61843d551847691f7088118eb8df5c50354fc271", "size": 276, "ext": "c", "lang": "C", "max_stars_repo_path": "Externals/PolyChord/testgsl.c", "max_stars_repo_name": "yuanfangtardis/vscode_project", "max_stars_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Externals/PolyChord/testgsl.c", "max_issues_repo_name": "yuanfangtardis/vscode_project", "max_issues_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_issues_repo_licenses": ["Apache-2.0"], "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/PolyChord/testgsl.c", "max_forks_repo_name": "yuanfangtardis/vscode_project", "max_forks_repo_head_hexsha": "2d78a85413cc85789cc4fee8ec991eb2a0563ef8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-15T12:22:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T12:22:30.000Z", "avg_line_length": 19.7142857143, "max_line_length": 37, "alphanum_fraction": 0.6123188406, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3502411947157023}}
{"text": "/*\n+---------------------------------------------------------------------------+\n|  Juzhen: C++ library for linear algebra                                   |\n+---------------------------------------------------------------------------+\n|                                                                           |\n|  Copyright 2011 Hui Chen                                                  |\n|                                                                           |\n|  Licensed under the Apache License, Version 2.0 (the \"License\");          |\n|  you may not use this file except in compliance with the License.         |\n|  You may obtain a copy of the License at                                  |\n|                                                                           |\n|      http://www.apache.org/licenses/LICENSE-2.0                           |\n|                                                                           |\n|  Unless required by applicable law or agreed to in writing, software      |\n|  distributed under the License is distributed on an \"AS IS\" BASIS,        |\n|  WITHOUT WARRANTIES OR CONDITIONS OF 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#ifndef SRC_ADAPTOR_BLAS_H_\n#define SRC_ADAPTOR_BLAS_H_\n#include <assert.h>\n\n#include <cblas.h>\n\nnamespace juzhen {\n\ntemplate<typename T>\nvoid gemm(\n    const int M, const int N,\n    const int K, const T *A, const int lda, const T *B,\n    const int ldb, T *c, const int ldc) {\n  assert(0);  // always fails\n}\n\ntemplate<> inline\nvoid gemm<float>(\n    const int M, const int N,\n    const int K, const float *A, const int lda, const float *B,\n    const int ldb, float *c, const int ldc) {\n  cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.,\n              A, lda, B, ldb, 0., c, ldc);\n}\n\ntemplate<> inline\nvoid gemm<double>(\n    const int M, const int N,\n    const int K, const double *A, const int lda, const double *B,\n    const int ldb, double *c, const int ldc) {\n  cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.,\n              A, lda, B, ldb, 0., c, ldc);\n}\n\ntemplate<> inline\nvoid gemm<CS>(\n    const int M, const int N,\n    const int K, const CS  *A, const int lda, const CS *B,\n    const int ldb, CS  *c, const int ldc) {\n  CS alpha(1., 0.);\n  CS beta(0., 0.);\n  cblas_cgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, &alpha,\n              A, lda, B, ldb, &beta, c, ldc);\n}\n\ntemplate<> inline\nvoid gemm<CD>(\n    const int M, const int N,\n    const int K, const CD  *A, const int lda, const CD  *B,\n    const int ldb, CD  *c, const int ldc) {\n  CD alpha(1., 0.);\n  CD beta(0., 0.);\n  cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, &alpha,\n              A, lda, B, ldb, &beta, c, ldc);\n}\n\ntemplate<typename T>\nint geev(\n    char nl, char nr, const int n,\n    T *a, const int lda, CD * w, T *vl, const int ldvl,\n    T *vr, const int ldvr) {\n  assert(0);  // always fails\n}\n\n/*\n * Linear solver\n */\ntemplate<typename T>\nint gesv(\n    const int n, const int nrhs,\n    T *a, const int lda, T *b, const int ldb) {\n  assert(0);  // always fails\n}\n\n/*\n * Matrix inversion \n */\ntemplate<typename T>\nint matrix_inverse(\n    const int m, const int n, T *a, const int lda) {\n  assert(0);  // always fails\n}\n\n/*\n * Matrix determinant \n */\ntemplate<typename T>\nT matrix_determinant(const int m, T *a) {\n  assert(0);  // always fails\n}\n}\n#endif  // SRC_ADAPTOR_BLAS_H_\n\n", "meta": {"hexsha": "98c5e45fc66c5717f61cab36f3957ef38336f9cd", "size": 3711, "ext": "h", "lang": "C", "max_stars_repo_path": "src/adaptor/blas.h", "max_stars_repo_name": "huichen/juzhen", "max_stars_repo_head_hexsha": "5af4308e683f79ab98081739c4a7a567757532b8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-09T10:00:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-30T20:17:59.000Z", "max_issues_repo_path": "src/adaptor/blas.h", "max_issues_repo_name": "huichen/juzhen", "max_issues_repo_head_hexsha": "5af4308e683f79ab98081739c4a7a567757532b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaptor/blas.h", "max_forks_repo_name": "huichen/juzhen", "max_forks_repo_head_hexsha": "5af4308e683f79ab98081739c4a7a567757532b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-07T10:42:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-30T20:18:02.000Z", "avg_line_length": 31.9913793103, "max_line_length": 77, "alphanum_fraction": 0.4955537591, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.35019806362968353}}
{"text": "/* include */\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n#include <sys/time.h>\n#include <time.h>\n#include <globes/globes.h>   /* GLoBES library */\n\n#include <gsl/gsl_math.h>    /* GNU Scientific library (required for root finding) */\n#include <gsl/gsl_roots.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_deriv.h>\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_cdf.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_spline.h>\n#include \"hdf5.h\"\n#include <stdarg.h>\n\n#define degree 0.0174\ndouble min (int n, ...) {\n\t/*\n\tn\u662f\u53c3\u6578\u500b\u6578\uff0c\u5f8c\u9762\u624d\u662f\u53c3\u6578\u672c\u8eab \n\t*/\n\tint \ti;\n\tdouble \tmin_num = 1e20;\n\tdouble \tinput;\n\tva_list vl;\n\tva_start(vl,n);\n\tfor ( i = 0 ; i < n ; i++ ) {\n\t\tinput = va_arg(vl,double);\n\t\tmin_num = min_num > input ? input : min_num;\n\t} \n\tva_end(vl);\n\treturn min_num;\n } \n\n/***************************************************************************\n *                            M A I N   P R O G R A M                      *\n ***************************************************************************/\n\n/* \u5b9a\u7fa93 sigma range \u7684Prior (For NO) */\ndouble prior_3sigma_NO(const glb_params in, void* user_data) {\n\tglb_params \t\tcentral_values \t= \tglbAllocParams();\n\tglb_params \t\tinput_errors \t= \tglbAllocParams();\n\tglb_projection \tp \t\t\t\t= \tglbAllocProjection();\n\n\tglbGetCentralValues(central_values);\n\tglbGetInputErrors(input_errors);\n\tglbGetProjection(p);\n\tint i;\n\tdouble \tpv = 0.0,\n\t\t  \tfit_theta12,\n\t\t   \tfit_theta13,\n\t\t   \tfit_theta23,\n\t\t   \tfit_deltacp,\n\t\t   \tfit_ldm,\n\t\t   \tfit_sdm;\n\n    /* \u53d6\u5f97\u53c3\u6578\u76ee\u524dFit Value */\n\tfit_theta12 = glbGetOscParams(in,0);\n\tfit_theta13 = glbGetOscParams(in,1);\n\tfit_theta23 = glbGetOscParams(in,2);\n\tfit_deltacp = glbGetOscParams(in,3);\n\tfit_sdm     = glbGetOscParams(in,4);\n\tfit_ldm     = glbGetOscParams(in,5);\n\n    /* \u5224\u65b7\u53c3\u6578\u662f\u5426\u8981\u5f15\u5165Prior */\n\tif (glbGetProjectionFlag(p,0)==GLB_FREE){\n\t\tif (fit_theta12  > 35.86 *degree || fit_theta12 < 31.27 *degree){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\tif (glbGetProjectionFlag(p,1)==GLB_FREE){\n\t\tif (fit_theta13  > 8.97 *degree || fit_theta13 < 8.20 *degree){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\tif (glbGetProjectionFlag(p,2)==GLB_FREE){\n\t\tif (fit_theta23 > 51.80 *degree  || fit_theta23 < 39.60 *degree ){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\tif (glbGetProjectionFlag(p,3)==GLB_FREE){\n\t\tif (fit_deltacp == 0 *degree || fit_deltacp == 180 *degree || fit_deltacp < 0 *degree|| fit_deltacp > 360 *degree){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\tif (glbGetProjectionFlag(p,4)==GLB_FREE){\n\t\tif (fit_sdm > 8.04 *1e-5  || fit_sdm  < 6.82 *1e-5){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\tif (glbGetProjectionFlag(p,5)==GLB_FREE){\n\t\tif (fit_ldm  > 2.598 *1e-3 || fit_ldm  < 2.431 *1e-3){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\n\tglbFreeParams(central_values);\n\tglbFreeParams(input_errors);\n\tglbFreeProjection(p);\n\treturn pv;\n}\n\n /* \u5b9a\u7fa93 sigma range \u7684Prior (For IO) */\ndouble prior_3sigma_IO(const glb_params in, void* user_data)\n{\n\tglb_params \t\tcentral_values \t= \tglbAllocParams();\n\tglb_params \t\tinput_errors \t= \tglbAllocParams();\n\tglb_projection \tp \t\t\t\t= \tglbAllocProjection();\n\t\n\tglbGetCentralValues(central_values);\n\tglbGetInputErrors(input_errors);\n\tglbGetProjection(p);\n\tint i;\n\tdouble \tpv = 0.0,\n\t\t   \tfit_theta12,\n\t\t   \tfit_theta13,\n\t\t   \tfit_theta23,\n\t\t   \tfit_deltacp,\n\t\t   \tfit_ldm,\n\t\t   \tfit_sdm;\n\n\t/* \u53d6\u5f97\u53c3\u6578\u76ee\u524dFit Value */\n\tfit_theta12 = glbGetOscParams(in,0);\n\tfit_theta13 = glbGetOscParams(in,1);\n\tfit_theta23 = glbGetOscParams(in,2);\n\tfit_deltacp = glbGetOscParams(in,3);\n\tfit_sdm     = glbGetOscParams(in,4);\n\tfit_ldm     = glbGetOscParams(in,5);\n\n\t/* \u5224\u65b7\u53c3\u6578\u662f\u5426\u8981\u5f15\u5165Prior */\n\tif(glbGetProjectionFlag(p,0)==GLB_FREE){\n\t\tif(fit_theta12  > 35.87 *degree || fit_theta12 < 31.27 *degree){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\tif(glbGetProjectionFlag(p,1)==GLB_FREE){\n\t\tif(fit_theta13  > 8.98 *degree || fit_theta13 < 8.24 *degree){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\tif(glbGetProjectionFlag(p,2)==GLB_FREE){\n\t\tif(fit_theta23 > 52.00 *degree  || fit_theta23 < 39.90 *degree ){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\tif(glbGetProjectionFlag(p,3)==GLB_FREE){\n\t\tif(fit_deltacp == 0 *degree || fit_deltacp == 180 *degree ){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\tif(glbGetProjectionFlag(p,4)==GLB_FREE){\n\t\tif(fit_sdm > 8.04 *1e-5  || fit_sdm  < 6.82 *1e-5){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\tif(glbGetProjectionFlag(p,5)==GLB_FREE){\n\t\tif(fit_ldm  < -2.583 *1e-3 || fit_ldm  > -2.412 *1e-3){\n\t\t    pv += 1e20;\n\t\t}\n\t}\n\n\tglbFreeParams(central_values);\n\tglbFreeParams(input_errors);\n\tglbFreeProjection(p);\n\treturn pv;\n}\n\n/* Poisson\u4e82\u6578\u751f\u6210\u5668 */\nint random_poisson(double mu) {\n\tconst \tgsl_rng_type * T;\n\tgsl_rng * r;\n\tint \ttest;\n\tint \ti;\n\tgsl_rng_env_setup();\n\tstruct \ttimeval tv; // Seed generation based on time\n\tgettimeofday(&tv,0);\n\tunsigned long mySeed = tv.tv_sec + tv.tv_usec;\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc (T);\n\tgsl_rng_set(r, mySeed);\n\tunsigned int k = gsl_ran_poisson (r, mu);\n\tgsl_rng_free (r);\n\treturn k;\n}\n\n/* \u5b9a\u7fa9Poisson Likelihood Function */\ninline double poisson_likelihood(double true_rate, double fit_rate) {\n\tdouble res = 0 ;\n\ttrue_rate = true_rate == 0 ? (true_rate+1e-9) : true_rate;\n\tfit_rate = fit_rate == 0 ? (fit_rate+1e-9) : fit_rate;\n\n\tres = fit_rate - true_rate;\n\tif (fit_rate <= 0.0) { \n\t\tres = 1e100;\n\t} else if (true_rate > 0) {\n\t\tres += true_rate * log(true_rate/fit_rate);\n\t}\n\t\t\n\treturn 2.0 * res;\n}\n\n/* \u5c0dTrue Value Spectrum \u505aPoisson Fluctuation */\nvoid do_poisson_fluctuation(glb_params test_values, int mode_expr, double* dataset, int* dset_info) {\n\t\n\tglbSetOscillationParameters(test_values);\n\tglbSetRates();\n\n\tint\t\tew_low, \n\t\t\tew_high, \n\t\t\ti, \n\t\t\tladder = 0;\n\tint    \tcount_dpf = 0;\n\tint \tnum_channel,\n\t\t\tnum_bins, \n\t\t\tcumu_bins;\n\tif (mode_expr == 0){\n\t\t/* Deprecated\n\t\tdouble *ve_dune      = glbGetRuleRatePtr(0, 0);\n\t\tdouble *vebar_dune   = glbGetRuleRatePtr(0, 1);\n\t\tdouble *vu_dune      = glbGetRuleRatePtr(0, 2);\n\t\tdouble *vubar_dune   = glbGetRuleRatePtr(0, 3);    \n\t\t*/\n\n\t\tnum_channel = 4;\n\t\tcumu_bins\t= 0;\n\t\tfor (int channel = 0; channel < num_channel; channel++){\n\t\t\tdouble *target = glbGetRuleRatePtr(mode_expr, channel);\n\t\t\tglbGetEnergyWindowBins(mode_expr, channel, &ew_low, &ew_high);\n\t\t\tnum_bins = ew_high - ew_low + 1;\n\t\t\tcount_dpf = 0;\n\t\t\tfor (i=ew_low; i <= ew_high; i++) { \n\t\t\t\t*(dataset + cumu_bins + count_dpf) = random_poisson(target[i]);\t\t\n\t\t\t\tcount_dpf += 1;\n\t\t\t}\n\t\t\tcumu_bins += num_bins;\n\t\t\t*(dset_info + channel) = num_bins;\n\t\t}\n\t} else if (mode_expr == 1){ \n\t\t/* Deprecated\n\t\tdouble *ve_t2hk      = glbGetRuleRatePtr(1, 0);\n\t\tdouble *vu_t2hk      = glbGetRuleRatePtr(1, 1);    \n\t\tdouble *vebar_t2hk   = glbGetRuleRatePtr(1, 2);\n\t\tdouble *vubar_t2hk   = glbGetRuleRatePtr(1, 3);\t\n\t\t*/\n\t\tnum_channel = 4;\n\t\tcumu_bins\t= 0;\n\t\tfor (int channel = 0; channel < num_channel; channel++){\n\t\t\tdouble *target = glbGetRuleRatePtr(mode_expr, channel);\n\t\t\tglbGetEnergyWindowBins(mode_expr, channel, &ew_low, &ew_high);\n\t\t\tnum_bins = ew_high - ew_low + 1;\n\t\t\tcount_dpf = 0;\n\t\t\tfor (i=ew_low; i <= ew_high; i++) { \n\t\t\t\t*(dataset + cumu_bins + count_dpf) = random_poisson(target[i]);\t\t\n\t\t\t\tcount_dpf += 1;\n\t\t\t}\n\t\t\tcumu_bins += num_bins;\n\t\t\t*(dset_info + channel) = num_bins;\n\t\t}\n\t} else if (mode_expr == -1) {\n\t\t/* Deprecated\n\t\tdouble *ve_dune      = glbGetRuleRatePtr(0, 0);\n\t\tdouble *vebar_dune   = glbGetRuleRatePtr(0, 1);\n\t\tdouble *vu_dune      = glbGetRuleRatePtr(0, 2);\n\t\tdouble *vubar_dune   = glbGetRuleRatePtr(0, 3);    \n\t\tdouble *ve_t2hk      = glbGetRuleRatePtr(1, 0);\n\t\tdouble *vu_t2hk      = glbGetRuleRatePtr(1, 1);    \n\t\tdouble *vebar_t2hk   = glbGetRuleRatePtr(1, 2);\n\t\tdouble *vubar_t2hk   = glbGetRuleRatePtr(1, 3);\n\t\t*/\n\t\tint num_expr\t= 2;\n\t\tnum_channel \t= 4;\n\t\tcumu_bins\t\t= 0;\n\t\tint expr;\n\t\tfor ( expr = 0; expr < num_expr; expr++) {\n\t\t\tfor (int channel = 0; channel < num_channel; channel++){\n\t\t\t\tdouble *target = glbGetRuleRatePtr(expr, channel);\n\t\t\t\tglbGetEnergyWindowBins(expr, channel, &ew_low, &ew_high);\n\t\t\t\tnum_bins = ew_high - ew_low + 1;\n\t\t\t\tcount_dpf = 0;\n\t\t\t\tfor (i=ew_low; i <= ew_high; i++) { \n\t\t\t\t\t*(dataset + cumu_bins + count_dpf) = random_poisson(target[i]);\t\t\n\t\t\t\t\tcount_dpf += 1;\n\t\t\t\t}\n\t\t\t\tcumu_bins += num_bins;\n\t\t\t\t*(dset_info + channel) = num_bins;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tprintf(\"Please inpuit a correct experiment protocol.\");\n\t}\n}\n\n/* \u5b9a\u7fa9 Chi Square */\ndouble chi2_poisson(int exp, int rule, int np, double *x, double *errors, void* user_data) {\n\tdouble \t*signal_fit_rate = glbGetSignalFitRatePtr(exp, rule);\n\tdouble \t*bg_fit_rate     = glbGetBGFitRatePtr(exp, rule);\n\tdouble \tfit_rate;\n\tdouble \tchi2 = 0.0;\n\tint \ti;\n\tint \tew_low, \n\t\t\tew_high;\n\tglbGetEnergyWindowBins(exp, rule, &ew_low, &ew_high);\n\tint \tsum_y = 0, \n\t\t\tindex, \n\t\t\tpos, \n\t\t\tcount_cp;\n\tint \tdata_info_dune[4] = { 66, 66, 66, 66}; /* {(y_axis_length)} */\n\tint \tdata_info_t2hk[4] = { 8, 12, 8, 12};\n\tint \tdata_info_all[8] = { 66, 66, 66, 66, 8, 12, 8, 12};\n\t\n\tswitch (exp) {\n\t\tcase 0:\n\t\t\tfor ( pos = 0; pos < rule; pos ++){\n\t\t\t\tsum_y += data_info_dune[pos];\n\t\t\t}\n\t\t\t\n\t\t\tfor (i=ew_low; i <= ew_high; i++) {\n\t\t\t\tfit_rate = signal_fit_rate[i] + bg_fit_rate[i];\n\t\t\t\tchi2 += poisson_likelihood( *( (double*) user_data + sum_y + i), fit_rate);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tfor ( pos = 0; pos < rule; pos ++){\n\t\t\t\tsum_y += data_info_t2hk[pos];\n\t\t\t}\n\t\t\t\n\t\t\tfor (i=ew_low; i <= ew_high; i++) {\n\t\t\t\tfit_rate = signal_fit_rate[i] + bg_fit_rate[i];\n\t\t\t\tchi2 += poisson_likelihood( *( (double*) user_data + sum_y + i), fit_rate);\n\t\t\t}\n\t\t\tbreak;\n\t}\n    return chi2;\n}\n\n\n/* \u5b9a\u7fa9 Test Statistic (Delta Chi-Square) */\n//\u53c3\u6578:{CP : [0, 180, 1], MO : [1, -1] , CPV Hypothesis\u7684deltacp}  \n// 0 : CPC at deltacp=0; 180 : CPC at deltacp=180; 1 : CPV at deltacp\n//\u9078\u5b9a\u5be6\u9a57EXP:[0,1,GLB_ALL]\n\ndouble delta_chi2 (int CP, int MO, double deltacp, int EXP) {\n\tdouble  a = 0,\n\t\t\tb = 0; \n\tdouble  chi_0_NO, \n\t\t\tchi_0_IO, \n\t\t\tchi_pi_NO, \n\t\t\tchi_pi_IO, \n\t\t\tchi_cpv_NO, \n\t\t\tchi_cpv_IO;\n\n\tint data_info_dune[6] = {4, 264, 66, 66, 66, 66}; /* {(y_axis_length)} */\n\tint data_info_t2hk[6] = {4, 40, 8, 12, 8, 12};\n\tint data_info_all[10] = {8, 304, 66, 66, 66, 66, 8, 12, 8, 12};\n\tdouble *darray;\n\tint sum_y  = 0,\n\t\tladder = 0,\n\t\tindex_sum, \n\t\ti_idx, j_idx;\n\tint LENGTH = EXP != -1 ? 4 : 8;\n\tint dset_y_info[LENGTH];\n\n\t/* \u5b9a\u7fa9global fit\u53c3\u6578(Normal Ordering, NuFIT 5.0, 2020) */\n\tdouble theta12_N = 33.44;\n\tdouble theta13_N = 8.57;\n\tdouble theta23_N = 49;\n\tdouble sdm_N = 7.42;\n\tdouble ldm_N = 2.514;\n\n\t/* \u5b9a\u7fa9global fit\u53c3\u6578(Inverse Ordering, NuFIT 5.0, 2020) */\n\tdouble theta12_I = 33.45;\n\tdouble theta13_I = 8.61;\n\tdouble theta23_I = 49.3;\n\tdouble sdm_I = 7.42;\n\tdouble ldm_I = -2.497;\n\n\tswitch (EXP){\n\t\tcase 0:\n\t\t\tfor ( index_sum = 2; index_sum < 6; index_sum++ ){\n\t\t\t\tsum_y += data_info_dune[index_sum];\n\t\t\t}\n\t\t\tdarray = malloc( data_info_dune[0] * sum_y * sizeof(double));\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tfor ( index_sum = 2; index_sum < 6; index_sum++ ){\n\t\t\t\tsum_y += data_info_t2hk[index_sum];\n\t\t\t}\n\t\t\tdarray = malloc( data_info_t2hk[0] * sum_y * sizeof(double));\n\t\t\tbreak;\n\t\tcase -1:\n\t\t\tfor ( index_sum = 2; index_sum < 10; index_sum++ ){\n\t\t\t\tsum_y += data_info_all[index_sum];\n\t\t\t}\n\t\t\tdarray = malloc( data_info_all[0] * sum_y * sizeof(double));\n\t\t\tbreak;\n\t}\n\n\t//\u6839\u64daCP\u3001MO\u7684\u5047\u8a2d\uff0c\u751f\u6210Poisson Sample\uff0c\u8a08\u7b97\u5176test statistic\n\t/* \u5b9a\u7fa9glb_params */\n\tglb_params test_values_cpc_0_NO  = glbAllocParams(); \n\tglb_params test_values_cpc_0_IO  = glbAllocParams(); \n\tglb_params test_values_cpc_pi_NO = glbAllocParams(); \n\tglb_params test_values_cpc_pi_IO = glbAllocParams(); \n\tglb_params test_values_cpv_NO    = glbAllocParams(); \n\tglb_params test_values_cpv_IO    = glbAllocParams();     \n\tglb_params input_errors = glbAllocParams(); \n\tglb_params minimum = glbAllocParams(); //////////\n\n\t/* \u5b9a\u7fa9test_values_cpc_0_NO */ \n\tglbDefineParams(test_values_cpc_0_NO, theta12_N*degree, theta13_N*degree, theta23_N*degree, 0*degree, 1e-5*sdm_N, 1e-3*ldm_N);\n\tglbSetDensityParams(test_values_cpc_0_NO,1.0,GLB_ALL);\n\n\t/* \u5b9a\u7fa9test_values_cpc_0_IO */ \n\tglbDefineParams(test_values_cpc_0_IO, theta12_I*degree, theta13_I*degree, theta23_I*degree, 0*degree, 1e-5*sdm_I, 1e-3*ldm_I);\n\tglbSetDensityParams(test_values_cpc_0_IO,1.0,GLB_ALL);\n\n\t/* \u5b9a\u7fa9test_values_cpc_pi_NO */ \n\tglbDefineParams(test_values_cpc_pi_NO, theta12_N*degree, theta13_N*degree, theta23_N*degree, 180*degree, 1e-5*sdm_N, 1e-3*ldm_N);\n\tglbSetDensityParams(test_values_cpc_pi_NO,1.0,GLB_ALL);      \n\n\t/* \u5b9a\u7fa9test_values_cpc_pi_IO */ \n\tglbDefineParams(test_values_cpc_pi_IO, theta12_I*degree, theta13_I*degree, theta23_I*degree, 180*degree, 1e-5*sdm_I, 1e-3*ldm_I);\n\tglbSetDensityParams(test_values_cpc_pi_IO,1.0,GLB_ALL);\n\n\t/* \u5b9a\u7fa9test_values_cpv_NO */                                                         //deltacp\u70baInput\u7684\u503c\n\tglbDefineParams(test_values_cpv_NO, theta12_N*degree, theta13_N*degree, theta23_N*degree, deltacp*degree, 1e-5*sdm_N, 1e-3*ldm_N);\n\tglbSetDensityParams(test_values_cpv_NO,1.0,GLB_ALL);\n\n\t/* \u5b9a\u7fa9test_values_cpv_IO */                                                         //deltacp\u70baInput\u7684\u503c\n\tglbDefineParams(test_values_cpv_IO, theta12_I*degree, theta13_I*degree, theta23_I*degree, deltacp*degree, 1e-5*sdm_I, 1e-3*ldm_I);\n\tglbSetDensityParams(test_values_cpv_IO,1.0,GLB_ALL);\n\n\t/* \u8a2d\u5b9aProjection */   \n\tglb_projection projection_cp_fixed = glbAllocProjection();\n\tglb_projection projection_cp_free  = glbAllocProjection();\n\n\t//GLB_FIXED/GLB_FREE                      theta12    theta13  theta23    deltacp     m21        m31\n\tglbDefineProjection(projection_cp_fixed, GLB_FIXED, GLB_FREE, GLB_FREE, GLB_FIXED, GLB_FIXED, GLB_FREE);//deltacp theta12 m21 \u4e0d\u52d5\uff0c\u5176\u4ed6\u53ef\u8b8a\n\tglbSetDensityProjectionFlag(projection_cp_fixed,GLB_FIXED,GLB_ALL);//matter density\u4e0d\u8b8a\n\n\t//GLB_FIXED/GLB_FREE                      theta12    theta13  theta23    deltacp     m21        m31\n\tglbDefineProjection(projection_cp_free,  GLB_FIXED, GLB_FREE, GLB_FREE, GLB_FREE, GLB_FIXED, GLB_FREE);// theta12 m21 \u4e0d\u52d5\uff0c\u5176\u4ed6\u53ef\u8b8a\n\tglbSetDensityProjectionFlag(projection_cp_free,GLB_FIXED,GLB_ALL);//matter density\u4e0d\u8b8a\n\n\n\t/* \u95dc\u9589\u7cfb\u7d71\u8aa4\u5dee */   \n\tglbSwitchSystematics(GLB_ALL,GLB_ALL,GLB_OFF);\n\n\t/* \u8a2d\u5b9aInput_errors */  \n\tglbDefineParams(input_errors,0,0,0,0,0,0);\n\tglbSetDensityParams(input_errors,0,GLB_ALL);\n\tglbSetInputErrors(input_errors);\n    \n\t/* \u6839\u64daMO,CP\u7684\u5047\u8a2d\uff0c\u751f\u6210 Poisson Spectrum */ \n\tswitch (MO) {\n\t\tcase 1:\t\n\t  \t\tif (CP == 0){ //CPC at deltacp=0\n\t\t\t\tprintf(\"\u751f\u6210deltacp = 0, NO \u7684Poisson Spectrum \\n\");\n\t\t\t\t/* \u6839\u64daCPC_0_NO\u7684\u5047\u8a2d\uff0c\u751f\u6210Poisson True Spectrum */   \n\t\t\t\tdo_poisson_fluctuation(test_values_cpc_0_NO, EXP, darray, dset_y_info);\n\t\t\t}\n\t  \t\tif (CP == 180){ //CPC at deltacp=180\n\t\t\t\tprintf(\"\u751f\u6210deltacp = 180, NO \u7684Poisson Spectrum \\n\");\n\t\t\t\t/* \u6839\u64daCPC_0_IO\u7684\u5047\u8a2d\uff0c\u751f\u6210Poisson True Spectrum */   \n\t\t  \t\tdo_poisson_fluctuation(test_values_cpc_pi_NO, EXP, darray, dset_y_info);\n\t\t\t}\n\t  \t\tif (CP == 1){ //CPV\n\t\t\t\tprintf(\"\u751f\u6210deltacp = input value, NO \u7684Poisson Spectrum \\n\");\n\t\t\t\t/* \u6839\u64daCPV_NO\u7684\u5047\u8a2d\uff0c\u751f\u6210Poisson True Spectrum */   \n\t\t\t\tdo_poisson_fluctuation(test_values_cpv_NO, EXP, darray, dset_y_info);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase -1:\t\n\t  \t\tif (CP == 0){ //CPC at deltacp=0\n\t\t\t\tprintf(\"\u751f\u6210deltacp = 0, IO \u7684Poisson Spectrum \\n\");\n\t\t\t\t/* \u6839\u64daCPC_0_NO\u7684\u5047\u8a2d\uff0c\u751f\u6210Poisson True Spectrum */   \n\t\t  \t\tdo_poisson_fluctuation(test_values_cpc_0_IO, EXP, darray, dset_y_info);\n\t\t\t}\n\t  \t\tif (CP == 180){ //CPC at deltacp=180\n\t\t\t\tprintf(\"\u751f\u6210deltacp = 180, IO \u7684Poisson Spectrum \\n\");\n\t\t\t\t/* \u6839\u64daCPC_0_IO\u7684\u5047\u8a2d\uff0c\u751f\u6210Poisson True Spectrum */   \n\t\t  \t\tdo_poisson_fluctuation(test_values_cpc_pi_IO, EXP, darray, dset_y_info);\n\t\t\t}\n\t  \t\tif (CP == 1){ //CPV\n\t\t\t\tprintf(\"\u751f\u6210deltacp = input value, IO \u7684Poisson Spectrum \\n\");\n\t\t\t\t/* \u6839\u64daCPV_IO\u7684\u5047\u8a2d\uff0c\u751f\u6210Poisson True Spectrum */   \n\t\t  \t\tdo_poisson_fluctuation(test_values_cpv_IO, EXP, darray, dset_y_info);\n\t\t\t}\n\t\t\tbreak;\n\t}\n \n\t/* \u8a08\u7b97CPC Hypothesis (4\u7a2e\u60c5\u6cc1)*/\n\n\t/* \u8a2d\u5b9aPrior (3 sigma range, Normal Ordering)*/\n\tglbRegisterPriorFunction(prior_3sigma_NO,NULL,NULL,NULL);\n\n\t/* \u8a08\u7b97Chi square under cpc_0_NO */ \n\tglbSetProjection(projection_cp_fixed); //\u8a2d\u5b9aProjection deltacp_Fixed\n\tglbSetOscillationParameters(test_values_cpc_0_NO);\n\tglbSetRates();\n\tglbDefineChiFunction(&chi2_poisson, 0, \"chi2_poisson\", darray);\n\tglbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, \"chi2_poisson\", NULL);\n\tglbSetCentralValues(test_values_cpc_0_NO); \n\tchi_0_NO = glbChiNP(test_values_cpc_0_NO, minimum ,EXP);\n\n\t/* \u8a08\u7b97Chi square under cpc_pi_NO */ \n\tglbSetProjection(projection_cp_fixed); //\u8a2d\u5b9aProjection deltacp_Fixed\n\tglbSetOscillationParameters(test_values_cpc_pi_NO);\n\tglbSetRates();\n\tglbDefineChiFunction(&chi2_poisson, 0, \"chi2_poisson\", darray);\n\tglbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, \"chi2_poisson\", NULL);\n\tglbSetCentralValues(test_values_cpc_pi_NO); \n\tchi_pi_NO = glbChiNP(test_values_cpc_pi_NO, minimum ,EXP);\n\n\t/* \u8a2d\u5b9aPrior (3 sigma range, Inverse Ordering)*/\n\tglbRegisterPriorFunction(prior_3sigma_IO,NULL,NULL,NULL);\n\n\t/* \u8a08\u7b97Chi square under cpc_0_IO */ \n\tglbSetProjection(projection_cp_fixed); //\u8a2d\u5b9aProjection deltacp_Fixed\n\tglbSetOscillationParameters(test_values_cpc_0_IO);\n\tglbSetRates();\n\tglbDefineChiFunction(&chi2_poisson, 0, \"chi2_poisson\", darray);\n\tglbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, \"chi2_poisson\", NULL);\n\tglbSetCentralValues(test_values_cpc_0_IO); \n\tchi_0_IO = glbChiNP(test_values_cpc_0_IO, minimum ,EXP);\n\n\t/* \u8a08\u7b97Chi square under cpc_pi_IO */ \n\tglbSetProjection(projection_cp_fixed); //\u8a2d\u5b9aProjection deltacp_Fixed\n\tglbSetOscillationParameters(test_values_cpc_pi_IO);\n\tglbSetRates();\n\tglbDefineChiFunction(&chi2_poisson, 0, \"chi2_poisson\", darray);\n\tglbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, \"chi2_poisson\", NULL);\n\tglbSetCentralValues(test_values_cpc_pi_IO); \n\tchi_pi_IO = glbChiNP(test_values_cpc_pi_IO, minimum ,EXP);\n\n\t/* \u53d6 chi_0_NO , chi_pi_NO, chi_0_IO , chi_pi_IO  \u56db\u8005\u4e4b\u6700\u5c0f\u503c */   \n\ta = min(4, chi_0_NO, chi_pi_NO, chi_0_IO, chi_pi_IO);\n          \n\t/* \u8a08\u7b97CPV Hypothesis (2\u7a2e\u60c5\u6cc1)*/      \n\n\t/* \u8a2d\u5b9aPrior (3 sigma range, Normal Ordering)*/\n\tglbRegisterPriorFunction(prior_3sigma_NO, NULL, NULL, NULL);\n\n\t/* \u8a2d\u5b9aProjection (deltacp_Free)*/  \n\tglbSetProjection(projection_cp_free);\n\n\t/* \u8a08\u7b97Chi square under cpv_NO */ \n\tglbSetOscillationParameters(test_values_cpv_NO);\n\tglbSetRates();\n\tglbDefineChiFunction(&chi2_poisson, 0, \"chi2_poisson\", darray);\n\tglbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, \"chi2_poisson\", NULL);\n\tglbSetCentralValues(test_values_cpv_NO); \n\tchi_cpv_NO = glbChiNP(test_values_cpv_NO, minimum, EXP);\n\t\t                                                    \n\n\t/* \u8a2d\u5b9aPrior (3 sigma range, Inverse Ordering)*/\n\tglbRegisterPriorFunction(prior_3sigma_IO, NULL, NULL, NULL);\n\n\t/* \u8a2d\u5b9aProjection (deltacp_Free)*/  \n\tglbSetProjection(projection_cp_free);\n    \n\t/* \u8a08\u7b97Chi square under cpv_IO */ \n\tglbSetOscillationParameters(test_values_cpv_IO);\n\tglbSetRates();\n\tglbDefineChiFunction(&chi2_poisson, 0, \"chi2_poisson\", darray);\n\tglbSetChiFunction(GLB_ALL, GLB_ALL, GLB_OFF, \"chi2_poisson\", NULL);\n\tglbSetCentralValues(test_values_cpv_IO); \n\tchi_cpv_IO = glbChiNP(test_values_cpv_IO, minimum, EXP);\n\n\t/* \u53d6 chi_cpv_NO , chi_cpv_IO  \u5169\u8005\u4e4b\u6700\u5c0f\u503c */   \n\tb = min(2, chi_cpv_NO, chi_cpv_IO);\n\n\t/* \u8f38\u51faDelta Chi square */ \n\tprintf(\"a = %g, b = %g  \\n\",a,b);\n\tprintf(\"a - b = %g  \\n\",a-b);\n\tfree(darray);\n\treturn a-b;\n}\n\n\nint main(int argc, char *argv[]) { \n\n\tchar   filename[32];\n\tstrcpy(filename, argv[1]);\n\tint    TOTALsample = atof(argv[2]);\n\tdouble angle       = atof(argv[3]);\n\tint    expr        = atof(argv[4]);\n\n\t/*\n     * Declare the variables for hdf5.\n     */\n\thid_t\t\tfile_id, \n\t\t\t\tspace_id, \n\t\t\t\tdset_id,\n\t\t\t\tgroup_id,\n\t\t\t\tsub_group_id;\n\therr_t\t\tstatus;\n\thsize_t\t\tdims_q0[2] = {TOTALsample, 4}, \n\t\t\t\tdims_q1[1] = {TOTALsample};\n\t\n\n\tglbInit(argv[0]);\n\tglbInitExperiment(\"./DUNE2021/DUNE_GLoBES.glb\",&glb_experiment_list[0],&glb_num_of_exps);\n\tglbInitExperiment(\"./HK_globes/HK_combined_coarse.glb\",&glb_experiment_list[0],&glb_num_of_exps);\n\n\tprintf(\"File name: %s\\n\",filename);\n\n\tdouble \tq0,  q1;\n\tdouble \tQ0[TOTALsample][4], \n\t\t\tQ1[TOTALsample];\n\tfor (int num_simulatiom = 0; num_simulatiom < TOTALsample; num_simulatiom++) { \n\t\tq0 = delta_chi2(0 , 1 , angle, expr); \n\t\tQ0[num_simulatiom][0] = q0;\n\n\t\tq0 = delta_chi2(180, 1 , angle, expr);\n\t\tQ0[num_simulatiom][1] = q0; \n\n\t\tq0 = delta_chi2(0, -1 , angle, expr);\n\t\tQ0[num_simulatiom][2] = q0;\n\n\t\tq0 = delta_chi2(180, -1 , angle, expr);\n\t\tQ0[num_simulatiom][3] = q0;\n\n\t\tq1 = delta_chi2(1 , 1, angle, expr);\n\t\tQ1[num_simulatiom] = q1;\n\t}\n\n\tfile_id   \t= \tH5Fcreate(filename, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n\tspace_id  \t=  \tH5Screate_simple(2, dims_q0, NULL);\n\tdset_id    \t=  \tH5Dcreate(file_id, \"q0\", H5T_NATIVE_DOUBLE, space_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n\tstatus     \t=  \tH5Dwrite(dset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, Q0);\n\tstatus    \t=  \tH5Dclose(dset_id);\n\tstatus    \t=  \tH5Sclose(space_id);\n\t\n\tspace_id  \t=  \tH5Screate_simple(1, dims_q1, NULL);\n\tdset_id    \t=  \tH5Dcreate(file_id, \"q1\", H5T_NATIVE_DOUBLE, space_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n\tstatus     \t=  \tH5Dwrite(dset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, Q1);\n\tstatus    \t=  \tH5Dclose(dset_id);\n\tstatus    \t=  \tH5Sclose(space_id);\n\tstatus     \t=  \tH5Fclose(file_id);\n\treturn 0;  \n}\n\n", "meta": {"hexsha": "64829f2d8c97c24141d299e0ab14456c129d99e6", "size": 20646, "ext": "c", "lang": "C", "max_stars_repo_path": "script/simulation/poisson.c", "max_stars_repo_name": "davidho27941/ML4NO", "max_stars_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/simulation/poisson.c", "max_issues_repo_name": "davidho27941/ML4NO", "max_issues_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/simulation/poisson.c", "max_forks_repo_name": "davidho27941/ML4NO", "max_forks_repo_head_hexsha": "5d9c6312180c06dfb9cb85bd28a40457849204d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T16:25:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T16:25:35.000Z", "avg_line_length": 31.8611111111, "max_line_length": 134, "alphanum_fraction": 0.6690884433, "num_tokens": 7542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3500375703179442}}
