{"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 \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \"Rand.h\"\n#include \n#include \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& data, double& ave, double& squareave, double& var);\n\nvoid Statistics(const vector& data, double& max, double& min, double& ave, double& var, double& error);\nvoid Statistics(const vector& data, double& max, double& min, double& ave, double& var, double& error);\nvoid Statistics(const vector& data, double& xmax, double& xmin, double& xave, double& xvar, double& xerror, double& x2ave);\n\n//void Statistics(const vector& data, double& xmax, double& xmin, double& xave, double& xvar, double& xerror, double& x2ave, double& x1inverseave);\n\nvoid Statistics(const vector& 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& data, double &ave, double &adev, double &sdev, double &var, double &skew, double &curt);\n\nvoid StatisticalDispersion(vector& X, double& H7, double& H8, double& H9, double& H10);\n\ndouble GetXsecondmin(const vector& data, double Xmin);\n\nvoid Statistics(const vector& 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& data, int B, vector& Binsize, vector& Q);\nint GetBinIndex(const double& x, const vector& 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 \n#include \n#include \n#include \n#include \n#include \n#include \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; iEdgtoEls[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; kWD[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 __LLVUTILS_H__\n#define __LLVUTILS_H__ 1\n\n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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=1?\"resonance\":\"non-resonance\"));\n\n fprintf(stderr, \"orbital parameters of outermost binaries:\\n\");\n for (j=0; jn >= 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": "#include \n#include \n#include \n#include \n#include \n#include \"hdf5.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mclib_3d.h\"\n//#include \"mclib.h\"\n#include \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;i98784000-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 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 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 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;ir0), 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\n#include \n#include \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": "/*\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 \n#include \n#include \n#include \n#include \n#include \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": "#ifndef __CNN_CONV_H__\n#define __CNN_CONV_H__\n\n#include \n#include \n\n#include \"cnn_macro.h\"\n#include \"cnn_types.h\"\n\n#ifdef CNN_WITH_CUDA\n#include \n#include \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": "/* 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 \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \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, µ, 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, µ);\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, µ, 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 = ¶ms;\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, ¶ms);\n double rmax = dEdt(Thetae_hi, ¶ms);\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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(\"█\");\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(\"█\");\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 \n#include \n#include \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": "/* 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 π / \\p lx,2 π / \\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 *\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 \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 Mworld_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 Mhouseholder == 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; iN, 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(MN, 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(Mworld_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#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \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 \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 [ ]\", 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": "/* 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 \n#include \n#include \n#include \n#include \n#include \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 \n\n// Prefer MKL if available:\n#ifdef DDM_ENABLE_MKL\n#include \n#include \n#include \n#include \n#include \n// BLAS support:\n#elif defined(DDM_ENABLE_BLAS)\nextern \"C\"\n{\n #include \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\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\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\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 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,\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(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(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 get_a;\n ddm::Future 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(\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(\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(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(\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\n * to \\c ddm::summa\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::satisfied::value &&\n summa_pattern_constraints::satisfied::value &&\n summa_pattern_constraints::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": "/* 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 \n#include \n#include \n#include \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": "#include \n\n//#ifndef DARWIN \n//#include \n//#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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; isize1; 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; isize1);\n \n for (i=0; isize1);\n\n//for (l=0; l<1; l++){ //DELETE\n\n //Inserting values into matricies and vectors\n for (i=0; isize1);\n\n //Inserting values into matricies and vectors\n for (i=0; isize1);\n\n // INITIALISE GROUP MATRICES\n for (i=0; isize1);\n\n //printf(\"Memory allocated\\n\");\n for (star_count=0; star_countdata, 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 \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \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 \n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#else\n#include \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 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 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 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 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 \n#include \n#include \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": "/* 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 \n#include \n#include \n#include \n#include \n#include \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; nuk, 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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= 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 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= 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= 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= 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= 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#include \n#include \n#include \n#include \n#include // for int limits etc.\n#include \n#include \n#include \n#include \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<= 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 \n//#include \n//#include \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_xkernel_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_xn_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_elln_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_elln_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_elln_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->statusstatus = 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_elln_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": "/* 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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= 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= 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= 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 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\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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;ito=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;isoft_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;ito=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;iseeds;\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;jto;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;jto;j++) G_s[data->M*seeds[j] +j]+= data->tel_prob; \n\t\t}\n\t}while(iterM, data->from, data->to) >TOL);\n\n\tif(flag==1){\n\t\tfor(sz_long i=0;ifrom;jto;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 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\n//#include \n#include \n#include \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\nvoid dump_point(std::ostream & out, Point const& point)\n{\n out << boost::geometry::wkt(point);\n}\n\ntemplate\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\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 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\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 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 distribution(((double)cur_subtree_size) / total_subtree_size, total_sample_size);\n std::binomial_distribution 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(\n total_sample_size,\n ((double)cur_subtree_size) / total_subtree_size\n )(rng);\n*/\n}\n\ntemplate\ninline\nvoid\nnext_sample_size_bulk(int trials, const std::vector &prefix_weights, std::vector &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 each_trial;\n //each_trial.resize(trials);\n\n //std::uniform_int_distribution 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 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": "/**\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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": "/**\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 \n#include \n#include \n#include \n#include \n\n#include \n#include \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** hemodynamic modelling for single-subject LISA\n**\n** G.Lohmann, MPI-KYB, 2018\n*/\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \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; isize1; i++) {\n for (j=0; jsize2; 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; isize2; i++) {\n for (j=0; jsize1; 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; isize; 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; isize1; i++) {\n fprintf(fp,\" %8.2f\",t);\n for (j=0; jsize2; 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= 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= 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; jsize1; 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; jsize1; 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; jsize1; 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; isize2; i++) {\n for (j=0; jsize1; 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 \n#include \n#include \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; l0u; --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; l0u; --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; l0u; --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; l0u; --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; l0u; --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; l0u; --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; l0u; --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; l0u; --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 \n#include \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": "/*\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 \n#include \n#include \n#include \n#include \n#include \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 \n#endif\n\n#ifdef OpenBLAS_AVAILABLE\n#include \n#endif\n\n#include \n#include \n#include \n#include \ntemplate\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 \n int sgn(const T val) const {\n return (T(0) < val) - (val < T(0));\n }\n\n using MatrixType_ = Eigen::Matrix;\n using VectorType_ = Eigen::Matrix;\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 HA_MPO;\n Eigen::Tensor HB_MPO;\n Eigen::Tensor Lblock;\n Eigen::Tensor Rblock;\n Eigen::Tensor Lblock2;\n Eigen::Tensor Rblock2;\n\n Eigen::Tensor HAHB;\n Eigen::Tensor HAHB2;\n Eigen::DSizes dsizes;\n class_tic_toc t_lbfgs;\n class_xDMRG_full_functor(\n const Eigen::Tensor &HA_MPO_,\n const Eigen::Tensor &HB_MPO_,\n const Eigen::Tensor &Lblock_,\n const Eigen::Tensor &Rblock_,\n const Eigen::Tensor &Lblock2_,\n const Eigen::Tensor &Rblock2_,\n const Eigen::DSizes &dsizes_\n );\n\n double get_vH2v(const Eigen::Matrix &v);\n double get_vHv(const Eigen::Matrix &v);\n Eigen::VectorXd get_vH2 (const Eigen::Matrix &v);\n Eigen::VectorXd get_vH (const Eigen::Matrix &v);\n double operator()(const Eigen::Matrix &v, Eigen::Matrix &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 \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 0.0) || (survey_area[2] > 0.0))) {\n for (i=0; i 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 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 = ¶ms;\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 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 = ¶ms;\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 0) {\n for (i=0; i 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 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 = ¶ms;\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 0) {\n for (i=0; i 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 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 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\n#include \n#include \n#include \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ÇÃO */\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ÇÃO 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ÇÃO 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ÇÃO 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ÇÕES */\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 \n#include \n#include \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, &l);\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 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 __MATH_GSL_MATRIX__\n#define __MATH_GSL_MATRIX__\n\n#include \n#include \n#include \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 \n#include \n#include \n#include \"compearth.h\"\n/*\n#ifdef COMPEARTH_USE_MKL\n#include \n#else\n#include \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 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 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\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \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 \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __APPLE__\n\n#include \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 \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": "/* 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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#ifdef WITH_OPENMP\n\n#include \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": "#include \n#include \n#include \n#include \n#include \n\n#ifdef _MACOSX\n#include \n#else\n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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; iDIM)-i,j,k)]);\n }\n }\n\n // all of j\n for (j=1; jDIM)-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; jDIM)-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; iN_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_xDIM; 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_yDIM; 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; iDIM; i++){\n for (j=0; jDIM; j++){\n for (k=0; kDIM; 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; iHII_DIM; i++){\n for (j=0; jHII_DIM; j++){\n for (k=0; kHII_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_xDIM; 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_yDIM; 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; iHII_DIM; i++){\n for (j=0; jHII_DIM; j++){\n for (k=0; kHII_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; iHII_DIM; i++){\n for (j=0; jHII_DIM; j++){\n for (k=0; kHII_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_xDIM; 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_yDIM; 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; iPERTURB_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; iDIM; i++){\n for (j=0; jDIM; j++){\n for (k=0; kDIM; 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_xDIM; 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_yDIM; 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; iDIM; i++){\n for (j=0; jDIM; j++){\n for (k=0; kDIM; 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_xDIM; 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_yDIM; 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; iDIM; i++){\n for (j=0; jDIM; j++){\n for (k=0; kDIM; 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; iDIM; i++){\n for (j=0; jDIM; j++){\n for (k=0; kDIM; 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_xDIM; 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_yDIM; 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; iPERTURB_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; iN_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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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; jOrbitR/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; jnext;\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; jnext;\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; ifreq;\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; jfreq;\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; jOrbitOmega*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": "/*\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 \n#include \n#include \n#include \n#include \n#include \n#include \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 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 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\n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace rev {\n\ntemplate \nstruct Triangle {\n std::array 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 clippedBoundingBox(const AxisAlignedBoundingBox& box)\n {\n // Alternate between these two buffers for input and output\n std::array buf1{};\n std::array 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 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 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 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 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::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 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 \nstruct LeafNode {\n std::unordered_set*> triangles;\n};\n\ntemplate \nstruct BranchNode;\n\ntemplate \nusing MapNode = std::variant, BranchNode>;\n\ntemplate \nstruct BranchNode {\n AxisAlignedPlane split;\n\n std::unique_ptr> left;\n std::unique_ptr> right;\n};\n\ntemplate \nclass KDTree {\npublic:\n KDTree(std::vector>> triangles,\n std::unique_ptr> 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* triangle;\n glm::vec2 uv;\n float t;\n };\n\n std::optional castRay(\n const Ray& ray, float maxDistance = std::numeric_limits::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 \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), _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 getHit(const MapNode& 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 getHit(const BranchNode& 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* 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 getHit(const LeafNode& node, const Ray& ray,\n const AxisAlignedBoundingBox& box, AxisAlignedBoundingBox::Hit& entryPoint,\n float maxDistance) const\n {\n float t = std::numeric_limits::infinity();\n std::optional 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 \n void visitTrianglesIntersectingSphereInNode(const Sphere& sphere, Visitor&& visitor,\n const AxisAlignedBoundingBox& box, const LeafNode& 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 \n void visitTrianglesIntersectingSphereInNode(const Sphere& sphere, Visitor&& visitor,\n const AxisAlignedBoundingBox& box, const BranchNode& 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), 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), 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& 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& 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& 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>> _triangles;\n std::unique_ptr> _root;\n AxisAlignedBoundingBox _boundingBox;\n};\n\ntemplate \nclass KDTreeBuilder {\npublic:\n void addTriangle(std::array 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{ 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 build()\n {\n Expects(!_triangles.empty());\n Expects(!_events.empty());\n\n std::unordered_set*> 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{ 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* triangle;\n AxisAlignedPlane separationPlane;\n Type type;\n };\n\n std::unique_ptr> createNode(const AxisAlignedBoundingBox& box,\n std::set events, std::unordered_set*> 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(triangleCount) * kIntersectionCost;\n if (terminateCost > cost) {\n std::unordered_set*> leftTriangles;\n std::unordered_set*> 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 leftEvents;\n std::set 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>(BranchNode{\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>(\n LeafNode{ std::move(triangles) });\n }\n\n std::set buildTriangleEvents(\n const AxisAlignedBoundingBox& boundingBox, Triangle* triangle)\n {\n AxisAlignedBoundingBox actualBox = triangle->getBoundingBox();\n std::set 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 findBestSplit(\n const AxisAlignedBoundingBox& box, const std::set& events, size_t triangleCount)\n {\n float bestCost = std::numeric_limits::infinity();\n AxisAlignedPlane bestPlane;\n Side bestSide;\n\n std::array leftTriangleCounts{ 0 };\n std::array 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 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(leftTriangleCount) * leftArea\n + static_cast(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>> _triangles;\n std::set _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": "/* 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 \n#include \n#include \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 \n#include \n#include \n#include \n\n#include \n\n// ****************************************************************************\n// Struct for partial template specialization\n// ****************************************************************************\n\ntemplate\nstruct Syrk {\n static void apply(DTRes *& res, const DTArg * arg, DCTX(ctx)) = delete;\n};\n\n// ****************************************************************************\n// Convenience function\n// ****************************************************************************\n\ntemplate\nvoid syrk(DTRes *& res, const DTArg * arg, DCTX(ctx)) {\n Syrk::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> {\n static void apply(DenseMatrix *& res, const DenseMatrix * 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>(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> {\n static void apply(DenseMatrix *& res, const DenseMatrix * 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>(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\nstruct Syrk, CSRMatrix> {\n static void apply(CSRMatrix *& res, const CSRMatrix * 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>(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": "/* 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 \n#include \n#include \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 \n#include \n#include \n\n#include \n#include \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": "/* 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 \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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \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; inbmode, 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; inbmode; 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": "#ifndef _fim_h_included_\n#define _fim_h_included_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \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 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 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 const & I) {\n\t\t\tassert(I.size1() == I.size2());\n\t\t\tL_(debug) << I;\n\t\t\tublas::matrix inv =\n\t\t\t\tublas::zero_matrix(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 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 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 bruteforce_fim(shared_ptr readp,\n\t\t\t\tvector const & iso_probs) {\n\t\t\tL_(debug) << \"FIM::bruteforce_fim\";\n\t\t\treset_ofim_call_count();\n\t\t\tshared_ptr ars = readp->get_ARS();\n\t\t\tunsigned long K = ars->get_num_isoforms();\n\t\t\tublas::matrix I = ublas::zero_matrix(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 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 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 fast_fim(shared_ptr readp,\n\t\t\t\tvector const & iso_probs) {\n\t\t\tL_(debug) << \"FIM::fast_fim\";\n\t\t\treset_ofim_call_count();\n\t\t\tshared_ptr ars = readp->get_ARS();\n\t\t\tunsigned long K = ars->get_num_isoforms();\n\t\t\tublas::matrix I = ublas::zero_matrix(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 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 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 faster_fim(shared_ptr readp,\n\t\t\t\tvector const & iso_probs) {\n\t\t\tL_(debug) << \"FIM::faster_fim\";\n\t\t\treset_ofim_call_count();\n\t\t\tshared_ptr ars = readp->get_ARS();\n\t\t\tunsigned long K = ars->get_num_isoforms();\n\t\t\tublas::matrix I = ublas::zero_matrix(K-1, K-1);\n\t\t\tvector > covered_sample_starts;\n\t\t\tfor (unsigned long k = 0; k < K; ++k) {\n\t\t\t\tinterval_list 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 sign;\n\t\t\t\t\tublas::matrix 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 ofim(shared_ptr readp,\n\t\t\t\tvector const & iso_probs,\n\t\t\t\tublas::matrix & sign) {\n\t\t\t++ofim_call_count;\n\t\t\tshared_ptr ars = readp->get_ARS();\n\t\t\tunsigned long K = ars->get_num_isoforms();\n\t\t\tublas::matrix m = ublas::zero_matrix(K-1,K-1);\n\t\t\tsign = ublas::zero_matrix(K-1, K-1);\n\t\t\tvector 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": "#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 \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 \n#include \n#include \n#include \n#include \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": "/* ============================================================ *\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 \n#include \n#include \n#include \n#include \n#include \n\n\n#include \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 *\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 \n#include \n#include \n#include \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 \n#include \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": "#include \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 \n#include \n#include \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 = rR ? 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 = rR ? 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(++itergrsolve);\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": "/* 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nstruct mass_eff_scalar_density_params\n{\n vector scalar_coeff;\n vector scalar_exp;\n double number_density;\n double nucleon_mass;\n double degeneracy;\n double temperature;\n vector vec_coeff;\n vector 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 scalar_exp;\n vector vec_exp;\n unsigned int* terms;\n};\n//struct for the parameters for finding the critical point\nstruct crit_params\n{\n vector scalar_coeff;\n vector scalar_exp;\n vector vec_coeff;\n vector 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 get_mass_eff_scalar_density(double degeneracy, double nucleon_mass,vector scalar_coeff ,vector 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 get_T_mass_eff_mu_eff_scalar_density(vector scalar_coeff, vector scalar_exp, vector vec_coeff, vector 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 get_coeff(double nucleon_mass, double saturation_density, double binding_energy, double degeneracy, vector scalar_exp, vector vec_exp, bool print, unsigned int terms[2], bool * success=NULL);\nint crit_root(const gsl_vector * x, void *params, gsl_vector * f);\npair get_crit(double nucleon_mass,double saturation_density, double binding_energy, double degeneracy, vector scalar_exp, vector vec_exp, bool print, double crit_T=19.09, double crit_density=540000, vector scalar_coeff={0.0}, vector 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 get_interaction_4D(void * p, bool print,vector init_exp={2.05,2.05},vector 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, vector, bool> get_interaction_2crit(void * p, bool print,vector init_exp={2.05,2.05,3,3},vector 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 scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp);\ndouble energy_pp_minus_mass_dn_solv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp);\ndouble press_solv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp);\ndouble press_dn_solv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp);\ndouble incsolv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp,double delta=1);\ndouble T_press_solv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp, double temperature);\ndouble T_press_dmu_solv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp, double temperature, double delta=1.);\ndouble T_press_dT_solv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp, double temperature, double delta=1e-2);\ndouble T_press_dn_solv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp, double temperature, double delta=1e3);\ndouble T_press_dn2_solv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp,double temperature, double delta=1e3);\npair T_press_dn12_solv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp, double temperature, double delta=1e3);\ndouble T_eps_solv(double degeneracy, double nucleon_mass,double number_density,vector scalar_coeff,vector scalar_exp, vector vec_coeff, vector vec_exp, double temperature);\nvoid gsl_handler (const char * reason, const char * file, int line, int gsl_errno);\nbool validate_interaction(double error, vector coeff_guess, vector exp_guess,vector coeff, vector 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érémy 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 // For the Cholesky decomposition\n#include \n#include \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\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": "/**\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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 /* 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; isize != 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; ifreq->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; ifreqseries->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; ifreq->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; ifreq->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; ifreq->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)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)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;iifreq->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": "\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 \n#include \n#include \n#include \n#include \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= 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 eps) {\n \n //xold=x;\n for (i=0; irank);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; ejmy; ej++) {\n nj0 = ej*(c->npe_1d-1);\n \n for (ei=0; eimx; ei++) {\n ni0 = ei*(c->npe_1d-1);\n \n emap = &c->element[c->npe*ecnt];\n \n for (j=0; jnpe_1d; j++) {\n for (i=0; inpe_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; ejmy; ej++) {\n \n for (ei=0; eimx; 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; jnpe_1d; j++) {\n for (i=0; inpe_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; jnpe_1d; j++) {\n for (i=0; inpe_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; knpe_1d-1)) == 0) {\n *si = k;\n *si_g = gi+k;\n break;\n }\n }\n for (k=0; knpe_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; ejmy; ej++) {\n nj0 = sj + ej*(c->npe_1d-1);\n \n for (ei=0; eimx; ei++) {\n ni0 = si + ei*(c->npe_1d-1);\n \n emap = &c->element[c->npe*ecnt];\n \n for (j=0; jnpe_1d; j++) {\n for (i=0; inpe_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; ejmy; ej++) {\n \n for (ei=0; eimx; 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; jnpe_1d; j++) {\n for (i=0; inpe_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; rnpe_1d - 1);\n }\n lx[ranks[0]-1]++;\n\n /*for (r=0; rnpe_1d - 1);\n }\n ly[ranks[1]-1]++;\n \n /*for (r=0; rnx_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; jnpe_1d; j++) {\n for (i=0; inpe_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; qne; 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; ene; 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; qelbuf_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; ene; e++) {\n /* get element -> node map */\n elnidx = &element[nbasis*e];\n \n \n /* generate dofs */\n for (i=0; inpe_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; qnqp; 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; ilambda;\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; idm,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; jnpe_1d; j++) {\n for (i=0; inpe_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; knpe; 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; ene; e++) {\n /* get element -> node map */\n elnidx = &element[nbasis*e];\n \n \n /* generate dofs */\n for (i=0; inqp; 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; jjnpe_1d; jj++) {\n for (ii=0; iinpe_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; jjnpe_1d; jj++) {\n for (ii=0; iinpe_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; ene; e++) {\n ierr = SpecFECtxGetDRCellData(c,e,&dr_celldata);CHKERRQ(ierr);\n }\n \n for (e=0; ene; 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; inpe_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; qnqp; 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; inqp; 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; ilambda;\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; idm,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; ene; 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; inpe_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; qnqp; 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; inqp; 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; idelta,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; ene; e++) {\n /* get element -> node map */\n elnidx = &element[nbasis*e];\n \n /* generate dofs */\n for (i=0; inpe_1d,&detJ);\n \n /* get access to element->quadrature points */\n celldata = &c->cell_data[e];\n\n for (q=0; qw[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; nnpe_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; ene; 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; qnqp; 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; nnpe; 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; jnpe_1d; j++) {\n for (i=0; inpe_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; knpe; 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; knpe; 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 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; nnpe; 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 %+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 ()\\n\");\n fprintf(fp,\"# time(1)\\n\");\n for (r=0; r 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; rmx_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; rdm,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 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; nnpe; 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 : %d\\n\",nr_local);\n fprintf(fp,\"# + takes displ/velo/accel from basis nearest to requested receiver location\\n\");\n for (r=0; r %+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 ()\\n\");\n fprintf(fp,\"# time(1)\\n\");\n\n \n for (r=0; r 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,\"# No receivers found on this sub-domain\\n\");\n fprintf(fp,\"# 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; rrank; }\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; rdm,&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; rdN_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; knpe; 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; knpe; 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 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; ene; e++) {\n PetscReal xcell[] = {0,0};\n \n elbasis = &element[c->npe*e];\n for (i=0; inpe; 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; nnpe; 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 %+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; inpe; 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 ()\\n\");\n fprintf(fp,\"# time(1)\\n\");\n for (r=0; r 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; rdim);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; kdm,&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": "/*********************\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 \n *\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \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; iv[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; ix[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 \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \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;i0) {\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 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;i1, 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( (istep;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 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 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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \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; ispline_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; ispline_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; ispline_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; ispline_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": "/**\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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": "/**\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n#include \"waveform.h\"\n#include \"LISAgeometry.h\"\n\n#include /* 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; isize; 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; isize;\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; isize;\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; isize;\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\n}\n#endif\n\n\nstruct QuantizationParams\n{\n\tfloat scale;\n\tuint8_t zero_point;\n};\n\ntemplate\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\nvoid cpu_axpy(uint64_t N, Dtype alpha, Dtype* X, Dtype* Y, Dtype* C); // c = alpha * x + y\n\ntemplate\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\nvoid cpu_mul(uint64_t N, Dtype* A_ptr, Dtype* B_ptr, Dtype* C_ptr); // c = a * b\n\ntemplate\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\nvoid cpu_mul(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha * a\n\ntemplate\nvoid cpu_add(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha + a\n\ntemplate\nvoid cpu_div(uint64_t N, Dtype* A_ptr, Dtype* B_ptr, Dtype* C_ptr); // c += a / b\n\ntemplate\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\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\nvoid cpu_sig(uint64_t N, const Dtype* A_ptr, Dtype* B_ptr); // b = sig(a)\n\ntemplate\nvoid cpu_tanh(uint64_t N, const Dtype* A_ptr, Dtype* B_ptr); // b = tanh(a)\n\ntemplate\nvoid cpu_powx(uint64_t N, const Dtype* A_ptr, Dtype x, Dtype* B_ptr); // b = pow(a,x)\n\ntemplate\nvoid cpu_copy(uint64_t N, Dtype* A_ptr, Dtype* B_ptr); // b = a\n\ntemplate\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\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\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\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\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\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\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\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\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\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\nvoid cpu_dropout(Dtype* dst, Dtype* src, unsigned int* mask, unsigned int threshold, Dtype scale, uint64_t len);\n\ntemplate\nvoid cpu_sig_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels);\n\ntemplate\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\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\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\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\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\nvoid gpu_mul(uint64_t N, Dtype alpha, Dtype* A, Dtype* B, Dtype beta, Dtype* C); // c = beta * c + alpha * a * b\n\ntemplate\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\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\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\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\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\nvoid gpu_sum(Dtype* data, Dtype* sum, uint64_t len);\n\ntemplate\nvoid gpu_nll(Dtype* input, Dtype* target, Dtype* loss, uint64_t len, uint64_t batches);\n\ntemplate\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\nvoid gpu_fill(Dtype* memory, uint64_t size, Dtype value);\n\ntemplate\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\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\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\nvoid gpu_powx(uint64_t N, const Dtype* A, Dtype x, Dtype* B); // b = pow(a,x)\n\ntemplate\nvoid gpu_exp(Dtype* dst, const Dtype* src, const uint64_t numels);\n\ntemplate\nvoid gpu_log(Dtype* dst, const Dtype* src, const uint64_t numels);\n\ntemplate\nvoid gpu_sig(Dtype* dst, const Dtype* src, const uint64_t numels);\n\ntemplate\nvoid gpu_sig_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels);\n\ntemplate\nvoid gpu_tanh(Dtype* dst, const Dtype* src, const uint64_t numels);\n\ntemplate\nvoid gpu_tanh_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels);\n\ntemplate\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\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\nvoid gpu_add(uint64_t N, Dtype alpha, Dtype* A_ptr, Dtype* B_ptr); // b = alpha + a\n\ntemplate\nvoid gpu_axpy(uint64_t N, Dtype alpha, Dtype* X_ptr, Dtype* Y_ptr, Dtype* C_ptr);\n\ntemplate\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\nvoid gpu_relu(Dtype* dst, Dtype* src, uint64_t len);\n\ntemplate\nvoid gpu_relu_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t len);\n\n\ntemplate\nvoid gpu_dropout(Dtype* dst, Dtype* src, unsigned int* mask, unsigned int threshold, Dtype scale, uint64_t len);\n\ntemplate\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\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\nvoid gpu_cat_backward(Dtype* dest, Dtype* src, uint64_t dest_stride, uint64_t src_stride, uint64_t dest_numels);\n\ntemplate\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\nvoid gpu_embedding(Dtype* dst, Dtype* wts, int* indices, uint64_t numels, uint64_t indices_per_batch, unsigned int embedding_dim);\n\ntemplate\nvoid gpu_embedding_backward(Dtype* dst, Dtype* wts, int* indices, uint64_t numels, uint64_t indices_per_batch, unsigned int embedding_dim);\n\ntemplate\nvoid gpu_sqrt(Dtype* dst, const Dtype* src, const uint64_t numels);\n\ntemplate\nvoid gpu_sqrt_backward(Dtype* bottom, const Dtype* top, const Dtype* middle, const uint64_t numels);\n\ntemplate\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\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\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\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\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\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": "#include \n#include \n#include \n#include \n#include \n#include \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": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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": "#ifndef IBS_HPP\n#define IBS_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n#include \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 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 sigma_xbet, sigma_xbetp, sigma_y, sigma_yp;\n std::vector storage_u;\n std::vector storage_v;\n std::vector storage_opt;\n std::vector 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 optical_strage;\n std::vector 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 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;\n std::vector itgrl;\n void init_optc(const Lattice &lattice);\n double det(std::array,3>& l);\n double inv(std::array,3>& l, std::array,3>& v);\n double trace(std::array,3>& l){return l[0][0]+l[1][1]+l[2][2];}\n void calc_l(const Lattice& lattice, int i, std::array,3>& lh,\n std::array,3>& lv, std::array,3>& ls);\n void calc_itgl(int i, std::array,3>& ii, std::array,3>& l,\n std::array,3>& ll, std::array,3>& lh,\n std::array,3>& lv, std::array,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 integral;\n// std::vector optical;\n// struct debug {\n// double a, b, c, ax, bx, ay, by, al, bl, ix, iy, is;\n// };\n// std::vector 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& 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 the instrumental noise for LISA-type detectors.\n *\n * Formulas taken from Królak&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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \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": "/*\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 /* for getenv */\n#include /* for size_t type */\n#include /* for memcpy */\n#include /* 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 \ntypedef wchar_t char16_t;\n#else /* not ARCH_MACI64 */\n#include \n#endif /* ARCH_MACI64 */\n\n#include \n#include \n#include \n#include \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=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; jcopy_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 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 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 1) {\n\t\tmxFree(threadIDs);\n\t}\n\tfor (i_thread=0; i_thread 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 \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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 \n#endif\n#include \n#include \n#if defined(TESTDRIVE)\n#include \n#include \"primegen.h\"\n#endif\n#if defined(TESTDRIVE)\n#include \n#include \n#include \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 = ¶m;\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 [ ]\\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 = α \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 = α \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 = α \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 = α\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 = α \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, ¶ms);\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, ¶ms);\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, ¶ms);\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, ¶ms);\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; ikmax) 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\n#include \n#include \n#include \n#include \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; nulast_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 \n#include \n#include \n#include \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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \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 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 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 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 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 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 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 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 threshold) *pa = 1;\n pa++;\n }\n\n for (b=1; b 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 * 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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\" // tag -- set\n#define S_TAG (const xmlChar*) \"S\" // tag -- rts\n#define I_TAG (const xmlChar*) \"i\" // tag -- task\n#define SET_SIZE_ATTR (const xmlChar*) \"size\" // \"size\" attribute in tag\n#define SET_RTS_SIZE_ATTR (const xmlChar*) \"n\" // \"n\" attribute in tag\n#define SET_UF_ATTR (const xmlChar*) \"u\" // \"u\" attribute in tag\n#define RTS_ID_ATTR (const xmlChar*) \"count\" // \"count\" attribute in tag\n#define RTS_UF_ATTR (const xmlChar*) \"U\" // \"U\" attribute in tag\n#define ID_ATTR (const xmlChar*) \"nro\" // \"nro\" attribute in tag\n#define WCET_ATTR (const xmlChar*) \"C\" // \"C\" attribute in tag\n#define T_ATTR (const xmlChar*) \"T\" // \"T\" attribute in tag\n#define D_ATTR (const xmlChar*) \"D\" // \"D\" attribute in 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 -- 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 -- 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 -- 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(¤t_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": "#include \n#include \n#include \n\n#include \n\n#include \n#include \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, &l, &phase);\n SAMPLE(lower_rng, &l, &phase);\n } else {\n SAMPLE(lower_rng, &l, &phase);\n SAMPLE(this_rng, &l, &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 \n#include \n#include \n#include \n#include \n#include \n#include \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; ix[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; ix[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 \n#include \n#include \n#include \n\n#include \"tz_error.h\"\n#if HAVE_LIBGSL == 1\n#include \n#include \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 \",\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": "/* Copyright (c) 2011-2012, Jérémy 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 \n#include \n#include \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\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 \n#include \n#include \n\n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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;igraph.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(*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= 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 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;imax ) ? 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; imax ) ? 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;iis_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;i0) 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 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\n#include \n#include \n#include \n#include \n// #include \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 \n#include \n#include \n#include \n#ifndef NOMPI\n#include \n#endif\n#include \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 \n#include \n#include \n#include \n#include \n#include \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": "#ifndef L_Katyusha_H\n#define L_Katyusha_H\n\n\n#include \n#include \n#include \n#include /* printf */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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\nclass L_Katyusha\n{\n\n\nprotected:\n\n // involved variables\n\n\n\n\n\n\n\n std::vector proba_vector;\n\n std::vector tilde_proba_vector;\n\n\n std::vector group_C;\n\n std::vector index_group_C;\n\n std::vector maxp_group_C;\n\n std::vector isolated_I;\n\n std::vector sump_group_C;\n std::vector theta_S; //theta_S in the paper\n\n\n\n\n std::vector Li; // the Lipchitz constant of phi_i\n\n\n\n\n std::vector gk; // the vector g^k in the paper\n\n std::vector gradient_f_w; // gradient of f at w\n std::vector gradient_f_x; // gradient of f at x\n std::vector 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 batch_i;\n vector 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 x;\n std::vector w;\n std::vector y;\n std::vector z;\n std::vector 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 &, vector &, vector &){} //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 &, vector &){}\n\n\n L_Katyusha()\n {\n\n }\n\n\n void update_x(){\n for(L i=0; i q(nsamples);\n D sumq=0;\n cout<<\"start setting group sampling probablity\"<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=\"<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;itmp) tmp=st;\n }\n L2=tmp/nsamples/tau;\n cout<<\"L2=\"<tmp) tmp=st;\n }\n L2=tmp/nsamples;\n }\n cout<<\"set_L2=\"< >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=\"<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=\"<=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=\"< & 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=\"<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::max();\n\n /**setup parameters**/\n max_nb_loops=max_nb;\n mu=val_mu;\n cout<<\"mu=\"<c*tau/(this->nsamples)))<<\"; \"<c*tau/(this->nsamples)))<<\" \"<c*tau/(this->nsamples)))<<\"; \"<c*tau/(this->nsamples)))<<\" \"< sampled_groups;\n for(L i=0;iproba_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 & 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< & 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=\"< epsilon)\n {\n compute_and_record_result2();\n start = std::clock();\n\n nb_loops++;\n\n //cout<<\"before the loop time elapsed=\"<\n#include \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; inr; 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 \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#ifndef NOBLAS\n#ifdef MKL\n#include \n#else\n#include \n#endif\n#endif\n\n#include \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 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 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 n) iend = n;\n\t for(i=istart;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;kam){\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 n) jjend = n-j;\n\t for(jj=0;jj n) jjend = n-j;\n\t for(jj=0;jj n) jjend = n-j;\n\t for(jj=0;jj 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 n) jjend = n-j;\n\t for(jj=0;jj n) jjend = n-j;\n\t for(jj=0;jj>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>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>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>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>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 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#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \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": "/*\nCopyright (C) 2019-2020 JingWeiZhangHuai \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 \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=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(;iheight;\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;cheight;\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;cheight;\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;cprev = 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;ikernel[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;bbatch;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;bbatch;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;bbatch;b++)\n \n \n // }\n\n for(int b=0;bbatch;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=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;c0) 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=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;cheight;\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=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;cprev = 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;ikernel[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;bbatch;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;bbatch;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;bbatch;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;bbatch;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 SCOL_H\n#define SCOL_H\n#include \"Common.h\"\n// SP_IVP.h\n// Spherical Collapse IVP\n//#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include /* prototypes for CVODE fcts., consts. */\n#include /* access to serial N_Vector */\n#include /* access to dense SUNMatrix */\n#include /* access to dense SUNLinearSolver */\n#include /* access to CVDls interface */\n#include /* defs. of realtype, sunindextype */\n#include /* 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": "/*System includes*/\n#include \n#include \n#include \n#include \n\n/*GSL includes*/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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": "/* 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 \n#include \n#include \n#include \n#include \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; kval = 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; kval = -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 \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \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 coord_;\n\n /// \\f$ (\\theta, \\phi) \\f$ angles of points.\n mdarray tp_;\n\n /// Point weights.\n std::vector w_;\n\n /// Backward transformation from Ylm to spherical coordinates.\n mdarray ylm_backward_;\n\n /// Forward transformation from spherical coordinates to Ylm.\n mdarray ylm_forward_;\n\n /// Backward transformation from Rlm to spherical coordinates.\n mdarray rlm_backward_;\n\n /// Forward transformation from spherical coordinates to Rlm.\n mdarray 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 x(num_points_);\n std::vector y(num_points_);\n std::vector z(num_points_);\n\n coord_ = mdarray(3, num_points_);\n\n tp_ = mdarray(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(lmmax_, num_points_);\n\n ylm_forward_ = mdarray(num_points_, lmmax_);\n\n rlm_backward_ = mdarray(lmmax_, num_points_);\n\n rlm_forward_ = mdarray(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(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::geinv(lmmax_, ylm_forward_);\n linalg::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 flm(lmmax_);\n std::vector 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 \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 \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 ftp(ftp__, num_points_, ncol);\n // mdarray ftp1(num_points_, ncol);\n //\n // blas::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::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 spherical_coordinates(vector3d vc)\n {\n vector3d 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 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 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 coord(int idx__) const\n {\n return vector3d(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& 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 euler_angles, int proper_rotation,\n double_complex* rot_mtrx__, int ld)\n {\n mdarray rot_mtrx(rot_mtrx__, ld, 2 * l + 1);\n\n mdarray 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 euler_angles, int proper_rotation,\n double* rot_mtrx__, int ld)\n {\n mdarray rot_mtrx_rlm(rot_mtrx__, ld, 2 * l + 1);\n mdarray rot_mtrx_ylm(2 * l + 1, 2 * l + 1);\n\n mdarray 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({0}) : std::vector({-m1, m1});\n\n for (int m2 = -l; m2 <= l; m2++)\n {\n auto i24 = (m2 == 0) ? std::vector({0}) : std::vector({-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 \n static void rotation_matrix(int lmax,\n vector3d euler_angles,\n int proper_rotation,\n mdarray& 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& 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& 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 rotation_matrix_su2(const matrix3d& m)\n {\n double det = m.det() > 0 ? 1.0 : -1.0;\n\n matrix3d mat = m * det;\n mdarray 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& r__, mdarray& 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 dtheta_dr({std::cos(phi) * std::cos(theta), std::cos(theta) * std::sin(phi), -std::sin(theta)});\n vector3d dphi_dr({-std::sin(phi), std::cos(phi), 0.0});\n\n mdarray dRlm_dt(lmmax);\n mdarray 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 cosxn(int n__, double x__)\n {\n assert(n__ > 0);\n mdarray 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 sinxn(int n__, double x__)\n {\n assert(n__ > 0);\n mdarray 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(int ld, double const* flm, int nr, int lmmax, double* ftp)\n{\n assert(lmmax <= lmmax_);\n assert(ld >= lmmax);\n linalg::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(int ld, double_complex const* flm, int nr, int lmmax, double_complex* ftp)\n{\n assert(lmmax <= lmmax_);\n assert(ld >= lmmax);\n linalg::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 const* ftp, int nr, int lmmax, int ld, double* flm)\n{\n assert(lmmax <= lmmax_);\n assert(ld >= lmmax);\n linalg::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 const* ftp, int nr, int lmmax, int ld, double_complex* flm)\n{\n assert(lmmax <= lmmax_);\n assert(ld >= lmmax);\n linalg::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 * @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 \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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\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 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 SubbandBeamformerPtr;\ntypedef Inherit SubbandDSPtr;\ntypedef Inherit SubbandGSCPtr;\ntypedef Inherit SubbandGSCRLSPtr;\ntypedef Inherit SubbandMMIPtr;\ntypedef Inherit SubbandMVDRPtr;\ntypedef Inherit 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 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 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 DOAEstimatorSRPBasePtr;\ntypedef Inherit 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": "/*\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 \n#include \n#include \n#include \n#include \n#include \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 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\n#include \"fitsio.h\"\n#include \n#include \n#include \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": "#include \n#include \n#include \n#include \n#include \n#include \n#include \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": "/***********************************************************\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 \n#include \n#include \n#include \n#include \n#include \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 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 \n#include \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#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \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 &grid);\n\n static void convertFromFrequencyToWavelength(std::array &grid);\n\n static void convertFromWavelengthToFrequency(std::vector &grid);\n\n static void convertFromFrequencyToWavelength(\n std::vector>> &transitions);\n\n static void convertFromWavelengthToFrequency(\n std::vector>> &transitions);\n\n PAHEmissionModel();\n\n PAHEmissionModel(\n const std::vector>> &transitions);\n\n void setTransitions(\n const std::vector>> &transitions);\n\n void getTransitions(\n std::vector>> &transitions);\n\n void shiftTransitions(double shift);\n\n void setGrid(const std::vector &grid);\n\n void makeGrid(const std::vector &frange, double step);\n\n void makeGrid(double fmin, double fmax, double step);\n\n std::vector const &getGrid() const;\n\n void printTransitions();\n\n void applyCascadeWithEnergy(double energy, std::vector &temperatures);\n\n void applyTemperatureWithEnergy(double energy,\n std::vector &temperatures);\n\n void applyBlackbodyWithTemperature(double temperature);\n\n void\n applyBlackbodyWithTemperatureForEach(const std::vector &temperatures);\n\n void getSpectraAndConvolveWithLorentianOfFHWM(\n std::vector> &vector, double fwhm = 15);\n\n void getSpectraAndConvolveWithGaussianOfFHWM(\n std::vector> &vector, double fwhm = 15);\n\n void\n getSpectraAndConvolveWithDrudeOfFHWM(std::vector> &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>> _transitions;\n\n std::vector _grid;\n\n double _fmin;\n\n double _fmax;\n\n double\n solveInitialTemperature(double energy,\n std::vector> &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 &frange,\n double step) {\n makeGrid(frange[0], frange[1], step);\n}\n\ninline std::vector 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 \n#include \n#include \n#include \n#include \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° rotation */\n position_180 += (uint32_t)ipow(states, p) *\n ((i / (uint32_t)ipow(states, neigh_size - p)) % states);\n\n /* 90° 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° 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 *\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 \n#include \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 * ‘x’, ‘y’, ‘z’ for 1st, 2nd or 3d dimension;\n * ‘dN’ for linear averaging over N points;\n * ‘3’ for linear averaging over 3 points;\n * ‘5’ 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 * ‘x‘,‘y‘,‘z‘ for directions,\n * ‘d‘ for daubechies, ‘D‘ for centered daubechies,\n * ‘h‘ for haar, ‘H‘ for centered haar,\n * ‘b‘ for bspline, ‘B‘ for centered bspline,\n * ‘i‘ 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 \n#include \n#include \n#include \n#include \n#include \n#include \"../Parameter_files/COSMOLOGY.H\"\n#include \"../Parameter_files/INIT_PARAMS.H\"\n#include \n#include \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=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=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\n#include \n#include \n#include \"QuEST_debug.h\"\n#include \"QuEST_tn.h\"\n#include \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> 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 + |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\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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": "/*\n** TFCE heuristic\n**\n** M. Kuhlmann, MPI-KYB, Sept 2015\n*/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \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= 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 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 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 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\n#include \n#include \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": "/**\n * Copyright 2016 José Manuel Abuín Mosquera \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 .\n */\n\n#include \n#include \n#include \n\n#include \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] \\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 \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \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": "// Data Structure and Routines for peak fiting\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \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 \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if HAVE_MPI\n#include \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": "/* -*- 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 \n#include \n#include \n#include \n\n#include \"fec_mtrx_impl.h\"\n#include \n#include \n#include \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": "/* 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 \n#include \n#include \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érémy 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 // For the Cholesky decomposition\n#include \n#include \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\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": "/*\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 \n#include \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 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 \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \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": "/* -*- 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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\n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \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; stepsteps; step++) {\n double t = (1.0+step) / (1.0+setup->steps);\n for(int i=0; iN; 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; iN; i++)\n for(int j=i+1; jN; 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; iN = 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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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#include \n#include \n//#include //MPI_Wtime()\n\n#include \"starpu.h\"\n#ifdef MKL\n#include \n//#pragma message(\"MKL is used\")\n#else\n#include \n#ifdef LAPACKE_UTILS\n#include \n#endif\n#include \n//#pragma message(\"MKL is NOT used\")\n#endif\n\n#include \"starsh-spatial.h\"\n\n#include \n#include \"hicma_z.h\"\n#include \"auxcompute_z.h\"\n#include \"auxdescutil.h\"\n#include \"hicma.h\"\n#include \n#include \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": "/**\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 \n#include \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>= 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 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= 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= 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 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 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 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= n0) && ((n0+N) >= firstcol ) && (n0 < lastcol) ) {\n\n jj = max( n0, firstcol );\n j = jj - n0;\n\n for (; j\n#include \n#include \n#include \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": "/* 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 \n#include \n#include \n#include \n#include \n#include \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": "/* 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 \n#include \n#include \n#include \n#include \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": "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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; kval = 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; ellval = 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; kval = 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": "/* 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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": "/*\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 \n#include \n#include \n#include \n#include \n\n#include \n#include \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 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; kk0\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; kk0\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 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 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 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 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 = ∥\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; ddx, 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 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; kk0);\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 (%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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \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 \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 [ ]\", 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 \n#include \n#include \n\n#include \n#include \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": "#include \n#include \n#include \n\n#include \n\n/* Pull in the CBLAS header. */\n#ifdef _MACOSX\n#include \n#else\n#ifdef _ATLAS\n#include \n#else\n#include \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": "/* 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 * 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 \n#include \n#include \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": "/*\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 \n#include \n#include \n#include \n#include \n#include \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": "/* 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 \n#include \n#include \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 \n#include \n#include \n#include \n#include \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;isize;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;isize;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;jsize;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;jdata+(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; jsize; ++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;isize;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;isize;i++) {\n\n /* : Coradj_pix=squeeze(rho_vol(pix,slice,:)); */\n float* pCoradj = Coradj_pix->data+1;\n for(k=0;ksize-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;jsize1;j++) {\n for(k=0;ksize2;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;jsize1;j++) {\n for(k=0;ksize2;k++) {\n if(jsize2);\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;jsize1;j++) {\n for(k=0;ksize2;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;jsize1,1);\n\tfmat_x_mat(Vmhalf,&subm.matrix,buffer_01);\n\tfor(j=nl;jsize2);\n fmat_x_mat(A, &subm.matrix, buffer_03);\n for(j=0;jsize1;j++) {\n\n for(k=0;ksize2;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;jsize2;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;isize;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) 2011-2012, Jérémy 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 // For the Cholesky decomposition\n#include \n#include \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\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": "/* 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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/* 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 \n#include \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 \n#include \n#include \n#include \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; isize1 > 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 \n#include \n#include \n#include \n\n#include \n#include \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;ixythr) ythr=y[ix];\n }\n ythr*=frac;\n\n //Find minimum\n for(ix=0;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;iispl_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;jspl_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;jspl_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;iiw->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;iin_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;iin_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;iin_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;iitracer_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\n#include \n#include \n#include \n#include \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;icrane.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\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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, ¶ms);\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 = ¶ms;\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, ¶ms);\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": "/* 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 \n#include \n#include \n#include \n#include \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": "/* 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 \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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": "#ifndef _COMMON_\n#define _COMMON_\n\n#include \n#include \n#include \n#include \n#include \n#include \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": "// 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=] [CEED_DIR=]\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 \n#include \n#include \n#include \n#include \n#include \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 \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, °ree, 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 \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à degli Studi di Trieste\n *\n * \n */\n\n#include \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 \n//#include \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 TMatrixT;\n\ntemplate class TMatrixTSparse : public TMatrixTBase {\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 &a,const TMatrixTSparse &b,Int_t constr=0) {\n const TMatrixTSparse bt(TMatrixTSparse::kTransposed,b); AMultBt(a,bt,constr); }\n void AMultB (const TMatrixTSparse &a,const TMatrixT &b,Int_t constr=0) {\n const TMatrixTSparse bsp = b;\n const TMatrixTSparse bt(TMatrixTSparse::kTransposed,bsp); AMultBt(a,bt,constr); }\n void AMultB (const TMatrixT &a,const TMatrixTSparse &b,Int_t constr=0) {\n const TMatrixTSparse bt(TMatrixTSparse::kTransposed,b); AMultBt(a,bt,constr); }\n\n void AMultBt(const TMatrixTSparse &a,const TMatrixTSparse &b,Int_t constr=0);\n void AMultBt(const TMatrixTSparse &a,const TMatrixT &b,Int_t constr=0);\n void AMultBt(const TMatrixT &a,const TMatrixTSparse &b,Int_t constr=0);\n\n void APlusB (const TMatrixTSparse &a,const TMatrixTSparse &b,Int_t constr=0);\n void APlusB (const TMatrixTSparse &a,const TMatrixT &b,Int_t constr=0);\n void APlusB (const TMatrixT &a,const TMatrixTSparse &b,Int_t constr=0) { APlusB(b,a,constr); }\n\n void AMinusB(const TMatrixTSparse &a,const TMatrixTSparse &b,Int_t constr=0);\n void AMinusB(const TMatrixTSparse &a,const TMatrixT &b,Int_t constr=0);\n void AMinusB(const TMatrixT &a,const TMatrixTSparse &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 &another);\n TMatrixTSparse(const TMatrixT &another);\n\n TMatrixTSparse(EMatrixCreatorsOp1 op,const TMatrixTSparse &prototype);\n TMatrixTSparse(const TMatrixTSparse &a,EMatrixCreatorsOp2 op,const TMatrixTSparse &b);\n TMatrixTSparse(const TMatrixTSparse &a,EMatrixCreatorsOp2 op,const TMatrixT &b);\n TMatrixTSparse(const TMatrixT &a,EMatrixCreatorsOp2 op,const TMatrixTSparse &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 &SetRowIndexArray(Int_t *data) { memmove(fRowIndex,data,(this->fNrows+1)*sizeof(Int_t)); return *this; }\n virtual TMatrixTBase &SetColIndexArray(Int_t *data) { memmove(fColIndex,data,this->fNelems*sizeof(Int_t)); return *this; }\n\n TMatrixTSparse &SetSparseIndex (Int_t nelem_new);\n TMatrixTSparse &SetSparseIndex (const TMatrixTBase &another);\n TMatrixTSparse &SetSparseIndexAB(const TMatrixTSparse &a,const TMatrixTSparse &b);\n TMatrixTSparse &SetSparseIndexAB(const TMatrixT &a,const TMatrixTSparse &b);\n TMatrixTSparse &SetSparseIndexAB(const TMatrixTSparse &a,const TMatrixT &b)\n { return SetSparseIndexAB(b,a); }\n\n virtual void GetMatrix2Array (Element *data,Option_t * /*option*/ =\"\") const;\n virtual TMatrixTBase &SetMatrixArray (const Element *data,Option_t * /*option*/=\"\")\n { memcpy(fElements,data,this->fNelems*sizeof(Element)); return *this; }\n virtual TMatrixTBase &SetMatrixArray (Int_t nr_nonzeros,Int_t *irow,Int_t *icol,Element *data);\n virtual TMatrixTBase &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 &ResizeTo(Int_t nrows,Int_t ncols,Int_t nr_nonzeros=-1);\n virtual TMatrixTBase &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 &ResizeTo(const TMatrixTSparse &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 &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 &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&)\n ((const_cast *>(this))->Use(row_lwb,row_upb,col_lwb,col_upb,nr_nonzeros,\n const_cast(pRowIndex),\n const_cast(pColIndex),\n const_cast(pData))); }\n TMatrixTSparse &Use (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,\n Int_t *pRowIndex,Int_t *pColIndex,Element *pData);\n const TMatrixTSparse &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 &Use (TMatrixTSparse &a);\n const TMatrixTSparse &Use (const TMatrixTSparse &a) const;\n\n virtual TMatrixTBase &GetSub(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,\n TMatrixTBase &target,Option_t *option=\"S\") const;\n TMatrixTSparse 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 &SetSub(Int_t row_lwb,Int_t col_lwb,const TMatrixTBase &source);\n\n virtual Bool_t IsSymmetric() const { return (*this == TMatrixTSparse(kTransposed,*this)); }\n TMatrixTSparse &Transpose (const TMatrixTSparse &source);\n inline TMatrixTSparse &T () { return this->Transpose(*this); }\n\n inline void Mult(const TMatrixTSparse &a,const TMatrixTSparse &b) { AMultB(a,b,0); }\n\n virtual TMatrixTBase &Zero ();\n virtual TMatrixTBase &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 &NormByDiag(const TVectorT &/*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 operator[](Int_t rown) const { return TMatrixTSparseRow_const(*this,rown); }\n inline TMatrixTSparseRow operator[](Int_t rown) { return TMatrixTSparseRow (*this,rown); }\n\n TMatrixTSparse &operator=(const TMatrixT &source);\n TMatrixTSparse &operator=(const TMatrixTSparse &source);\n\n TMatrixTSparse &operator= (Element val);\n TMatrixTSparse &operator-=(Element val);\n TMatrixTSparse &operator+=(Element val);\n TMatrixTSparse &operator*=(Element val);\n\n TMatrixTSparse &operator+=(const TMatrixTSparse &source) { TMatrixTSparse tmp(*this); Clear();\n if (this == &source) APlusB (tmp,tmp,1);\n else APlusB (tmp,source,1);\n return *this; }\n TMatrixTSparse &operator+=(const TMatrixT &source) { TMatrixTSparse tmp(*this); Clear();\n APlusB(tmp,source,1); return *this; }\n TMatrixTSparse &operator-=(const TMatrixTSparse &source) { TMatrixTSparse tmp(*this); Clear();\n if (this == &source) AMinusB (tmp,tmp,1);\n else AMinusB(tmp,source,1);\n return *this; }\n TMatrixTSparse &operator-=(const TMatrixT &source) { TMatrixTSparse tmp(*this); Clear();\n AMinusB(tmp,source,1); return *this; }\n TMatrixTSparse &operator*=(const TMatrixTSparse &source) { TMatrixTSparse tmp(*this); Clear();\n if (this == &source) AMultB (tmp,tmp,1);\n else AMultB (tmp,source,1);\n return *this; }\n TMatrixTSparse &operator*=(const TMatrixT &source) { TMatrixTSparse tmp(*this); Clear();\n AMultB(tmp,source,1);\n return *this; }\n\n virtual TMatrixTBase &Randomize (Element alpha,Element beta,Double_t &seed);\n virtual TMatrixTSparse &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::Class();\n#endif // __CINT__\n\ntemplate inline const Element *TMatrixTSparse::GetMatrixArray () const { return fElements; }\ntemplate inline Element *TMatrixTSparse::GetMatrixArray () { return fElements; }\ntemplate inline const Int_t *TMatrixTSparse::GetRowIndexArray() const { return fRowIndex; }\ntemplate inline Int_t *TMatrixTSparse::GetRowIndexArray() { return fRowIndex; }\ntemplate inline const Int_t *TMatrixTSparse::GetColIndexArray() const { return fColIndex; }\ntemplate inline Int_t *TMatrixTSparse::GetColIndexArray() { return fColIndex; }\n\ntemplate \ninline TMatrixTSparse &TMatrixTSparse::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 \ninline const TMatrixTSparse &TMatrixTSparse::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 \ninline TMatrixTSparse &TMatrixTSparse::Use (TMatrixTSparse &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 \ninline const TMatrixTSparse &TMatrixTSparse::Use (const TMatrixTSparse &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 \ninline TMatrixTSparse TMatrixTSparse::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 tmp;\n this->GetSub(row_lwb,row_upb,col_lwb,col_upb,tmp,option);\n return tmp;\n }\n\ntemplate TMatrixTSparse operator+ (const TMatrixTSparse &source1,const TMatrixTSparse &source2);\ntemplate TMatrixTSparse operator+ (const TMatrixTSparse &source1,const TMatrixT &source2);\ntemplate TMatrixTSparse operator+ (const TMatrixT &source1,const TMatrixTSparse &source2);\ntemplate TMatrixTSparse operator+ (const TMatrixTSparse &source , Element val );\ntemplate TMatrixTSparse operator+ ( Element val ,const TMatrixTSparse &source );\ntemplate TMatrixTSparse operator- (const TMatrixTSparse &source1,const TMatrixTSparse &source2);\ntemplate TMatrixTSparse operator- (const TMatrixTSparse &source1,const TMatrixT &source2);\ntemplate TMatrixTSparse operator- (const TMatrixT &source1,const TMatrixTSparse &source2);\ntemplate TMatrixTSparse operator- (const TMatrixTSparse &source , Element val );\ntemplate TMatrixTSparse operator- ( Element val ,const TMatrixTSparse &source );\ntemplate TMatrixTSparse operator* (const TMatrixTSparse &source1,const TMatrixTSparse &source2);\ntemplate TMatrixTSparse operator* (const TMatrixTSparse &source1,const TMatrixT &source2);\ntemplate TMatrixTSparse operator* (const TMatrixT &source1,const TMatrixTSparse &source2);\ntemplate TMatrixTSparse operator* ( Element val ,const TMatrixTSparse &source );\ntemplate TMatrixTSparse operator* (const TMatrixTSparse &source, Element val );\n\ntemplate TMatrixTSparse &Add (TMatrixTSparse &target, Element scalar,\n const TMatrixTSparse &source);\ntemplate TMatrixTSparse &ElementMult(TMatrixTSparse &target,const TMatrixTSparse &source);\ntemplate TMatrixTSparse &ElementDiv (TMatrixTSparse &target,const TMatrixTSparse &source);\n\ntemplate Bool_t AreCompatible(const TMatrixTSparse &m1,const TMatrixTSparse &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 \n#include \n#include \n#include \n#include \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 .\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 \n#include \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 ); //!( 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": "/*! \\file interp.h\n \\brief Functions for interpolation to initialize the root solver\n */\n\n// used by the gsl interpolation functions\n#include \n#include \n#include \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 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 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\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": "/** \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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; ilock);\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; pnum_points; p+=stride) {\n double min_err = 1e308;\n for (size_t m=0; mk; ++m) {\n double err = 0;\n for (size_t j=0; jdim; ++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; thrnum_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; thrnum_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; mk; ++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; pnum_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; jdim; ++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; mk; ++m) {\n /*printf(\"Updating cluster %lu to\", m);*/\n for (size_t j=0; jdim; ++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; iblock->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 && iblock->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; iblock->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": "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include \n#include \n#include \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 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 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.\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 \n#include \n#include \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": "#include \n#include \n#if !defined(__APPLE__)\n#include \n#endif\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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\r\n#include \r\n#include \r\n#include /* printf */\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \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() 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\r\nclass PDCD_SMSVM\r\n{\r\nprivate:\r\n\r\n std::vector Au;\r\n std::vector Az;\r\n\r\n std::vector Mu;\r\n std::vector Mz;\r\n\r\n\r\n std::vector Mx;\r\n std::vector Ax;\r\n std::vector 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 u;\r\n\r\n std::vector z;\r\n\r\n std::vector x;\r\n\r\n std::vector v;\r\n\r\n std::vector L_M;\r\n\r\n std::vector L_f;\r\n\r\n std::vector 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 proba_vector;\r\n\r\n std::vector S;\r\n\r\n std::vector all_n;\r\n\r\n std::vector 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 data_A;\r\n\r\n Matrix data_M;\r\n\r\n std::vector lambda;\r\n\r\n std::vector 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(taun;i++){\r\n res+=value_of_g_i(x[i],i);\r\n }\r\n for(L j=0;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 & x0, vector & 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=\"< 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::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;jlfi) minv=lfi;\r\n }\r\n if(tau==n){\r\n for(L i=0;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=\"< & x0){\r\n for(L j=0;j & x0){\r\n for(L j=0;j & x0){\r\n for(L j=0;j & x0){\r\n for(L j=0;j & x0){\r\n for(L j=0;j & x0){\r\n for(L j=0;jn,0);\r\n for(L i=0;in;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 & x0,vector & 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\"<<\" ; \"< 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 \n#include \n#include \n#include \n#include \n#include \n#include \"Globals.h\"\n#include \"constitutive_equations.h\"\n#include \"Watershed.h\"\n#include \"manufactured_solution.h\"\n#include \n#include \n#include \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; iNumNodes;\t\n\n\t\tfor (int j = 0; jNodalB[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; iNumEl; ++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; jNumEl; ++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 \n#include \n#include \n#include \n#include \n#include \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": "#include \n#include \n#include \n#include \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* ) <ransforeT , (void*) &td1);\n iret2 = pthread_create( &thread2, NULL, (void* ) <ransforeT , (void*) &td2);\n }else{\n iret1 = pthread_create( &thread1, NULL, (void* ) <ransbackT , (void*) &td1);\n iret2 = pthread_create( &thread2, NULL, (void* ) <ransbackT , (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": "/* 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 \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n\n/* standard headers */\n#include \n#include \n\n/* gsl headers */\n#include \n#include \n#include \n#include \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": "#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Simulator {\ntemplate class UnitBase : public boost::multiplicative {\n public:\n UnitBase() = default;\n explicit constexpr UnitBase(double val) : _val(val) {}\n explicit constexpr UnitBase(long double val) : _val(gsl::narrow_cast(val)) {}\n explicit constexpr UnitBase(int val) : _val(gsl::narrow(val)) {}\n explicit constexpr UnitBase(std::int64_t val) : _val(gsl::narrow(val)) {}\n\n explicit constexpr operator double() const noexcept { return _val; }\n explicit constexpr operator int() const noexcept { return gsl::narrow_cast(_val); }\n explicit constexpr operator std::int64_t() const noexcept { return gsl::narrow_cast(_val); }\n explicit constexpr operator float() const noexcept { return gsl::narrow_cast(_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(*this);\n }\n\n template constexpr T operator+(const UnitBase &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(*this);\n }\n\n template constexpr T operator-(const UnitBase &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(*this);\n }\n\n constexpr T &operator/=(double rhs) noexcept {\n _val /= rhs;\n return static_cast(*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 { \\\n public: \\\n static constexpr name infinity() { return name(std::numeric_limits::infinity()); } \\\n using category = cat; \\\n static constexpr double scale = (s); \\\n using UnitBase::UnitBase; \\\n constexpr name(const UnitBase &other) : UnitBase(other) {} \\\n template \\\n constexpr name(const UnitBase &other) : UnitBase(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()); } \\\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 \n#include \"lib.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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;jd_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": "#include \n#include \n#include \n#include \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": "/**\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 \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \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": "// ************************************************\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 \r\n#include \r\n\r\n#if USE_GSL\r\n#include \r\n#include \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> 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> 1) ^ mag01[y & 0x1UL];\r\n }\r\n for (;kk> 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)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)=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": "/*\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \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 \n#ifdef LAPACKE_FOLDER\n#include \n#else\n#include \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 \n#include \n\n#include \"linmath.h\"\n\n#ifdef _WIN32\n#define SURVIVE_LOCAL_ONLY\n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \"parmt_postProcess.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#else\n#include \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 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 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 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\n#include \n#include \n#include \n#include \n#include \n#include /* GLoBES library */\n\n#include /* GNU Scientific library (required for root finding) */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"hdf5.h\"\n#include \n\n#define degree 0.0174\ndouble min (int n, ...) {\n\t/*\n\tn是參數個數,後面才是參數本身 \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/* 定義3 sigma range 的Prior (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 /* 取得參數目前Fit 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 /* 判斷參數是否要引入Prior */\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 /* 定義3 sigma range 的Prior (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/* 取得參數目前Fit 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/* 判斷參數是否要引入Prior */\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亂數生成器 */\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/* 定義Poisson 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/* 對True Value Spectrum 做Poisson 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/* 定義 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/* 定義 Test Statistic (Delta Chi-Square) */\n//參數:{CP : [0, 180, 1], MO : [1, -1] , CPV Hypothesis的deltacp} \n// 0 : CPC at deltacp=0; 180 : CPC at deltacp=180; 1 : CPV at deltacp\n//選定實驗EXP:[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/* 定義global fit參數(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/* 定義global fit參數(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//根據CP、MO的假設,生成Poisson Sample,計算其test statistic\n\t/* 定義glb_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/* 定義test_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/* 定義test_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/* 定義test_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/* 定義test_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/* 定義test_values_cpv_NO */ //deltacp為Input的值\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/* 定義test_values_cpv_IO */ //deltacp為Input的值\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/* 設定Projection */ \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 不動,其他可變\n\tglbSetDensityProjectionFlag(projection_cp_fixed,GLB_FIXED,GLB_ALL);//matter density不變\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 不動,其他可變\n\tglbSetDensityProjectionFlag(projection_cp_free,GLB_FIXED,GLB_ALL);//matter density不變\n\n\n\t/* 關閉系統誤差 */ \n\tglbSwitchSystematics(GLB_ALL,GLB_ALL,GLB_OFF);\n\n\t/* 設定Input_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/* 根據MO,CP的假設,生成 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(\"生成deltacp = 0, NO 的Poisson Spectrum \\n\");\n\t\t\t\t/* 根據CPC_0_NO的假設,生成Poisson 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(\"生成deltacp = 180, NO 的Poisson Spectrum \\n\");\n\t\t\t\t/* 根據CPC_0_IO的假設,生成Poisson 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(\"生成deltacp = input value, NO 的Poisson Spectrum \\n\");\n\t\t\t\t/* 根據CPV_NO的假設,生成Poisson 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(\"生成deltacp = 0, IO 的Poisson Spectrum \\n\");\n\t\t\t\t/* 根據CPC_0_NO的假設,生成Poisson 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(\"生成deltacp = 180, IO 的Poisson Spectrum \\n\");\n\t\t\t\t/* 根據CPC_0_IO的假設,生成Poisson 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(\"生成deltacp = input value, IO 的Poisson Spectrum \\n\");\n\t\t\t\t/* 根據CPV_IO的假設,生成Poisson 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/* 計算CPC Hypothesis (4種情況)*/\n\n\t/* 設定Prior (3 sigma range, Normal Ordering)*/\n\tglbRegisterPriorFunction(prior_3sigma_NO,NULL,NULL,NULL);\n\n\t/* 計算Chi square under cpc_0_NO */ \n\tglbSetProjection(projection_cp_fixed); //設定Projection 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/* 計算Chi square under cpc_pi_NO */ \n\tglbSetProjection(projection_cp_fixed); //設定Projection 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/* 設定Prior (3 sigma range, Inverse Ordering)*/\n\tglbRegisterPriorFunction(prior_3sigma_IO,NULL,NULL,NULL);\n\n\t/* 計算Chi square under cpc_0_IO */ \n\tglbSetProjection(projection_cp_fixed); //設定Projection 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/* 計算Chi square under cpc_pi_IO */ \n\tglbSetProjection(projection_cp_fixed); //設定Projection 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/* 取 chi_0_NO , chi_pi_NO, chi_0_IO , chi_pi_IO 四者之最小值 */ \n\ta = min(4, chi_0_NO, chi_pi_NO, chi_0_IO, chi_pi_IO);\n \n\t/* 計算CPV Hypothesis (2種情況)*/ \n\n\t/* 設定Prior (3 sigma range, Normal Ordering)*/\n\tglbRegisterPriorFunction(prior_3sigma_NO, NULL, NULL, NULL);\n\n\t/* 設定Projection (deltacp_Free)*/ \n\tglbSetProjection(projection_cp_free);\n\n\t/* 計算Chi 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/* 設定Prior (3 sigma range, Inverse Ordering)*/\n\tglbRegisterPriorFunction(prior_3sigma_IO, NULL, NULL, NULL);\n\n\t/* 設定Projection (deltacp_Free)*/ \n\tglbSetProjection(projection_cp_free);\n \n\t/* 計算Chi 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/* 取 chi_cpv_NO , chi_cpv_IO 兩者之最小值 */ \n\tb = min(2, chi_cpv_NO, chi_cpv_IO);\n\n\t/* 輸出Delta 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}}